book.tex 307 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181
  1. % Why direct style instead of continuation passing style?
  2. %% Student project ideas:
  3. %% * high-level optimizations like procedure inlining, etc.
  4. %% * closure optimization
  5. %% * adding letrec to the language
  6. %% (Thought: in the book and regular course, replace top-level defines
  7. %% with letrec.)
  8. %% * alternative back ends (ARM, LLVM)
  9. %% * alternative calling convention (a la Dybvig)
  10. %% * lazy evaluation
  11. %% * gradual typing
  12. %% * continuations (frames in heap a la SML or segmented stack a la Dybvig)
  13. %% * exceptions
  14. %% * self hosting
  15. %% * I/O
  16. %% * foreign function interface
  17. %% * quasi-quote and unquote
  18. %% * macros (too difficult?)
  19. %% * alternative garbage collector
  20. %% * alternative register allocator
  21. %% * parametric polymorphism
  22. %% * type classes (too difficulty?)
  23. %% * loops (too easy? combine with something else?)
  24. %% * loop optimization (fusion, etc.)
  25. %% * deforestation
  26. %% * records and subtyping
  27. %% * object-oriented features
  28. %% - objects, object types, and structural subtyping (e.g. Abadi & Cardelli)
  29. %% - class-based objects and nominal subtyping (e.g. Featherweight Java)
  30. %% * multi-threading, fork join, futures, implicit parallelism
  31. %% * dataflow analysis, type analysis and specialization
  32. \documentclass[11pt]{book}
  33. \usepackage[T1]{fontenc}
  34. \usepackage[utf8]{inputenc}
  35. \usepackage{lmodern}
  36. \usepackage{hyperref}
  37. \usepackage{graphicx}
  38. \usepackage[english]{babel}
  39. \usepackage{listings}
  40. \usepackage{amsmath}
  41. \usepackage{amsthm}
  42. \usepackage{amssymb}
  43. \usepackage{natbib}
  44. \usepackage{stmaryrd}
  45. \usepackage{xypic}
  46. \usepackage{semantic}
  47. \usepackage{wrapfig}
  48. \usepackage{tcolorbox}
  49. \usepackage{multirow}
  50. \usepackage{color}
  51. \usepackage{upquote}
  52. \definecolor{lightgray}{gray}{1}
  53. \newcommand{\black}[1]{{\color{black} #1}}
  54. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  55. \newcommand{\gray}[1]{{\color{gray} #1}}
  56. %% For pictures
  57. \usepackage{tikz}
  58. \usetikzlibrary{arrows.meta}
  59. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  60. % Computer Modern is already the default. -Jeremy
  61. %\renewcommand{\ttdefault}{cmtt}
  62. \definecolor{comment-red}{rgb}{0.8,0,0}
  63. \if{0}
  64. % Peanut gallery comments:
  65. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  66. \newcommand{\margincomment}[1]{\marginpar{#1}}
  67. \else
  68. \newcommand{\rn}[1]{}
  69. \newcommand{\margincomment}[1]{}
  70. \fi
  71. \lstset{%
  72. language=Lisp,
  73. basicstyle=\ttfamily\small,
  74. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then},
  75. deletekeywords={read},
  76. escapechar=|,
  77. columns=flexible,
  78. moredelim=[is][\color{red}]{~}{~}
  79. }
  80. \newtheorem{theorem}{Theorem}
  81. \newtheorem{lemma}[theorem]{Lemma}
  82. \newtheorem{corollary}[theorem]{Corollary}
  83. \newtheorem{proposition}[theorem]{Proposition}
  84. \newtheorem{constraint}[theorem]{Constraint}
  85. \newtheorem{definition}[theorem]{Definition}
  86. \newtheorem{exercise}[theorem]{Exercise}
  87. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  88. % 'dedication' environment: To add a dedication paragraph at the start of book %
  89. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  90. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  91. \newenvironment{dedication}
  92. {
  93. \cleardoublepage
  94. \thispagestyle{empty}
  95. \vspace*{\stretch{1}}
  96. \hfill\begin{minipage}[t]{0.66\textwidth}
  97. \raggedright
  98. }
  99. {
  100. \end{minipage}
  101. \vspace*{\stretch{3}}
  102. \clearpage
  103. }
  104. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  105. % Chapter quote at the start of chapter %
  106. % Source: http://tex.stackexchange.com/a/53380 %
  107. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  108. \makeatletter
  109. \renewcommand{\@chapapp}{}% Not necessary...
  110. \newenvironment{chapquote}[2][2em]
  111. {\setlength{\@tempdima}{#1}%
  112. \def\chapquote@author{#2}%
  113. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  114. \itshape}
  115. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  116. \makeatother
  117. \input{defs}
  118. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  119. \title{\Huge \textbf{Essentials of Compilation} \\
  120. \huge An Incremental Approach}
  121. \author{\textsc{Jeremy G. Siek} \\
  122. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  123. Indiana University \\
  124. \\
  125. with contributions from: \\
  126. Carl Factora \\
  127. Andre Kuhlenschmidt \\
  128. Ryan R. Newton \\
  129. Ryan Scott \\
  130. Cameron Swords \\
  131. Michael M. Vitousek \\
  132. Michael Vollmer
  133. }
  134. \begin{document}
  135. \frontmatter
  136. \maketitle
  137. \begin{dedication}
  138. This book is dedicated to the programming language wonks at Indiana
  139. University.
  140. \end{dedication}
  141. \tableofcontents
  142. \listoffigures
  143. %\listoftables
  144. \mainmatter
  145. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  146. \chapter*{Preface}
  147. The tradition of compiler writing at Indiana University goes back to
  148. research and courses about programming languages by Daniel Friedman in
  149. the 1970's and 1980's. Dan conducted research on lazy
  150. evaluation~\citep{Friedman:1976aa} in the context of
  151. Lisp~\citep{McCarthy:1960dz} and then studied
  152. continuations~\citep{Felleisen:kx} and
  153. macros~\citep{Kohlbecker:1986dk} in the context of the
  154. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  155. of those courses, Kent Dybvig, went on to build Chez
  156. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  157. compiler for Scheme. After completing his Ph.D. at the University of
  158. North Carolina, Kent returned to teach at Indiana University.
  159. Throughout the 1990's and 2000's, Kent continued development of Chez
  160. Scheme and taught the compiler course.
  161. The compiler course evolved to incorporate novel pedagogical ideas
  162. while also including elements of effective real-world compilers. One
  163. of Dan's ideas was to split the compiler into many small ``passes'' so
  164. that the code for each pass would be easy to understood in isolation.
  165. (In contrast, most compilers of the time were organized into only a
  166. few monolithic passes for reasons of compile-time efficiency.) Kent,
  167. with later help from his students Dipanwita Sarkar and Andrew Keep,
  168. developed infrastructure to support this approach and evolved the
  169. course, first to use micro-sized passes and then into even smaller
  170. nano passes~\citep{Sarkar:2004fk,Keep:2012aa}. Jeremy Siek was a
  171. student in this compiler course in the early 2000's, as part of his
  172. Ph.D. studies at Indiana University. Needless to say, Jeremy enjoyed
  173. the course immensely!
  174. During that time, another student named Abdulaziz Ghuloum observed
  175. that the front-to-back organization of the course made it difficult
  176. for students to understand the rationale for the compiler
  177. design. Abdulaziz proposed an incremental approach in which the
  178. students build the compiler in stages; they start by implementing a
  179. complete compiler for a very small subset of the input language and in
  180. each subsequent stage they add a language feature and add or modify
  181. passes to handle the new feature~\citep{Ghuloum:2006bh}. In this way,
  182. the students see how the language features motivate aspects of the
  183. compiler design.
  184. After graduating from Indiana University in 2005, Jeremy went on to
  185. teach at the University of Colorado. He adapted the nano pass and
  186. incremental approaches to compiling a subset of the Python
  187. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  188. on the surface but there is a large overlap in the compiler techniques
  189. required for the two languages. Thus, Jeremy was able to teach much of
  190. the same content from the Indiana compiler course. He very much
  191. enjoyed teaching the course organized in this way, and even better,
  192. many of the students learned a lot and got excited about compilers.
  193. Jeremy returned to teach at Indiana University in 2013. In his
  194. absence the compiler course had switched from the front-to-back
  195. organization to a back-to-front organization. Seeing how well the
  196. incremental approach worked at Colorado, he started porting and
  197. adapting the structure of the Colorado course back into the land of
  198. Scheme. In the meantime Indiana had moved on from Scheme to Racket, so
  199. the course is now about compiling a subset of Racket (and Typed
  200. Racket) to the x86 assembly language. The compiler is implemented in
  201. Racket 7.1~\citep{plt-tr}.
  202. This is the textbook for the incremental version of the compiler
  203. course at Indiana University (Spring 2016 - present) and it is the
  204. first open textbook for an Indiana compiler course. With this book we
  205. hope to make the Indiana compiler course available to people that have
  206. not had the chance to study in Bloomington in person. Many of the
  207. compiler design decisions in this book are drawn from the assignment
  208. descriptions of \cite{Dybvig:2010aa}. We have captured what we think
  209. are the most important topics from \cite{Dybvig:2010aa} but we have
  210. omitted topics that we think are less interesting conceptually and we
  211. have made simplifications to reduce complexity. In this way, this
  212. book leans more towards pedagogy than towards the efficiency of the
  213. generated code. Also, the book differs in places where we saw the
  214. opportunity to make the topics more fun, such as in relating register
  215. allocation to Sudoku (Chapter~\ref{ch:register-allocation-r1}).
  216. \section*{Prerequisites}
  217. The material in this book is challenging but rewarding. It is meant to
  218. prepare students for a lifelong career in programming languages.
  219. The book uses the Racket language both for the implementation of the
  220. compiler and for the language that is compiled, so a student should be
  221. proficient with Racket (or Scheme) prior to reading this book. There
  222. are many excellent resources for learning Scheme and
  223. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. It
  224. is helpful but not necessary for the student to have prior exposure to
  225. the x86 (or x86-64) assembly language~\citep{Intel:2015aa}, as one might
  226. obtain from a computer systems
  227. course~\citep{Bryant:2005aa,Bryant:2010aa}. This book introduces the
  228. parts of x86-64 assembly language that are needed.
  229. %\section*{Structure of book}
  230. % You might want to add short description about each chapter in this book.
  231. %\section*{About the companion website}
  232. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  233. %\begin{itemize}
  234. % \item A link to (freely downlodable) latest version of this document.
  235. % \item Link to download LaTeX source for this document.
  236. % \item Miscellaneous material (e.g. suggested readings etc).
  237. %\end{itemize}
  238. \section*{Acknowledgments}
  239. Many people have contributed to the ideas, techniques, organization,
  240. and teaching of the materials in this book. We especially thank the
  241. following people.
  242. \begin{itemize}
  243. \item Bor-Yuh Evan Chang
  244. \item Kent Dybvig
  245. \item Daniel P. Friedman
  246. \item Ronald Garcia
  247. \item Abdulaziz Ghuloum
  248. \item Jay McCarthy
  249. \item Dipanwita Sarkar
  250. \item Andrew Keep
  251. \item Oscar Waddell
  252. \item Michael Wollowski
  253. \end{itemize}
  254. \mbox{}\\
  255. \noindent Jeremy G. Siek \\
  256. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  257. %\noindent Spring 2016
  258. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  259. \chapter{Preliminaries}
  260. \label{ch:trees-recur}
  261. In this chapter we review the basic tools that are needed to implement
  262. a compiler. Programs are typically input by a programmer as text,
  263. i.e., a sequence of characters. The program-as-text representation is
  264. called \emph{concrete syntax}. We use concrete syntax to concisely
  265. write down and talk about programs. Inside the compiler, we use
  266. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  267. that efficiently supports the operations that the compiler needs to
  268. perform.
  269. %
  270. The translation from concrete syntax to abstract syntax is a process
  271. called \emph{parsing}~\cite{Aho:1986qf}. We do not cover the theory
  272. and implementation of parsing in this book. A parser is provided in
  273. the supporting materials for translating from concrete syntax to
  274. abstract syntax for the languages used in this book.
  275. ASTs can be represented in many different ways inside the compiler,
  276. depending on the programming language used to write the compiler.
  277. %
  278. We use Racket's \code{struct} feature to represent ASTs
  279. (Section~\ref{sec:ast}). We use grammars to define the abstract syntax
  280. of programming languages (Section~\ref{sec:grammar}) and pattern
  281. matching to inspect individual nodes in an AST
  282. (Section~\ref{sec:pattern-matching}). We use recursion to construct
  283. and deconstruct entire ASTs (Section~\ref{sec:recursion}). This
  284. chapter provides an brief introduction to these ideas.
  285. \section{Abstract Syntax Trees and Racket Structures}
  286. \label{sec:ast}
  287. Compilers use abstract syntax trees to represent programs because
  288. compilers often need to ask questions like: for a given part of a
  289. program, what kind of language feature is it? What are the sub-parts
  290. of this part of the program? Consider the program on the left and its
  291. AST on the right. This program is an addition and it has two
  292. sub-parts, a read operation and a negation. The negation has another
  293. sub-part, the integer constant \code{8}. By using a tree to represent
  294. the program, we can easily follow the links to go from one part of a
  295. program to its sub-parts.
  296. \begin{center}
  297. \begin{minipage}{0.4\textwidth}
  298. \begin{lstlisting}
  299. (+ (read) (- 8))
  300. \end{lstlisting}
  301. \end{minipage}
  302. \begin{minipage}{0.4\textwidth}
  303. \begin{equation}
  304. \begin{tikzpicture}
  305. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  306. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  307. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  308. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  309. \draw[->] (plus) to (read);
  310. \draw[->] (plus) to (minus);
  311. \draw[->] (minus) to (8);
  312. \end{tikzpicture}
  313. \label{eq:arith-prog}
  314. \end{equation}
  315. \end{minipage}
  316. \end{center}
  317. We use the standard terminology for trees to describe ASTs: each
  318. circle above is called a \emph{node}. The arrows connect a node to its
  319. \emph{children} (which are also nodes). The top-most node is the
  320. \emph{root}. Every node except for the root has a \emph{parent} (the
  321. node it is the child of). If a node has no children, it is a
  322. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  323. %% Recall that an \emph{symbolic expression} (S-expression) is either
  324. %% \begin{enumerate}
  325. %% \item an atom, or
  326. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  327. %% where $e_1$ and $e_2$ are each an S-expression.
  328. %% \end{enumerate}
  329. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  330. %% null value \code{'()}, etc. We can create an S-expression in Racket
  331. %% simply by writing a backquote (called a quasi-quote in Racket)
  332. %% followed by the textual representation of the S-expression. It is
  333. %% quite common to use S-expressions to represent a list, such as $a, b
  334. %% ,c$ in the following way:
  335. %% \begin{lstlisting}
  336. %% `(a . (b . (c . ())))
  337. %% \end{lstlisting}
  338. %% Each element of the list is in the first slot of a pair, and the
  339. %% second slot is either the rest of the list or the null value, to mark
  340. %% the end of the list. Such lists are so common that Racket provides
  341. %% special notation for them that removes the need for the periods
  342. %% and so many parenthesis:
  343. %% \begin{lstlisting}
  344. %% `(a b c)
  345. %% \end{lstlisting}
  346. %% The following expression creates an S-expression that represents AST
  347. %% \eqref{eq:arith-prog}.
  348. %% \begin{lstlisting}
  349. %% `(+ (read) (- 8))
  350. %% \end{lstlisting}
  351. %% When using S-expressions to represent ASTs, the convention is to
  352. %% represent each AST node as a list and to put the operation symbol at
  353. %% the front of the list. The rest of the list contains the children. So
  354. %% in the above case, the root AST node has operation \code{`+} and its
  355. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  356. %% diagram \eqref{eq:arith-prog}.
  357. %% To build larger S-expressions one often needs to splice together
  358. %% several smaller S-expressions. Racket provides the comma operator to
  359. %% splice an S-expression into a larger one. For example, instead of
  360. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  361. %% we could have first created an S-expression for AST
  362. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  363. %% S-expression.
  364. %% \begin{lstlisting}
  365. %% (define ast1.4 `(- 8))
  366. %% (define ast1.1 `(+ (read) ,ast1.4))
  367. %% \end{lstlisting}
  368. %% In general, the Racket expression that follows the comma (splice)
  369. %% can be any expression that produces an S-expression.
  370. We define a Racket \code{struct} for each kind of node. For this
  371. chapter we require just two kinds of nodes: one for integer constants
  372. and one for primitive operations. The following is the \code{struct}
  373. definition for integer constants.
  374. \begin{lstlisting}
  375. (struct Int (value))
  376. \end{lstlisting}
  377. An integer node includes just one thing: the integer value.
  378. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  379. \begin{lstlisting}
  380. (define eight (Int 8))
  381. \end{lstlisting}
  382. We say that the value created by \code{(Int 8)} is an
  383. \emph{instance} of the \code{Int} structure.
  384. The following is the \code{struct} definition for primitives operations.
  385. \begin{lstlisting}
  386. (struct Prim (op arg*))
  387. \end{lstlisting}
  388. A primitive operation node includes an operator symbol \code{op}
  389. and a list of children \code{arg*}. For example, to create
  390. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  391. \begin{lstlisting}
  392. (define neg-eight (Prim '- (list eight)))
  393. \end{lstlisting}
  394. Primitive operations may have zero or more children. The \code{read}
  395. operator has zero children:
  396. \begin{lstlisting}
  397. (define rd (Prim 'read '()))
  398. \end{lstlisting}
  399. whereas the addition operator has two children:
  400. \begin{lstlisting}
  401. (define ast1.1 (Prim '+ (list rd neg-eight)))
  402. \end{lstlisting}
  403. We have made a design choice regarding the \code{Prim} structure.
  404. Instead of using one structure for many different operations
  405. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  406. structure for each operation, as follows.
  407. \begin{lstlisting}
  408. (struct Read ())
  409. (struct Add (left right))
  410. (struct Neg (value))
  411. \end{lstlisting}
  412. The reason we choose to use just one structure is that in many parts
  413. of the compiler the code for the different primitive operators is the
  414. same, so we might as well just write that code once, which is enabled
  415. by using a single structure.
  416. When compiling a program such as \eqref{eq:arith-prog}, we need to
  417. know that the operation associated with the root node is addition and
  418. we need to be able to access its two children. Racket provides pattern
  419. matching over structures to support these kinds of queries, as we
  420. shall see in Section~\ref{sec:pattern-matching}.
  421. In this book, we often write down the concrete syntax of a program
  422. even when we really have in mind the AST because the concrete syntax
  423. is more concise. We recommend that, in your mind, you always think of
  424. programs as abstract syntax trees.
  425. \section{Grammars}
  426. \label{sec:grammar}
  427. A programming language can be thought of as a \emph{set} of programs.
  428. The set is typically infinite (one can always create larger and larger
  429. programs), so one cannot simply describe a language by listing all of
  430. the programs in the language. Instead we write down a set of rules, a
  431. \emph{grammar}, for building programs. Grammars are often used to
  432. define the concrete syntax of a language, but they can also be used to
  433. describe the abstract syntax. We shall write our rules in a variant of
  434. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}. As an
  435. example, we describe a small language, named $R_0$, that consists of
  436. integers and arithmetic operations.
  437. The first grammar rule for the abstract syntax of $R_0$ says that an
  438. instance of the \code{Int} structure is an expression:
  439. \begin{equation}
  440. \Exp ::= \INT{\Int} \label{eq:arith-int}
  441. \end{equation}
  442. %
  443. Each rule has a left-hand-side and a right-hand-side. The way to read
  444. a rule is that if you have all the program parts on the
  445. right-hand-side, then you can create an AST node and categorize it
  446. according to the left-hand-side.
  447. %
  448. A name such as $\Exp$ that is
  449. defined by the grammar rules is a \emph{non-terminal}.
  450. %
  451. The name $\Int$ is a also a non-terminal, but instead of defining it
  452. with a grammar rule, we define it with the following explanation. We
  453. make the simplifying design decision that all of the languages in this
  454. book only handle machine-representable integers. On most modern
  455. machines this corresponds to integers represented with 64-bits, i.e.,
  456. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  457. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  458. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  459. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  460. that the sequence of decimals represent an integer in range $-2^{62}$
  461. to $2^{62}-1$.
  462. The second grammar rule is the \texttt{read} operation that receives
  463. an input integer from the user of the program.
  464. \begin{equation}
  465. \Exp ::= \READ{} \label{eq:arith-read}
  466. \end{equation}
  467. The third rule says that, given an $\Exp$ node, you can build another
  468. $\Exp$ node by negating it.
  469. \begin{equation}
  470. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  471. \end{equation}
  472. Symbols in typewriter font such as \key{-} and \key{read} are
  473. \emph{terminal} symbols and must literally appear in the program for
  474. the rule to be applicable.
  475. We can apply the rules to build ASTs in the $R_0$
  476. language. For example, by rule \eqref{eq:arith-int}, \texttt{(Int 8)} is an
  477. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  478. an $\Exp$.
  479. \begin{center}
  480. \begin{minipage}{0.4\textwidth}
  481. \begin{lstlisting}
  482. (Prim '- (list (Int 8)))
  483. \end{lstlisting}
  484. \end{minipage}
  485. \begin{minipage}{0.25\textwidth}
  486. \begin{equation}
  487. \begin{tikzpicture}
  488. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  489. \node[draw, circle] (8) at (0, -1.2) {$8$};
  490. \draw[->] (minus) to (8);
  491. \end{tikzpicture}
  492. \label{eq:arith-neg8}
  493. \end{equation}
  494. \end{minipage}
  495. \end{center}
  496. The next grammar rule defines addition expressions:
  497. \begin{equation}
  498. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  499. \end{equation}
  500. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  501. $R_0$. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  502. \eqref{eq:arith-read} and we have already shown that \code{(Prim '-
  503. (list (Int 8)))} is an $\Exp$, so we apply rule \eqref{eq:arith-add}
  504. to show that
  505. \begin{lstlisting}
  506. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  507. \end{lstlisting}
  508. is an $\Exp$ in the $R_0$ language.
  509. If you have an AST for which the above rules do not apply, then the
  510. AST is not in $R_0$. For example, the program \code{(- (read) (+ 8))}
  511. is not in $R_0$ because there are no rules for \code{+} with only one
  512. argument, nor for \key{-} with two arguments. Whenever we define a
  513. language with a grammar, the language only includes those programs
  514. that are justified by the rules.
  515. The last grammar rule for $R_0$ states that there is a \code{Program}
  516. node to mark the top of the whole program:
  517. \[
  518. R_0 ::= \PROGRAM{\code{'()}}{\Exp}
  519. \]
  520. The \code{Program} structure is defined as follows
  521. \begin{lstlisting}
  522. (struct Program (info body))
  523. \end{lstlisting}
  524. where \code{body} is an expression. In later chapters, the \code{info}
  525. part will be used to store auxiliary information but for now it is
  526. just the empty list.
  527. It is common to have many grammar rules with the same left-hand side
  528. but different right-hand sides, such as the rules for $\Exp$ in the
  529. grammar of $R_0$. As a short-hand, a vertical bar can be used to
  530. combine several right-hand-sides into a single rule.
  531. We collect all of the grammar rules for the abstract syntax of $R_0$
  532. in Figure~\ref{fig:r0-syntax}. The concrete syntax for $R_0$ is
  533. defined in Figure~\ref{fig:r0-concrete-syntax}.
  534. The \code{read-program} function provided in \code{utilities.rkt} of
  535. the support materials reads a program in from a file (the sequence of
  536. characters in the concrete syntax of Racket) and parses it into an
  537. abstract syntax tree. See the description of \code{read-program} in
  538. Appendix~\ref{appendix:utilities} for more details.
  539. \begin{figure}[tp]
  540. \fbox{
  541. \begin{minipage}{0.96\textwidth}
  542. \[
  543. \begin{array}{rcl}
  544. \begin{array}{rcl}
  545. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)\\
  546. R_0 &::=& \Exp
  547. \end{array}
  548. \end{array}
  549. \]
  550. \end{minipage}
  551. }
  552. \caption{The concrete syntax of $R_0$.}
  553. \label{fig:r0-concrete-syntax}
  554. \end{figure}
  555. \begin{figure}[tp]
  556. \fbox{
  557. \begin{minipage}{0.96\textwidth}
  558. \[
  559. \begin{array}{rcl}
  560. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  561. &\mid& \ADD{\Exp}{\Exp} \\
  562. R_0 &::=& \PROGRAM{\code{'()}}{\Exp}
  563. \end{array}
  564. \]
  565. \end{minipage}
  566. }
  567. \caption{The abstract syntax of $R_0$.}
  568. \label{fig:r0-syntax}
  569. \end{figure}
  570. \section{Pattern Matching}
  571. \label{sec:pattern-matching}
  572. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  573. the parts of an AST node. Racket provides the \texttt{match} form to
  574. access the parts of a structure. Consider the following example and
  575. the output on the right.
  576. \begin{center}
  577. \begin{minipage}{0.5\textwidth}
  578. \begin{lstlisting}
  579. (match ast1.1
  580. [(Prim op (list child1 child2))
  581. (print op)])
  582. \end{lstlisting}
  583. \end{minipage}
  584. \vrule
  585. \begin{minipage}{0.25\textwidth}
  586. \begin{lstlisting}
  587. '+
  588. \end{lstlisting}
  589. \end{minipage}
  590. \end{center}
  591. In the above example, the \texttt{match} form takes the AST
  592. \eqref{eq:arith-prog} and binds its parts to the three pattern
  593. variables \texttt{op}, \texttt{child1}, and \texttt{child2}. In
  594. general, a match clause consists of a \emph{pattern} and a
  595. \emph{body}. Patterns are recursively defined to be either a pattern
  596. variable, a structure name followed by a pattern for each of the
  597. structure's arguments, or an S-expression (symbols, lists, etc.).
  598. (See Chapter 12 of The Racket
  599. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  600. and Chapter 9 of The Racket
  601. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  602. for a complete description of \code{match}.)
  603. %
  604. The body of a match clause may contain arbitrary Racket code. The
  605. pattern variables can be used in the scope of the body.
  606. A \code{match} form may contain several clauses, as in the following
  607. function \code{leaf?} that recognizes when an $R_0$ node is
  608. a leaf. The \code{match} proceeds through the clauses in order,
  609. checking whether the pattern can match the input AST. The
  610. body of the first clause that matches is executed. The output of
  611. \code{leaf?} for several ASTs is shown on the right.
  612. \begin{center}
  613. \begin{minipage}{0.6\textwidth}
  614. \begin{lstlisting}
  615. (define (leaf? arith)
  616. (match arith
  617. [(Int n) #t]
  618. [(Prim 'read '()) #t]
  619. [(Prim '- (list c1)) #f]
  620. [(Prim '+ (list c1 c2)) #f]))
  621. (leaf? (Prim 'read '()))
  622. (leaf? (Prim '- (list (Int 8))))
  623. (leaf? (Int 8))
  624. \end{lstlisting}
  625. \end{minipage}
  626. \vrule
  627. \begin{minipage}{0.25\textwidth}
  628. \begin{lstlisting}
  629. #t
  630. #f
  631. #t
  632. \end{lstlisting}
  633. \end{minipage}
  634. \end{center}
  635. When writing a \code{match}, we refer to the grammar definition to
  636. identify which non-terminal we are expecting to match against, then we
  637. make sure that 1) we have one clause for each alternative of that
  638. non-terminal and 2) that the pattern in each clause corresponds to the
  639. corresponding right-hand side of a grammar rule. For the \code{match}
  640. in the \code{leaf?} function, we refer to the grammar for $R_0$ in
  641. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  642. alternatives, so the \code{match} has 4 clauses. The pattern in each
  643. clause corresponds to the right-hand side of a grammar rule. For
  644. example, the pattern \code{(Prim '+ (list c1 c2))} corresponds to the
  645. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  646. patterns, replace non-terminals such as $\Exp$ with pattern variables
  647. of your choice (e.g. \code{c1} and \code{c2}).
  648. \section{Recursion}
  649. \label{sec:recursion}
  650. Programs are inherently recursive. For example, an $R_0$ expression is
  651. often made of smaller expressions. Thus, the natural way to process an
  652. entire program is with a recursive function. As a first example of
  653. such a recursive function, we define \texttt{exp?} below, which takes
  654. an arbitrary value and determines whether or not it is an $R_0$
  655. expression.
  656. %
  657. When a recursive function is defined using a sequence of match clauses
  658. that correspond to a grammar, and the body of each clause makes a
  659. recursive call on each child node, then we say the function is defined
  660. by \emph{structural recursion}\footnote{This principle of structuring
  661. code according to the data definition is advocated in the book
  662. \emph{How to Design Programs}
  663. \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}. Below we also
  664. define a second function, named \code{R0?}, that determines whether a
  665. value is an $R_0$ program. In general we can expect to write one
  666. recursive function to handle each non-terminal in a grammar.
  667. %
  668. \begin{center}
  669. \begin{minipage}{0.7\textwidth}
  670. \begin{lstlisting}
  671. (define (exp? ast)
  672. (match ast
  673. [(Int n) #t]
  674. [(Prim 'read '()) #t]
  675. [(Prim '- (list e)) (exp? e)]
  676. [(Prim '+ (list e1 e2))
  677. (and (exp? e1) (exp? e2))]
  678. [else #f]))
  679. (define (R0? ast)
  680. (match ast
  681. [(Program '() e) (exp? e)]
  682. [else #f]))
  683. (R0? (Program '() ast1.1)
  684. (R0? (Program '()
  685. (Prim '- (list (Prim 'read '())
  686. (Prim '+ (list (Num 8)))))))
  687. \end{lstlisting}
  688. \end{minipage}
  689. \vrule
  690. \begin{minipage}{0.25\textwidth}
  691. \begin{lstlisting}
  692. #t
  693. #f
  694. \end{lstlisting}
  695. \end{minipage}
  696. \end{center}
  697. You may be tempted to merge the two functions into one, like this:
  698. \begin{center}
  699. \begin{minipage}{0.5\textwidth}
  700. \begin{lstlisting}
  701. (define (R0? ast)
  702. (match ast
  703. [(Int n) #t]
  704. [(Prim 'read '()) #t]
  705. [(Prim '- (list e)) (R0? e)]
  706. [(Prim '+ (list e1 e2)) (and (R0? e1) (R0? e2))]
  707. [(Program '() e) (R0? e)]
  708. [else #f]))
  709. \end{lstlisting}
  710. \end{minipage}
  711. \end{center}
  712. %
  713. Sometimes such a trick will save a few lines of code, especially when
  714. it comes to the \code{Program} wrapper. Yet this style is generally
  715. \emph{not} recommended because it can get you into trouble.
  716. %
  717. For example, the above function is subtly wrong:
  718. \lstinline{(R0? (Program '() (Program '() (Int 3))))}
  719. will return true, when it should return false.
  720. %% NOTE FIXME - must check for consistency on this issue throughout.
  721. \section{Interpreters}
  722. \label{sec:interp-R0}
  723. The meaning, or semantics, of a program is typically defined in the
  724. specification of the language. For example, the Scheme language is
  725. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  726. defined in its reference manual~\citep{plt-tr}. In this book we use an
  727. interpreter to define the meaning of each language that we consider,
  728. following Reynolds' advice~\citep{reynolds72:_def_interp}. An
  729. interpreter that is designated (by some people) as the definition of a
  730. language is called a \emph{definitional interpreter}. We warm up by
  731. creating a definitional interpreter for the $R_0$ language, which
  732. serves as a second example of structural recursion. The
  733. \texttt{interp-R0} function is defined in
  734. Figure~\ref{fig:interp-R0}. The body of the function is a match on the
  735. input program followed by a call to the \lstinline{interp-exp} helper
  736. function, which in turn has one match clause per grammar rule for
  737. $R_0$ expressions.
  738. \begin{figure}[tp]
  739. \begin{lstlisting}
  740. (define (interp-exp e)
  741. (match e
  742. [(Int n) n]
  743. [(Prim 'read '())
  744. (define r (read))
  745. (cond [(fixnum? r) r]
  746. [else (error 'interp-R1 "expected an integer" r)])]
  747. [(Prim '- (list e))
  748. (define v (interp-exp e))
  749. (fx- 0 v)]
  750. [(Prim '+ (list e1 e2))
  751. (define v1 (interp-exp e1))
  752. (define v2 (interp-exp e2))
  753. (fx+ v1 v2)]
  754. ))
  755. (define (interp-R0 p)
  756. (match p
  757. [(Program '() e) (interp-exp e)]
  758. ))
  759. \end{lstlisting}
  760. \caption{Interpreter for the $R_0$ language.}
  761. \label{fig:interp-R0}
  762. \end{figure}
  763. Let us consider the result of interpreting a few $R_0$ programs. The
  764. following program adds two integers.
  765. \begin{lstlisting}
  766. (+ 10 32)
  767. \end{lstlisting}
  768. The result is \key{42}. We wrote the above program in concrete syntax,
  769. whereas the parsed abstract syntax is:
  770. \begin{lstlisting}
  771. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  772. \end{lstlisting}
  773. The next example demonstrates that expressions may be nested within
  774. each other, in this case nesting several additions and negations.
  775. \begin{lstlisting}
  776. (+ 10 (- (+ 12 20)))
  777. \end{lstlisting}
  778. What is the result of the above program?
  779. As mentioned previously, the $R_0$ language does not support
  780. arbitrarily-large integers, but only $63$-bit integers, so we
  781. interpret the arithmetic operations of $R_0$ using fixnum arithmetic
  782. in Racket.
  783. Suppose
  784. \[
  785. n = 999999999999999999
  786. \]
  787. which indeed fits in $63$-bits. What happens when we run the
  788. following program in our interpreter?
  789. \begin{lstlisting}
  790. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  791. \end{lstlisting}
  792. It produces an error:
  793. \begin{lstlisting}
  794. fx+: result is not a fixnum
  795. \end{lstlisting}
  796. We establish the convention that if running the definitional
  797. interpreter on a program produces an error, then the meaning of that
  798. program is \emph{unspecified}. That means a compiler for the language
  799. is under no obligations regarding that program; it may or may not
  800. produce an executable, and if it does, that executable can do
  801. anything. This convention applies to the languages defined in this
  802. book, as a way to simplify the student's task of implementing them,
  803. but this convention is not applicable to all programming languages.
  804. Moving on to the last feature of the $R_0$ language, the \key{read}
  805. operation prompts the user of the program for an integer. Recall that
  806. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  807. \code{8}. So if we run
  808. \begin{lstlisting}
  809. (interp-R0 ast1.1)
  810. \end{lstlisting}
  811. and if the input is \code{50}, then we get the answer to life, the
  812. universe, and everything: \code{42}!\footnote{\emph{The Hitchhiker's
  813. Guide to the Galaxy} by Douglas Adams.}
  814. We include the \key{read} operation in $R_0$ so a clever student
  815. cannot implement a compiler for $R_0$ that simply runs the interpreter
  816. during compilation to obtain the output and then generates the trivial
  817. code to produce the output. (Yes, a clever student did this in the
  818. first instance of this course.)
  819. The job of a compiler is to translate a program in one language into a
  820. program in another language so that the output program behaves the
  821. same way as the input program does according to its definitional
  822. interpreter. This idea is depicted in the following diagram. Suppose
  823. we have two languages, $\mathcal{L}_1$ and $\mathcal{L}_2$, and an
  824. interpreter for each language. Suppose that the compiler translates
  825. program $P_1$ in language $\mathcal{L}_1$ into program $P_2$ in
  826. language $\mathcal{L}_2$. Then interpreting $P_1$ and $P_2$ on their
  827. respective interpreters with input $i$ should yield the same output
  828. $o$.
  829. \begin{equation} \label{eq:compile-correct}
  830. \begin{tikzpicture}[baseline=(current bounding box.center)]
  831. \node (p1) at (0, 0) {$P_1$};
  832. \node (p2) at (3, 0) {$P_2$};
  833. \node (o) at (3, -2.5) {$o$};
  834. \path[->] (p1) edge [above] node {compile} (p2);
  835. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  836. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  837. \end{tikzpicture}
  838. \end{equation}
  839. In the next section we see our first example of a compiler.
  840. \section{Example Compiler: a Partial Evaluator}
  841. \label{sec:partial-evaluation}
  842. In this section we consider a compiler that translates $R_0$ programs
  843. into $R_0$ programs that may be more efficient, that is, this compiler
  844. is an optimizer. This optimizer eagerly computes the parts of the
  845. program that do not depend on any inputs, a process known as
  846. \emph{partial evaluation}~\cite{Jones:1993uq}. For example, given the
  847. following program
  848. \begin{lstlisting}
  849. (+ (read) (- (+ 5 3)))
  850. \end{lstlisting}
  851. our compiler will translate it into the program
  852. \begin{lstlisting}
  853. (+ (read) -8)
  854. \end{lstlisting}
  855. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  856. evaluator for the $R_0$ language. The output of the partial evaluator
  857. is an $R_0$ program. In Figure~\ref{fig:pe-arith}, the structural
  858. recursion over $\Exp$ is captured in the \code{pe-exp} function
  859. whereas the code for partially evaluating the negation and addition
  860. operations is factored into two separate helper functions:
  861. \code{pe-neg} and \code{pe-add}. The input to these helper
  862. functions is the output of partially evaluating the children.
  863. \begin{figure}[tp]
  864. \begin{lstlisting}
  865. (define (pe-neg r)
  866. (match r
  867. [(Int n) (Int (fx- 0 n))]
  868. [else (Prim '- (list r))]))
  869. (define (pe-add r1 r2)
  870. (match* (r1 r2)
  871. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  872. [(_ _) (Prim '+ (list r1 r2))]))
  873. (define (pe-exp e)
  874. (match e
  875. [(Int n) (Int n)]
  876. [(Prim 'read '()) (Prim 'read '())]
  877. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  878. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]
  879. ))
  880. (define (pe-R0 p)
  881. (match p
  882. [(Program info e) (Program info (pe-exp e))]
  883. ))
  884. \end{lstlisting}
  885. \caption{A partial evaluator for $R_0$ expressions.}
  886. \label{fig:pe-arith}
  887. \end{figure}
  888. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  889. arguments are integers and if they are, perform the appropriate
  890. arithmetic. Otherwise, they create an AST node for the operation
  891. (either negation or addition).
  892. To gain some confidence that the partial evaluator is correct, we can
  893. test whether it produces programs that get the same result as the
  894. input programs. That is, we can test whether it satisfies Diagram
  895. \eqref{eq:compile-correct}. The following code runs the partial
  896. evaluator on several examples and tests the output program. The
  897. \texttt{parse-program} and \texttt{assert} functions are defined in
  898. Appendix~\ref{appendix:utilities}.\\
  899. \begin{minipage}{1.0\textwidth}
  900. \begin{lstlisting}
  901. (define (test-pe p)
  902. (assert "testing pe-R0"
  903. (equal? (interp-R0 p) (interp-R0 (pe-R0 p)))))
  904. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  905. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  906. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  907. \end{lstlisting}
  908. \end{minipage}
  909. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  910. \chapter{Integers and Variables}
  911. \label{ch:int-exp}
  912. This chapter is about compiling the subset of Racket that includes
  913. integer arithmetic and local variable binding, which we name $R_1$, to
  914. x86-64 assembly code~\citep{Intel:2015aa}. Henceforth we shall refer
  915. to x86-64 simply as x86. The chapter begins with a description of the
  916. $R_1$ language (Section~\ref{sec:s0}) followed by a description of x86
  917. (Section~\ref{sec:x86}). The x86 assembly language is large, so we
  918. discuss only what is needed for compiling $R_1$. We introduce more of
  919. x86 in later chapters. Once we have introduced $R_1$ and x86, we
  920. reflect on their differences and come up with a plan to break down the
  921. translation from $R_1$ to x86 into a handful of steps
  922. (Section~\ref{sec:plan-s0-x86}). The rest of the sections in this
  923. chapter give detailed hints regarding each step
  924. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  925. to give enough hints that the well-prepared reader, together with a
  926. few friends, can implement a compiler from $R_1$ to x86 in a couple
  927. weeks while at the same time leaving room for some fun and creativity.
  928. To give the reader a feeling for the scale of this first compiler, the
  929. instructor solution for the $R_1$ compiler is less than 500 lines of
  930. code.
  931. \section{The $R_1$ Language}
  932. \label{sec:s0}
  933. The $R_1$ language extends the $R_0$ language with variable
  934. definitions. The concrete syntax of the $R_1$ language is defined by
  935. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  936. syntax is defined in Figure~\ref{fig:r1-syntax}. The non-terminal
  937. \Var{} may be any Racket identifier. As in $R_0$, \key{read} is a
  938. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  939. operator. Similar to $R_0$, the abstract syntax of $R_1$ includes the
  940. \key{Program} struct to mark the top of the program.
  941. %% The $\itm{info}$
  942. %% field of the \key{Program} structure contains an \emph{association
  943. %% list} (a list of key-value pairs) that is used to communicate
  944. %% auxiliary data from one compiler pass the next.
  945. Despite the simplicity of the $R_1$ language, it is rich enough to
  946. exhibit several compilation techniques.
  947. \begin{figure}[tp]
  948. \centering
  949. \fbox{
  950. \begin{minipage}{0.96\textwidth}
  951. \[
  952. \begin{array}{rcl}
  953. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)\\
  954. &\mid& \Var \mid (\key{let}~([\Var~\Exp])~\Exp) \\
  955. R_1 &::=& \Exp
  956. \end{array}
  957. \]
  958. \end{minipage}
  959. }
  960. \caption{The concrete syntax of $R_1$.}
  961. \label{fig:r1-concrete-syntax}
  962. \end{figure}
  963. \begin{figure}[tp]
  964. \centering
  965. \fbox{
  966. \begin{minipage}{0.96\textwidth}
  967. \[
  968. \begin{array}{rcl}
  969. \Exp &::=& \INT{\Int} \mid \READ{} \\
  970. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  971. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  972. R_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  973. \end{array}
  974. \]
  975. \end{minipage}
  976. }
  977. \caption{The abstract syntax of $R_1$.}
  978. \label{fig:r1-syntax}
  979. \end{figure}
  980. Let us dive further into the syntax and semantics of the $R_1$
  981. language. The \key{Let} feature defines a variable for use within its
  982. body and initializes the variable with the value of an expression.
  983. The abstract syntax for \key{Let} is defined in Figure~\ref{fig:r1-syntax}.
  984. The concrete syntax for \key{Let} is
  985. \begin{lstlisting}
  986. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  987. \end{lstlisting}
  988. For example, the following program initializes \code{x} to $32$ and then
  989. evaluates the body \code{(+ 10 x)}, producing $42$.
  990. \begin{lstlisting}
  991. (let ([x (+ 12 20)]) (+ 10 x))
  992. \end{lstlisting}
  993. When there are multiple \key{let}'s for the same variable, the closest
  994. enclosing \key{let} is used. That is, variable definitions overshadow
  995. prior definitions. Consider the following program with two \key{let}'s
  996. that define variables named \code{x}. Can you figure out the result?
  997. \begin{lstlisting}
  998. (let ([x 32]) (+ (let ([x 10]) x) x))
  999. \end{lstlisting}
  1000. For the purposes of depicting which variable uses correspond to which
  1001. definitions, the following shows the \code{x}'s annotated with
  1002. subscripts to distinguish them. Double check that your answer for the
  1003. above is the same as your answer for this annotated version of the
  1004. program.
  1005. \begin{lstlisting}
  1006. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1007. \end{lstlisting}
  1008. The initializing expression is always evaluated before the body of the
  1009. \key{let}, so in the following, the \key{read} for \code{x} is
  1010. performed before the \key{read} for \code{y}. Given the input
  1011. $52$ then $10$, the following produces $42$ (not $-42$).
  1012. \begin{lstlisting}
  1013. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1014. \end{lstlisting}
  1015. \begin{wrapfigure}[24]{r}[1.0in]{0.6\textwidth}
  1016. \small
  1017. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1018. An \emph{association list} (alist) is a list of key-value pairs.
  1019. For example, we can map people to their ages with an alist.
  1020. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1021. (define ages
  1022. '((jane . 25) (sam . 24) (kate . 45)))
  1023. \end{lstlisting}
  1024. The \emph{dictionary} interface is for mapping keys to values.
  1025. Every alist implements this interface. The package
  1026. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1027. provides many functions for working with dictionaries. Here
  1028. are a few of them:
  1029. \begin{description}
  1030. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1031. returns the value associated with the given $\itm{key}$.
  1032. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1033. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1034. but otherwise is the same as $\itm{dict}$.
  1035. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1036. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1037. of keys and values in $\itm{dict}$. For example, the following
  1038. creates a new alist in which the ages are incremented.
  1039. \end{description}
  1040. \vspace{-10pt}
  1041. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1042. (for/list ([(k v) (in-dict ages)])
  1043. (cons k (add1 v)))
  1044. \end{lstlisting}
  1045. \end{tcolorbox}
  1046. \end{wrapfigure}
  1047. Figure~\ref{fig:interp-R1} shows the definitional interpreter for the
  1048. $R_1$ language. It extends the interpreter for $R_0$ with two new
  1049. \key{match} clauses for variables and for \key{let}. For \key{let},
  1050. we need a way to communicate the value of a variable to all the uses
  1051. of a variable. To accomplish this, we maintain a mapping from
  1052. variables to values. Throughout the compiler we often need to map
  1053. variables to information about them. We refer to these mappings as
  1054. \emph{environments}
  1055. \footnote{Another common term for environment in the compiler
  1056. literature is \emph{symbol table}.}. For simplicity, we use an
  1057. association list (alist) to represent the environment. The sidebar to
  1058. the right gives a brief introduction to alists and the
  1059. \code{racket/dict} package. The \code{interp-R1} function takes the
  1060. current environment, \code{env}, as an extra parameter. When the
  1061. interpreter encounters a variable, it finds the corresponding value
  1062. using the \code{dict-ref} function. When the interpreter encounters a
  1063. \key{Let}, it evaluates the initializing expression, extends the
  1064. environment with the result value bound to the variable, using
  1065. \code{dict-set}, then evaluates the body of the \key{Let}.
  1066. \begin{figure}[tp]
  1067. \begin{lstlisting}
  1068. (define (interp-exp env)
  1069. (lambda (e)
  1070. (match e
  1071. [(Int n) n]
  1072. [(Prim 'read '())
  1073. (define r (read))
  1074. (cond [(fixnum? r) r]
  1075. [else (error 'interp-R1 "expected an integer" r)])]
  1076. [(Prim '- (list e))
  1077. (define v ((interp-exp env) e))
  1078. (fx- 0 v)]
  1079. [(Prim '+ (list e1 e2))
  1080. (define v1 ((interp-exp env) e1))
  1081. (define v2 ((interp-exp env) e2))
  1082. (fx+ v1 v2)]
  1083. [(Var x) (dict-ref env x)]
  1084. [(Let x e body)
  1085. (define new-env (dict-set env x ((interp-exp env) e)))
  1086. ((interp-exp new-env) body)]
  1087. )))
  1088. (define (interp-R1 p)
  1089. (match p
  1090. [(Program info e) ((interp-exp '()) e)]
  1091. ))
  1092. \end{lstlisting}
  1093. \caption{Interpreter for the $R_1$ language.}
  1094. \label{fig:interp-R1}
  1095. \end{figure}
  1096. The goal for this chapter is to implement a compiler that translates
  1097. any program $P_1$ written in the $R_1$ language into an x86 assembly
  1098. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1099. computer as the $P_1$ program interpreted by \code{interp-R1}. That
  1100. is, they both output the same integer $n$. We depict this correctness
  1101. criteria in the following diagram.
  1102. \[
  1103. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1104. \node (p1) at (0, 0) {$P_1$};
  1105. \node (p2) at (4, 0) {$P_2$};
  1106. \node (o) at (4, -2) {$n$};
  1107. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1108. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  1109. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  1110. \end{tikzpicture}
  1111. \]
  1112. In the next section we introduce enough of the x86 assembly
  1113. language to compile $R_1$.
  1114. \section{The x86 Assembly Language}
  1115. \label{sec:x86}
  1116. Figure~\ref{fig:x86-0-concrete} defines the concrete syntax for the subset of
  1117. the x86 assembly language needed for this chapter.
  1118. %
  1119. An x86 program begins with a \code{main} label followed by a sequence
  1120. of instructions. In the grammar, the superscript $+$ is used to
  1121. indicate a sequence of one or more items, e.g., $\Instr^{+}$ is a
  1122. sequence of instructions.
  1123. %
  1124. An x86 program is stored in the computer's memory and the computer has
  1125. a \emph{program counter} that points to the address of the next
  1126. instruction to be executed. For most instructions, once the
  1127. instruction is executed, the program counter is incremented to point
  1128. to the immediately following instruction in memory. Most x86
  1129. instructions take two operands, where each operand is either an
  1130. integer constant (called \emph{immediate value}), a \emph{register},
  1131. or a memory location. A register is a special kind of variable. Each
  1132. one holds a 64-bit value; there are 16 registers in the computer and
  1133. their names are given in Figure~\ref{fig:x86-0-concrete}. The computer's memory
  1134. as a mapping of 64-bit addresses to 64-bit values%
  1135. \footnote{This simple story suffices for describing how sequential
  1136. programs access memory but is not sufficient for multi-threaded
  1137. programs. However, multi-threaded execution is beyond the scope of
  1138. this book.}.
  1139. %
  1140. We use the AT\&T syntax expected by the GNU assembler, which comes
  1141. with the \key{gcc} compiler that we use for compiling assembly code to
  1142. machine code.
  1143. %
  1144. Appendix~\ref{sec:x86-quick-reference} is a quick-reference for all of
  1145. the x86 instructions used in this book.
  1146. % to do: finish treatment of imulq
  1147. % it's needed for vector's in R6/R7
  1148. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1149. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1150. && \key{r8} \mid \key{r9} \mid \key{r10}
  1151. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1152. \mid \key{r14} \mid \key{r15}}
  1153. \begin{figure}[tp]
  1154. \fbox{
  1155. \begin{minipage}{0.96\textwidth}
  1156. \[
  1157. \begin{array}{lcl}
  1158. \Reg &::=& \allregisters{} \\
  1159. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1160. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1161. \key{subq} \; \Arg\key{,} \Arg \mid
  1162. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1163. && \key{callq} \; \mathit{label} \mid
  1164. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} \\
  1165. && \itm{label}\key{:}\; \Instr \\
  1166. \Prog &::= & \key{.globl main}\\
  1167. & & \key{main:} \; \Instr^{+}
  1168. \end{array}
  1169. \]
  1170. \end{minipage}
  1171. }
  1172. \caption{The concrete syntax of the $x86_0$ assembly language (AT\&T syntax).}
  1173. \label{fig:x86-0-concrete}
  1174. \end{figure}
  1175. An immediate value is written using the notation \key{\$}$n$ where $n$
  1176. is an integer.
  1177. %
  1178. A register is written with a \key{\%} followed by the register name,
  1179. such as \key{\%rax}.
  1180. %
  1181. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1182. which obtains the address stored in register $r$ and then adds $n$
  1183. bytes to the address. The resulting address is used to either load or
  1184. store to memory depending on whether it occurs as a source or
  1185. destination argument of an instruction.
  1186. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1187. source $s$ and destination $d$, applies the arithmetic operation, then
  1188. writes the result back to the destination $d$.
  1189. %
  1190. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1191. stores the result in $d$.
  1192. %
  1193. The $\key{callq}\,\itm{label}$ instruction executes the procedure
  1194. specified by the label and $\key{retq}$ returns from a procedure to
  1195. its caller. We discuss procedure calls in more detail later in this
  1196. chapter and in Chapter~\ref{ch:functions}. The
  1197. $\key{jmp}\,\itm{label}$ instruction updates the program counter to
  1198. the address of the instruction after the specified label.
  1199. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  1200. to \code{(+ 10 32)}. The \key{globl} directive says that the
  1201. \key{main} procedure is externally visible, which is necessary so
  1202. that the operating system can call it. The label \key{main:}
  1203. indicates the beginning of the \key{main} procedure which is where
  1204. the operating system starts executing this program. The instruction
  1205. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  1206. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  1207. $10$ in \key{rax} and puts the result, $42$, back into
  1208. \key{rax}.
  1209. %
  1210. The last instruction, \key{retq}, finishes the \key{main} function by
  1211. returning the integer in \key{rax} to the operating system. The
  1212. operating system interprets this integer as the program's exit
  1213. code. By convention, an exit code of 0 indicates that a program
  1214. completed successfully, and all other exit codes indicate various
  1215. errors. Nevertheless, we return the result of the program as the exit
  1216. code.
  1217. %\begin{wrapfigure}{r}{2.25in}
  1218. \begin{figure}[tbp]
  1219. \begin{lstlisting}
  1220. .globl main
  1221. main:
  1222. movq $10, %rax
  1223. addq $32, %rax
  1224. retq
  1225. \end{lstlisting}
  1226. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1227. \label{fig:p0-x86}
  1228. %\end{wrapfigure}
  1229. \end{figure}
  1230. Unfortunately, x86 varies in a couple ways depending on what operating
  1231. system it is assembled in. The code examples shown here are correct on
  1232. Linux and most Unix-like platforms, but when assembled on Mac OS X,
  1233. labels like \key{main} must be prefixed with an underscore, as in
  1234. \key{\_main}.
  1235. We exhibit the use of memory for storing intermediate results in the
  1236. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1237. equivalent to \code{(+ 52 (- 10))}. This program uses a region of
  1238. memory called the \emph{procedure call stack} (or \emph{stack} for
  1239. short). The stack consists of a separate \emph{frame} for each
  1240. procedure call. The memory layout for an individual frame is shown in
  1241. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1242. \emph{stack pointer} and points to the item at the top of the
  1243. stack. The stack grows downward in memory, so we increase the size of
  1244. the stack by subtracting from the stack pointer. Some operating
  1245. systems require the frame size to be a multiple of 16 bytes. In the
  1246. context of a procedure call, the \emph{return address} is the next
  1247. instruction after the call instruction on the caller side. During a
  1248. function call, the return address is pushed onto the stack. The
  1249. register \key{rbp} is the \emph{base pointer} and is used to access
  1250. variables associated with the current procedure call. The base
  1251. pointer of the caller is pushed onto the stack after the return
  1252. address. We number the variables from $1$ to $n$. Variable $1$ is
  1253. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  1254. $-16\key{(\%rbp)}$, etc.
  1255. \begin{figure}[tbp]
  1256. \begin{lstlisting}
  1257. start:
  1258. movq $10, -8(%rbp)
  1259. negq -8(%rbp)
  1260. movq -8(%rbp), %rax
  1261. addq $52, %rax
  1262. jmp conclusion
  1263. .globl main
  1264. main:
  1265. pushq %rbp
  1266. movq %rsp, %rbp
  1267. subq $16, %rsp
  1268. jmp start
  1269. conclusion:
  1270. addq $16, %rsp
  1271. popq %rbp
  1272. retq
  1273. \end{lstlisting}
  1274. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1275. \label{fig:p1-x86}
  1276. \end{figure}
  1277. \begin{figure}[tbp]
  1278. \centering
  1279. \begin{tabular}{|r|l|} \hline
  1280. Position & Contents \\ \hline
  1281. 8(\key{\%rbp}) & return address \\
  1282. 0(\key{\%rbp}) & old \key{rbp} \\
  1283. -8(\key{\%rbp}) & variable $1$ \\
  1284. -16(\key{\%rbp}) & variable $2$ \\
  1285. \ldots & \ldots \\
  1286. 0(\key{\%rsp}) & variable $n$\\ \hline
  1287. \end{tabular}
  1288. \caption{Memory layout of a frame.}
  1289. \label{fig:frame}
  1290. \end{figure}
  1291. Getting back to the program in Figure~\ref{fig:p1-x86}, the first
  1292. three instructions are the typical \emph{prelude} for a procedure.
  1293. The instruction \key{pushq \%rbp} saves the base pointer for the
  1294. caller onto the stack and subtracts $8$ from the stack pointer. The
  1295. second instruction \key{movq \%rsp, \%rbp} changes the base pointer so
  1296. that it points the location of the old base pointer. The instruction
  1297. \key{subq \$16, \%rsp} moves the stack pointer down to make enough
  1298. room for storing variables. This program needs one variable ($8$
  1299. bytes) but because the frame size is required to be a multiple of 16
  1300. bytes, the space for variables is rounded up to 16 bytes.
  1301. The four instructions under the label \code{start} carry out the work
  1302. of computing \code{(+ 52 (- 10)))}. The first instruction
  1303. \key{movq \$10, -8(\%rbp)} stores $10$ in variable $1$. The
  1304. instruction \key{negq -8(\%rbp)} changes variable $1$ to $-10$. The
  1305. instruction \key{movq \$52, \%rax} places $52$ in the register \key{rax} and
  1306. finally \key{addq -8(\%rbp), \%rax} adds the contents of variable $1$ to
  1307. \key{rax}, at which point \key{rax} contains $42$.
  1308. The three instructions under the label \code{conclusion} are the
  1309. typical \emph{finale} of a procedure. The first two instructions are
  1310. necessary to get the state of the machine back to where it was at the
  1311. beginning of the procedure. The instruction \key{addq \$16, \%rsp}
  1312. moves the stack pointer back to point at the old base pointer. The
  1313. amount added here needs to match the amount that was subtracted in the
  1314. prelude of the procedure. Then \key{popq \%rbp} returns the old base
  1315. pointer to \key{rbp} and adds $8$ to the stack pointer. The last
  1316. instruction, \key{retq}, jumps back to the procedure that called this
  1317. one and adds 8 to the stack pointer, which returns the stack pointer
  1318. to where it was prior to the procedure call.
  1319. The compiler needs a convenient representation for manipulating x86
  1320. programs, so we define an abstract syntax for x86 in
  1321. Figure~\ref{fig:x86-0-ast}. We refer to this language as $x86_0$ with
  1322. a subscript $0$ because later we introduce extended versions of this
  1323. assembly language. The main difference compared to the concrete syntax
  1324. of x86 (Figure~\ref{fig:x86-0-concrete}) is that it does not allow labeled
  1325. instructions to appear anywhere, but instead organizes instructions
  1326. into groups called \emph{blocks} and associates a label with every
  1327. block, which is why the \key{CFG} struct (for control-flow graph)
  1328. includes an alist mapping labels to blocks. The reason for this
  1329. organization becomes apparent in Chapter~\ref{ch:bool-types} when we
  1330. introduce conditional branching. The \code{Block} structure includes
  1331. an $\itm{info}$ field that is not needed for this chapter, but will
  1332. become useful in Chapter~\ref{ch:register-allocation-r1}. For now,
  1333. the $\itm{info}$ field should just contain an empty list.
  1334. \begin{figure}[tp]
  1335. \fbox{
  1336. \begin{minipage}{0.96\textwidth}
  1337. \small
  1338. \[
  1339. \begin{array}{lcl}
  1340. \Reg &::=& \allregisters{} \\
  1341. \Arg &::=& \IMM{\Int} \mid \REG{\code{'}\Reg}
  1342. \mid \DEREF{\Reg}{\Int} \\
  1343. \Instr &::=& \BININSTR{\code{'addq}}{\Arg}{\Arg}
  1344. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} \\
  1345. &\mid& \BININSTR{\code{'movq}}{\Arg}{\Arg}
  1346. \mid \UNIINSTR{\code{'negq}}{\Arg}\\
  1347. &\mid& \CALLQ{\itm{label}} \mid \RETQ{}
  1348. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  1349. \Block &::= & \BLOCK{\itm{info}}{\Instr^{+}} \\
  1350. x86_0 &::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}^{+}}}
  1351. \end{array}
  1352. \]
  1353. \end{minipage}
  1354. }
  1355. \caption{The abstract syntax of $x86_0$ assembly.}
  1356. \label{fig:x86-0-ast}
  1357. \end{figure}
  1358. \section{Planning the trip to x86 via the $C_0$ language}
  1359. \label{sec:plan-s0-x86}
  1360. To compile one language to another it helps to focus on the
  1361. differences between the two languages because the compiler will need
  1362. to bridge those differences. What are the differences between $R_1$
  1363. and x86 assembly? Here are some of the most important ones:
  1364. \begin{enumerate}
  1365. \item[(a)] x86 arithmetic instructions typically have two arguments
  1366. and update the second argument in place. In contrast, $R_1$
  1367. arithmetic operations take two arguments and produce a new value.
  1368. An x86 instruction may have at most one memory-accessing argument.
  1369. Furthermore, some instructions place special restrictions on their
  1370. arguments.
  1371. \item[(b)] An argument of an $R_1$ operator can be any expression,
  1372. whereas x86 instructions restrict their arguments to be integers
  1373. constants, registers, and memory locations.
  1374. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1375. sequence of instructions and jumps to labeled positions, whereas in
  1376. $R_1$ the order of evaluation is a left-to-right depth-first
  1377. traversal of the abstract syntax tree.
  1378. \item[(d)] An $R_1$ program can have any number of variables whereas
  1379. x86 has 16 registers and the procedure calls stack.
  1380. \item[(e)] Variables in $R_1$ can overshadow other variables with the
  1381. same name. The registers and memory locations of x86 all have unique
  1382. names or addresses.
  1383. \end{enumerate}
  1384. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1385. the problem into several steps, dealing with the above differences one
  1386. at a time. Each of these steps is called a \emph{pass} of the
  1387. compiler.
  1388. %
  1389. This terminology comes from each step traverses (i.e. passes over) the
  1390. AST of the program.
  1391. %
  1392. We begin by sketching how we might implement each pass, and give them
  1393. names. We then figure out an ordering of the passes and the
  1394. input/output language for each pass. The very first pass has $R_1$ as
  1395. its input language and the last pass has x86 as its output
  1396. language. In between we can choose whichever language is most
  1397. convenient for expressing the output of each pass, whether that be
  1398. $R_1$, x86, or new \emph{intermediate languages} of our own design.
  1399. Finally, to implement each pass we write one recursive function per
  1400. non-terminal in the grammar of the input language of the pass.
  1401. \begin{description}
  1402. \item[Pass \key{select-instructions}] To handle the difference between
  1403. $R_1$ operations and x86 instructions we convert each $R_1$
  1404. operation to a short sequence of instructions that accomplishes the
  1405. same task.
  1406. \item[Pass \key{remove-complex-opera*}] To ensure that each
  1407. subexpression (i.e. operator and operand, and hence the name
  1408. \key{opera*}) is an \emph{atomic} expression (a variable or
  1409. integer), we introduce temporary variables to hold the results
  1410. of subexpressions.
  1411. \item[Pass \key{explicate-control}] To make the execution order of the
  1412. program explicit, we convert from the abstract syntax tree
  1413. representation into a \emph{control-flow graph} in which each node
  1414. contains a sequence of statements and the edges between nodes say
  1415. where to go at the end of the sequence.
  1416. \item[Pass \key{assign-homes}] To handle the difference between the
  1417. variables in $R_1$ versus the registers and stack locations in x86,
  1418. we assignment of each variable to a register or stack location.
  1419. \item[Pass \key{uniquify}] This pass deals with the shadowing of variables
  1420. by renaming every variable to a unique name, so that shadowing no
  1421. longer occurs.
  1422. \end{description}
  1423. The next question is: in what order should we apply these passes? This
  1424. question can be challenging because it is difficult to know ahead of
  1425. time which orders will be better (easier to implement, produce more
  1426. efficient code, etc.) so oftentimes trial-and-error is
  1427. involved. Nevertheless, we can try to plan ahead and make educated
  1428. choices regarding the ordering.
  1429. Let us consider the ordering of \key{uniquify} and
  1430. \key{remove-complex-opera*}. The assignment of subexpressions to
  1431. temporary variables involves introducing new variables and moving
  1432. subexpressions, which might change the shadowing of variables and
  1433. inadvertently change the behavior of the program. But if we apply
  1434. \key{uniquify} first, this will not be an issue. Of course, this means
  1435. that in \key{remove-complex-opera*}, we need to ensure that the
  1436. temporary variables that it creates are unique.
  1437. What should be the ordering of \key{explicate-control} with respect to
  1438. \key{uniquify}? The \key{uniquify} pass should come first because
  1439. \key{explicate-control} changes all the \key{let}-bound variables to
  1440. become local variables whose scope is the entire program, which would
  1441. confuse variables with the same name.
  1442. %
  1443. Likewise, we place \key{explicate-control} after
  1444. \key{remove-complex-opera*} because \key{explicate-control} removes
  1445. the \key{let} form, but it is convenient to use \key{let} in the
  1446. output of \key{remove-complex-opera*}.
  1447. %
  1448. Regarding \key{assign-homes}, it is helpful to place
  1449. \key{explicate-control} first because \key{explicate-control} changes
  1450. \key{let}-bound variables into program-scope variables. This means
  1451. that the \key{assign-homes} pass can read off the variables from the
  1452. $\itm{info}$ of the \key{Program} AST node instead of traversing the
  1453. entire program in search of \key{let}-bound variables.
  1454. Last, we need to decide on the ordering of \key{select-instructions}
  1455. and \key{assign-homes}. These two passes are intertwined, creating a
  1456. Gordian Knot. To do a good job of assigning homes, it is helpful to
  1457. have already determined which instructions will be used, because x86
  1458. instructions have restrictions about which of their arguments can be
  1459. registers versus stack locations. One might want to give preferential
  1460. treatment to variables that occur in register-argument positions. On
  1461. the other hand, it may turn out to be impossible to make sure that all
  1462. such variables are assigned to registers, and then one must redo the
  1463. selection of instructions. Some compilers handle this problem by
  1464. iteratively repeating these two passes until a good solution is found.
  1465. We shall use a simpler approach in which \key{select-instructions}
  1466. comes first, followed by the \key{assign-homes}, then a third
  1467. pass named \key{patch-instructions} that uses a reserved register to
  1468. patch-up outstanding problems regarding instructions with too many
  1469. memory accesses. The disadvantage of this approach is some programs
  1470. may not execute as efficiently as they would if we used the iterative
  1471. approach and used all of the registers for variables.
  1472. \begin{figure}[tbp]
  1473. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1474. \node (R1) at (0,2) {\large $R_1$};
  1475. \node (R1-2) at (3,2) {\large $R_1$};
  1476. \node (R1-3) at (6,2) {\large $R_1^{\dagger}$};
  1477. %\node (C0-1) at (6,0) {\large $C_0$};
  1478. \node (C0-2) at (3,0) {\large $C_0$};
  1479. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_0$};
  1480. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_0$};
  1481. \node (x86-4) at (9,-2) {\large $\text{x86}_0$};
  1482. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}_0$};
  1483. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1484. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  1485. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-2);
  1486. %\path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  1487. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1488. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1489. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1490. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1491. \end{tikzpicture}
  1492. \caption{Overview of the passes for compiling $R_1$. }
  1493. \label{fig:R1-passes}
  1494. \end{figure}
  1495. Figure~\ref{fig:R1-passes} presents the ordering of the compiler
  1496. passes in the form of a graph. Each pass is an edge and the
  1497. input/output language of each pass is a node in the graph. The output
  1498. of \key{uniquify} and \key{remove-complex-opera*} are programs that
  1499. are still in the $R_1$ language, but the output of the pass
  1500. \key{explicate-control} is in a different language $C_0$ that is
  1501. designed to make the order of evaluation explicit in its syntax, which
  1502. we introduce in the next section. The \key{select-instruction} pass
  1503. translates from $C_0$ to a variant of x86. The \key{assign-homes} and
  1504. \key{patch-instructions} passes input and output variants of x86
  1505. assembly. The last pass in Figure~\ref{fig:R1-passes} is
  1506. \key{print-x86}, which converts from the abstract syntax of
  1507. $\text{x86}_0$ to the concrete syntax of x86.
  1508. In the next sections we discuss the $C_0$ language and the
  1509. $\text{x86}^{*}_0$ and $\text{x86}^{\dagger}_0$ dialects of x86. The
  1510. remainder of this chapter gives hints regarding the implementation of
  1511. each of the compiler passes in Figure~\ref{fig:R1-passes}.
  1512. \subsection{The $C_0$ Intermediate Language}
  1513. The output of \key{explicate-control} is similar to the $C$
  1514. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1515. categories for expressions and statements, so we name it $C_0$. The
  1516. concrete syntax for $C_0$ is defined in
  1517. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for $C_0$
  1518. is defined in Figure~\ref{fig:c0-syntax}.
  1519. %
  1520. The $C_0$ language supports the same operators as $R_1$ but the
  1521. arguments of operators are restricted to atomic expressions (variables
  1522. and integers), thanks to the \key{remove-complex-opera*} pass. Instead
  1523. of \key{Let} expressions, $C_0$ has assignment statements which can be
  1524. executed in sequence using the \key{Seq} form. A sequence of
  1525. statements always ends with \key{Return}, a guarantee that is baked
  1526. into the grammar rules for the \itm{tail} non-terminal. The naming of
  1527. this non-terminal comes from the term \emph{tail position}, which
  1528. refers to an expression that is the last one to execute within a
  1529. function. (A expression in tail position may contain subexpressions,
  1530. and those may or may not be in tail position depending on the kind of
  1531. expression.)
  1532. A $C_0$ program consists of a control-flow graph (represented as an
  1533. alist mapping labels to tails). This is more general than
  1534. necessary for the present chapter, as we do not yet need to introduce
  1535. \key{goto} for jumping to labels, but it saves us from having to
  1536. change the syntax of the program construct in
  1537. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1538. \key{start}, and the whole program is its tail.
  1539. %
  1540. The $\itm{info}$ field of the \key{Program} form, after the
  1541. \key{explicate-control} pass, contains a mapping from the symbol
  1542. \key{locals} to a list of variables, that is, a list of all the
  1543. variables used in the program. At the start of the program, these
  1544. variables are uninitialized; they become initialized on their first
  1545. assignment.
  1546. \begin{figure}[tbp]
  1547. \fbox{
  1548. \begin{minipage}{0.96\textwidth}
  1549. \[
  1550. \begin{array}{lcl}
  1551. \Atm &::=& \Int \mid \Var \\
  1552. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  1553. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  1554. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  1555. C_0 & ::= & (\itm{label}\key{:}~ \Tail)^{+}
  1556. \end{array}
  1557. \]
  1558. \end{minipage}
  1559. }
  1560. \caption{The concrete syntax of the $C_0$ intermediate language.}
  1561. \label{fig:c0-concrete-syntax}
  1562. \end{figure}
  1563. \begin{figure}[tbp]
  1564. \fbox{
  1565. \begin{minipage}{0.96\textwidth}
  1566. \[
  1567. \begin{array}{lcl}
  1568. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1569. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1570. &\mid& \ADD{\Atm}{\Atm}\\
  1571. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  1572. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1573. C_0 & ::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}^{+}}}
  1574. \end{array}
  1575. \]
  1576. \end{minipage}
  1577. }
  1578. \caption{The abstract syntax of the $C_0$ intermediate language.}
  1579. \label{fig:c0-syntax}
  1580. \end{figure}
  1581. %% The \key{select-instructions} pass is optimistic in the sense that it
  1582. %% treats variables as if they were all mapped to registers. The
  1583. %% \key{select-instructions} pass generates a program that consists of
  1584. %% x86 instructions but that still uses variables, so it is an
  1585. %% intermediate language that is technically different than x86, which
  1586. %% explains the asterisks in the diagram above.
  1587. %% In this Chapter we shall take the easy road to implementing
  1588. %% \key{assign-homes} and simply map all variables to stack locations.
  1589. %% The topic of Chapter~\ref{ch:register-allocation-r1} is implementing a
  1590. %% smarter approach in which we make a best-effort to map variables to
  1591. %% registers, resorting to the stack only when necessary.
  1592. %% Once variables have been assigned to their homes, we can finalize the
  1593. %% instruction selection by dealing with an idiosyncrasy of x86
  1594. %% assembly. Many x86 instructions have two arguments but only one of the
  1595. %% arguments may be a memory reference (and the stack is a part of
  1596. %% memory). Because some variables may get mapped to stack locations,
  1597. %% some of our generated instructions may violate this restriction. The
  1598. %% purpose of the \key{patch-instructions} pass is to fix this problem by
  1599. %% replacing every violating instruction with a short sequence of
  1600. %% instructions that use the \key{rax} register. Once we have implemented
  1601. %% a good register allocator (Chapter~\ref{ch:register-allocation-r1}), the
  1602. %% need to patch instructions will be relatively rare.
  1603. \subsection{The dialects of x86}
  1604. The x86$^{*}_0$ language, pronounced ``pseudo x86'', is the output of
  1605. the pass \key{select-instructions}. It extends $x86_0$ with an
  1606. unbounded number of program-scope variables and has looser rules
  1607. regarding instruction arguments. The x86$^{\dagger}$ language, the
  1608. output of \key{print-x86}, is the concrete syntax for x86.
  1609. \section{Uniquify Variables}
  1610. \label{sec:uniquify-s0}
  1611. The \code{uniquify} pass compiles arbitrary $R_1$ programs into $R_1$
  1612. programs in which every \key{let} uses a unique variable name. For
  1613. example, the \code{uniquify} pass should translate the program on the
  1614. left into the program on the right. \\
  1615. \begin{tabular}{lll}
  1616. \begin{minipage}{0.4\textwidth}
  1617. \begin{lstlisting}
  1618. (let ([x 32])
  1619. (+ (let ([x 10]) x) x))
  1620. \end{lstlisting}
  1621. \end{minipage}
  1622. &
  1623. $\Rightarrow$
  1624. &
  1625. \begin{minipage}{0.4\textwidth}
  1626. \begin{lstlisting}
  1627. (let ([x.1 32])
  1628. (+ (let ([x.2 10]) x.2) x.1))
  1629. \end{lstlisting}
  1630. \end{minipage}
  1631. \end{tabular} \\
  1632. %
  1633. The following is another example translation, this time of a program
  1634. with a \key{let} nested inside the initializing expression of another
  1635. \key{let}.\\
  1636. \begin{tabular}{lll}
  1637. \begin{minipage}{0.4\textwidth}
  1638. \begin{lstlisting}
  1639. (let ([x (let ([x 4])
  1640. (+ x 1))])
  1641. (+ x 2))
  1642. \end{lstlisting}
  1643. \end{minipage}
  1644. &
  1645. $\Rightarrow$
  1646. &
  1647. \begin{minipage}{0.4\textwidth}
  1648. \begin{lstlisting}
  1649. (let ([x.2 (let ([x.1 4])
  1650. (+ x.1 1))])
  1651. (+ x.2 2))
  1652. \end{lstlisting}
  1653. \end{minipage}
  1654. \end{tabular}
  1655. We recommend implementing \code{uniquify} by creating a function named
  1656. \code{uniquify-exp} that is structurally recursive function and mostly
  1657. just copies the input program. However, when encountering a \key{let},
  1658. it should generate a unique name for the variable (the Racket function
  1659. \code{gensym} is handy for this) and associate the old name with the
  1660. new unique name in an alist. The \code{uniquify-exp}
  1661. function will need to access this alist when it gets to a
  1662. variable reference, so we add another parameter to \code{uniquify-exp}
  1663. for the alist.
  1664. The skeleton of the \code{uniquify-exp} function is shown in
  1665. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1666. convenient to partially apply it to a symbol table and then apply it
  1667. to different expressions, as in the last clause for primitive
  1668. operations in Figure~\ref{fig:uniquify-s0}. The \key{for/list} form
  1669. is useful for applying a function to each element of a list to produce
  1670. a new list.
  1671. \begin{exercise}
  1672. \normalfont % I don't like the italics for exercises. -Jeremy
  1673. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1674. implement the clauses for variables and for the \key{let} form.
  1675. \end{exercise}
  1676. \begin{figure}[tbp]
  1677. \begin{lstlisting}
  1678. (define (uniquify-exp symtab)
  1679. (lambda (e)
  1680. (match e
  1681. [(Var x) ___]
  1682. [(Int n) (Int n)]
  1683. [(Let x e body) ___]
  1684. [(Prim op es)
  1685. (Prim op (for/list ([e es]) ((uniquify-exp symtab) e)))]
  1686. )))
  1687. (define (uniquify p)
  1688. (match p
  1689. [(Program info e)
  1690. (Program info ((uniquify-exp '()) e))]
  1691. )))
  1692. \end{lstlisting}
  1693. \caption{Skeleton for the \key{uniquify} pass.}
  1694. \label{fig:uniquify-s0}
  1695. \end{figure}
  1696. \begin{exercise}
  1697. \normalfont % I don't like the italics for exercises. -Jeremy
  1698. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1699. and checking whether the output programs produce the same result as
  1700. the input programs. The $R_1$ programs should be designed to test the
  1701. most interesting parts of the \key{uniquify} pass, that is, the
  1702. programs should include \key{let} forms, variables, and variables
  1703. that overshadow each other. The five programs should be in a
  1704. subdirectory named \key{tests} and they should have the same file name
  1705. except for a different integer at the end of the name, followed by the
  1706. ending \key{.rkt}. Use the \key{interp-tests} function
  1707. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1708. your \key{uniquify} pass on the example programs. See the
  1709. \key{run-tests.rkt} script in the student support code for an example
  1710. of how to use \key{interp-tests}.
  1711. \end{exercise}
  1712. \section{Remove Complex Operands}
  1713. \label{sec:remove-complex-opera-r1}
  1714. The \code{remove-complex-opera*} pass compiles $R_1$ programs into
  1715. $R_1$ programs in which the arguments of operations are atomic
  1716. expressions. Put another way, this pass removes complex operands,
  1717. such as the expression \code{(- 10)} in the program below. This is
  1718. accomplished by introducing a new \key{let}-bound variable, binding
  1719. the complex operand to the new variable, and then using the new
  1720. variable in place of the complex operand, as shown in the output of
  1721. \code{remove-complex-opera*} on the right.\\
  1722. \begin{tabular}{lll}
  1723. \begin{minipage}{0.4\textwidth}
  1724. % s0_19.rkt
  1725. \begin{lstlisting}
  1726. (+ 52 (- 10))
  1727. \end{lstlisting}
  1728. \end{minipage}
  1729. &
  1730. $\Rightarrow$
  1731. &
  1732. \begin{minipage}{0.4\textwidth}
  1733. \begin{lstlisting}
  1734. (let ([tmp.1 (- 10)])
  1735. (+ 52 tmp.1))
  1736. \end{lstlisting}
  1737. \end{minipage}
  1738. \end{tabular}
  1739. \begin{figure}[tp]
  1740. \centering
  1741. \fbox{
  1742. \begin{minipage}{0.96\textwidth}
  1743. \[
  1744. \begin{array}{rcl}
  1745. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1746. \Exp &::=& \Atm \mid \READ{} \\
  1747. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  1748. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  1749. R_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1750. \end{array}
  1751. \]
  1752. \end{minipage}
  1753. }
  1754. \caption{$R_1^{\dagger}$ is $R_1$ in administrative normal form (ANF).}
  1755. \label{fig:r1-anf-syntax}
  1756. \end{figure}
  1757. Figure~\ref{fig:r1-anf-syntax} presents the grammar for the output of
  1758. this pass, language $R_1^{\dagger}$. The main difference is that
  1759. operator arguments are required to be atomic expressions. In the
  1760. literature this is called \emph{administrative normal form}, or ANF
  1761. for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  1762. We recommend implementing this pass with two mutually recursive
  1763. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1764. \code{rco-atom} to subexpressions that are required to be atomic and
  1765. to apply \code{rco-exp} to subexpressions that can be atomic or
  1766. complex (see Figure~\ref{fig:r1-anf-syntax}). Both functions take an
  1767. $R_1$ expression as input. The \code{rco-exp} function returns an
  1768. expression. The \code{rco-atom} function returns two things: an
  1769. atomic expression and alist mapping temporary variables to complex
  1770. subexpressions. You can return multiple things from a function using
  1771. Racket's \key{values} form and you can receive multiple things from a
  1772. function call using the \key{define-values} form. If you are not
  1773. familiar with these features, review the Racket documentation. Also,
  1774. the \key{for/lists} form is useful for applying a function to each
  1775. element of a list, in the case where the function returns multiple
  1776. values.
  1777. The following shows the output of \code{rco-atom} on the expression
  1778. \code{(- 10)} (using concrete syntax to be concise).
  1779. \begin{tabular}{lll}
  1780. \begin{minipage}{0.4\textwidth}
  1781. \begin{lstlisting}
  1782. (- 10)
  1783. \end{lstlisting}
  1784. \end{minipage}
  1785. &
  1786. $\Rightarrow$
  1787. &
  1788. \begin{minipage}{0.4\textwidth}
  1789. \begin{lstlisting}
  1790. tmp.1
  1791. ((tmp.1 . (- 10)))
  1792. \end{lstlisting}
  1793. \end{minipage}
  1794. \end{tabular}
  1795. Take special care of programs such as the next one that \key{let}-bind
  1796. variables with integers or other variables. You should leave them
  1797. unchanged, as shown in to the program on the right \\
  1798. \begin{tabular}{lll}
  1799. \begin{minipage}{0.4\textwidth}
  1800. % s0_20.rkt
  1801. \begin{lstlisting}
  1802. (let ([a 42])
  1803. (let ([b a])
  1804. b))
  1805. \end{lstlisting}
  1806. \end{minipage}
  1807. &
  1808. $\Rightarrow$
  1809. &
  1810. \begin{minipage}{0.4\textwidth}
  1811. \begin{lstlisting}
  1812. (let ([a 42])
  1813. (let ([b a])
  1814. b))
  1815. \end{lstlisting}
  1816. \end{minipage}
  1817. \end{tabular} \\
  1818. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  1819. produce the following output.\\
  1820. \begin{minipage}{0.4\textwidth}
  1821. \begin{lstlisting}
  1822. (let ([tmp.1 42])
  1823. (let ([a tmp.1])
  1824. (let ([tmp.2 a])
  1825. (let ([b tmp.2])
  1826. b))))
  1827. \end{lstlisting}
  1828. \end{minipage}
  1829. \begin{exercise}
  1830. \normalfont Implement the \code{remove-complex-opera*} pass and test
  1831. it on all of the example programs that you created to test the
  1832. \key{uniquify} pass and create three new example programs that are
  1833. designed to exercise the interesting code in the
  1834. \code{remove-complex-opera*} pass. Use the \key{interp-tests} function
  1835. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1836. your passes on the example programs.
  1837. \end{exercise}
  1838. \section{Explicate Control}
  1839. \label{sec:explicate-control-r1}
  1840. The \code{explicate-control} pass compiles $R_1$ programs into $C_0$
  1841. programs that make the order of execution explicit in their
  1842. syntax. For now this amounts to flattening \key{let} constructs into a
  1843. sequence of assignment statements. For example, consider the following
  1844. $R_1$ program.\\
  1845. % s0_11.rkt
  1846. \begin{minipage}{0.96\textwidth}
  1847. \begin{lstlisting}
  1848. (let ([y (let ([x 20])
  1849. (+ x (let ([x 22]) x)))])
  1850. y)
  1851. \end{lstlisting}
  1852. \end{minipage}\\
  1853. %
  1854. The output of the previous pass and of \code{explicate-control} is
  1855. shown below. Recall that the right-hand-side of a \key{let} executes
  1856. before its body, so the order of evaluation for this program is to
  1857. assign \code{20} to \code{x.1}, assign \code{22} to \code{x.2}, assign
  1858. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  1859. output of \code{explicate-control} makes this ordering explicit.\\
  1860. \begin{tabular}{lll}
  1861. \begin{minipage}{0.4\textwidth}
  1862. \begin{lstlisting}
  1863. (let ([y (let ([x.1 20])
  1864. (let ([x.2 22])
  1865. (+ x.1 x.2)))])
  1866. y)
  1867. \end{lstlisting}
  1868. \end{minipage}
  1869. &
  1870. $\Rightarrow$
  1871. &
  1872. \begin{minipage}{0.4\textwidth}
  1873. \begin{lstlisting}
  1874. locals: y x.1 x.2
  1875. start:
  1876. x.1 = 20;
  1877. x.2 = 22;
  1878. y = (+ x.1 x.2);
  1879. return y;
  1880. \end{lstlisting}
  1881. \end{minipage}
  1882. \end{tabular}
  1883. We recommend implementing \code{explicate-control} using two mutually
  1884. recursive functions: \code{explicate-tail} and
  1885. \code{explicate-assign}. The first function should be applied to
  1886. expressions in tail position whereas the second should be applied to
  1887. expressions that occur on the right-hand-side of a \key{let}. The
  1888. \code{explicate-tail} function takes an $R_1$ expression as input and
  1889. produces a $C_0$ $\Tail$ (see Figure~\ref{fig:c0-syntax}) and a list
  1890. of formerly \key{let}-bound variables. The \code{explicate-assign}
  1891. function takes an $R_1$ expression, the variable that it is to be
  1892. assigned to, and $C_0$ code (a $\Tail$) that should come after the
  1893. assignment (e.g., the code generated for the body of the \key{let}).
  1894. It returns a $\Tail$ and a list of variables. The top-level
  1895. \code{explicate-control} function should invoke \code{explicate-tail}
  1896. on the body of the \key{program} and then associate the \code{locals}
  1897. symbol with the resulting list of variables in the $\itm{info}$ field,
  1898. as in the above example.
  1899. \section{Select Instructions}
  1900. \label{sec:select-r1}
  1901. In the \code{select-instructions} pass we begin the work of
  1902. translating from $C_0$ to $\text{x86}^{*}_0$. The target language of
  1903. this pass is a variant of x86 that still uses variables, so we add an
  1904. AST node of the form $\VAR{\itm{var}}$ to the $\text{x86}_0$ abstract
  1905. syntax of Figure~\ref{fig:x86-0-ast}. We recommend implementing the
  1906. \code{select-instructions} in terms of three auxiliary functions, one
  1907. for each of the non-terminals of $C_0$: $\Atm$, $\Stmt$, and $\Tail$.
  1908. The cases for $\Atm$ are straightforward, variables stay
  1909. the same and integer constants are changed to immediates:
  1910. $\INT{n}$ changes to $\IMM{n}$.
  1911. Next we consider the cases for $\Stmt$, starting with arithmetic
  1912. operations. For example, in $C_0$ an addition operation can take the
  1913. form below, to the left of the $\Rightarrow$. To translate to x86, we
  1914. need to use the \key{addq} instruction which does an in-place
  1915. update. So we must first move \code{10} to \code{x}. \\
  1916. \begin{tabular}{lll}
  1917. \begin{minipage}{0.4\textwidth}
  1918. \begin{lstlisting}
  1919. x = (+ 10 32);
  1920. \end{lstlisting}
  1921. \end{minipage}
  1922. &
  1923. $\Rightarrow$
  1924. &
  1925. \begin{minipage}{0.4\textwidth}
  1926. \begin{lstlisting}
  1927. movq $10, x
  1928. addq $32, x
  1929. \end{lstlisting}
  1930. \end{minipage}
  1931. \end{tabular} \\
  1932. %
  1933. There are cases that require special care to avoid generating
  1934. needlessly complicated code. If one of the arguments of the addition
  1935. is the same as the left-hand side of the assignment, then there is no
  1936. need for the extra move instruction. For example, the following
  1937. assignment statement can be translated into a single \key{addq}
  1938. instruction.\\
  1939. \begin{tabular}{lll}
  1940. \begin{minipage}{0.4\textwidth}
  1941. \begin{lstlisting}
  1942. x = (+ 10 x);
  1943. \end{lstlisting}
  1944. \end{minipage}
  1945. &
  1946. $\Rightarrow$
  1947. &
  1948. \begin{minipage}{0.4\textwidth}
  1949. \begin{lstlisting}
  1950. addq $10, x
  1951. \end{lstlisting}
  1952. \end{minipage}
  1953. \end{tabular} \\
  1954. The \key{read} operation does not have a direct counterpart in x86
  1955. assembly, so we have instead implemented this functionality in the C
  1956. language, with the function \code{read\_int} in the file
  1957. \code{runtime.c}. In general, we refer to all of the functionality in
  1958. this file as the \emph{runtime system}, or simply the \emph{runtime}
  1959. for short. When compiling your generated x86 assembly code, you need
  1960. to compile \code{runtime.c} to \code{runtime.o} (an ``object file'',
  1961. using \code{gcc} option \code{-c}) and link it into the
  1962. executable. For our purposes of code generation, all you need to do is
  1963. translate an assignment of \key{read} into some variable $\itm{lhs}$
  1964. (for left-hand side) into a call to the \code{read\_int} function
  1965. followed by a move from \code{rax} to the left-hand side. The move
  1966. from \code{rax} is needed because the return value from
  1967. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  1968. \begin{tabular}{lll}
  1969. \begin{minipage}{0.3\textwidth}
  1970. \begin{lstlisting}
  1971. |$\itm{var}$| = (read);
  1972. \end{lstlisting}
  1973. \end{minipage}
  1974. &
  1975. $\Rightarrow$
  1976. &
  1977. \begin{minipage}{0.3\textwidth}
  1978. \begin{lstlisting}
  1979. callq read_int
  1980. movq %rax, |$\itm{var}$|
  1981. \end{lstlisting}
  1982. \end{minipage}
  1983. \end{tabular} \\
  1984. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  1985. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  1986. assignment to the \key{rax} register followed by a jump to the
  1987. conclusion of the program (so the conclusion needs to be labeled).
  1988. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  1989. recursively and append the resulting instructions.
  1990. \begin{exercise}
  1991. \normalfont
  1992. Implement the \key{select-instructions} pass and test it on all of the
  1993. example programs that you created for the previous passes and create
  1994. three new example programs that are designed to exercise all of the
  1995. interesting code in this pass. Use the \key{interp-tests} function
  1996. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1997. your passes on the example programs.
  1998. \end{exercise}
  1999. \section{Assign Homes}
  2000. \label{sec:assign-r1}
  2001. The \key{assign-homes} pass compiles $\text{x86}^{*}_0$ programs to
  2002. $\text{x86}^{*}_0$ programs that no longer use program variables.
  2003. Thus, the \key{assign-homes} pass is responsible for placing all of
  2004. the program variables in registers or on the stack. For runtime
  2005. efficiency, it is better to place variables in registers, but as there
  2006. are only 16 registers, some programs must necessarily resort to
  2007. placing some variables on the stack. In this chapter we focus on the
  2008. mechanics of placing variables on the stack. We study an algorithm for
  2009. placing variables in registers in
  2010. Chapter~\ref{ch:register-allocation-r1}.
  2011. Consider again the following $R_1$ program.
  2012. % s0_20.rkt
  2013. \begin{lstlisting}
  2014. (let ([a 42])
  2015. (let ([b a])
  2016. b))
  2017. \end{lstlisting}
  2018. For reference, we repeat the output of \code{select-instructions} on
  2019. the left and show the output of \code{assign-homes} on the right.
  2020. Recall that \key{explicate-control} associated the list of
  2021. variables with the \code{locals} symbol in the program's $\itm{info}$
  2022. field, so \code{assign-homes} has convenient access to the them. In
  2023. this example, we assign variable \code{a} to stack location
  2024. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.\\
  2025. \begin{tabular}{l}
  2026. \begin{minipage}{0.4\textwidth}
  2027. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2028. locals: a b
  2029. start:
  2030. movq $42, a
  2031. movq a, b
  2032. movq b, %rax
  2033. jmp conclusion
  2034. \end{lstlisting}
  2035. \end{minipage}
  2036. {$\Rightarrow$}
  2037. \begin{minipage}{0.4\textwidth}
  2038. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2039. stack-space: 16
  2040. start:
  2041. movq $42, -8(%rbp)
  2042. movq -8(%rbp), -16(%rbp)
  2043. movq -16(%rbp), %rax
  2044. jmp conclusion
  2045. \end{lstlisting}
  2046. \end{minipage}
  2047. \end{tabular} \\
  2048. In the process of assigning variables to stack locations, it is
  2049. convenient to compute and store the size of the frame (in bytes) in
  2050. the $\itm{info}$ field of the \key{Program} node, with the key
  2051. \code{stack-space}, which will be needed later to generate the
  2052. procedure conclusion. Some operating systems place restrictions on
  2053. the frame size. For example, Mac OS X requires the frame size to be a
  2054. multiple of 16 bytes.
  2055. \begin{exercise}
  2056. \normalfont Implement the \key{assign-homes} pass and test it on all
  2057. of the example programs that you created for the previous passes pass.
  2058. We recommend that \key{assign-homes} take an extra parameter that is a
  2059. mapping of variable names to homes (stack locations for now). Use the
  2060. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  2061. \key{utilities.rkt} to test your passes on the example programs.
  2062. \end{exercise}
  2063. \section{Patch Instructions}
  2064. \label{sec:patch-s0}
  2065. The \code{patch-instructions} pass compiles $\text{x86}^{*}_0$
  2066. programs to $\text{x86}_0$ programs by making sure that each
  2067. instruction adheres to the restrictions of the x86 assembly language.
  2068. In particular, at most one argument of an instruction may be a memory
  2069. reference.
  2070. We return to the following running example.
  2071. % s0_20.rkt
  2072. \begin{lstlisting}
  2073. (let ([a 42])
  2074. (let ([b a])
  2075. b))
  2076. \end{lstlisting}
  2077. After the \key{assign-homes} pass, the above program has been translated to
  2078. the following. \\
  2079. \begin{minipage}{0.5\textwidth}
  2080. \begin{lstlisting}
  2081. stack-space: 16
  2082. start:
  2083. movq $42, -8(%rbp)
  2084. movq -8(%rbp), -16(%rbp)
  2085. movq -16(%rbp), %rax
  2086. jmp conclusion
  2087. \end{lstlisting}
  2088. \end{minipage}\\
  2089. The second \key{movq} instruction is problematic because both
  2090. arguments are stack locations. We suggest fixing this problem by
  2091. moving from the source location to the register \key{rax} and then
  2092. from \key{rax} to the destination location, as follows.
  2093. \begin{lstlisting}
  2094. movq -8(%rbp), %rax
  2095. movq %rax, -16(%rbp)
  2096. \end{lstlisting}
  2097. \begin{exercise}
  2098. \normalfont
  2099. Implement the \key{patch-instructions} pass and test it on all of the
  2100. example programs that you created for the previous passes and create
  2101. three new example programs that are designed to exercise all of the
  2102. interesting code in this pass. Use the \key{interp-tests} function
  2103. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2104. your passes on the example programs.
  2105. \end{exercise}
  2106. \section{Print x86}
  2107. \label{sec:print-x86}
  2108. The last step of the compiler from $R_1$ to x86 is to convert the
  2109. $\text{x86}_0$ AST (defined in Figure~\ref{fig:x86-0-ast}) to the
  2110. string representation (defined in Figure~\ref{fig:x86-0-concrete}). The Racket
  2111. \key{format} and \key{string-append} functions are useful in this
  2112. regard. The main work that this step needs to perform is to create the
  2113. \key{main} function and the standard instructions for its prelude and
  2114. conclusion, as shown in Figure~\ref{fig:p1-x86} of
  2115. Section~\ref{sec:x86}. You need to know the number of stack-allocated
  2116. variables, so we suggest computing it in the \key{assign-homes} pass
  2117. (Section~\ref{sec:assign-r1}) and storing it in the $\itm{info}$ field
  2118. of the \key{program} node.
  2119. %% Your compiled code should print the result of the program's execution
  2120. %% by using the \code{print\_int} function provided in
  2121. %% \code{runtime.c}. If your compiler has been implemented correctly so
  2122. %% far, this final result should be stored in the \key{rax} register.
  2123. %% We'll talk more about how to perform function calls with arguments in
  2124. %% general later on, but for now, place the following after the compiled
  2125. %% code for the $R_1$ program but before the conclusion:
  2126. %% \begin{lstlisting}
  2127. %% movq %rax, %rdi
  2128. %% callq print_int
  2129. %% \end{lstlisting}
  2130. %% These lines move the value in \key{rax} into the \key{rdi} register, which
  2131. %% stores the first argument to be passed into \key{print\_int}.
  2132. If you want your program to run on Mac OS X, your code needs to
  2133. determine whether or not it is running on a Mac, and prefix
  2134. underscores to labels like \key{main}. You can determine the platform
  2135. with the Racket call \code{(system-type 'os)}, which returns
  2136. \code{'macosx}, \code{'unix}, or \code{'windows}.
  2137. %% In addition to
  2138. %% placing underscores on \key{main}, you need to put them in front of
  2139. %% \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  2140. %% \_print\_int}).
  2141. \begin{exercise}
  2142. \normalfont Implement the \key{print-x86} pass and test it on all of
  2143. the example programs that you created for the previous passes. Use the
  2144. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  2145. \key{utilities.rkt} to test your complete compiler on the example
  2146. programs. See the \key{run-tests.rkt} script in the student support
  2147. code for an example of how to use \key{compiler-tests}. Also, remember
  2148. to compile the provided \key{runtime.c} file to \key{runtime.o} using
  2149. \key{gcc}.
  2150. \end{exercise}
  2151. \section{Challenge: Partial Evaluator for $R_1$}
  2152. \label{sec:pe-R1}
  2153. This section describes optional challenge exercises that involve
  2154. adapting and improving the partial evaluator for $R_0$ that was
  2155. introduced in Section~\ref{sec:partial-evaluation}.
  2156. \begin{exercise}\label{ex:pe-R1}
  2157. \normalfont
  2158. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2159. (Figure~\ref{fig:pe-arith}) so that it applies to $R_1$ programs
  2160. instead of $R_0$ programs. Recall that $R_1$ adds \key{let} binding
  2161. and variables to the $R_0$ language, so you will need to add cases for
  2162. them in the \code{pe-exp} function. Also, note that the \key{program}
  2163. form changes slightly to include an $\itm{info}$ field. Once
  2164. complete, add the partial evaluation pass to the front of your
  2165. compiler and make sure that your compiler still passes all of the
  2166. tests.
  2167. \end{exercise}
  2168. The next exercise builds on Exercise~\ref{ex:pe-R1}.
  2169. \begin{exercise}
  2170. \normalfont
  2171. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2172. \code{pe-add} auxiliary functions with functions that know more about
  2173. arithmetic. For example, your partial evaluator should translate
  2174. \begin{lstlisting}
  2175. (+ 1 (+ (read) 1))
  2176. \end{lstlisting}
  2177. into
  2178. \begin{lstlisting}
  2179. (+ 2 (read))
  2180. \end{lstlisting}
  2181. To accomplish this, the \code{pe-exp} function should produce output
  2182. in the form of the $\itm{residual}$ non-terminal of the following
  2183. grammar.
  2184. \[
  2185. \begin{array}{lcl}
  2186. \itm{inert} &::=& \Var \mid (\key{read}) \mid (\key{-} \;(\key{read}))
  2187. \mid (\key{+} \; \itm{inert} \; \itm{inert})\\
  2188. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \itm{inert}) \mid \itm{inert}
  2189. \end{array}
  2190. \]
  2191. The \code{pe-add} and \code{pe-neg} functions may therefore assume
  2192. that their inputs are $\itm{residual}$ expressions and they should
  2193. return $\itm{residual}$ expressions. Once the improvements are
  2194. complete, make sure that your compiler still passes all of the tests.
  2195. After all, fast code is useless if it produces incorrect results!
  2196. \end{exercise}
  2197. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2198. \chapter{Register Allocation}
  2199. \label{ch:register-allocation-r1}
  2200. In Chapter~\ref{ch:int-exp} we placed all variables on the stack to
  2201. make our life easier. However, we can improve the performance of the
  2202. generated code if we instead place some variables into registers. The
  2203. CPU can access a register in a single cycle, whereas accessing the
  2204. stack takes many cycles if the relevant data is in cache or many more
  2205. to access main memory if the data is not in cache.
  2206. Figure~\ref{fig:reg-eg} shows a program with four variables that
  2207. serves as a running example. We show the source program and also the
  2208. output of instruction selection. At that point the program is almost
  2209. x86 assembly but not quite; it still contains variables instead of
  2210. stack locations or registers.
  2211. \begin{figure}
  2212. \begin{minipage}{0.45\textwidth}
  2213. Example $R_1$ program:
  2214. % s0_28.rkt
  2215. \begin{lstlisting}
  2216. (let ([v 1])
  2217. (let ([w 42])
  2218. (let ([x (+ v 7)])
  2219. (let ([y x])
  2220. (let ([z (+ x w)])
  2221. (+ z (- y)))))))
  2222. \end{lstlisting}
  2223. \end{minipage}
  2224. \begin{minipage}{0.45\textwidth}
  2225. After instruction selection:
  2226. \begin{lstlisting}
  2227. locals: (v w x y z t)
  2228. start:
  2229. movq $1, v
  2230. movq $42, w
  2231. movq v, x
  2232. addq $7, x
  2233. movq x, y
  2234. movq x, z
  2235. addq w, z
  2236. movq y, t
  2237. negq t
  2238. movq z, %rax
  2239. addq t, %rax
  2240. jmp conclusion
  2241. \end{lstlisting}
  2242. \end{minipage}
  2243. \caption{An example program for register allocation.}
  2244. \label{fig:reg-eg}
  2245. \end{figure}
  2246. The goal of register allocation is to fit as many variables into
  2247. registers as possible. A program sometimes has more variables than
  2248. registers, so we cannot map each variable to a different
  2249. register. Fortunately, it is common for different variables to be
  2250. needed during different periods of time during program execution, and
  2251. in such cases several variables can be mapped to the same register.
  2252. Consider variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}.
  2253. After the variable \code{x} is moved to \code{z} it is no longer
  2254. needed. Variable \code{y}, on the other hand, is used only after this
  2255. point, so \code{x} and \code{y} could share the same register. The
  2256. topic of Section~\ref{sec:liveness-analysis-r1} is how to compute
  2257. where a variable is needed. Once we have that information, we compute
  2258. which variables are needed at the same time, i.e., which ones
  2259. \emph{interfere}, and represent this relation as an undirected graph
  2260. whose vertices are variables and edges indicate when two variables
  2261. interfere with each other (Section~\ref{sec:build-interference}). We
  2262. then model register allocation as a graph coloring problem, which we
  2263. discuss in Section~\ref{sec:graph-coloring}.
  2264. In the event that we run out of registers despite these efforts, we
  2265. place the remaining variables on the stack, similar to what we did in
  2266. Chapter~\ref{ch:int-exp}. It is common to use the verb \emph{spill}
  2267. for assigning a variable to a stack location. The process of spilling
  2268. variables is handled as part of the graph coloring process described
  2269. in \ref{sec:graph-coloring}.
  2270. \section{Registers and Calling Conventions}
  2271. \label{sec:calling-conventions}
  2272. As we perform register allocation, we need to be aware of the
  2273. conventions that govern the way in which registers interact with
  2274. function calls, such as calls to the \code{read\_int} function. The
  2275. convention for x86 is that the caller is responsible for freeing up
  2276. some registers, the \emph{caller-saved registers}, prior to the
  2277. function call, and the callee is responsible for saving and restoring
  2278. some other registers, the \emph{callee-saved registers}, before and
  2279. after using them. The caller-saved registers are
  2280. \begin{lstlisting}
  2281. rax rdx rcx rsi rdi r8 r9 r10 r11
  2282. \end{lstlisting}
  2283. while the callee-saved registers are
  2284. \begin{lstlisting}
  2285. rsp rbp rbx r12 r13 r14 r15
  2286. \end{lstlisting}
  2287. Another way to think about this caller/callee convention is the
  2288. following. The caller should assume that all the caller-saved registers
  2289. get overwritten with arbitrary values by the callee. On the other
  2290. hand, the caller can safely assume that all the callee-saved registers
  2291. contain the same values after the call that they did before the call.
  2292. The callee can freely use any of the caller-saved registers. However,
  2293. if the callee wants to use a callee-saved register, the callee must
  2294. arrange to put the original value back in the register prior to
  2295. returning to the caller, which is usually accomplished by saving and
  2296. restoring the value from the stack.
  2297. \section{Liveness Analysis}
  2298. \label{sec:liveness-analysis-r1}
  2299. A variable is \emph{live} if the variable is used at some later point
  2300. in the program and there is not an intervening assignment to the
  2301. variable.
  2302. %
  2303. To understand the latter condition, consider the following code
  2304. fragment in which there are two writes to \code{b}. Are \code{a} and
  2305. \code{b} both live at the same time?
  2306. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2307. movq $5, a
  2308. movq $30, b
  2309. movq a, c
  2310. movq $10, b
  2311. addq b, c
  2312. \end{lstlisting}
  2313. The answer is no because the integer \code{30} written to \code{b} on
  2314. line 2 is never used. The variable \code{b} is read on line 5 and
  2315. there is an intervening write to \code{b} on line 4, so the read on
  2316. line 5 receives the value written on line 4, not line 2.
  2317. The live variables can be computed by traversing the instruction
  2318. sequence back to front (i.e., backwards in execution order). Let
  2319. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2320. $L_{\mathsf{after}}(k)$ for the set of live variables after
  2321. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2322. variables before instruction $I_k$. The live variables after an
  2323. instruction are always the same as the live variables before the next
  2324. instruction.
  2325. \begin{equation} \label{eq:live-after-before-next}
  2326. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2327. \end{equation}
  2328. To start things off, there are no live variables after the last
  2329. instruction, so
  2330. \begin{equation}\label{eq:live-last-empty}
  2331. L_{\mathsf{after}}(n) = \emptyset
  2332. \end{equation}
  2333. We then apply the following rule repeatedly, traversing the
  2334. instruction sequence back to front.
  2335. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2336. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2337. \end{equation}
  2338. where $W(k)$ are the variables written to by instruction $I_k$ and
  2339. $R(k)$ are the variables read by instruction $I_k$.
  2340. Let us walk through the above example, applying these formulas
  2341. starting with the instruction on line 5. We collect the answers in the
  2342. below listing. The $L_{\mathsf{after}}$ for the \code{addq b, c}
  2343. instruction is $\emptyset$ because it is the last instruction
  2344. (formula~\ref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  2345. this instruction is $\{b,c\}$ because it reads from variables $b$ and
  2346. $c$ (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that
  2347. is
  2348. \[
  2349. L_{\mathsf{before}}(5) = (\emptyset - \{c\}) \cup \{ b, c \} = \{ b, c \}
  2350. \]
  2351. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2352. the live-before set from line 5 to be the live-after set for this
  2353. instruction (formula~\ref{eq:live-after-before-next}).
  2354. \[
  2355. L_{\mathsf{after}}(4) = \{ b, c \}
  2356. \]
  2357. This move instruction writes to $b$ and does not read from any
  2358. variables, so we have the following live-before set
  2359. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2360. \[
  2361. L_{\mathsf{before}}(4) = (\{b,c\} - \{b\}) \cup \emptyset = \{ c \}
  2362. \]
  2363. Moving on more quickly, the live-before for instruction \code{movq a, c}
  2364. is $\{a\}$ because it writes to $\{c\}$ and reads from $\{a\}$
  2365. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2366. live-before for \code{movq \$30, b} is $\{a\}$ because it writes to a
  2367. variable that is not live and does not read from a variable.
  2368. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2369. because it writes to variable $a$.
  2370. \begin{center}
  2371. \begin{minipage}{0.45\textwidth}
  2372. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2373. movq $5, a
  2374. movq $30, b
  2375. movq a, c
  2376. movq $10, b
  2377. addq b, c
  2378. \end{lstlisting}
  2379. \end{minipage}
  2380. \vrule\hspace{10pt}
  2381. \begin{minipage}{0.45\textwidth}
  2382. \begin{align*}
  2383. L_{\mathsf{before}}(1)= \emptyset,
  2384. L_{\mathsf{after}}(1)= \{a\}\\
  2385. L_{\mathsf{before}}(2)= \{a\},
  2386. L_{\mathsf{after}}(2)= \{a\}\\
  2387. L_{\mathsf{before}}(3)= \{a\},
  2388. L_{\mathsf{after}}(2)= \{c\}\\
  2389. L_{\mathsf{before}}(4)= \{c\},
  2390. L_{\mathsf{after}}(4)= \{b,c\}\\
  2391. L_{\mathsf{before}}(5)= \{b,c\},
  2392. L_{\mathsf{after}}(5)= \emptyset
  2393. \end{align*}
  2394. \end{minipage}
  2395. \end{center}
  2396. Figure~\ref{fig:live-eg} shows the results of live variables analysis
  2397. for the running example program, with the live-before and live-after
  2398. sets shown between each instruction to make the figure easy to read.
  2399. \begin{figure}[tbp]
  2400. \hspace{20pt}
  2401. \begin{minipage}{0.45\textwidth}
  2402. \begin{lstlisting}
  2403. |$\{\}$|
  2404. movq $1, v
  2405. |$\{v\}$|
  2406. movq $42, w
  2407. |$\{v,w\}$|
  2408. movq v, x
  2409. |$\{w,x\}$|
  2410. addq $7, x
  2411. |$\{w,x\}$|
  2412. movq x, y
  2413. |$\{w,x,y\}$|
  2414. movq x, z
  2415. |$\{w,y,z\}$|
  2416. addq w, z
  2417. |$\{y,z\}$|
  2418. movq y, t
  2419. |$\{t,z\}$|
  2420. negq t
  2421. |$\{t,z\}$|
  2422. movq z, %rax
  2423. |$\{t\}$|
  2424. addq t, %rax
  2425. |$\{\}$|
  2426. jmp conclusion
  2427. |$\{\}$|
  2428. \end{lstlisting}
  2429. \end{minipage}
  2430. \caption{The running example annotated with live-after sets.}
  2431. \label{fig:live-eg}
  2432. \end{figure}
  2433. \begin{exercise}\normalfont
  2434. Implement the compiler pass named \code{uncover-live} that computes
  2435. the live-after sets. We recommend storing the live-after sets (a list
  2436. of lists of variables) in the $\itm{info}$ field of the \key{Block}
  2437. structure.
  2438. %
  2439. We recommend organizing your code to use a helper function that takes
  2440. a list of instructions and an initial live-after set (typically empty)
  2441. and returns the list of live-after sets.
  2442. %
  2443. We recommend creating helper functions to 1) compute the set of
  2444. variables that appear in an argument (of an instruction), 2) compute
  2445. the variables read by an instruction which corresponds to the $R$
  2446. function discussed above, and 3) the variables written by an
  2447. instruction which corresponds to $W$.
  2448. \end{exercise}
  2449. \section{Building the Interference Graph}
  2450. \label{sec:build-interference}
  2451. Based on the liveness analysis, we know where each variable is needed.
  2452. However, during register allocation, we need to answer questions of
  2453. the specific form: are variables $u$ and $v$ live at the same time?
  2454. (And therefore cannot be assigned to the same register.) To make this
  2455. question easier to answer, we create an explicit data structure, an
  2456. \emph{interference graph}. An interference graph is an undirected
  2457. graph that has an edge between two variables if they are live at the
  2458. same time, that is, if they interfere with each other.
  2459. The most obvious way to compute the interference graph is to look at
  2460. the set of live variables between each statement in the program and
  2461. add an edge to the graph for every pair of variables in the same set.
  2462. This approach is less than ideal for two reasons. First, it can be
  2463. expensive because it takes $O(n^2)$ time to look at every pair in a
  2464. set of $n$ live variables. Second, there is a special case in which
  2465. two variables that are live at the same time do not actually interfere
  2466. with each other: when they both contain the same value because we have
  2467. assigned one to the other.
  2468. A better way to compute the interference graph is to focus on the
  2469. writes~\cite{Appel:2003fk}. We do not want the write performed by an
  2470. instruction to overwrite something in a live variable. So for each
  2471. instruction, we create an edge between the variable being written to
  2472. and all the \emph{other} live variables. (One should not create self
  2473. edges.) For a \key{callq} instruction, think of all caller-saved
  2474. registers as being written to, so an edge must be added between every
  2475. live variable and every caller-saved register. For \key{movq}, we deal
  2476. with the above-mentioned special case by not adding an edge between a
  2477. live variable $v$ and destination $d$ if $v$ matches the source of the
  2478. move. So we have the following three rules.
  2479. \begin{enumerate}
  2480. \item If instruction $I_k$ is an arithmetic instruction such as
  2481. \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2482. L_{\mathsf{after}}(k)$ unless $v = d$.
  2483. \item If instruction $I_k$ is of the form \key{callq}
  2484. $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2485. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2486. \item If instruction $I_k$ is a move: \key{movq} $s$\key{,} $d$, then add
  2487. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  2488. d$ or $v = s$.
  2489. \end{enumerate}
  2490. \margincomment{JM: I think you could give examples of each one of these
  2491. using the example program and use those to help explain why these
  2492. rules are correct.\\
  2493. JS: Agreed.}
  2494. Working from the top to bottom of Figure~\ref{fig:live-eg}, we obtain
  2495. the following interference for each instruction.
  2496. \begin{quote}
  2497. \begin{tabular}{ll}
  2498. \lstinline{movq $1, v}& no interference by rule 3,\\
  2499. \lstinline{movq $42, w}& $w$ interferes with $v$ by rule 3,\\
  2500. \lstinline{movq v, x}& $x$ interferes with $w$ by rule 3,\\
  2501. \lstinline{addq $7, x}& $x$ interferes with $w$ by rule 1,\\
  2502. \lstinline{movq x, y}& $y$ interferes with $w$ but not $x$ by rule 3,\\
  2503. \lstinline{movq x, z}& $z$ interferes with $w$ and $y$ by rule 3,\\
  2504. \lstinline{addq w, z}& $z$ interferes with $y$ by rule 1, \\
  2505. \lstinline{movq y, t}& $t$ interferes with $z$ by rule 3, \\
  2506. \lstinline{negq t}& $t$ interferes with $z$ by rule 1, \\
  2507. \lstinline{movq z, %rax} & no interference (ignore rax), \\
  2508. \lstinline{addq t, %rax} & no interference (ignore rax). \\
  2509. \lstinline{jmp conclusion}& no interference.
  2510. \end{tabular}
  2511. \end{quote}
  2512. The resulting interference graph is shown in
  2513. Figure~\ref{fig:interfere}.
  2514. \begin{figure}[tbp]
  2515. \large
  2516. \[
  2517. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2518. \node (t1) at (0,2) {$t$};
  2519. \node (z) at (3,2) {$z$};
  2520. \node (x) at (6,2) {$x$};
  2521. \node (y) at (3,0) {$y$};
  2522. \node (w) at (6,0) {$w$};
  2523. \node (v) at (9,0) {$v$};
  2524. \draw (t1) to (z);
  2525. \draw (z) to (y);
  2526. \draw (z) to (w);
  2527. \draw (x) to (w);
  2528. \draw (y) to (w);
  2529. \draw (v) to (w);
  2530. \end{tikzpicture}
  2531. \]
  2532. \caption{The interference graph of the example program.}
  2533. \label{fig:interfere}
  2534. \end{figure}
  2535. %% Our next concern is to choose a data structure for representing the
  2536. %% interference graph. There are many choices for how to represent a
  2537. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2538. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2539. %% data structure is to study the algorithm that uses the data structure,
  2540. %% determine what operations need to be performed, and then choose the
  2541. %% data structure that provide the most efficient implementations of
  2542. %% those operations. Often times the choice of data structure can have an
  2543. %% effect on the time complexity of the algorithm, as it does here. If
  2544. %% you skim the next section, you will see that the register allocation
  2545. %% algorithm needs to ask the graph for all of its vertices and, given a
  2546. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2547. %% correct choice of graph representation is that of an adjacency
  2548. %% list. There are helper functions in \code{utilities.rkt} for
  2549. %% representing graphs using the adjacency list representation:
  2550. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2551. %% (Appendix~\ref{appendix:utilities}).
  2552. %% %
  2553. %% \margincomment{\footnotesize To do: change to use the
  2554. %% Racket graph library. \\ --Jeremy}
  2555. %% %
  2556. %% In particular, those functions use a hash table to map each vertex to
  2557. %% the set of adjacent vertices, and the sets are represented using
  2558. %% Racket's \key{set}, which is also a hash table.
  2559. \begin{exercise}\normalfont
  2560. Implement the compiler pass named \code{build-interference} according
  2561. to the algorithm suggested above. We recommend using the Racket
  2562. \code{graph} package to create and inspect the interference graph.
  2563. The output graph of this pass should be stored in the $\itm{info}$
  2564. field of the program, under the key \code{conflicts}.
  2565. \end{exercise}
  2566. \section{Graph Coloring via Sudoku}
  2567. \label{sec:graph-coloring}
  2568. We come to the main event, mapping variables to registers (or to stack
  2569. locations in the event that we run out of registers). We need to make
  2570. sure that two variables do not get mapped to the same register if the
  2571. two variables interfere with each other. Thinking about the
  2572. interference graph, this means that adjacent vertices must be mapped
  2573. to different registers. If we think of registers as colors, the
  2574. register allocation problem becomes the widely-studied graph coloring
  2575. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2576. The reader may be more familiar with the graph coloring problem than he
  2577. or she realizes; the popular game of Sudoku is an instance of the
  2578. graph coloring problem. The following describes how to build a graph
  2579. out of an initial Sudoku board.
  2580. \begin{itemize}
  2581. \item There is one vertex in the graph for each Sudoku square.
  2582. \item There is an edge between two vertices if the corresponding squares
  2583. are in the same row, in the same column, or if the squares are in
  2584. the same $3\times 3$ region.
  2585. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2586. \item Based on the initial assignment of numbers to squares in the
  2587. Sudoku board, assign the corresponding colors to the corresponding
  2588. vertices in the graph.
  2589. \end{itemize}
  2590. If you can color the remaining vertices in the graph with the nine
  2591. colors, then you have also solved the corresponding game of Sudoku.
  2592. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2593. the corresponding graph with colored vertices. We map the Sudoku
  2594. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2595. sampling of the vertices (the colored ones) because showing edges for
  2596. all of the vertices would make the graph unreadable.
  2597. \begin{figure}[tbp]
  2598. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2599. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2600. \caption{A Sudoku game board and the corresponding colored graph.}
  2601. \label{fig:sudoku-graph}
  2602. \end{figure}
  2603. Given that Sudoku is an instance of graph coloring, one can use Sudoku
  2604. strategies to come up with an algorithm for allocating registers. For
  2605. example, one of the basic techniques for Sudoku is called Pencil
  2606. Marks. The idea is to use a process of elimination to determine what
  2607. numbers no longer make sense for a square and write down those
  2608. numbers in the square (writing very small). For example, if the number
  2609. $1$ is assigned to a square, then by process of elimination, you can
  2610. write the pencil mark $1$ in all the squares in the same row, column,
  2611. and region. Many Sudoku computer games provide automatic support for
  2612. Pencil Marks.
  2613. %
  2614. The Pencil Marks technique corresponds to the notion of
  2615. \emph{saturation} due to \cite{Brelaz:1979eu}. The saturation of a
  2616. vertex, in Sudoku terms, is the set of numbers that are no longer
  2617. available. In graph terminology, we have the following definition:
  2618. \begin{equation*}
  2619. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  2620. \text{ and } \mathrm{color}(v) = c \}
  2621. \end{equation*}
  2622. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  2623. edge with $u$.
  2624. Using the Pencil Marks technique leads to a simple strategy for
  2625. filling in numbers: if there is a square with only one possible number
  2626. left, then choose that number! But what if there are no squares with
  2627. only one possibility left? One brute-force approach is to try them
  2628. all: choose the first and if it ultimately leads to a solution,
  2629. great. If not, backtrack and choose the next possibility. One good
  2630. thing about Pencil Marks is that it reduces the degree of branching in
  2631. the search tree. Nevertheless, backtracking can be horribly time
  2632. consuming. One way to reduce the amount of backtracking is to use the
  2633. most-constrained-first heuristic. That is, when choosing a square,
  2634. always choose one with the fewest possibilities left (the vertex with
  2635. the highest saturation). The idea is that choosing highly constrained
  2636. squares earlier rather than later is better because later on there may
  2637. not be any possibilities left for those squares.
  2638. However, register allocation is easier than Sudoku because the
  2639. register allocator can map variables to stack locations when the
  2640. registers run out. Thus, it makes sense to drop backtracking in favor
  2641. of greedy search, that is, make the best choice at the time and keep
  2642. going. We still wish to minimize the number of colors needed, so
  2643. keeping the most-constrained-first heuristic is a good idea.
  2644. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  2645. algorithm for register allocation based on saturation and the
  2646. most-constrained-first heuristic. It is roughly equivalent to the
  2647. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2648. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just as in
  2649. Sudoku, the algorithm represents colors with integers. The first $k$
  2650. colors corresponding to the $k$ registers in a given machine and the
  2651. rest of the integers corresponding to stack locations.
  2652. \begin{figure}[btp]
  2653. \centering
  2654. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2655. Algorithm: DSATUR
  2656. Input: a graph |$G$|
  2657. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  2658. |$W \gets \mathit{vertices}(G)$|
  2659. while |$W \neq \emptyset$| do
  2660. pick a vertex |$u$| from |$W$| with the highest saturation,
  2661. breaking ties randomly
  2662. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  2663. |$\mathrm{color}[u] \gets c$|
  2664. |$W \gets W - \{u\}$|
  2665. \end{lstlisting}
  2666. \caption{The saturation-based greedy graph coloring algorithm.}
  2667. \label{fig:satur-algo}
  2668. \end{figure}
  2669. With this algorithm in hand, let us return to the running example and
  2670. consider how to color the interference graph in
  2671. Figure~\ref{fig:interfere}. Initially, all of the vertices are not yet
  2672. colored and they are unsaturated, so we annotate each of them with a
  2673. dash for their color and an empty set for the saturation.
  2674. \[
  2675. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2676. \node (t1) at (0,2) {$t:-,\{\}$};
  2677. \node (z) at (3,2) {$z:-,\{\}$};
  2678. \node (x) at (6,2) {$x:-,\{\}$};
  2679. \node (y) at (3,0) {$y:-,\{\}$};
  2680. \node (w) at (6,0) {$w:-,\{\}$};
  2681. \node (v) at (9,0) {$v:-,\{\}$};
  2682. \draw (t1) to (z);
  2683. \draw (z) to (y);
  2684. \draw (z) to (w);
  2685. \draw (x) to (w);
  2686. \draw (y) to (w);
  2687. \draw (v) to (w);
  2688. \end{tikzpicture}
  2689. \]
  2690. The algorithm says to select a maximally saturated vertex and color it
  2691. $0$. In this case we have a 6-way tie, so we arbitrarily pick
  2692. $t$. We then mark color $0$ as no longer available for $z$ because
  2693. it interferes with $t$.
  2694. \[
  2695. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2696. \node (t1) at (0,2) {$t:0,\{\}$};
  2697. \node (z) at (3,2) {$z:-,\{0\}$};
  2698. \node (x) at (6,2) {$x:-,\{\}$};
  2699. \node (y) at (3,0) {$y:-,\{\}$};
  2700. \node (w) at (6,0) {$w:-,\{\}$};
  2701. \node (v) at (9,0) {$v:-,\{\}$};
  2702. \draw (t1) to (z);
  2703. \draw (z) to (y);
  2704. \draw (z) to (w);
  2705. \draw (x) to (w);
  2706. \draw (y) to (w);
  2707. \draw (v) to (w);
  2708. \end{tikzpicture}
  2709. \]
  2710. Next we repeat the process, selecting another maximally saturated
  2711. vertex, which is $z$, and color it with the first available number,
  2712. which is $1$.
  2713. \[
  2714. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2715. \node (t1) at (0,2) {$t:0,\{1\}$};
  2716. \node (z) at (3,2) {$z:1,\{0\}$};
  2717. \node (x) at (6,2) {$x:-,\{\}$};
  2718. \node (y) at (3,0) {$y:-,\{1\}$};
  2719. \node (w) at (6,0) {$w:-,\{1\}$};
  2720. \node (v) at (9,0) {$v:-,\{\}$};
  2721. \draw (t1) to (z);
  2722. \draw (z) to (y);
  2723. \draw (z) to (w);
  2724. \draw (x) to (w);
  2725. \draw (y) to (w);
  2726. \draw (v) to (w);
  2727. \end{tikzpicture}
  2728. \]
  2729. The most saturated vertices are now $w$ and $y$. We color $w$ with the
  2730. first available color, which is $0$.
  2731. \[
  2732. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2733. \node (t1) at (0,2) {$t:0,\{1\}$};
  2734. \node (z) at (3,2) {$z:1,\{0\}$};
  2735. \node (x) at (6,2) {$x:-,\{0\}$};
  2736. \node (y) at (3,0) {$y:-,\{0,1\}$};
  2737. \node (w) at (6,0) {$w:0,\{1\}$};
  2738. \node (v) at (9,0) {$v:-,\{0\}$};
  2739. \draw (t1) to (z);
  2740. \draw (z) to (y);
  2741. \draw (z) to (w);
  2742. \draw (x) to (w);
  2743. \draw (y) to (w);
  2744. \draw (v) to (w);
  2745. \end{tikzpicture}
  2746. \]
  2747. Vertex $y$ is now the most highly saturated, so we color $y$ with $2$.
  2748. We cannot choose $0$ or $1$ because those numbers are in $y$'s
  2749. saturation set. Indeed, $y$ interferes with $w$ and $z$, whose colors
  2750. are $0$ and $1$ respectively.
  2751. \[
  2752. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2753. \node (t1) at (0,2) {$t:0,\{1\}$};
  2754. \node (z) at (3,2) {$z:1,\{0,2\}$};
  2755. \node (x) at (6,2) {$x:-,\{0\}$};
  2756. \node (y) at (3,0) {$y:2,\{0,1\}$};
  2757. \node (w) at (6,0) {$w:0,\{1,2\}$};
  2758. \node (v) at (9,0) {$v:-,\{0\}$};
  2759. \draw (t1) to (z);
  2760. \draw (z) to (y);
  2761. \draw (z) to (w);
  2762. \draw (x) to (w);
  2763. \draw (y) to (w);
  2764. \draw (v) to (w);
  2765. \end{tikzpicture}
  2766. \]
  2767. Now $x$ and $v$ are the most saturated, so we color $v$ it $1$.
  2768. \[
  2769. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2770. \node (t1) at (0,2) {$t:0,\{1\}$};
  2771. \node (z) at (3,2) {$z:1,\{0,2\}$};
  2772. \node (x) at (6,2) {$x:-,\{0\}$};
  2773. \node (y) at (3,0) {$y:2,\{0,1\}$};
  2774. \node (w) at (6,0) {$w:0,\{1,2\}$};
  2775. \node (v) at (9,0) {$v:1,\{0\}$};
  2776. \draw (t1) to (z);
  2777. \draw (z) to (y);
  2778. \draw (z) to (w);
  2779. \draw (x) to (w);
  2780. \draw (y) to (w);
  2781. \draw (v) to (w);
  2782. \end{tikzpicture}
  2783. \]
  2784. In the last step of the algorithm, we color $x$ with $1$.
  2785. \[
  2786. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2787. \node (t1) at (0,2) {$t:0,\{1,\}$};
  2788. \node (z) at (3,2) {$z:1,\{0,2\}$};
  2789. \node (x) at (6,2) {$x:1,\{0\}$};
  2790. \node (y) at (3,0) {$y:2,\{0,1\}$};
  2791. \node (w) at (6,0) {$w:0,\{1,2\}$};
  2792. \node (v) at (9,0) {$v:1,\{0\}$};
  2793. \draw (t1) to (z);
  2794. \draw (z) to (y);
  2795. \draw (z) to (w);
  2796. \draw (x) to (w);
  2797. \draw (y) to (w);
  2798. \draw (v) to (w);
  2799. \end{tikzpicture}
  2800. \]
  2801. With the coloring complete, we finalize the assignment of variables to
  2802. registers and stack locations. Recall that if we have $k$ registers,
  2803. we map the first $k$ colors to registers and the rest to stack
  2804. locations. Suppose for the moment that we have just one register to
  2805. use for register allocation, \key{rcx}. Then the following is the
  2806. mapping of colors to registers and stack allocations.
  2807. \[
  2808. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  2809. \]
  2810. Putting this mapping together with the above coloring of the
  2811. variables, we arrive at the following assignment of variables to
  2812. registers and stack locations.
  2813. \begin{gather*}
  2814. \{ v \mapsto \key{\%rcx}, \,
  2815. w \mapsto \key{\%rcx}, \,
  2816. x \mapsto \key{-8(\%rbp)}, \\
  2817. y \mapsto \key{-16(\%rbp)}, \,
  2818. z\mapsto \key{-8(\%rbp)},
  2819. t\mapsto \key{\%rcx} \}
  2820. \end{gather*}
  2821. Applying this assignment to our running example, on the left, yields
  2822. the program on the right.
  2823. % why frame size of 32? -JGS
  2824. \begin{center}
  2825. \begin{minipage}{0.3\textwidth}
  2826. \begin{lstlisting}
  2827. movq $1, v
  2828. movq $42, w
  2829. movq v, x
  2830. addq $7, x
  2831. movq x, y
  2832. movq x, z
  2833. addq w, z
  2834. movq y, t
  2835. negq t
  2836. movq z, %rax
  2837. addq t, %rax
  2838. jmp conclusion
  2839. \end{lstlisting}
  2840. \end{minipage}
  2841. $\Rightarrow\qquad$
  2842. \begin{minipage}{0.45\textwidth}
  2843. \begin{lstlisting}
  2844. movq $1, %rcx
  2845. movq $42, %rcx
  2846. movq %rcx, -8(%rbp)
  2847. addq $7, -8(%rbp)
  2848. movq -8(%rbp), -16(%rbp)
  2849. movq -8(%rbp), -8(%rbp)
  2850. addq %rcx, -8(%rbp)
  2851. movq -16(%rbp), %rcx
  2852. negq %rcx
  2853. movq -8(%rbp), %rax
  2854. addq %rcx, %rax
  2855. jmp conclusion
  2856. \end{lstlisting}
  2857. \end{minipage}
  2858. \end{center}
  2859. The resulting program is almost an x86 program. The remaining step is
  2860. the patch instructions pass. In this example, the trivial move of
  2861. \code{-8(\%rbp)} to itself is deleted and the addition of
  2862. \code{-8(\%rbp)} to \key{-16(\%rbp)} is fixed by going through
  2863. \code{rax} as follows.
  2864. \begin{lstlisting}
  2865. movq -8(%rbp), %rax
  2866. addq %rax, -16(%rbp)
  2867. \end{lstlisting}
  2868. An overview of all of the passes involved in register allocation is
  2869. shown in Figure~\ref{fig:reg-alloc-passes}.
  2870. \begin{figure}[tbp]
  2871. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2872. \node (R1) at (0,2) {\large $R_1$};
  2873. \node (R1-2) at (3,2) {\large $R_1$};
  2874. \node (R1-3) at (6,2) {\large $R_1$};
  2875. \node (C0-1) at (6,0) {\large $C_0$};
  2876. \node (C0-2) at (3,0) {\large $C_0$};
  2877. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  2878. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  2879. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  2880. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  2881. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  2882. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  2883. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  2884. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  2885. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  2886. \path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  2887. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  2888. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  2889. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  2890. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  2891. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  2892. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  2893. \end{tikzpicture}
  2894. \caption{Diagram of the passes for $R_1$ with register allocation.}
  2895. \label{fig:reg-alloc-passes}
  2896. \end{figure}
  2897. \begin{exercise}\normalfont
  2898. Implement the pass \code{allocate-registers}, which should come
  2899. after the \code{build-interference} pass. The three new passes,
  2900. \code{uncover-live}, \code{build-interference}, and
  2901. \code{allocate-registers} replace the \code{assign-homes} pass of
  2902. Section~\ref{sec:assign-r1}.
  2903. We recommend that you create a helper function named
  2904. \code{color-graph} that takes an interference graph and a list of
  2905. all the variables in the program. This function should return a
  2906. mapping of variables to their colors (represented as natural
  2907. numbers). By creating this helper function, you will be able to
  2908. reuse it in Chapter~\ref{ch:functions} when you add support for
  2909. functions.
  2910. Once you have obtained the coloring from \code{color-graph}, you can
  2911. assign the variables to registers or stack locations and then reuse
  2912. code from the \code{assign-homes} pass from
  2913. Section~\ref{sec:assign-r1} to replace the variables with their
  2914. assigned location.
  2915. Test your updated compiler by creating new example programs that
  2916. exercise all of the register allocation algorithm, such as forcing
  2917. variables to be spilled to the stack.
  2918. \end{exercise}
  2919. \section{Print x86 and Conventions for Registers}
  2920. \label{sec:print-x86-reg-alloc}
  2921. Recall that the \code{print-x86} pass generates the prelude and
  2922. conclusion instructions for the \code{main} function.
  2923. %
  2924. The prelude saved the values in \code{rbp} and \code{rsp} and the
  2925. conclusion returned those values to \code{rbp} and \code{rsp}. The
  2926. reason for this is that our \code{main} function must adhere to the
  2927. x86 calling conventions that we described in
  2928. Section~\ref{sec:calling-conventions}. In addition, the \code{main}
  2929. function needs to restore (in the conclusion) any callee-saved
  2930. registers that get used during register allocation. The simplest
  2931. approach is to save and restore all of the callee-saved registers. The
  2932. more efficient approach is to keep track of which callee-saved
  2933. registers were used and only save and restore them. Either way, make
  2934. sure to take this use of stack space into account when you are
  2935. calculating the size of the frame. Also, don't forget that the size of
  2936. the frame needs to be a multiple of 16 bytes.
  2937. \section{Challenge: Move Biasing}
  2938. \label{sec:move-biasing}
  2939. This section describes an optional enhancement to register allocation
  2940. for those students who are looking for an extra challenge or who have
  2941. a deeper interest in register allocation.
  2942. We return to the running example, but we remove the supposition that
  2943. we only have one register to use. So we have the following mapping of
  2944. color numbers to registers.
  2945. \[
  2946. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx} \}
  2947. \]
  2948. Using the same assignment of variables to color numbers that was
  2949. produced by the register allocator described in the last section, we
  2950. get the following program.
  2951. \begin{minipage}{0.3\textwidth}
  2952. \begin{lstlisting}
  2953. movq $1, v
  2954. movq $46, w
  2955. movq v, x
  2956. addq $7, x
  2957. movq x, y
  2958. addq $4, y
  2959. movq x, z
  2960. addq w, z
  2961. movq y, t
  2962. negq t
  2963. movq z, %rax
  2964. addq t, %rax
  2965. jmp conclusion
  2966. \end{lstlisting}
  2967. \end{minipage}
  2968. $\Rightarrow\qquad$
  2969. \begin{minipage}{0.45\textwidth}
  2970. \begin{lstlisting}
  2971. movq $1, %rbx
  2972. movq $46, %rdx
  2973. movq %rbx, %rcx
  2974. addq $7, %rcx
  2975. movq %rcx, %rbx
  2976. addq $4, %rbx
  2977. movq %rcx, %rcx
  2978. addq %rdx, %rcx
  2979. movq %rbx, %rbx
  2980. negq %rbx
  2981. movq %rcx, %rax
  2982. addq %rbx, %rax
  2983. jmp conclusion
  2984. \end{lstlisting}
  2985. \end{minipage}
  2986. While this allocation is quite good, we could do better. For example,
  2987. the variables \key{v} and \key{x} ended up in different registers, but
  2988. if they had been placed in the same register, then the move from
  2989. \key{v} to \key{x} could be removed.
  2990. We say that two variables $p$ and $q$ are \emph{move related} if they
  2991. participate together in a \key{movq} instruction, that is, \key{movq}
  2992. $p$\key{,} $q$ or \key{movq} $q$\key{,} $p$. When the register
  2993. allocator chooses a color for a variable, it should prefer a color
  2994. that has already been used for a move-related variable (assuming that
  2995. they do not interfere). Of course, this preference should not override
  2996. the preference for registers over stack locations. This preference
  2997. should be used as a tie breaker when choosing between registers or
  2998. when choosing between stack locations.
  2999. We recommend representing the move relationships in a graph, similar
  3000. to how we represented interference. The following is the \emph{move
  3001. graph} for our running example.
  3002. \[
  3003. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3004. \node (v) at (0,0) {$v$};
  3005. \node (w) at (3,0) {$w$};
  3006. \node (x) at (6,0) {$x$};
  3007. \node (y) at (3,-1.5) {$y$};
  3008. \node (z) at (6,-1.5) {$z$};
  3009. \node (t1) at (9,-1.5) {$t.1$};
  3010. \draw[bend left=15] (t1) to (y);
  3011. \draw[bend left=15] (v) to (x);
  3012. \draw (x) to (y);
  3013. \draw (x) to (z);
  3014. \end{tikzpicture}
  3015. \]
  3016. Now we replay the graph coloring, pausing to see the coloring of $x$
  3017. and $v$. So we have the following coloring and the most saturated
  3018. vertex is $x$.
  3019. \[
  3020. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3021. \node (v) at (0,0) {$v:-,\{2\}$};
  3022. \node (w) at (3,0) {$w:2,\{0,1\}$};
  3023. \node (x) at (6,0) {$x:-,\{0,2\}$};
  3024. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  3025. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  3026. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  3027. \draw (t1) to (z);
  3028. \draw (v) to (w);
  3029. \foreach \i in {w,x,y}
  3030. {
  3031. \foreach \j in {w,x,y}
  3032. {
  3033. \draw (\i) to (\j);
  3034. }
  3035. }
  3036. \draw (z) to (w);
  3037. \draw (z) to (y);
  3038. \end{tikzpicture}
  3039. \]
  3040. Last time we chose to color $x$ with $1$,
  3041. %
  3042. which so happens to be the color of $z$, and $x$ is move related to
  3043. $z$. This was lucky, and if the program had been a little different,
  3044. and say $z$ had been already assigned to $2$, then $x$ would still get
  3045. $1$ and our luck would have run out. With move biasing, we use the
  3046. fact that $x$ and $z$ are move related to influence the choice of
  3047. color for $x$, in this case choosing $1$ because that is the color of
  3048. $z$.
  3049. \[
  3050. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3051. \node (v) at (0,0) {$v:-,\{2\}$};
  3052. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  3053. \node (x) at (6,0) {$x:\mathbf{1},\{0,2\}$};
  3054. \node (y) at (3,-1.5) {$y:0,\{\mathbf{1},2\}$};
  3055. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  3056. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  3057. \draw (t1) to (z);
  3058. \draw (v) to (w);
  3059. \foreach \i in {w,x,y}
  3060. {
  3061. \foreach \j in {w,x,y}
  3062. {
  3063. \draw (\i) to (\j);
  3064. }
  3065. }
  3066. \draw (z) to (w);
  3067. \draw (z) to (y);
  3068. \end{tikzpicture}
  3069. \]
  3070. Next we consider coloring the variable $v$. We need to avoid choosing
  3071. $2$ because of the interference with $w$. Last time we chose the color
  3072. $0$ because it was the lowest, but this time we know that $v$ is move
  3073. related to $x$, so we choose the color $1$.
  3074. \[
  3075. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3076. \node (v) at (0,0) {$v:\mathbf{1},\{2\}$};
  3077. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  3078. \node (x) at (6,0) {$x:1,\{0,2\}$};
  3079. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  3080. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  3081. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  3082. \draw (t1) to (z);
  3083. \draw (v) to (w);
  3084. \foreach \i in {w,x,y}
  3085. {
  3086. \foreach \j in {w,x,y}
  3087. {
  3088. \draw (\i) to (\j);
  3089. }
  3090. }
  3091. \draw (z) to (w);
  3092. \draw (z) to (y);
  3093. \end{tikzpicture}
  3094. \]
  3095. We apply this register assignment to the running example, on the left,
  3096. to obtain the code on right.
  3097. \begin{minipage}{0.3\textwidth}
  3098. \begin{lstlisting}
  3099. movq $1, v
  3100. movq $46, w
  3101. movq v, x
  3102. addq $7, x
  3103. movq x, y
  3104. addq $4, y
  3105. movq x, z
  3106. addq w, z
  3107. movq y, t.1
  3108. negq t.1
  3109. movq z, %rax
  3110. addq t.1, %rax
  3111. jmp conclusion
  3112. \end{lstlisting}
  3113. \end{minipage}
  3114. $\Rightarrow\qquad$
  3115. \begin{minipage}{0.45\textwidth}
  3116. \begin{lstlisting}
  3117. movq $1, %rcx
  3118. movq $46, %rbx
  3119. movq %rcx, %rcx
  3120. addq $7, %rcx
  3121. movq %rcx, %rdx
  3122. addq $4, %rdx
  3123. movq %rcx, %rcx
  3124. addq %rbx, %rcx
  3125. movq %rdx, %rbx
  3126. negq %rbx
  3127. movq %rcx, %rax
  3128. addq %rbx, %rax
  3129. jmp conclusion
  3130. \end{lstlisting}
  3131. \end{minipage}
  3132. The \code{patch-instructions} then removes the trivial moves from
  3133. \key{v} to \key{x} and from \key{x} to \key{z} to obtain the following
  3134. result.
  3135. \begin{minipage}{0.45\textwidth}
  3136. \begin{lstlisting}
  3137. movq $1 %rcx
  3138. movq $46 %rbx
  3139. addq $7 %rcx
  3140. movq %rcx %rdx
  3141. addq $4 %rdx
  3142. addq %rbx %rcx
  3143. movq %rdx %rbx
  3144. negq %rbx
  3145. movq %rcx %rax
  3146. addq %rbx %rax
  3147. jmp conclusion
  3148. \end{lstlisting}
  3149. \end{minipage}
  3150. \begin{exercise}\normalfont
  3151. Change your implementation of \code{allocate-registers} to take move
  3152. biasing into account. Make sure that your compiler still passes all of
  3153. the previous tests. Create two new tests that include at least one
  3154. opportunity for move biasing and visually inspect the output x86
  3155. programs to make sure that your move biasing is working properly.
  3156. \end{exercise}
  3157. \margincomment{\footnotesize To do: another neat challenge would be to do
  3158. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3159. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3160. \chapter{Booleans and Control Flow}
  3161. \label{ch:bool-types}
  3162. The $R_0$ and $R_1$ languages only have a single kind of value, the
  3163. integers. In this chapter we add a second kind of value, the Booleans,
  3164. to create the $R_2$ language. The Boolean values \emph{true} and
  3165. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  3166. Racket. The $R_2$ language includes several operations that involve
  3167. Booleans (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the
  3168. conditional \key{if} expression. With the addition of \key{if}
  3169. expressions, programs can have non-trivial control flow which which
  3170. significantly impacts the \code{explicate-control} and the liveness
  3171. analysis for register allocation. Also, because we now have two kinds
  3172. of values, we need to handle programs that apply an operation to the
  3173. wrong kind of value, such as \code{(not 1)}.
  3174. There are two language design options for such situations. One option
  3175. is to signal an error and the other is to provide a wider
  3176. interpretation of the operation. The Racket language uses a mixture of
  3177. these two options, depending on the operation and the kind of
  3178. value. For example, the result of \code{(not 1)} in Racket is
  3179. \code{\#f} because Racket treats non-zero integers as if they were
  3180. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  3181. error in Racket stating that \code{car} expects a pair.
  3182. The Typed Racket language makes similar design choices as Racket,
  3183. except much of the error detection happens at compile time instead of
  3184. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  3185. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  3186. reports a compile-time error because Typed Racket expects the type of
  3187. the argument to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  3188. For the $R_2$ language we choose to be more like Typed Racket in that
  3189. we shall perform type checking during compilation. In
  3190. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  3191. is, how to compile a dynamically typed language like Racket. The
  3192. $R_2$ language is a subset of Typed Racket but by no means includes
  3193. all of Typed Racket. For many operations we take a narrower
  3194. interpretation than Typed Racket, for example, rejecting \code{(not 1)}.
  3195. This chapter is organized as follows. We begin by defining the syntax
  3196. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  3197. then introduce the idea of type checking and build a type checker for
  3198. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  3199. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  3200. Section~\ref{sec:c1}. The remaining sections of this chapter discuss
  3201. how our compiler passes need to change to accommodate Booleans and
  3202. conditional control flow.
  3203. \section{The $R_2$ Language}
  3204. \label{sec:r2-lang}
  3205. The concrete syntax of the $R_2$ language is defined in
  3206. Figure~\ref{fig:r2-concrete-syntax} and the abstract syntax is defined
  3207. in Figure~\ref{fig:r2-syntax}. The $R_2$ language includes all of
  3208. $R_1$ (shown in gray), the Boolean literals \code{\#t} and \code{\#f},
  3209. and the conditional \code{if} expression. Also, we expand the
  3210. operators to include
  3211. \begin{enumerate}
  3212. \item subtraction on integers,
  3213. \item the logical operators \key{and}, \key{or} and \key{not},
  3214. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  3215. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  3216. comparing integers.
  3217. \end{enumerate}
  3218. \begin{figure}[tp]
  3219. \centering
  3220. \fbox{
  3221. \begin{minipage}{0.96\textwidth}
  3222. \[
  3223. \begin{array}{lcl}
  3224. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3225. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3226. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) } \mid (\key{-}\;\Exp\;\Exp) \\
  3227. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) } \\
  3228. &\mid& \itm{bool}
  3229. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  3230. \mid (\key{not}\;\Exp) \\
  3231. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid (\key{if}~\Exp~\Exp~\Exp) \\
  3232. R_2 &::=& \Exp
  3233. \end{array}
  3234. \]
  3235. \end{minipage}
  3236. }
  3237. \caption{The concrete syntax of $R_2$, extending $R_1$
  3238. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  3239. \label{fig:r2-concrete-syntax}
  3240. \end{figure}
  3241. \begin{figure}[tp]
  3242. \centering
  3243. \fbox{
  3244. \begin{minipage}{0.96\textwidth}
  3245. \[
  3246. \begin{array}{lcl}
  3247. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3248. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3249. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} } \\
  3250. &\mid& \gray{ \NEG{\Exp} \mid \ADD{\Exp}{\Exp} }\\
  3251. &\mid& \BINOP{\code{'-}}{\Exp}{\Exp} \\
  3252. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  3253. &\mid& \BOOL{\itm{bool}} \mid \AND{\Exp}{\Exp}\\
  3254. &\mid& \OR{\Exp}{\Exp} \mid \NOT{\Exp} \\
  3255. &\mid& \BINOP{\code{'}\itm{cmp}}{\Exp}{\Exp} \mid \IF{\Exp}{\Exp}{\Exp} \\
  3256. R_2 &::=& \PROGRAM{\key{'()}}{\Exp}
  3257. \end{array}
  3258. \]
  3259. \end{minipage}
  3260. }
  3261. \caption{The abstract syntax of $R_2$.}
  3262. \label{fig:r2-syntax}
  3263. \end{figure}
  3264. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  3265. the parts that are the same as the interpreter for $R_1$
  3266. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  3267. evaluate to the corresponding Boolean values. The conditional
  3268. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  3269. the Boolean expression \itm{cnd} and then either evaluates \itm{thn}
  3270. or \itm{els} depending on whether \itm{cnd} produced \code{\#t} or
  3271. \code{\#f}. The logical operations \code{not} and \code{and} behave as
  3272. you might expect, but note that the \code{and} operation is
  3273. short-circuiting. That is, given the expression
  3274. $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not evaluated if
  3275. $e_1$ evaluates to \code{\#f}.
  3276. With the addition of the comparison operations, there are quite a few
  3277. primitive operations and the interpreter code for them could become
  3278. repetitive without some care. In Figure~\ref{fig:interp-R2} we factor
  3279. out the different parts of the code for primitive operations into the
  3280. \code{interp-op} function and the similar parts of the code into the
  3281. match clause for \code{Prim} shown in Figure~\ref{fig:interp-R2}. We
  3282. do not use \code{interp-op} for the \code{and} operation because of
  3283. the short-circuiting behavior in the order of evaluation of its
  3284. arguments.
  3285. \begin{figure}[tbp]
  3286. \begin{lstlisting}
  3287. (define (interp-op op)
  3288. (match op
  3289. ...
  3290. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  3291. ['eq? (lambda (v1 v2)
  3292. (cond [(or (and (fixnum? v1) (fixnum? v2))
  3293. (and (boolean? v1) (boolean? v2)))
  3294. (eq? v1 v2)]))]
  3295. ['< (lambda (v1 v2)
  3296. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  3297. ['<= (lambda (v1 v2)
  3298. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  3299. ['> (lambda (v1 v2)
  3300. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  3301. ['>= (lambda (v1 v2)
  3302. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  3303. [else (error 'interp-op "unknown operator")]))
  3304. (define (interp-exp env)
  3305. (lambda (e)
  3306. (define recur (interp-exp env))
  3307. (match e
  3308. ...
  3309. [(Bool b) b]
  3310. [(If cnd thn els)
  3311. (define b (recur cnd))
  3312. (match b
  3313. [#t (recur thn)]
  3314. [#f (recur els)])]
  3315. [(Prim 'and (list e1 e2))
  3316. (define v1 (recur e1))
  3317. (match v1
  3318. [#t (match (recur e2) [#t #t] [#f #f])]
  3319. [#f #f])]
  3320. [(Prim op args)
  3321. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  3322. )))
  3323. (define (interp-R2 p)
  3324. (match p
  3325. [(Program info e)
  3326. ((interp-exp '()) e)]
  3327. ))
  3328. \end{lstlisting}
  3329. \caption{Interpreter for the $R_2$ language.}
  3330. \label{fig:interp-R2}
  3331. \end{figure}
  3332. \section{Type Checking $R_2$ Programs}
  3333. \label{sec:type-check-r2}
  3334. It is helpful to think about type checking in two complementary
  3335. ways. A type checker predicts the type of value that will be produced
  3336. by each expression in the program. For $R_2$, we have just two types,
  3337. \key{Integer} and \key{Boolean}. So a type checker should predict that
  3338. \begin{lstlisting}
  3339. (+ 10 (- (+ 12 20)))
  3340. \end{lstlisting}
  3341. produces an \key{Integer} while
  3342. \begin{lstlisting}
  3343. (and (not #f) #t)
  3344. \end{lstlisting}
  3345. produces a \key{Boolean}.
  3346. Another way to think about type checking is that it enforces a set of
  3347. rules about which operators can be applied to which kinds of
  3348. values. For example, our type checker for $R_2$ will signal an error
  3349. for the below expression because, as we have seen above, the
  3350. expression \code{(+ 10 ...)} has type \key{Integer} but the type
  3351. checker enforces the rule that the argument of \code{not} must be a
  3352. \key{Boolean}.
  3353. \begin{lstlisting}
  3354. (not (+ 10 (- (+ 12 20))))
  3355. \end{lstlisting}
  3356. The type checker for $R_2$ is a structurally recursive function over
  3357. the AST. Figure~\ref{fig:type-check-R2} shows many of the clauses for
  3358. the \code{type-check-exp} function. Given an input expression
  3359. \code{e}, the type checker either returns a type (\key{Integer} or
  3360. \key{Boolean}) or it signals an error. The type of an integer literal
  3361. is \code{Integer} and the type of a Boolean literal is \code{Boolean}.
  3362. To handle variables, the type checker uses an environment that maps
  3363. variables to types. Consider the clause for \key{let}. We type check
  3364. the initializing expression to obtain its type \key{T} and then
  3365. associate type \code{T} with the variable \code{x} in the
  3366. environment. When the type checker encounters a use of variable
  3367. \code{x} in the body of the \key{let}, it can find its type in the
  3368. environment.
  3369. \begin{figure}[tbp]
  3370. \begin{lstlisting}
  3371. (define (type-check-exp env)
  3372. (lambda (e)
  3373. (match e
  3374. [(Var x) (dict-ref env x)]
  3375. [(Int n) 'Integer]
  3376. [(Bool b) 'Boolean]
  3377. [(Let x e body)
  3378. (define Te ((type-check-exp env) e))
  3379. (define Tb ((type-check-exp (dict-set env x Te)) body))
  3380. Tb]
  3381. ...
  3382. [else
  3383. (error "type-check-exp couldn't match" e)])))
  3384. (define (type-check env)
  3385. (lambda (e)
  3386. (match e
  3387. [(Program info body)
  3388. (define Tb ((type-check-exp '()) body))
  3389. (unless (equal? Tb 'Integer)
  3390. (error "result of the program must be an integer, not " Tb))
  3391. (Program info body)]
  3392. )))
  3393. \end{lstlisting}
  3394. \caption{Skeleton of a type checker for the $R_2$ language.}
  3395. \label{fig:type-check-R2}
  3396. \end{figure}
  3397. \begin{exercise}\normalfont
  3398. Complete the implementation of \code{type-check-R2} and test it on 10
  3399. new example programs in $R_2$ that you choose based on how thoroughly
  3400. they test the type checking function. Half of the example programs
  3401. should have a type error to make sure that your type checker properly
  3402. rejects them. The other half of the example programs should not have
  3403. type errors. Your testing should check that the result of the type
  3404. checker agrees with the value returned by the interpreter, that is, if
  3405. the type checker returns \key{Integer}, then the interpreter should
  3406. return an integer. Likewise, if the type checker returns
  3407. \key{Boolean}, then the interpreter should return \code{\#t} or
  3408. \code{\#f}. Note that if your type checker does not signal an error
  3409. for a program, then interpreting that program should not encounter an
  3410. error. If it does, there is something wrong with your type checker.
  3411. \end{exercise}
  3412. \section{Shrink the $R_2$ Language}
  3413. \label{sec:shrink-r2}
  3414. The $R_2$ language includes several operators that are easily
  3415. expressible in terms of other operators. For example, subtraction is
  3416. expressible in terms of addition and negation.
  3417. \[
  3418. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  3419. \]
  3420. Several of the comparison operations are expressible in terms of
  3421. less-than and logical negation.
  3422. \[
  3423. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  3424. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  3425. \]
  3426. The \key{let} is needed in the above translation to ensure that
  3427. expression $e_1$ is evaluated before $e_2$.
  3428. By performing these translations near the front-end of the compiler,
  3429. the later passes of the compiler do not need to deal with these
  3430. constructs, making those passes shorter. On the other hand, sometimes
  3431. these translations make it more difficult to generate the most
  3432. efficient code with respect to the number of instructions. However,
  3433. these differences typically do not affect the number of accesses to
  3434. memory, which is the primary factor that determines execution time on
  3435. modern computer architectures.
  3436. \begin{exercise}\normalfont
  3437. Implement the pass \code{shrink} that removes subtraction,
  3438. \key{and}, \key{or}, \key{<=}, \key{>}, and \key{>=} from the language
  3439. by translating them to other constructs in $R_2$. Create tests to
  3440. make sure that the behavior of all of these constructs stays the
  3441. same after translation.
  3442. \end{exercise}
  3443. \section{XOR, Comparisons, and Control Flow in x86}
  3444. \label{sec:x86-1}
  3445. To implement the new logical operations, the comparison operations,
  3446. and the \key{if} expression, we need to delve further into the x86
  3447. language. Figure~\ref{fig:x86-1} defines the abstract syntax for a
  3448. larger subset of x86 that includes instructions for logical
  3449. operations, comparisons, and jumps.
  3450. One small challenge is that x86 does not provide an instruction that
  3451. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  3452. However, the \code{xorq} instruction can be used to encode \code{not}.
  3453. The \key{xorq} instruction takes two arguments, performs a pairwise
  3454. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  3455. and writes the results into its second argument. Recall the truth
  3456. table for exclusive-or:
  3457. \begin{center}
  3458. \begin{tabular}{l|cc}
  3459. & 0 & 1 \\ \hline
  3460. 0 & 0 & 1 \\
  3461. 1 & 1 & 0
  3462. \end{tabular}
  3463. \end{center}
  3464. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  3465. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  3466. for the bit $1$, the result is the opposite of the second bit. Thus,
  3467. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  3468. the first argument:
  3469. \[
  3470. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  3471. \qquad\Rightarrow\qquad
  3472. \begin{array}{l}
  3473. \key{movq}~ \Arg\key{,} \Var\\
  3474. \key{xorq}~ \key{\$1,} \Var
  3475. \end{array}
  3476. \]
  3477. \begin{figure}[tp]
  3478. \fbox{
  3479. \begin{minipage}{0.96\textwidth}
  3480. \small
  3481. \[
  3482. \begin{array}{lcl}
  3483. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\code{'}\Reg} \mid \DEREF{\Reg}{\Int}}
  3484. \mid \BYTEREG{\code{'}\Reg} \\
  3485. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3486. \Instr &::=& \gray{ \BININSTR{\code{'addq}}{\Arg}{\Arg}
  3487. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} } \\
  3488. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  3489. \mid \UNIINSTR{\code{'negq}}{\Arg} } \\
  3490. &\mid& \gray{ \CALLQ{\itm{label}} \mid \RETQ{}
  3491. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  3492. &\mid& \BININSTR{\code{'xorq}}{\Arg}{\Arg}
  3493. \mid \BININSTR{\code{'cmpq}}{\Arg}{\Arg}\\
  3494. &\mid& \BININSTR{\code{'set}}{\code{'}\itm{cc}}{\Arg}
  3495. \mid \BININSTR{\code{'movzbq}}{\Arg}{\Arg}\\
  3496. &\mid& \JMPIF{\code{'}\itm{cc}}{\itm{label}} \\
  3497. \Block &::= & \gray{\BLOCK{\itm{info}}{\Instr^{+}}} \\
  3498. x86_1 &::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}^{+}}}}
  3499. \end{array}
  3500. \]
  3501. \end{minipage}
  3502. }
  3503. \caption{The abstract syntax of $x86_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-ast}).}
  3504. \label{fig:x86-1}
  3505. \end{figure}
  3506. Next we consider the x86 instructions that are relevant for compiling
  3507. the comparison operations. The \key{cmpq} instruction compares its two
  3508. arguments to determine whether one argument is less than, equal, or
  3509. greater than the other argument. The \key{cmpq} instruction is unusual
  3510. regarding the order of its arguments and where the result is
  3511. placed. The argument order is backwards: if you want to test whether
  3512. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  3513. \key{cmpq} is placed in the special EFLAGS register. This register
  3514. cannot be accessed directly but it can be queried by a number of
  3515. instructions, including the \key{set} instruction. The \key{set}
  3516. instruction puts a \key{1} or \key{0} into its destination depending
  3517. on whether the comparison came out according to the condition code
  3518. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  3519. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  3520. The \key{set} instruction has an annoying quirk in that its
  3521. destination argument must be single byte register, such as \code{al},
  3522. which is part of the \code{rax} register. Thankfully, the
  3523. \key{movzbq} instruction can then be used to move from a single byte
  3524. register to a normal 64-bit register.
  3525. The x86 instruction for conditional jump are relevant to the
  3526. compilation of \key{if} expressions. The \key{JmpIf} instruction
  3527. updates the program counter to point to the instruction after the
  3528. indicated label depending on whether the result in the EFLAGS register
  3529. matches the condition code \itm{cc}, otherwise the \key{JmpIf}
  3530. instruction falls through to the next instruction. The abstract
  3531. syntax for \key{JmpIf} differs from the concrete syntax for x86 in
  3532. that it separates the instruction name from the condition code. For
  3533. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  3534. the \key{JmpIf} instruction relies on the EFLAGS register, it is
  3535. common for the \key{JmpIf} to be immediately preceded by a \key{cmpq}
  3536. instruction to set the EFLAGS register.
  3537. \section{The $C_1$ Intermediate Language}
  3538. \label{sec:c1}
  3539. As with $R_1$, we compile $R_2$ to a C-like intermediate language, but
  3540. we need to grow that intermediate language to handle the new features
  3541. in $R_2$: Booleans and conditional expressions.
  3542. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of
  3543. $C_1$ and Figure~\ref{fig:c1-syntax} defines the abstract syntax. In
  3544. particular, we add logical and comparison operators to the $\Exp$
  3545. non-terminal and the literals \key{\#t} and \key{\#f} to the $\Arg$
  3546. non-terminal. Regarding control flow, $C_1$ differs considerably from
  3547. $R_2$. Instead of \key{if} expressions, $C_1$ has \key{goto} and
  3548. conditional \key{goto} in the grammar for $\Tail$. This means that a
  3549. sequence of statements may now end with a \code{goto} or a conditional
  3550. \code{goto}. The conditional \code{goto} jumps to one of two labels
  3551. depending on the outcome of the comparison. In
  3552. Section~\ref{sec:explicate-control-r2} we discuss how to translate
  3553. from $R_2$ to $C_1$, bridging this gap between \key{if} expressions
  3554. and \key{goto}'s.
  3555. \begin{figure}[tbp]
  3556. \fbox{
  3557. \begin{minipage}{0.96\textwidth}
  3558. \small
  3559. \[
  3560. \begin{array}{lcl}
  3561. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  3562. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3563. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  3564. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  3565. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  3566. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  3567. \mid \key{goto}~\itm{label}\key{;}\\
  3568. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  3569. C_1 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)^{+} }
  3570. \end{array}
  3571. \]
  3572. \end{minipage}
  3573. }
  3574. \caption{The concrete syntax of the $C_1$ intermediate language.}
  3575. \label{fig:c1-concrete-syntax}
  3576. \end{figure}
  3577. \begin{figure}[tp]
  3578. \fbox{
  3579. \begin{minipage}{0.96\textwidth}
  3580. \small
  3581. \[
  3582. \begin{array}{lcl}
  3583. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  3584. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3585. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  3586. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  3587. &\mid& \UNIOP{\key{'not}}{\Atm}
  3588. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  3589. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  3590. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  3591. \mid \GOTO{\itm{label}} \\
  3592. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  3593. C_1 & ::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}^{+}}}}
  3594. \end{array}
  3595. \]
  3596. \end{minipage}
  3597. }
  3598. \caption{The abstract syntax of $C_1$, extending $C_0$ with Booleans and conditionals.}
  3599. \label{fig:c1-syntax}
  3600. \end{figure}
  3601. \section{Explicate Control}
  3602. \label{sec:explicate-control-r2}
  3603. Recall that the purpose of \code{explicate-control} is to make the
  3604. order of evaluation explicit in the syntax of the program. With the
  3605. addition of \key{if} in $R_2$ this get more interesting.
  3606. As a motivating example, consider the following program that has an
  3607. \key{if} expression nested in the predicate of another \key{if}.
  3608. % s1_38.rkt
  3609. \begin{center}
  3610. \begin{minipage}{0.96\textwidth}
  3611. \begin{lstlisting}
  3612. (if (if (eq? (read) 1)
  3613. (eq? (read) 0)
  3614. (eq? (read) 2))
  3615. (+ 10 32)
  3616. (+ 700 77))
  3617. \end{lstlisting}
  3618. \end{minipage}
  3619. \end{center}
  3620. %
  3621. The naive way to compile \key{if} and \key{eq?} would be to handle
  3622. each of them in isolation, regardless of their context. Each
  3623. \key{eq?} would be translated into a \key{cmpq} instruction followed
  3624. by a couple instructions to move the result from the EFLAGS register
  3625. into a general purpose register or stack location. Each \key{if} would
  3626. be translated into the combination of a \key{cmpq} and \key{JmpIf}.
  3627. However, if we take context into account we can do better and reduce
  3628. the use of \key{cmpq} and EFLAG-accessing instructions.
  3629. One idea is to try and reorganize the code at the level of $R_2$,
  3630. pushing the outer \key{if} inside the inner one. This would yield the
  3631. following code.
  3632. \begin{center}
  3633. \begin{minipage}{0.96\textwidth}
  3634. \begin{lstlisting}
  3635. (if (eq? (read) 1)
  3636. (if (eq? (read) 0)
  3637. (+ 10 32)
  3638. (+ 700 77))
  3639. (if (eq? (read) 2))
  3640. (+ 10 32)
  3641. (+ 700 77))
  3642. \end{lstlisting}
  3643. \end{minipage}
  3644. \end{center}
  3645. Unfortunately, this approach duplicates the two branches, and a
  3646. compiler must never duplicate code!
  3647. We need a way to perform the above transformation, but without
  3648. duplicating code. The solution is straightforward if we think at the
  3649. level of x86 assembly: we can label the code for each of the branches
  3650. and insert jumps in all the places that need to execute the
  3651. branches. Put another way, we need to move away from abstract syntax
  3652. \emph{trees} and instead use \emph{graphs}. In particular, we shall
  3653. use a standard program representation called a \emph{control flow
  3654. graph} (CFG), due to Frances Elizabeth \citet{Allen:1970uq}. Each
  3655. vertex is a labeled sequence of code, called a \emph{basic block}, and
  3656. each edge represents a jump to another block. The \key{Program}
  3657. construct of $C_0$ and $C_1$ contains a control flow graph represented
  3658. as an alist mapping labels to basic blocks. Each block is
  3659. represented by the $\Tail$ non-terminal.
  3660. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  3661. \code{remove-complex-opera*} pass and then the
  3662. \code{explicate-control} pass on the example program. We walk through
  3663. the output program and then discuss the algorithm.
  3664. %
  3665. Following the order of evaluation in the output of
  3666. \code{remove-complex-opera*}, we first have the \code{(read)} and
  3667. comparison to \code{1} from the predicate of the inner \key{if}. In
  3668. the output of \code{explicate-control}, in the \code{start} block,
  3669. this becomes a \code{(read)} followed by a conditional \key{goto} to
  3670. either \code{block61} or \code{block62}. Each of these contains the
  3671. translations of the code \code{(eq? (read) 0)} and \code{(eq? (read)
  3672. 1)}, respectively. Regarding \code{block61}, we start with the
  3673. \code{(read)} and comparison to \code{0} and then have a conditional
  3674. goto, either to \code{block59} or \code{block60}, which indirectly
  3675. take us to \code{block55} and \code{block56}, the two branches of the
  3676. outer \key{if}, i.e., \code{(+ 10 32)} and \code{(+ 700 77)}. The
  3677. story for \code{block62} is similar.
  3678. \begin{figure}[tbp]
  3679. \begin{tabular}{lll}
  3680. \begin{minipage}{0.4\textwidth}
  3681. \begin{lstlisting}
  3682. (if (if (eq? (read) 1)
  3683. (eq? (read) 0)
  3684. (eq? (read) 2))
  3685. (+ 10 32)
  3686. (+ 700 77))
  3687. \end{lstlisting}
  3688. \hspace{40pt}$\Downarrow$
  3689. \begin{lstlisting}
  3690. (if (if (let ([tmp52 (read)])
  3691. (eq? tmp52 1))
  3692. (let ([tmp53 (read)])
  3693. (eq? tmp53 0))
  3694. (let ([tmp54 (read)])
  3695. (eq? tmp54 2)))
  3696. (+ 10 32)
  3697. (+ 700 77))
  3698. \end{lstlisting}
  3699. \end{minipage}
  3700. &
  3701. $\Rightarrow$
  3702. &
  3703. \begin{minipage}{0.55\textwidth}
  3704. \begin{lstlisting}
  3705. block62:
  3706. tmp54 = (read);
  3707. if (eq? tmp54 2) then
  3708. goto block59;
  3709. else
  3710. goto block60;
  3711. block61:
  3712. tmp53 = (read);
  3713. if (eq? tmp53 0) then
  3714. goto block57;
  3715. else
  3716. goto block58;
  3717. block60:
  3718. goto block56;
  3719. block59:
  3720. goto block55;
  3721. block58:
  3722. goto block56;
  3723. block57:
  3724. goto block55;
  3725. block56:
  3726. return (+ 700 77);
  3727. block55:
  3728. return (+ 10 32);
  3729. start:
  3730. tmp52 = (read);
  3731. if (eq? tmp52 1) then
  3732. goto block61;
  3733. else
  3734. goto block62;
  3735. \end{lstlisting}
  3736. \end{minipage}
  3737. \end{tabular}
  3738. \caption{Example translation from $R_2$ to $C_1$
  3739. via the \code{explicate-control}.}
  3740. \label{fig:explicate-control-s1-38}
  3741. \end{figure}
  3742. The nice thing about the output of \code{explicate-control} is that
  3743. there are no unnecessary uses of \code{eq?} and every use of
  3744. \code{eq?} is part of a conditional jump. The down-side of this output
  3745. is that it includes trivial blocks, such as \code{block57} through
  3746. \code{block60}, that only jump to another block. We discuss a solution
  3747. to this problem in Section~\ref{sec:opt-jumps}.
  3748. Recall that in Section~\ref{sec:explicate-control-r1} we implement
  3749. \code{explicate-control} for $R_1$ using two mutually recursive
  3750. functions, \code{explicate-tail} and \code{explicate-assign}. The
  3751. former function translates expressions in tail position whereas the
  3752. later function translates expressions on the right-hand-side of a
  3753. \key{let}. With the addition of \key{if} expression in $R_2$ we have a
  3754. new kind of context to deal with: the predicate position of the
  3755. \key{if}. We need another function, \code{explicate-pred}, that takes
  3756. an $R_2$ expression and two pieces of $C_1$ code (two $\Tail$'s) for
  3757. the then-branch and else-branch. The output of \code{explicate-pred}
  3758. is a $C_1$ $\Tail$ and a list of formerly \key{let}-bound variables.
  3759. Note that the three explicate functions need to construct a
  3760. control-flow graph, which we recommend they do via updates to a global
  3761. variable.
  3762. In the following paragraphs we consider the specific additions to the
  3763. \code{explicate-tail} and \code{explicate-assign} functions, and some
  3764. of cases for the \code{explicate-pred} function.
  3765. The \code{explicate-tail} function needs an additional case for
  3766. \key{if}. The branches of the \key{if} inherit the current context, so
  3767. they are in tail position. Let $B_1$ be the result of
  3768. \code{explicate-tail} on the ``then'' branch of the \key{if} and $B_2$
  3769. be the result of apply \code{explicate-tail} to the ``else''
  3770. branch. Then the \key{if} as a whole translates to the block $B_3$
  3771. which is the result of applying \code{explicate-pred} to the predicate
  3772. $\itm{cnd}$ and the blocks $B_1$ and $B_2$.
  3773. \[
  3774. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  3775. \]
  3776. Next we consider the case for \key{if} in the \code{explicate-assign}
  3777. function. The context of the \key{if} is an assignment to some
  3778. variable $x$ and then the control continues to some block $B_1$. The
  3779. code that we generate for the ``then'' and ``else'' branches needs to
  3780. continue to $B_1$, so we add $B_1$ to the control flow graph with a
  3781. fresh label $\ell_1$. Again, the branches of the \key{if} inherit the
  3782. current context, so that are in assignment positions. Let $B_2$ be
  3783. the result of applying \code{explicate-assign} to the ``then'' branch,
  3784. variable $x$, and the block \GOTO{$\ell_1$}. Let $B_3$ be the result
  3785. of applying \code{explicate-assign} to the ``else'' branch, variable
  3786. $x$, and the block \GOTO{$\ell_1$}. The \key{if} translates to the
  3787. block $B_4$ which is the result of applying \code{explicate-pred} to
  3788. the predicate $\itm{cnd}$ and the blocks $B_2$ and $B_3$.
  3789. \[
  3790. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  3791. \]
  3792. The function \code{explicate-pred} will need a case for every
  3793. expression that can have type \code{Boolean}. We detail a few cases
  3794. here and leave the rest for the reader. The input to this function is
  3795. an expression and two blocks, $B_1$ and $B_2$, for the two branches of
  3796. the enclosing \key{if}. Suppose the expression is the Boolean
  3797. \code{\#t}. Then we can perform a kind of partial evaluation and
  3798. translate it to the ``then'' branch $B_1$. Likewise, we translate
  3799. \code{\#f} to the ``else`` branch $B_2$.
  3800. \[
  3801. \key{\#t} \quad\Rightarrow\quad B_1,
  3802. \qquad\qquad\qquad
  3803. \key{\#f} \quad\Rightarrow\quad B_2
  3804. \]
  3805. Next, suppose the expression is a less-than comparison. We translate
  3806. it to a conditional \code{goto}. We need labels for the two branches
  3807. $B_1$ and $B_2$, so we add those blocks to the control flow graph and
  3808. obtain some labels $\ell_1$ and $\ell_2$. The translation of the
  3809. less-than comparison is as follows.
  3810. \[
  3811. (\key{<}~e_1~e_2) \quad\Rightarrow\quad
  3812. \begin{array}{l}
  3813. \key{if}~(\key{<}~e_1~e_2)~\key{then} \\
  3814. \qquad\key{goto}~\ell_1\key{;}\\
  3815. \key{else}\\
  3816. \qquad\key{goto}~\ell_2\key{;}
  3817. \end{array}
  3818. \]
  3819. The case for \key{if} in \code{explicate-pred} is particularly
  3820. illuminating as it deals with the challenges that we discussed above
  3821. regarding the example of the nested \key{if} expressions. Again, we
  3822. add the two branches $B_1$ and $B_2$ to the control flow graph and
  3823. obtain the labels $\ell_1$ and $\ell_2$. The ``then'' and ``else''
  3824. branches of the current \key{if} inherit their context from the
  3825. current one, that is, predicate context. So we apply
  3826. \code{explicate-pred} to the ``then'' branch with the two blocks
  3827. \GOTO{$\ell_1$} and \GOTO{$\ell_2$} to obtain $B_3$. Proceed in a
  3828. similar way with the ``else'' branch to obtain $B_4$. Finally, we
  3829. apply \code{explicate-pred} to the predicate of hte \code{if} and the
  3830. blocks $B_3$ and $B_4$ to obtain the result $B_5$.
  3831. \[
  3832. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  3833. \quad\Rightarrow\quad
  3834. B_5
  3835. \]
  3836. \begin{exercise}\normalfont
  3837. Implement the pass \code{explicate-control} by adding the cases for
  3838. \key{if} to the functions for tail and assignment contexts, and
  3839. implement \code{explicate-pred} for predicate contexts. Create test
  3840. cases that exercise all of the new cases in the code for this pass.
  3841. \end{exercise}
  3842. \section{Select Instructions}
  3843. \label{sec:select-r2}
  3844. Recall that the \code{select-instructions} pass lowers from our
  3845. $C$-like intermediate representation to the pseudo-x86 language, which
  3846. is suitable for conducting register allocation. The pass is
  3847. implemented using three auxiliary functions, one for each of the
  3848. non-terminals $\Atm$, $\Stmt$, and $\Tail$.
  3849. For $\Atm$, we have new cases for the Booleans. We take the usual
  3850. approach of encoding them as integers, with true as 1 and false as 0.
  3851. \[
  3852. \key{\#t} \Rightarrow \key{1}
  3853. \qquad
  3854. \key{\#f} \Rightarrow \key{0}
  3855. \]
  3856. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  3857. be implemented in terms of \code{xorq} as we discussed at the
  3858. beginning of this section. Given an assignment
  3859. $\itm{var}$ \key{=} \key{(not} $\Arg$\key{);},
  3860. if the left-hand side $\itm{var}$ is
  3861. the same as $\Arg$, then just the \code{xorq} suffices.
  3862. \[
  3863. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  3864. \quad\Rightarrow\quad
  3865. \key{xorq}~\key{\$}1\key{,}~\Var
  3866. \]
  3867. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  3868. semantics of x86. Let $\Arg'$ be the result of recursively processing
  3869. $\Arg$. Then we have
  3870. \[
  3871. \Var~\key{=}~ \key{(not}\; \Arg\key{);}
  3872. \quad\Rightarrow\quad
  3873. \begin{array}{l}
  3874. \key{movq}~\Arg'\key{,}~\Var\\
  3875. \key{xorq}~\key{\$}1\key{,}~\Var
  3876. \end{array}
  3877. \]
  3878. Next consider the cases for \code{eq?} and less-than comparison.
  3879. Translating these operations to x86 is slightly involved due to the
  3880. unusual nature of the \key{cmpq} instruction discussed above. We
  3881. recommend translating an assignment from \code{eq?} into the following
  3882. sequence of three instructions. \\
  3883. \begin{tabular}{lll}
  3884. \begin{minipage}{0.4\textwidth}
  3885. \begin{lstlisting}
  3886. |$\Var$| = (eq? |$\Arg_1$| |$\Arg_2$|);
  3887. \end{lstlisting}
  3888. \end{minipage}
  3889. &
  3890. $\Rightarrow$
  3891. &
  3892. \begin{minipage}{0.4\textwidth}
  3893. \begin{lstlisting}
  3894. cmpq |$\Arg'_2$|, |$\Arg'_1$|
  3895. sete %al
  3896. movzbq %al, |$\Var$|
  3897. \end{lstlisting}
  3898. \end{minipage}
  3899. \end{tabular} \\
  3900. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  3901. and conditional \key{goto}. Both are straightforward to handle. A
  3902. \key{goto} becomes a jump instruction.
  3903. \[
  3904. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  3905. \]
  3906. A conditional \key{goto} becomes a compare instruction followed
  3907. by a conditional jump (for ``then'') and the fall-through is
  3908. to a regular jump (for ``else'').\\
  3909. \begin{tabular}{lll}
  3910. \begin{minipage}{0.4\textwidth}
  3911. \begin{lstlisting}
  3912. if (eq? |$\Arg_1$| |$\Arg_2$|) then
  3913. goto |$\ell_1$|;
  3914. else
  3915. goto |$\ell_2$|;
  3916. \end{lstlisting}
  3917. \end{minipage}
  3918. &
  3919. $\Rightarrow$
  3920. &
  3921. \begin{minipage}{0.4\textwidth}
  3922. \begin{lstlisting}
  3923. cmpq |$\Arg'_2$| |$\Arg'_1$|
  3924. je |$\ell_1$|
  3925. jmp |$\ell_2$|
  3926. \end{lstlisting}
  3927. \end{minipage}
  3928. \end{tabular} \\
  3929. \begin{exercise}\normalfont
  3930. Expand your \code{select-instructions} pass to handle the new features
  3931. of the $R_2$ language. Test the pass on all the examples you have
  3932. created and make sure that you have some test programs that use the
  3933. \code{eq?} and \code{<} operators, creating some if necessary. Test
  3934. the output using the \code{interp-x86} interpreter
  3935. (Appendix~\ref{appendix:interp}).
  3936. \end{exercise}
  3937. \section{Register Allocation}
  3938. \label{sec:register-allocation-r2}
  3939. The changes required for $R_2$ affect liveness analysis, building the
  3940. interference graph, and assigning homes, but the graph coloring
  3941. algorithm itself does not change.
  3942. \subsection{Liveness Analysis}
  3943. \label{sec:liveness-analysis-r2}
  3944. Recall that for $R_1$ we implemented liveness analysis for a single
  3945. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  3946. addition of \key{if} expressions to $R_2$, \code{explicate-control}
  3947. produces many basic blocks arranged in a control-flow graph. The first
  3948. question we need to consider is: what order should we process the
  3949. basic blocks? Recall that to perform liveness analysis, we need to
  3950. know the live-after set. If a basic block has no successor blocks
  3951. (i.e. no out-edges in the control flow graph), then it has an empty
  3952. live-after set and we can immediately apply liveness analysis to
  3953. it. If a basic block has some successors, then we need to complete
  3954. liveness analysis on those blocks first. Furthermore, we know that
  3955. the control flow graph does not contain any cycles because $R_2$ does
  3956. not include loops
  3957. %
  3958. \footnote{If we were to add loops to the language, then the CFG could
  3959. contain cycles and we would instead need to use the classic worklist
  3960. algorithm for computing the fixed point of the liveness
  3961. analysis~\citep{Aho:1986qf}.}.
  3962. %
  3963. Returning to the question of what order should we process the basic
  3964. blocks, the answer is reverse topological order. We recommend using
  3965. the \code{tsort} (topological sort) and \code{transpose} functions of
  3966. the Racket \code{graph} package to obtain this ordering.
  3967. The next question is how to compute the live-after set of a block
  3968. given the live-before sets of all its successor blocks. (There can be
  3969. more than one because of conditional jumps.) During compilation we do
  3970. not know which way a conditional jump will go, so we do not know which
  3971. of the successor's live-before set to use. The solution to this
  3972. challenge is based on the observation that there is no harm to the
  3973. correctness of the compiler if we classify more variables as live than
  3974. the ones that are truly live during a particular execution of the
  3975. block. Thus, we can take the union of the live-before sets from all
  3976. the successors to be the live-after set for the block. Once we have
  3977. computed the live-after set, we can proceed to perform liveness
  3978. analysis on the block just as we did in
  3979. Section~\ref{sec:liveness-analysis-r1}.
  3980. The helper functions for computing the variables in an instruction's
  3981. argument and for computing the variables read-from ($R$) or written-to
  3982. ($W$) by an instruction need to be updated to handle the new kinds of
  3983. arguments and instructions in x86$_1$.
  3984. \subsection{Build Interference}
  3985. \label{sec:build-interference-r2}
  3986. Many of the new instructions in x86$_1$ can be handled in the same way
  3987. as the instructions in x86$_0$. Thus, if your code was already quite
  3988. general, it will not need to be changed to handle the new
  3989. instructions. If you code is not general enough, I recommend that you
  3990. change your code to be more general. For example, you can factor out
  3991. the computing of the the read and write sets for each kind of
  3992. instruction into two auxiliary functions.
  3993. Note that the \key{movzbq} instruction requires some special care,
  3994. just like the \key{movq} instruction. See rule number 3 in
  3995. Section~\ref{sec:build-interference}.
  3996. %% \subsection{Assign Homes}
  3997. %% \label{sec:assign-homes-r2}
  3998. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  3999. %% to be updated to handle the \key{if} statement, simply by recursively
  4000. %% processing the child nodes. Hopefully your code already handles the
  4001. %% other new instructions, but if not, you can generalize your code.
  4002. \begin{exercise}\normalfont
  4003. Update the \code{register-allocation} pass so that it works for $R_2$
  4004. and test your compiler using your previously created programs on the
  4005. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4006. \end{exercise}
  4007. \section{Patch Instructions}
  4008. The second argument of the \key{cmpq} instruction must not be an
  4009. immediate value (such as an integer). So if you are comparing two
  4010. immediates, we recommend inserting a \key{movq} instruction to put the
  4011. second argument in \key{rax}.
  4012. %
  4013. The second argument of the \key{movzbq} must be a register.
  4014. %
  4015. There are no special restrictions on the x86 instructions \key{JmpIf}
  4016. and \key{Jmp}.
  4017. \begin{exercise}\normalfont
  4018. Update \code{patch-instructions} to handle the new x86 instructions.
  4019. Test your compiler using your previously created programs on the
  4020. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4021. \end{exercise}
  4022. \section{An Example Translation}
  4023. Figure~\ref{fig:if-example-x86} shows a simple example program in
  4024. $R_2$ translated to x86, showing the results of
  4025. \code{explicate-control}, \code{select-instructions}, and the final
  4026. x86 assembly code.
  4027. \begin{figure}[tbp]
  4028. \begin{tabular}{lll}
  4029. \begin{minipage}{0.5\textwidth}
  4030. % s1_20.rkt
  4031. \begin{lstlisting}
  4032. (if (eq? (read) 1) 42 0)
  4033. \end{lstlisting}
  4034. $\Downarrow$
  4035. \begin{lstlisting}
  4036. start:
  4037. tmp7951 = (read);
  4038. if (eq? tmp7951 1) then
  4039. goto block7952;
  4040. else
  4041. goto block7953;
  4042. block7952:
  4043. return 42;
  4044. block7953:
  4045. return 0;
  4046. \end{lstlisting}
  4047. $\Downarrow$
  4048. \begin{lstlisting}
  4049. start:
  4050. callq read_int
  4051. movq %rax, tmp7951
  4052. cmpq $1, tmp7951
  4053. je block7952
  4054. jmp block7953
  4055. block7953:
  4056. movq $0, %rax
  4057. jmp conclusion
  4058. block7952:
  4059. movq $42, %rax
  4060. jmp conclusion
  4061. \end{lstlisting}
  4062. \end{minipage}
  4063. &
  4064. $\Rightarrow\qquad$
  4065. \begin{minipage}{0.4\textwidth}
  4066. \begin{lstlisting}
  4067. start:
  4068. callq read_int
  4069. movq %rax, %rcx
  4070. cmpq $1, %rcx
  4071. je block7952
  4072. jmp block7953
  4073. block7953:
  4074. movq $0, %rax
  4075. jmp conclusion
  4076. block7952:
  4077. movq $42, %rax
  4078. jmp conclusion
  4079. .globl main
  4080. main:
  4081. pushq %rbp
  4082. movq %rsp, %rbp
  4083. pushq %r13
  4084. pushq %r12
  4085. pushq %rbx
  4086. pushq %r14
  4087. subq $0, %rsp
  4088. jmp start
  4089. conclusion:
  4090. addq $0, %rsp
  4091. popq %r14
  4092. popq %rbx
  4093. popq %r12
  4094. popq %r13
  4095. popq %rbp
  4096. retq
  4097. \end{lstlisting}
  4098. \end{minipage}
  4099. \end{tabular}
  4100. \caption{Example compilation of an \key{if} expression to x86.}
  4101. \label{fig:if-example-x86}
  4102. \end{figure}
  4103. \begin{figure}[p]
  4104. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4105. \node (R2) at (0,2) {\large $R_2$};
  4106. \node (R2-2) at (3,2) {\large $R_2$};
  4107. \node (R2-3) at (6,2) {\large $R_2$};
  4108. \node (R2-4) at (9,2) {\large $R_2$};
  4109. \node (R2-5) at (12,2) {\large $R_2$};
  4110. \node (C1-1) at (6,0) {\large $C_1$};
  4111. %\node (C1-2) at (3,0) {\large $C_1$};
  4112. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  4113. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  4114. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}$};
  4115. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  4116. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  4117. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  4118. \path[->,bend left=15] (R2) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R2-2);
  4119. \path[->,bend left=15] (R2-2) edge [above] node {\ttfamily\footnotesize\color{red} shrink} (R2-3);
  4120. \path[->,bend left=15] (R2-3) edge [above] node {\ttfamily\footnotesize uniquify} (R2-4);
  4121. \path[->,bend left=15] (R2-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R2-5);
  4122. \path[->,bend left=15] (R2-5) edge [right] node {\ttfamily\footnotesize\color{red} explicate-control} (C1-1);
  4123. %\path[->,bend right=15] (C1-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C1-2);
  4124. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize\color{red} select-instructions} (x86-2);
  4125. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  4126. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  4127. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4128. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  4129. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize\color{red} print-x86 } (x86-5);
  4130. \end{tikzpicture}
  4131. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  4132. \label{fig:R2-passes}
  4133. \end{figure}
  4134. Figure~\ref{fig:R2-passes} lists all the passes needed for the
  4135. compilation of $R_2$.
  4136. \section{Challenge: Optimize Jumps}
  4137. \label{sec:opt-jumps}
  4138. Recall that in the example output of \code{explicate-control} in
  4139. Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  4140. \code{block60} are trivial blocks, they do nothing but jump to another
  4141. block. The first goal of this challenge assignment is to remove those
  4142. blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  4143. \code{explicate-control} on the left and shows the result of bypassing
  4144. the trivial blocks on the right. Let us focus on \code{block61}. The
  4145. \code{then} branch jumps to \code{block57}, which in turn jumps to
  4146. \code{block55}. The optimized code on the right of
  4147. Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  4148. \code{then} branch jumping directly to \code{block55}. The story is
  4149. similar for the \code{else} branch, as well as for the two branches in
  4150. \code{block62}. After the jumps in \code{block61} and \code{block62}
  4151. have been optimized in this way, there are no longer any jumps to
  4152. blocks \code{block57} through \code{block60}, so they can be removed.
  4153. \begin{figure}[tbp]
  4154. \begin{tabular}{lll}
  4155. \begin{minipage}{0.4\textwidth}
  4156. \begin{lstlisting}
  4157. block62:
  4158. tmp54 = (read);
  4159. if (eq? tmp54 2) then
  4160. goto block59;
  4161. else
  4162. goto block60;
  4163. block61:
  4164. tmp53 = (read);
  4165. if (eq? tmp53 0) then
  4166. goto block57;
  4167. else
  4168. goto block58;
  4169. block60:
  4170. goto block56;
  4171. block59:
  4172. goto block55;
  4173. block58:
  4174. goto block56;
  4175. block57:
  4176. goto block55;
  4177. block56:
  4178. return (+ 700 77);
  4179. block55:
  4180. return (+ 10 32);
  4181. start:
  4182. tmp52 = (read);
  4183. if (eq? tmp52 1) then
  4184. goto block61;
  4185. else
  4186. goto block62;
  4187. \end{lstlisting}
  4188. \end{minipage}
  4189. &
  4190. $\Rightarrow$
  4191. &
  4192. \begin{minipage}{0.55\textwidth}
  4193. \begin{lstlisting}
  4194. block62:
  4195. tmp54 = (read);
  4196. if (eq? tmp54 2) then
  4197. goto block55;
  4198. else
  4199. goto block56;
  4200. block61:
  4201. tmp53 = (read);
  4202. if (eq? tmp53 0) then
  4203. goto block55;
  4204. else
  4205. goto block56;
  4206. block56:
  4207. return (+ 700 77);
  4208. block55:
  4209. return (+ 10 32);
  4210. start:
  4211. tmp52 = (read);
  4212. if (eq? tmp52 1) then
  4213. goto block61;
  4214. else
  4215. goto block62;
  4216. \end{lstlisting}
  4217. \end{minipage}
  4218. \end{tabular}
  4219. \caption{Optimize jumps by removing trivial blocks.}
  4220. \label{fig:optimize-jumps}
  4221. \end{figure}
  4222. The name of this pass is \code{optimize-jumps}. We recommend
  4223. implementing this pass in two phases. The first phrase builds a hash
  4224. table that maps labels to possibly improved labels. The second phase
  4225. changes the target of each \code{goto} to use the improved label. If
  4226. the label is for a trivial block, then the hash table should map the
  4227. label to the first non-trivial block that can be reached from this
  4228. label by jumping through trivial blocks. If the label is for a
  4229. non-trivial block, then the hash table should map the label to itself;
  4230. we do not want to change jumps to non-trivial blocks.
  4231. The first phase can be accomplished by constructing an empty hash
  4232. table, call it \code{short-cut}, and then iterating over the control
  4233. flow graph. Each time you encouter a block that is just a \code{goto},
  4234. then update the hash table, mapping the block's source to the target
  4235. of the \code{goto}. Also, the hash table may already have mapped some
  4236. labels to the block's source, to you must iterate through the hash
  4237. table and update all of those so that they instead map to the target
  4238. of the \code{goto}.
  4239. For the second phase, we recommend iterating through the $\Tail$ of
  4240. each block in the program, updating the target of every \code{goto}
  4241. according to the mapping in \code{short-cut}.
  4242. \begin{exercise}\normalfont
  4243. Implement the \code{optimize-jumps} pass and check that it remove
  4244. trivial blocks in a few example programs. Then check that your
  4245. compiler still passes all of your tests.
  4246. \end{exercise}
  4247. There is another opportunity for optimizing jumps that is apparent in
  4248. the example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  4249. end with a jump to \code{block7953} and there are no other jumps to
  4250. \code{block7953} in the rest of the program. In this situation we can
  4251. avoid the runtime overhead of this jump by merging \code{block7953}
  4252. into the preceeding block, in this case the \code{start} block.
  4253. Figure~\ref{fig:remove-jumps} shows the output of
  4254. \code{select-instructions} on the left and the result of this
  4255. optimization on the right.
  4256. \begin{figure}[tbp]
  4257. \begin{tabular}{lll}
  4258. \begin{minipage}{0.5\textwidth}
  4259. % s1_20.rkt
  4260. \begin{lstlisting}
  4261. start:
  4262. callq read_int
  4263. movq %rax, tmp7951
  4264. cmpq $1, tmp7951
  4265. je block7952
  4266. jmp block7953
  4267. block7953:
  4268. movq $0, %rax
  4269. jmp conclusion
  4270. block7952:
  4271. movq $42, %rax
  4272. jmp conclusion
  4273. \end{lstlisting}
  4274. \end{minipage}
  4275. &
  4276. $\Rightarrow\qquad$
  4277. \begin{minipage}{0.4\textwidth}
  4278. \begin{lstlisting}
  4279. start:
  4280. callq read_int
  4281. movq %rax, tmp7951
  4282. cmpq $1, tmp7951
  4283. je block7952
  4284. movq $0, %rax
  4285. jmp conclusion
  4286. block7952:
  4287. movq $42, %rax
  4288. jmp conclusion
  4289. \end{lstlisting}
  4290. \end{minipage}
  4291. \end{tabular}
  4292. \caption{Merging basic blocks by removing unnecessary jumps.}
  4293. \label{fig:remove-jumps}
  4294. \end{figure}
  4295. \begin{exercise}\normalfont
  4296. Implement a pass named \code{remove-jumps} that merges basic blocks
  4297. into their preceeding basic block, when there is only one preceeding
  4298. block. Check that your pass accomplishes this goal on several test
  4299. programs and check that your compiler passes all of your tests.
  4300. \end{exercise}
  4301. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4302. \chapter{Tuples and Garbage Collection}
  4303. \label{ch:tuples}
  4304. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  4305. things to discuss in this chapter. \\ --Jeremy}
  4306. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  4307. all the IR grammars are spelled out! \\ --Jeremy}
  4308. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  4309. but keep type annotations on vector creation and local variables, function
  4310. parameters, etc. \\ --Jeremy}
  4311. \margincomment{\scriptsize Be more explicit about how to deal with
  4312. the root stack. \\ --Jeremy}
  4313. In this chapter we study the implementation of mutable tuples (called
  4314. ``vectors'' in Racket). This language feature is the first to use the
  4315. computer's \emph{heap} because the lifetime of a Racket tuple is
  4316. indefinite, that is, a tuple lives forever from the programmer's
  4317. viewpoint. Of course, from an implementer's viewpoint, it is important
  4318. to reclaim the space associated with a tuple when it is no longer
  4319. needed, which is why we also study \emph{garbage collection}
  4320. techniques in this chapter.
  4321. Section~\ref{sec:r3} introduces the $R_3$ language including its
  4322. interpreter and type checker. The $R_3$ language extends the $R_2$
  4323. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  4324. \code{void} value. The reason for including the later is that the
  4325. \code{vector-set!} operation returns a value of type
  4326. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  4327. called the \code{Unit} type in the programming languages
  4328. literature. Racket's \code{Void} type is inhabited by a single value
  4329. \code{void} which corresponds to \code{unit} or \code{()} in the
  4330. literature~\citep{Pierce:2002hj}.}.
  4331. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  4332. copying live objects back and forth between two halves of the
  4333. heap. The garbage collector requires coordination with the compiler so
  4334. that it can see all of the \emph{root} pointers, that is, pointers in
  4335. registers or on the procedure call stack.
  4336. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  4337. discuss all the necessary changes and additions to the compiler
  4338. passes, including a new compiler pass named \code{expose-allocation}.
  4339. \section{The $R_3$ Language}
  4340. \label{sec:r3}
  4341. Figure~\ref{fig:r3-concrete-syntax} defines the concrete syntax for
  4342. $R_3$ and Figure~\ref{fig:r3-syntax} defines the abstract syntax. The
  4343. $R_3$ language includes three new forms for creating a tuple, reading
  4344. an element of a tuple, and writing to an element of a tuple. The
  4345. program in Figure~\ref{fig:vector-eg} shows the usage of tuples in
  4346. Racket. We create a 3-tuple \code{t} and a 1-tuple. The 1-tuple is
  4347. stored at index $2$ of the 3-tuple, demonstrating that tuples are
  4348. first-class values. The element at index $1$ of \code{t} is
  4349. \code{\#t}, so the ``then'' branch of the \key{if} is taken. The
  4350. element at index $0$ of \code{t} is $40$, to which we add $2$, the
  4351. element at index $0$ of the 1-tuple. So the result of the program is
  4352. $42$.
  4353. \begin{figure}[tbp]
  4354. \begin{lstlisting}
  4355. (let ([t (vector 40 #t (vector 2))])
  4356. (if (vector-ref t 1)
  4357. (+ (vector-ref t 0)
  4358. (vector-ref (vector-ref t 2) 0))
  4359. 44))
  4360. \end{lstlisting}
  4361. \caption{Example program that creates tuples and reads from them.}
  4362. \label{fig:vector-eg}
  4363. \end{figure}
  4364. \begin{figure}[tbp]
  4365. \centering
  4366. \fbox{
  4367. \begin{minipage}{0.96\textwidth}
  4368. \[
  4369. \begin{array}{lcl}
  4370. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  4371. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}\\
  4372. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4373. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  4374. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  4375. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  4376. \mid (\key{and}\;\Exp\;\Exp)
  4377. \mid (\key{or}\;\Exp\;\Exp)
  4378. \mid (\key{not}\;\Exp) } \\
  4379. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  4380. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  4381. &\mid& (\key{vector}\;\Exp^{+})
  4382. \mid (\key{vector-ref}\;\Exp\;\Int) \\
  4383. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)\\
  4384. &\mid& (\key{void}) \\
  4385. R_3 &::=& \Exp
  4386. \end{array}
  4387. \]
  4388. \end{minipage}
  4389. }
  4390. \caption{The concrete syntax of $R_3$, extending $R_2$
  4391. (Figure~\ref{fig:r2-concrete-syntax}).}
  4392. \label{fig:r3-concrete-syntax}
  4393. \end{figure}
  4394. \begin{figure}[tp]
  4395. \centering
  4396. \fbox{
  4397. \begin{minipage}{0.96\textwidth}
  4398. \[
  4399. \begin{array}{lcl}
  4400. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  4401. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  4402. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  4403. &\mid& \gray{ \ADD{\Exp}{\Exp}
  4404. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  4405. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  4406. &\mid& \gray{ \BOOL{\itm{bool}}
  4407. \mid \AND{\Exp}{\Exp} }\\
  4408. &\mid& \gray{ \OR{\Exp}{\Exp}
  4409. \mid \NOT{\Exp} } \\
  4410. &\mid& \gray{ \BINOP{\code{'}\itm{cmp}}{\Exp}{\Exp}
  4411. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  4412. &\mid& \VECTOR{\Exp} \\
  4413. &\mid& \VECREF{\Exp}{\Int}\\
  4414. &\mid& \VECSET{\Exp}{\Int}{\Exp}\\
  4415. &\mid& \VOID{} \\
  4416. R_3 &::=& \PROGRAM{\key{'()}}{\Exp}
  4417. \end{array}
  4418. \]
  4419. \end{minipage}
  4420. }
  4421. \caption{The abstract syntax of $R_3$.}
  4422. \label{fig:r3-syntax}
  4423. \end{figure}
  4424. Tuples are our first encounter with heap-allocated data, which raises
  4425. several interesting issues. First, variable binding performs a
  4426. shallow-copy when dealing with tuples, which means that different
  4427. variables can refer to the same tuple, i.e., different variables can
  4428. be \emph{aliases} for the same thing. Consider the following example
  4429. in which both \code{t1} and \code{t2} refer to the same tuple. Thus,
  4430. the mutation through \code{t2} is visible when referencing the tuple
  4431. from \code{t1}, so the result of this program is \code{42}.
  4432. \begin{center}
  4433. \begin{minipage}{0.96\textwidth}
  4434. \begin{lstlisting}
  4435. (let ([t1 (vector 3 7)])
  4436. (let ([t2 t1])
  4437. (let ([_ (vector-set! t2 0 42)])
  4438. (vector-ref t1 0))))
  4439. \end{lstlisting}
  4440. \end{minipage}
  4441. \end{center}
  4442. The next issue concerns the lifetime of tuples. Of course, they are
  4443. created by the \code{vector} form, but when does their lifetime end?
  4444. Notice that the grammar in Figure~\ref{fig:r3-syntax} does not include
  4445. an operation for deleting tuples. Furthermore, the lifetime of a tuple
  4446. is not tied to any notion of static scoping. For example, the
  4447. following program returns \code{3} even though the variable \code{t}
  4448. goes out of scope prior to accessing the vector.
  4449. \begin{center}
  4450. \begin{minipage}{0.96\textwidth}
  4451. \begin{lstlisting}
  4452. (vector-ref
  4453. (let ([t (vector 3 7)])
  4454. t)
  4455. 0)
  4456. \end{lstlisting}
  4457. \end{minipage}
  4458. \end{center}
  4459. From the perspective of programmer-observable behavior, tuples live
  4460. forever. Of course, if they really lived forever, then many programs
  4461. would run out of memory.\footnote{The $R_3$ language does not have
  4462. looping or recursive function, so it is nigh impossible to write a
  4463. program in $R_3$ that will run out of memory. However, we add
  4464. recursive functions in the next Chapter!} A Racket implementation
  4465. must therefore perform automatic garbage collection.
  4466. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  4467. $R_3$ language. We define the \code{vector}, \code{vector-ref}, and
  4468. \code{vector-set!} operations for $R_3$ in terms of the corresponding
  4469. operations in Racket. One subtle point is that the \code{vector-set!}
  4470. operation returns the \code{\#<void>} value. The \code{\#<void>} value
  4471. can be passed around just like other values inside an $R_3$ program,
  4472. but there are no operations specific to the the \code{\#<void>} value
  4473. in $R_3$. In contrast, Racket defines the \code{void?} predicate that
  4474. returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  4475. otherwise.
  4476. \begin{figure}[tbp]
  4477. \begin{lstlisting}
  4478. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  4479. (define (interp-op op)
  4480. (match op
  4481. ...
  4482. ['vector vector]
  4483. ['vector-ref vector-ref]
  4484. ['vector-set! vector-set!]
  4485. [else (error 'interp-op "unknown operator")]))
  4486. (define (interp-R3 env)
  4487. (lambda (e)
  4488. (match e
  4489. ...
  4490. [else (error 'interp-R3 "unrecognized expression")]
  4491. )))
  4492. \end{lstlisting}
  4493. \caption{Interpreter for the $R_3$ language.}
  4494. \label{fig:interp-R3}
  4495. \end{figure}
  4496. Figure~\ref{fig:typecheck-R3} shows the type checker for $R_3$, which
  4497. deserves some explanation. As we shall see in Section~\ref{sec:GC}, we
  4498. need to know which variables are pointers into the heap, that is,
  4499. which variables are vectors. Also, when allocating a vector, we need
  4500. to know which elements of the vector are pointers. We can obtain this
  4501. information during type checking. The type checker in
  4502. Figure~\ref{fig:typecheck-R3} not only computes the type of an
  4503. expression, it also wraps every sub-expression $e$ with the form
  4504. $(\key{HasType}~e~T)$, where $T$ is $e$'s type.
  4505. % TODO: UPDATE? -Jeremy
  4506. Subsequently, in the \code{uncover-locals} pass
  4507. (Section~\ref{sec:uncover-locals-r3}) this type information is
  4508. propagated to all variables (including the temporaries generated by
  4509. \code{remove-complex-opera*}).
  4510. \begin{figure}[tbp]
  4511. \begin{lstlisting}
  4512. (define (type-check-exp env)
  4513. (lambda (e)
  4514. (define recur (type-check-exp env))
  4515. (match e
  4516. ...
  4517. [(Void) (values (HasType (Void) 'Void) 'Void)]
  4518. [(Prim 'vector es)
  4519. (define-values (e* t*) (for/lists (e* t*) ([e es])
  4520. (recur e)))
  4521. (let ([t `(Vector ,@t*)])
  4522. (values (HasType (Prim 'vector e*) t) t))]
  4523. [(Prim 'vector-ref (list e (Int i)))
  4524. (define-values (e^ t) (recur e))
  4525. (match t
  4526. [`(Vector ,ts ...)
  4527. (unless (and (exact-nonnegative-integer? i) (< i (length ts)))
  4528. (error 'type-check-exp "invalid index ~a" i))
  4529. (let ([t (list-ref ts i)])
  4530. (values
  4531. (HasType (Prim 'vector-ref (list e^ (HasType (Int i) 'Integer))) t)
  4532. t))]
  4533. [else (error "expected a vector in vector-ref, not" t)])]
  4534. [(Prim 'eq? (list e1 e2))
  4535. (define-values (e1^ T1) (recur e1))
  4536. (define-values (e2^ T2) (recur e2))
  4537. (unless (equal? T1 T2)
  4538. (error "arguments of eq? must have the same type, but are not"
  4539. (list T1 T2)))
  4540. (values (HasType (Prim 'eq? (list e1^ e2^)) 'Boolean) 'Boolean)]
  4541. ...
  4542. )))
  4543. \end{lstlisting}
  4544. \caption{Type checker for the $R_3$ language.}
  4545. \label{fig:typecheck-R3}
  4546. \end{figure}
  4547. \section{Garbage Collection}
  4548. \label{sec:GC}
  4549. Here we study a relatively simple algorithm for garbage collection
  4550. that is the basis of state-of-the-art garbage
  4551. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  4552. particular, we describe a two-space copying
  4553. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  4554. perform the
  4555. copy~\citep{Cheney:1970aa}. Figure~\ref{fig:copying-collector} gives a
  4556. coarse-grained depiction of what happens in a two-space collector,
  4557. showing two time steps, prior to garbage collection on the top and
  4558. after garbage collection on the bottom. In a two-space collector, the
  4559. heap is divided into two parts, the FromSpace and the
  4560. ToSpace. Initially, all allocations go to the FromSpace until there is
  4561. not enough room for the next allocation request. At that point, the
  4562. garbage collector goes to work to make more room.
  4563. The garbage collector must be careful not to reclaim tuples that will
  4564. be used by the program in the future. Of course, it is impossible in
  4565. general to predict what a program will do, but we can over approximate
  4566. the will-be-used tuples by preserving all tuples that could be
  4567. accessed by \emph{any} program given the current computer state. A
  4568. program could access any tuple whose address is in a register or on
  4569. the procedure call stack. These addresses are called the \emph{root
  4570. set}. In addition, a program could access any tuple that is
  4571. transitively reachable from the root set. Thus, it is safe for the
  4572. garbage collector to reclaim the tuples that are not reachable in this
  4573. way.
  4574. So the goal of the garbage collector is twofold:
  4575. \begin{enumerate}
  4576. \item preserve all tuple that are reachable from the root set via a
  4577. path of pointers, that is, the \emph{live} tuples, and
  4578. \item reclaim the memory of everything else, that is, the
  4579. \emph{garbage}.
  4580. \end{enumerate}
  4581. A copying collector accomplishes this by copying all of the live
  4582. objects from the FromSpace into the ToSpace and then performs a slight
  4583. of hand, treating the ToSpace as the new FromSpace and the old
  4584. FromSpace as the new ToSpace. In the example of
  4585. Figure~\ref{fig:copying-collector}, there are three pointers in the
  4586. root set, one in a register and two on the stack. All of the live
  4587. objects have been copied to the ToSpace (the right-hand side of
  4588. Figure~\ref{fig:copying-collector}) in a way that preserves the
  4589. pointer relationships. For example, the pointer in the register still
  4590. points to a 2-tuple whose first element is a 3-tuple and second
  4591. element is a 2-tuple. There are four tuples that are not reachable
  4592. from the root set and therefore do not get copied into the ToSpace.
  4593. (The situation in Figure~\ref{fig:copying-collector}, with a
  4594. cycle, cannot be created by a well-typed program in $R_3$. However,
  4595. creating cycles will be possible once we get to $R_6$. We design
  4596. the garbage collector to deal with cycles to begin with, so we will
  4597. not need to revisit this issue.)
  4598. \begin{figure}[tbp]
  4599. \centering
  4600. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  4601. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  4602. \caption{A copying collector in action.}
  4603. \label{fig:copying-collector}
  4604. \end{figure}
  4605. There are many alternatives to copying collectors (and their older
  4606. siblings, the generational collectors) when its comes to garbage
  4607. collection, such as mark-and-sweep and reference counting. The
  4608. strengths of copying collectors are that allocation is fast (just a
  4609. test and pointer increment), there is no fragmentation, cyclic garbage
  4610. is collected, and the time complexity of collection only depends on
  4611. the amount of live data, and not on the amount of
  4612. garbage~\citep{Wilson:1992fk}. The main disadvantage of two-space
  4613. copying collectors is that they use a lot of space, though that
  4614. problem is ameliorated in generational collectors. Racket and Scheme
  4615. programs tend to allocate many small objects and generate a lot of
  4616. garbage, so copying and generational collectors are a good fit. Of
  4617. course, garbage collection is an active research topic, especially
  4618. concurrent garbage collection~\citep{Tene:2011kx}. Researchers are
  4619. continuously developing new techniques and revisiting old
  4620. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa}.
  4621. \subsection{Graph Copying via Cheney's Algorithm}
  4622. \label{sec:cheney}
  4623. Let us take a closer look at how the copy works. The allocated objects
  4624. and pointers can be viewed as a graph and we need to copy the part of
  4625. the graph that is reachable from the root set. To make sure we copy
  4626. all of the reachable vertices in the graph, we need an exhaustive
  4627. graph traversal algorithm, such as depth-first search or breadth-first
  4628. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  4629. take into account the possibility of cycles by marking which vertices
  4630. have already been visited, so as to ensure termination of the
  4631. algorithm. These search algorithms also use a data structure such as a
  4632. stack or queue as a to-do list to keep track of the vertices that need
  4633. to be visited. We shall use breadth-first search and a trick due to
  4634. \citet{Cheney:1970aa} for simultaneously representing the queue and
  4635. copying tuples into the ToSpace.
  4636. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  4637. copy progresses. The queue is represented by a chunk of contiguous
  4638. memory at the beginning of the ToSpace, using two pointers to track
  4639. the front and the back of the queue. The algorithm starts by copying
  4640. all tuples that are immediately reachable from the root set into the
  4641. ToSpace to form the initial queue. When we copy a tuple, we mark the
  4642. old tuple to indicate that it has been visited. (We discuss the
  4643. marking in Section~\ref{sec:data-rep-gc}.) Note that any pointers
  4644. inside the copied tuples in the queue still point back to the
  4645. FromSpace. Once the initial queue has been created, the algorithm
  4646. enters a loop in which it repeatedly processes the tuple at the front
  4647. of the queue and pops it off the queue. To process a tuple, the
  4648. algorithm copies all the tuple that are directly reachable from it to
  4649. the ToSpace, placing them at the back of the queue. The algorithm then
  4650. updates the pointers in the popped tuple so they point to the newly
  4651. copied tuples. Getting back to Figure~\ref{fig:cheney}, in the first
  4652. step we copy the tuple whose second element is $42$ to the back of the
  4653. queue. The other pointer goes to a tuple that has already been copied,
  4654. so we do not need to copy it again, but we do need to update the
  4655. pointer to the new location. This can be accomplished by storing a
  4656. \emph{forwarding} pointer to the new location in the old tuple, back
  4657. when we initially copied the tuple into the ToSpace. This completes
  4658. one step of the algorithm. The algorithm continues in this way until
  4659. the front of the queue is empty, that is, until the front catches up
  4660. with the back.
  4661. \begin{figure}[tbp]
  4662. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  4663. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  4664. \label{fig:cheney}
  4665. \end{figure}
  4666. \subsection{Data Representation}
  4667. \label{sec:data-rep-gc}
  4668. The garbage collector places some requirements on the data
  4669. representations used by our compiler. First, the garbage collector
  4670. needs to distinguish between pointers and other kinds of data. There
  4671. are several ways to accomplish this.
  4672. \begin{enumerate}
  4673. \item Attached a tag to each object that identifies what type of
  4674. object it is~\citep{McCarthy:1960dz}.
  4675. \item Store different types of objects in different
  4676. regions~\citep{Steele:1977ab}.
  4677. \item Use type information from the program to either generate
  4678. type-specific code for collecting or to generate tables that can
  4679. guide the
  4680. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  4681. \end{enumerate}
  4682. Dynamically typed languages, such as Lisp, need to tag objects
  4683. anyways, so option 1 is a natural choice for those languages.
  4684. However, $R_3$ is a statically typed language, so it would be
  4685. unfortunate to require tags on every object, especially small and
  4686. pervasive objects like integers and Booleans. Option 3 is the
  4687. best-performing choice for statically typed languages, but comes with
  4688. a relatively high implementation complexity. To keep this chapter to a
  4689. 2-week time budget, we recommend a combination of options 1 and 2,
  4690. with separate strategies used for the stack and the heap.
  4691. Regarding the stack, we recommend using a separate stack for
  4692. pointers~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}, which
  4693. we call a \emph{root stack} (a.k.a. ``shadow stack''). That is, when a
  4694. local variable needs to be spilled and is of type \code{(Vector
  4695. $\Type_1 \ldots \Type_n$)}, then we put it on the root stack instead
  4696. of the normal procedure call stack. Furthermore, we always spill
  4697. vector-typed variables if they are live during a call to the
  4698. collector, thereby ensuring that no pointers are in registers during a
  4699. collection. Figure~\ref{fig:shadow-stack} reproduces the example from
  4700. Figure~\ref{fig:copying-collector} and contrasts it with the data
  4701. layout using a root stack. The root stack contains the two pointers
  4702. from the regular stack and also the pointer in the second
  4703. register.
  4704. \begin{figure}[tbp]
  4705. \centering \includegraphics[width=0.7\textwidth]{figs/root-stack}
  4706. \caption{Maintaining a root stack to facilitate garbage collection.}
  4707. \label{fig:shadow-stack}
  4708. \end{figure}
  4709. The problem of distinguishing between pointers and other kinds of data
  4710. also arises inside of each tuple. We solve this problem by attaching a
  4711. tag, an extra 64-bits, to each tuple. Figure~\ref{fig:tuple-rep} zooms
  4712. in on the tags for two of the tuples in the example from
  4713. Figure~\ref{fig:copying-collector}. Note that we have drawn the bits
  4714. in a big-endian way, from right-to-left, with bit location 0 (the
  4715. least significant bit) on the far right, which corresponds to the
  4716. directional of the x86 shifting instructions \key{salq} (shift
  4717. left) and \key{sarq} (shift right). Part of each tag is dedicated to
  4718. specifying which elements of the tuple are pointers, the part labeled
  4719. ``pointer mask''. Within the pointer mask, a 1 bit indicates there is
  4720. a pointer and a 0 bit indicates some other kind of data. The pointer
  4721. mask starts at bit location 7. We have limited tuples to a maximum
  4722. size of 50 elements, so we just need 50 bits for the pointer mask. The
  4723. tag also contains two other pieces of information. The length of the
  4724. tuple (number of elements) is stored in bits location 1 through
  4725. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  4726. to be copied to the ToSpace. If the bit has value 1, then this tuple
  4727. has not yet been copied. If the bit has value 0 then the entire tag
  4728. is in fact a forwarding pointer. (The lower 3 bits of an pointer are
  4729. always zero anyways because our tuples are 8-byte aligned.)
  4730. \begin{figure}[tbp]
  4731. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  4732. \caption{Representation for tuples in the heap.}
  4733. \label{fig:tuple-rep}
  4734. \end{figure}
  4735. \subsection{Implementation of the Garbage Collector}
  4736. \label{sec:organize-gz}
  4737. The implementation of the garbage collector needs to do a lot of
  4738. bit-level data manipulation and we need to link it with our
  4739. compiler-generated x86 code. Thus, we recommend implementing the
  4740. garbage collector in C~\citep{Kernighan:1988nx} and putting the code
  4741. in the \code{runtime.c} file. Figure~\ref{fig:gc-header} shows the
  4742. interface to the garbage collector. The \code{initialize} function
  4743. creates the FromSpace, ToSpace, and root stack. The \code{initialize}
  4744. function is meant to be called near the beginning of \code{main},
  4745. before the rest of the program executes. The \code{initialize}
  4746. function puts the address of the beginning of the FromSpace into the
  4747. global variable \code{free\_ptr}. The global \code{fromspace\_end}
  4748. points to the address that is 1-past the last element of the
  4749. FromSpace. (We use half-open intervals to represent chunks of
  4750. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} global
  4751. points to the first element of the root stack.
  4752. As long as there is room left in the FromSpace, your generated code
  4753. can allocate tuples simply by moving the \code{free\_ptr} forward.
  4754. %
  4755. \margincomment{\tiny Should we dedicate a register to the free pointer? \\
  4756. --Jeremy}
  4757. %
  4758. The amount of room left in FromSpace is the difference between the
  4759. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  4760. function should be called when there is not enough room left in the
  4761. FromSpace for the next allocation. The \code{collect} function takes
  4762. a pointer to the current top of the root stack (one past the last item
  4763. that was pushed) and the number of bytes that need to be
  4764. allocated. The \code{collect} function performs the copying collection
  4765. and leaves the heap in a state such that the next allocation will
  4766. succeed.
  4767. \begin{figure}[tbp]
  4768. \begin{lstlisting}
  4769. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  4770. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  4771. int64_t* free_ptr;
  4772. int64_t* fromspace_begin;
  4773. int64_t* fromspace_end;
  4774. int64_t** rootstack_begin;
  4775. \end{lstlisting}
  4776. \caption{The compiler's interface to the garbage collector.}
  4777. \label{fig:gc-header}
  4778. \end{figure}
  4779. \begin{exercise}
  4780. In the file \code{runtime.c} you will find the implementation of
  4781. \code{initialize} and a partial implementation of \code{collect}.
  4782. The \code{collect} function calls another function, \code{cheney},
  4783. to perform the actual copy, and that function is left to the reader
  4784. to implement. The following is the prototype for \code{cheney}.
  4785. \begin{lstlisting}
  4786. static void cheney(int64_t** rootstack_ptr);
  4787. \end{lstlisting}
  4788. The parameter \code{rootstack\_ptr} is a pointer to the top of the
  4789. rootstack (which is an array of pointers). The \code{cheney} function
  4790. also communicates with \code{collect} through the global
  4791. variables \code{fromspace\_begin} and \code{fromspace\_end}
  4792. mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  4793. the ToSpace:
  4794. \begin{lstlisting}
  4795. static int64_t* tospace_begin;
  4796. static int64_t* tospace_end;
  4797. \end{lstlisting}
  4798. The job of the \code{cheney} function is to copy all the live
  4799. objects (reachable from the root stack) into the ToSpace, update
  4800. \code{free\_ptr} to point to the next unused spot in the ToSpace,
  4801. update the root stack so that it points to the objects in the
  4802. ToSpace, and finally to swap the global pointers for the FromSpace
  4803. and ToSpace.
  4804. \end{exercise}
  4805. %% \section{Compiler Passes}
  4806. %% \label{sec:code-generation-gc}
  4807. The introduction of garbage collection has a non-trivial impact on our
  4808. compiler passes. We introduce one new compiler pass called
  4809. \code{expose-allocation} and make non-trivial changes to
  4810. \code{type-check}, \code{flatten}, \code{select-instructions},
  4811. \code{allocate-registers}, and \code{print-x86}. The following
  4812. program will serve as our running example. It creates two tuples, one
  4813. nested inside the other. Both tuples have length one. The example then
  4814. accesses the element in the inner tuple tuple via two vector
  4815. references.
  4816. % tests/s2_17.rkt
  4817. \begin{lstlisting}
  4818. (vector-ref (vector-ref (vector (vector 42)) 0) 0))
  4819. \end{lstlisting}
  4820. Next we proceed to discuss the new \code{expose-allocation} pass.
  4821. \section{Expose Allocation}
  4822. \label{sec:expose-allocation}
  4823. The pass \code{expose-allocation} lowers the \code{vector} creation
  4824. form into a conditional call to the collector followed by the
  4825. allocation. We choose to place the \code{expose-allocation} pass
  4826. before \code{flatten} because \code{expose-allocation} introduces new
  4827. variables, which can be done locally with \code{let}, but \code{let}
  4828. is gone after \code{flatten}. In the following, we show the
  4829. transformation for the \code{vector} form into let-bindings for the
  4830. initializing expressions, by a conditional \code{collect}, an
  4831. \code{allocate}, and the initialization of the vector.
  4832. (The \itm{len} is the length of the vector and \itm{bytes} is how many
  4833. total bytes need to be allocated for the vector, which is 8 for the
  4834. tag plus \itm{len} times 8.)
  4835. \begin{lstlisting}
  4836. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  4837. |$\Longrightarrow$|
  4838. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  4839. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  4840. (global-value fromspace_end))
  4841. (void)
  4842. (collect |\itm{bytes}|))])
  4843. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  4844. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  4845. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  4846. |$v$|) ... )))) ...)
  4847. \end{lstlisting}
  4848. (In the above, we suppressed all of the \code{has-type} forms in the
  4849. output for the sake of readability.) The placement of the initializing
  4850. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and
  4851. the sequence of \code{vector-set!}'s is important, as those expressions
  4852. may trigger garbage collection and we do not want an allocated but
  4853. uninitialized tuple to be present during a garbage collection.
  4854. The output of \code{expose-allocation} is a language that extends
  4855. $R_3$ with the three new forms that we use above in the translation of
  4856. \code{vector}.
  4857. \[
  4858. \begin{array}{lcl}
  4859. \Exp &::=& \cdots
  4860. \mid (\key{collect} \,\itm{int})
  4861. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  4862. \mid (\key{global-value} \,\itm{name})
  4863. \end{array}
  4864. \]
  4865. %% The \code{expose-allocation} inserts an \code{initialize} statement at
  4866. %% the beginning of the program which will instruct the garbage collector
  4867. %% to set up the FromSpace, ToSpace, and all the global variables. The
  4868. %% two arguments of \code{initialize} specify the initial allocated space
  4869. %% for the root stack and for the heap.
  4870. %
  4871. %% The \code{expose-allocation} pass annotates all of the local variables
  4872. %% in the \code{program} form with their type.
  4873. Figure~\ref{fig:expose-alloc-output} shows the output of the
  4874. \code{expose-allocation} pass on our running example.
  4875. \begin{figure}[tbp]
  4876. % tests/s2_17.rkt
  4877. \begin{lstlisting}
  4878. (vector-ref
  4879. (vector-ref
  4880. (let ([vecinit7976
  4881. (let ([vecinit7972 42])
  4882. (let ([collectret7974
  4883. (if (< (+ free_ptr 16) fromspace_end)
  4884. (void)
  4885. (collect 16);
  4886. )])
  4887. (let ([alloc7971 (allocate 1 (Vector Integer))])
  4888. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  4889. alloc7971)
  4890. )
  4891. )
  4892. )
  4893. ])
  4894. (let ([collectret7978
  4895. (if (< (+ free_ptr 16) fromspace_end)
  4896. (void)
  4897. (collect 16);
  4898. )])
  4899. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  4900. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  4901. alloc7975)
  4902. )
  4903. )
  4904. )
  4905. 0)
  4906. 0)
  4907. \end{lstlisting}
  4908. \caption{Output of the \code{expose-allocation} pass, minus
  4909. all of the \code{HasType} forms.}
  4910. \label{fig:expose-alloc-output}
  4911. \end{figure}
  4912. %\clearpage
  4913. \section{Explicate Control and the $C_2$ language}
  4914. \label{sec:explicate-control-r3}
  4915. \begin{figure}[tp]
  4916. \fbox{
  4917. \begin{minipage}{0.96\textwidth}
  4918. \small
  4919. \[
  4920. \begin{array}{lcl}
  4921. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  4922. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  4923. \Exp &::= & \gray{ \Atm \mid \READ{} \mid \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  4924. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  4925. &\mid& (\key{Allocate} \,\itm{int}\,\itm{type})
  4926. \mid \BINOP{\key{'vector-ref}}{\Atm}{\Int} \\
  4927. &\mid& (\key{Prim}~\key{'vector-set!}\,(\key{list}\,\Atm\,\Int\,\Atm))\\
  4928. &\mid& (\key{GlobalValue} \,\itm{name}) \mid (\key{Void}) \\
  4929. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} \mid \RETURN{\Exp} }
  4930. \mid (\key{Collect} \,\itm{int}) \\
  4931. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }\\
  4932. &\mid& \gray{ \GOTO{\itm{label}} }\\
  4933. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  4934. C_2 & ::= & \PROGRAM{\itm{info}}{\CFG{(\itm{label}\,\key{.}\,\Tail)^{+}}}
  4935. \end{array}
  4936. \]
  4937. \end{minipage}
  4938. }
  4939. \caption{The abstract syntax of the $C_2$ language.
  4940. TODO: UPDATE}
  4941. \label{fig:c2-syntax}
  4942. \end{figure}
  4943. The output of \code{explicate-control} is a program in the
  4944. intermediate language $C_2$, whose syntax is defined in
  4945. Figure~\ref{fig:c2-syntax}. The new forms of $C_2$ include the
  4946. \key{allocate}, \key{vector-ref}, and \key{vector-set!}, and
  4947. \key{global-value} expressions and the \code{collect} statement. The
  4948. \code{explicate-control} pass can treat these new forms much like the
  4949. other forms.
  4950. \section{Uncover Locals}
  4951. \label{sec:uncover-locals-r3}
  4952. Recall that the \code{explicate-control} function collects all of the
  4953. local variables so that it can store them in the $\itm{info}$ field of
  4954. the \code{Program} structure. Also recall that we need to know the
  4955. types of all the local variables for purposes of identifying the root
  4956. set for the garbage collector. Thus, we create a pass named
  4957. \code{uncover-locals} to collect not just the variables but the
  4958. variables and their types in the form of an alist. Thanks
  4959. to the \code{HasType} nodes, the types are readily available in the
  4960. AST. Figure~\ref{fig:uncover-locals-r3} lists the output of the
  4961. \code{uncover-locals} pass on the running example.
  4962. \begin{figure}[tbp]
  4963. % tests/s2_17.rkt
  4964. \begin{lstlisting}
  4965. program:
  4966. locals:
  4967. vecinit7976 : '(Vector Integer), tmp7980 : 'Integer,
  4968. alloc7975 : '(Vector (Vector Integer)), tmp7983 : 'Integer,
  4969. collectret7974 : 'Void, initret7977 : 'Void,
  4970. collectret7978 : 'Void, tmp7985 : '(Vector Integer),
  4971. tmp7984 : 'Integer, tmp7979 : 'Integer, tmp7982 : 'Integer,
  4972. alloc7971 : '(Vector Integer), tmp7981 : 'Integer, vecinit7972 : 'Integer,
  4973. initret7973 : 'Void,
  4974. block7991:
  4975. (collect 16);
  4976. goto block7989;
  4977. block7990:
  4978. collectret7974 = (void);
  4979. goto block7989;
  4980. block7989:
  4981. alloc7971 = (allocate 1 (Vector Integer));
  4982. initret7973 = (vector-set! alloc7971 0 vecinit7972);
  4983. vecinit7976 = alloc7971;
  4984. tmp7982 = free_ptr;
  4985. tmp7983 = (+ tmp7982 16);
  4986. tmp7984 = fromspace_end;
  4987. if (< tmp7983 tmp7984) then
  4988. goto block7987;
  4989. else
  4990. goto block7988;
  4991. block7988:
  4992. (collect 16);
  4993. goto block7986;
  4994. block7987:
  4995. collectret7978 = (void);
  4996. goto block7986;
  4997. block7986:
  4998. alloc7975 = (allocate 1 (Vector (Vector Integer)));
  4999. initret7977 = (vector-set! alloc7975 0 vecinit7976);
  5000. tmp7985 = (vector-ref alloc7975 0);
  5001. return (vector-ref tmp7985 0);
  5002. start:
  5003. vecinit7972 = 42;
  5004. tmp7979 = free_ptr;
  5005. tmp7980 = (+ tmp7979 16);
  5006. tmp7981 = fromspace_end;
  5007. if (< tmp7980 tmp7981) then
  5008. goto block7990;
  5009. else
  5010. goto block7991;
  5011. \end{lstlisting}
  5012. \caption{Output of \code{uncover-locals} for the running example.}
  5013. \label{fig:uncover-locals-r3}
  5014. \end{figure}
  5015. \clearpage
  5016. \section{Select Instructions}
  5017. \label{sec:select-instructions-gc}
  5018. %% void (rep as zero)
  5019. %% allocate
  5020. %% collect (callq collect)
  5021. %% vector-ref
  5022. %% vector-set!
  5023. %% global-value (postpone)
  5024. In this pass we generate x86 code for most of the new operations that
  5025. were needed to compile tuples, including \code{allocate},
  5026. \code{collect}, \code{vector-ref}, \code{vector-set!}, and
  5027. \code{(void)}. We postpone \code{global-value} to \code{print-x86}.
  5028. The \code{vector-ref} and \code{vector-set!} forms translate into
  5029. \code{movq} instructions with the appropriate \key{deref}. (The
  5030. plus one is to get past the tag at the beginning of the tuple
  5031. representation.)
  5032. \begin{lstlisting}
  5033. (assign |$\itm{lhs}$| (vector-ref |$\itm{vec}$| |$n$|))
  5034. |$\Longrightarrow$|
  5035. (movq |$\itm{vec}'$| (reg r11))
  5036. (movq (deref r11 |$8(n+1)$|) |$\itm{lhs}$|)
  5037. (assign |$\itm{lhs}$| (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|))
  5038. |$\Longrightarrow$|
  5039. (movq |$\itm{vec}'$| (reg r11))
  5040. (movq |$\itm{arg}'$| (deref r11 |$8(n+1)$|))
  5041. (movq (int 0) |$\itm{lhs}$|)
  5042. \end{lstlisting}
  5043. The $\itm{vec}'$ and $\itm{arg}'$ are obtained by recursively
  5044. processing $\itm{vec}$ and $\itm{arg}$. The move of $\itm{vec}'$ to
  5045. register \code{r11} ensures that offsets are only performed with
  5046. register operands. This requires removing \code{r11} from
  5047. consideration by the register allocating.
  5048. We compile the \code{allocate} form to operations on the
  5049. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  5050. is the next free address in the FromSpace, so we move it into the
  5051. \itm{lhs} and then move it forward by enough space for the tuple being
  5052. allocated, which is $8(\itm{len}+1)$ bytes because each element is 8
  5053. bytes (64 bits) and we use 8 bytes for the tag. Last but not least, we
  5054. initialize the \itm{tag}. Refer to Figure~\ref{fig:tuple-rep} to see
  5055. how the tag is organized. We recommend using the Racket operations
  5056. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag.
  5057. The type annotation in the \code{vector} form is used to determine the
  5058. pointer mask region of the tag.
  5059. \begin{lstlisting}
  5060. (assign |$\itm{lhs}$| (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|)))
  5061. |$\Longrightarrow$|
  5062. (movq (global-value free_ptr) |$\itm{lhs}'$|)
  5063. (addq (int |$8(\itm{len}+1)$|) (global-value free_ptr))
  5064. (movq |$\itm{lhs}'$| (reg r11))
  5065. (movq (int |$\itm{tag}$|) (deref r11 0))
  5066. \end{lstlisting}
  5067. The \code{collect} form is compiled to a call to the \code{collect}
  5068. function in the runtime. The arguments to \code{collect} are the top
  5069. of the root stack and the number of bytes that need to be allocated.
  5070. We shall use a dedicated register, \code{r15}, to store the pointer to
  5071. the top of the root stack. So \code{r15} is not available for use by
  5072. the register allocator.
  5073. \begin{lstlisting}
  5074. (collect |$\itm{bytes}$|)
  5075. |$\Longrightarrow$|
  5076. (movq (reg r15) (reg rdi))
  5077. (movq |\itm{bytes}| (reg rsi))
  5078. (callq collect)
  5079. \end{lstlisting}
  5080. \begin{figure}[tp]
  5081. \fbox{
  5082. \begin{minipage}{0.96\textwidth}
  5083. \[
  5084. \begin{array}{lcl}
  5085. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg}
  5086. \mid (\key{deref}\,\Reg\,\Int) } \\
  5087. &\mid& \gray{ (\key{byte-reg}\; \Reg) }
  5088. \mid (\key{global-value}\; \itm{name}) \\
  5089. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  5090. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  5091. (\key{subq} \; \Arg\; \Arg) \mid
  5092. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  5093. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  5094. (\key{pushq}\;\Arg) \mid
  5095. (\key{popq}\;\Arg) \mid
  5096. (\key{retq})} \\
  5097. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  5098. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  5099. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  5100. \mid (\key{jmp} \; \itm{label})
  5101. \mid (\key{jmp-if}\itm{cc} \; \itm{label})}\\
  5102. &\mid& \gray{(\key{label} \; \itm{label}) } \\
  5103. x86_2 &::= & \gray{ (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+}) }
  5104. \end{array}
  5105. \]
  5106. \end{minipage}
  5107. }
  5108. \caption{The x86$_2$ language (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  5109. \label{fig:x86-2}
  5110. \end{figure}
  5111. The syntax of the $x86_2$ language is defined in
  5112. Figure~\ref{fig:x86-2}. It differs from $x86_1$ just in the addition
  5113. of the form for global variables.
  5114. %
  5115. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  5116. \code{select-instructions} pass on the running example.
  5117. \begin{figure}[tbp]
  5118. \centering
  5119. \begin{minipage}{0.75\textwidth}
  5120. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5121. (program
  5122. ((locals . ((tmp54 . Integer) (tmp51 . Integer) (tmp53 . Integer)
  5123. (alloc43 . (Vector Integer)) (tmp55 . Integer)
  5124. (initret45 . Void) (alloc47 . (Vector (Vector Integer)))
  5125. (collectret46 . Void) (vecinit48 . (Vector Integer))
  5126. (tmp52 . Integer) (tmp57 Vector Integer) (vecinit44 . Integer)
  5127. (tmp56 . Integer) (initret49 . Void) (collectret50 . Void))))
  5128. ((block63 . (block ()
  5129. (movq (reg r15) (reg rdi))
  5130. (movq (int 16) (reg rsi))
  5131. (callq collect)
  5132. (jmp block61)))
  5133. (block62 . (block () (movq (int 0) (var collectret46)) (jmp block61)))
  5134. (block61 . (block ()
  5135. (movq (global-value free_ptr) (var alloc43))
  5136. (addq (int 16) (global-value free_ptr))
  5137. (movq (var alloc43) (reg r11))
  5138. (movq (int 3) (deref r11 0))
  5139. (movq (var alloc43) (reg r11))
  5140. (movq (var vecinit44) (deref r11 8))
  5141. (movq (int 0) (var initret45))
  5142. (movq (var alloc43) (var vecinit48))
  5143. (movq (global-value free_ptr) (var tmp54))
  5144. (movq (var tmp54) (var tmp55))
  5145. (addq (int 16) (var tmp55))
  5146. (movq (global-value fromspace_end) (var tmp56))
  5147. (cmpq (var tmp56) (var tmp55))
  5148. (jmp-if l block59)
  5149. (jmp block60)))
  5150. (block60 . (block ()
  5151. (movq (reg r15) (reg rdi))
  5152. (movq (int 16) (reg rsi))
  5153. (callq collect)
  5154. (jmp block58))
  5155. (block59 . (block ()
  5156. (movq (int 0) (var collectret50))
  5157. (jmp block58)))
  5158. (block58 . (block ()
  5159. (movq (global-value free_ptr) (var alloc47))
  5160. (addq (int 16) (global-value free_ptr))
  5161. (movq (var alloc47) (reg r11))
  5162. (movq (int 131) (deref r11 0))
  5163. (movq (var alloc47) (reg r11))
  5164. (movq (var vecinit48) (deref r11 8))
  5165. (movq (int 0) (var initret49))
  5166. (movq (var alloc47) (reg r11))
  5167. (movq (deref r11 8) (var tmp57))
  5168. (movq (var tmp57) (reg r11))
  5169. (movq (deref r11 8) (reg rax))
  5170. (jmp conclusion)))
  5171. (start . (block ()
  5172. (movq (int 42) (var vecinit44))
  5173. (movq (global-value free_ptr) (var tmp51))
  5174. (movq (var tmp51) (var tmp52))
  5175. (addq (int 16) (var tmp52))
  5176. (movq (global-value fromspace_end) (var tmp53))
  5177. (cmpq (var tmp53) (var tmp52))
  5178. (jmp-if l block62)
  5179. (jmp block63))))))
  5180. \end{lstlisting}
  5181. \end{minipage}
  5182. \caption{Output of the \code{select-instructions} pass.}
  5183. \label{fig:select-instr-output-gc}
  5184. \end{figure}
  5185. \clearpage
  5186. \section{Register Allocation}
  5187. \label{sec:reg-alloc-gc}
  5188. As discussed earlier in this chapter, the garbage collector needs to
  5189. access all the pointers in the root set, that is, all variables that
  5190. are vectors. It will be the responsibility of the register allocator
  5191. to make sure that:
  5192. \begin{enumerate}
  5193. \item the root stack is used for spilling vector-typed variables, and
  5194. \item if a vector-typed variable is live during a call to the
  5195. collector, it must be spilled to ensure it is visible to the
  5196. collector.
  5197. \end{enumerate}
  5198. The later responsibility can be handled during construction of the
  5199. inference graph, by adding interference edges between the call-live
  5200. vector-typed variables and all the callee-saved registers. (They
  5201. already interfere with the caller-saved registers.) The type
  5202. information for variables is in the \code{program} form, so we
  5203. recommend adding another parameter to the \code{build-interference}
  5204. function to communicate this alist.
  5205. The spilling of vector-typed variables to the root stack can be
  5206. handled after graph coloring, when choosing how to assign the colors
  5207. (integers) to registers and stack locations. The \code{program} output
  5208. of this pass changes to also record the number of spills to the root
  5209. stack.
  5210. % build-interference
  5211. %
  5212. % callq
  5213. % extra parameter for var->type assoc. list
  5214. % update 'program' and 'if'
  5215. % allocate-registers
  5216. % allocate spilled vectors to the rootstack
  5217. % don't change color-graph
  5218. \section{Print x86}
  5219. \label{sec:print-x86-gc}
  5220. \margincomment{\scriptsize We need to show the translation to x86 and what
  5221. to do about global-value. \\ --Jeremy}
  5222. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  5223. \code{print-x86} pass on the running example. In the prelude and
  5224. conclusion of the \code{main} function, we treat the root stack very
  5225. much like the regular stack in that we move the root stack pointer
  5226. (\code{r15}) to make room for all of the spills to the root stack,
  5227. except that the root stack grows up instead of down. For the running
  5228. example, there was just one spill so we increment \code{r15} by 8
  5229. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  5230. One issue that deserves special care is that there may be a call to
  5231. \code{collect} prior to the initializing assignments for all the
  5232. variables in the root stack. We do not want the garbage collector to
  5233. accidentally think that some uninitialized variable is a pointer that
  5234. needs to be followed. Thus, we zero-out all locations on the root
  5235. stack in the prelude of \code{main}. In
  5236. Figure~\ref{fig:print-x86-output-gc}, the instruction
  5237. %
  5238. \lstinline{movq $0, (%r15)}
  5239. %
  5240. accomplishes this task. The garbage collector tests each root to see
  5241. if it is null prior to dereferencing it.
  5242. \begin{figure}[htbp]
  5243. \begin{minipage}[t]{0.5\textwidth}
  5244. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5245. _block58:
  5246. movq _free_ptr(%rip), %rcx
  5247. addq $16, _free_ptr(%rip)
  5248. movq %rcx, %r11
  5249. movq $131, 0(%r11)
  5250. movq %rcx, %r11
  5251. movq -8(%r15), %rax
  5252. movq %rax, 8(%r11)
  5253. movq $0, %rdx
  5254. movq %rcx, %r11
  5255. movq 8(%r11), %rcx
  5256. movq %rcx, %r11
  5257. movq 8(%r11), %rax
  5258. jmp _conclusion
  5259. _block59:
  5260. movq $0, %rcx
  5261. jmp _block58
  5262. _block62:
  5263. movq $0, %rcx
  5264. jmp _block61
  5265. _block60:
  5266. movq %r15, %rdi
  5267. movq $16, %rsi
  5268. callq _collect
  5269. jmp _block58
  5270. _block63:
  5271. movq %r15, %rdi
  5272. movq $16, %rsi
  5273. callq _collect
  5274. jmp _block61
  5275. _start:
  5276. movq $42, %rbx
  5277. movq _free_ptr(%rip), %rdx
  5278. addq $16, %rdx
  5279. movq _fromspace_end(%rip), %rcx
  5280. cmpq %rcx, %rdx
  5281. jl _block62
  5282. jmp _block63
  5283. \end{lstlisting}
  5284. \end{minipage}
  5285. \begin{minipage}[t]{0.45\textwidth}
  5286. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5287. _block61:
  5288. movq _free_ptr(%rip), %rcx
  5289. addq $16, _free_ptr(%rip)
  5290. movq %rcx, %r11
  5291. movq $3, 0(%r11)
  5292. movq %rcx, %r11
  5293. movq %rbx, 8(%r11)
  5294. movq $0, %rdx
  5295. movq %rcx, -8(%r15)
  5296. movq _free_ptr(%rip), %rcx
  5297. addq $16, %rcx
  5298. movq _fromspace_end(%rip), %rdx
  5299. cmpq %rdx, %rcx
  5300. jl _block59
  5301. jmp _block60
  5302. .globl _main
  5303. _main:
  5304. pushq %rbp
  5305. movq %rsp, %rbp
  5306. pushq %r12
  5307. pushq %rbx
  5308. pushq %r13
  5309. pushq %r14
  5310. subq $0, %rsp
  5311. movq $16384, %rdi
  5312. movq $16, %rsi
  5313. callq _initialize
  5314. movq _rootstack_begin(%rip), %r15
  5315. movq $0, (%r15)
  5316. addq $8, %r15
  5317. jmp _start
  5318. _conclusion:
  5319. subq $8, %r15
  5320. addq $0, %rsp
  5321. popq %r14
  5322. popq %r13
  5323. popq %rbx
  5324. popq %r12
  5325. popq %rbp
  5326. retq
  5327. \end{lstlisting}
  5328. \end{minipage}
  5329. \caption{Output of the \code{print-x86} pass.}
  5330. \label{fig:print-x86-output-gc}
  5331. \end{figure}
  5332. \margincomment{\scriptsize Suggest an implementation strategy
  5333. in which the students first do the code gen and test that
  5334. without GC (just use a big heap), then after that is debugged,
  5335. implement the GC. \\ --Jeremy}
  5336. \begin{figure}[p]
  5337. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5338. \node (R3) at (0,2) {\large $R_3$};
  5339. \node (R3-2) at (3,2) {\large $R_3$};
  5340. \node (R3-3) at (6,2) {\large $R_3$};
  5341. \node (R3-4) at (9,2) {\large $R_3$};
  5342. \node (R3-5) at (12,2) {\large $R_3$};
  5343. \node (C2-4) at (3,0) {\large $C_2$};
  5344. \node (C2-3) at (6,0) {\large $C_2$};
  5345. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_2$};
  5346. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_2$};
  5347. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}_2$};
  5348. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}_2$};
  5349. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}_2$};
  5350. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}_2$};
  5351. \path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R3-2);
  5352. \path[->,bend left=15] (R3-2) edge [above] node {\ttfamily\footnotesize uniquify} (R3-3);
  5353. \path[->,bend left=15] (R3-3) edge [above] node {\ttfamily\footnotesize\color{red} expose-alloc.} (R3-4);
  5354. \path[->,bend left=15] (R3-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R3-5);
  5355. \path[->,bend left=20] (R3-5) edge [right] node {\ttfamily\footnotesize explicate-control} (C2-3);
  5356. \path[->,bend right=15] (C2-3) edge [above] node {\ttfamily\footnotesize\color{red} uncover-locals} (C2-4);
  5357. \path[->,bend right=15] (C2-4) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  5358. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  5359. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  5360. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  5361. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  5362. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  5363. \end{tikzpicture}
  5364. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  5365. \label{fig:R3-passes}
  5366. \end{figure}
  5367. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  5368. for the compilation of $R_3$.
  5369. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5370. \chapter{Functions}
  5371. \label{ch:functions}
  5372. This chapter studies the compilation of functions at the level of
  5373. abstraction of the C language. This corresponds to a subset of Typed
  5374. Racket in which only top-level function definitions are allowed. These
  5375. kind of functions are an important stepping stone to implementing
  5376. lexically-scoped functions in the form of \key{lambda} abstractions,
  5377. which is the topic of Chapter~\ref{ch:lambdas}.
  5378. \section{The $R_4$ Language}
  5379. The syntax for function definitions and function application is shown
  5380. in Figure~\ref{fig:r4-syntax}, where we define the $R_4$ language.
  5381. Programs in $R_4$ start with zero or more function definitions. The
  5382. function names from these definitions are in-scope for the entire
  5383. program, including all other function definitions (so the ordering of
  5384. function definitions does not matter). The syntax for function
  5385. application does not include an explicit keyword, which is error prone
  5386. when using \code{match}. To alleviate this problem, we change the
  5387. syntax from $(\Exp \; \Exp^{*})$ to $(\key{app}\; \Exp \; \Exp^{*})$
  5388. during type checking.
  5389. Functions are first-class in the sense that a function pointer is data
  5390. and can be stored in memory or passed as a parameter to another
  5391. function. Thus, we introduce a function type, written
  5392. \begin{lstlisting}
  5393. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  5394. \end{lstlisting}
  5395. for a function whose $n$ parameters have the types $\Type_1$ through
  5396. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  5397. these functions (with respect to Racket functions) is that they are
  5398. not lexically scoped. That is, the only external entities that can be
  5399. referenced from inside a function body are other globally-defined
  5400. functions. The syntax of $R_4$ prevents functions from being nested
  5401. inside each other.
  5402. \begin{figure}[tp]
  5403. \centering
  5404. \fbox{
  5405. \begin{minipage}{0.96\textwidth}
  5406. \[
  5407. \begin{array}{lcl}
  5408. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  5409. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} } \mid (\Type^{*} \; \key{->}\; \Type) \\
  5410. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  5411. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp)} \\
  5412. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  5413. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5414. \mid (\key{and}\;\Exp\;\Exp)
  5415. \mid (\key{or}\;\Exp\;\Exp)
  5416. \mid (\key{not}\;\Exp)} \\
  5417. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5418. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5419. (\key{vector-ref}\;\Exp\;\Int)} \\
  5420. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  5421. &\mid& (\Exp \; \Exp^{*}) \\
  5422. \Def &::=& (\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  5423. R_4 &::=& (\key{program} \;\itm{info}\; \Def^{*} \; \Exp)
  5424. \end{array}
  5425. \]
  5426. \end{minipage}
  5427. }
  5428. \caption{Syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-syntax})
  5429. with functions.}
  5430. \label{fig:r4-syntax}
  5431. \end{figure}
  5432. The program in Figure~\ref{fig:r4-function-example} is a
  5433. representative example of defining and using functions in $R_4$. We
  5434. define a function \code{map-vec} that applies some other function
  5435. \code{f} to both elements of a vector (a 2-tuple) and returns a new
  5436. vector containing the results. We also define a function \code{add1}
  5437. that does what its name suggests. The program then applies
  5438. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  5439. \code{(vector 1 42)}, from which we return the \code{42}.
  5440. \begin{figure}[tbp]
  5441. \begin{lstlisting}
  5442. (program ()
  5443. (define (map-vec [f : (Integer -> Integer)]
  5444. [v : (Vector Integer Integer)])
  5445. : (Vector Integer Integer)
  5446. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  5447. (define (add1 [x : Integer]) : Integer
  5448. (+ x 1))
  5449. (vector-ref (map-vec add1 (vector 0 41)) 1)
  5450. )
  5451. \end{lstlisting}
  5452. \caption{Example of using functions in $R_4$.}
  5453. \label{fig:r4-function-example}
  5454. \end{figure}
  5455. The definitional interpreter for $R_4$ is in
  5456. Figure~\ref{fig:interp-R4}. The case for the \code{program} form is
  5457. responsible for setting up the mutual recursion between the top-level
  5458. function definitions. We use the classic back-patching approach that
  5459. uses mutable variables and makes two passes over the function
  5460. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  5461. top-level environment using a mutable cons cell for each function
  5462. definition. Note that the \code{lambda} value for each function is
  5463. incomplete; it does not yet include the environment. Once the
  5464. top-level environment is constructed, we then iterate over it and
  5465. update the \code{lambda} value's to use the top-level environment.
  5466. \begin{figure}[tp]
  5467. \begin{lstlisting}
  5468. (define (interp-exp env)
  5469. (lambda (e)
  5470. (define recur (interp-exp env))
  5471. (match e
  5472. ...
  5473. [`(,fun ,args ...)
  5474. (define arg-vals (for/list ([e args]) (recur e)))
  5475. (define fun-val (recur fun))
  5476. (match fun-val
  5477. [`(lambda (,xs ...) ,body ,fun-env)
  5478. (define new-env (append (map cons xs arg-vals) fun-env))
  5479. ((interp-exp new-env) body)]
  5480. [else (error "interp-exp, expected function, not" fun-val)])]
  5481. [else (error 'interp-exp "unrecognized expression")]
  5482. )))
  5483. (define (interp-def d)
  5484. (match d
  5485. [`(define (,f [,xs : ,ps] ...) : ,rt ,body)
  5486. (mcons f `(lambda ,xs ,body ()))]
  5487. ))
  5488. (define (interp-R4 p)
  5489. (match p
  5490. [`(program ,ds ... ,body)
  5491. (let ([top-level (for/list ([d ds]) (interp-def d))])
  5492. (for/list ([b top-level])
  5493. (set-mcdr! b (match (mcdr b)
  5494. [`(lambda ,xs ,body ())
  5495. `(lambda ,xs ,body ,top-level)])))
  5496. ((interp-exp top-level) body))]
  5497. ))
  5498. \end{lstlisting}
  5499. \caption{Interpreter for the $R_4$ language.}
  5500. \label{fig:interp-R4}
  5501. \end{figure}
  5502. \section{Functions in x86}
  5503. \label{sec:fun-x86}
  5504. \margincomment{\tiny Make sure callee-saved registers are discussed
  5505. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  5506. \margincomment{\tiny Talk about the return address on the
  5507. stack and what callq and retq does.\\ --Jeremy }
  5508. The x86 architecture provides a few features to support the
  5509. implementation of functions. We have already seen that x86 provides
  5510. labels so that one can refer to the location of an instruction, as is
  5511. needed for jump instructions. Labels can also be used to mark the
  5512. beginning of the instructions for a function. Going further, we can
  5513. obtain the address of a label by using the \key{leaq} instruction and
  5514. \key{rip}-relative addressing. For example, the following puts the
  5515. address of the \code{add1} label into the \code{rbx} register.
  5516. \begin{lstlisting}
  5517. leaq add1(%rip), %rbx
  5518. \end{lstlisting}
  5519. In Section~\ref{sec:x86} we saw the use of the \code{callq}
  5520. instruction for jumping to a function whose location is given by a
  5521. label. Here we instead will be jumping to a function whose location is
  5522. given by an address, that is, we need to make an \emph{indirect
  5523. function call}. The x86 syntax is to give the register name prefixed
  5524. with an asterisk.
  5525. \begin{lstlisting}
  5526. callq *%rbx
  5527. \end{lstlisting}
  5528. \subsection{Calling Conventions}
  5529. The \code{callq} instruction provides partial support for implementing
  5530. functions, but it does not handle (1) parameter passing, (2) saving
  5531. and restoring frames on the procedure call stack, or (3) determining
  5532. how registers are shared by different functions. These issues require
  5533. coordination between the caller and the callee, which is often
  5534. assembly code written by different programmers or generated by
  5535. different compilers. As a result, people have developed
  5536. \emph{conventions} that govern how functions calls are performed.
  5537. Here we shall use the same conventions used by the \code{gcc}
  5538. compiler~\citep{Matz:2013aa}.
  5539. Regarding (1) parameter passing, the convention is to use the
  5540. following six registers: \code{rdi}, \code{rsi}, \code{rdx},
  5541. \code{rcx}, \code{r8}, and \code{r9}, in that order. If there are more
  5542. than six arguments, then the convention is to use space on the frame
  5543. of the caller for the rest of the arguments. However, to ease the
  5544. implementation of efficient tail calls (Section~\ref{sec:tail-call}),
  5545. we shall arrange to never have more than six arguments.
  5546. %
  5547. The register \code{rax} is for the return value of the function.
  5548. Regarding (2) frames and the procedure call stack, the convention is
  5549. that the stack grows down, with each function call using a chunk of
  5550. space called a frame. The caller sets the stack pointer, register
  5551. \code{rsp}, to the last data item in its frame. The callee must not
  5552. change anything in the caller's frame, that is, anything that is at or
  5553. above the stack pointer. The callee is free to use locations that are
  5554. below the stack pointer.
  5555. Regarding (3) the sharing of registers between different functions,
  5556. recall from Section~\ref{sec:calling-conventions} that the registers
  5557. are divided into two groups, the caller-saved registers and the
  5558. callee-saved registers. The caller should assume that all the
  5559. caller-saved registers get overwritten with arbitrary values by the
  5560. callee. Thus, the caller should either 1) not put values that are live
  5561. across a call in caller-saved registers, or 2) save and restore values
  5562. that are live across calls. We shall recommend option 1). On the flip
  5563. side, if the callee wants to use a callee-saved register, the callee
  5564. must save the contents of those registers on their stack frame and
  5565. then put them back prior to returning to the caller. The base
  5566. pointer, register \code{rbp}, is used as a point-of-reference within a
  5567. frame, so that each local variable can be accessed at a fixed offset
  5568. from the base pointer.
  5569. %
  5570. Figure~\ref{fig:call-frames} shows the layout of the caller and callee
  5571. frames.
  5572. %% If we were to use stack arguments, they would be between the
  5573. %% caller locals and the callee return address.
  5574. \begin{figure}[tbp]
  5575. \centering
  5576. \begin{tabular}{r|r|l|l} \hline
  5577. Caller View & Callee View & Contents & Frame \\ \hline
  5578. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  5579. 0(\key{\%rbp}) & & old \key{rbp} \\
  5580. -8(\key{\%rbp}) & & callee-saved $1$ \\
  5581. \ldots & & \ldots \\
  5582. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  5583. $-8(j+1)$(\key{\%rbp}) & & local $1$ \\
  5584. \ldots & & \ldots \\
  5585. $-8(j+k)$(\key{\%rbp}) & & local $k$ \\
  5586. %% & & \\
  5587. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  5588. %% & \ldots & \ldots \\
  5589. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  5590. \hline
  5591. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  5592. & 0(\key{\%rbp}) & old \key{rbp} \\
  5593. & -8(\key{\%rbp}) & callee-saved $1$ \\
  5594. & \ldots & \ldots \\
  5595. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  5596. & $-8(n+1)$(\key{\%rbp}) & local $1$ \\
  5597. & \ldots & \ldots \\
  5598. & $-8(n+m)$(\key{\%rsp}) & local $m$\\ \hline
  5599. \end{tabular}
  5600. \caption{Memory layout of caller and callee frames.}
  5601. \label{fig:call-frames}
  5602. \end{figure}
  5603. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  5604. %% local variables and for storing the values of callee-saved registers
  5605. %% (we shall refer to all of these collectively as ``locals''), and that
  5606. %% at the beginning of a function we move the stack pointer \code{rsp}
  5607. %% down to make room for them.
  5608. %% We recommend storing the local variables
  5609. %% first and then the callee-saved registers, so that the local variables
  5610. %% can be accessed using \code{rbp} the same as before the addition of
  5611. %% functions.
  5612. %% To make additional room for passing arguments, we shall
  5613. %% move the stack pointer even further down. We count how many stack
  5614. %% arguments are needed for each function call that occurs inside the
  5615. %% body of the function and find their maximum. Adding this number to the
  5616. %% number of locals gives us how much the \code{rsp} should be moved at
  5617. %% the beginning of the function. In preparation for a function call, we
  5618. %% offset from \code{rsp} to set up the stack arguments. We put the first
  5619. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  5620. %% so on.
  5621. %% Upon calling the function, the stack arguments are retrieved by the
  5622. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  5623. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  5624. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  5625. %% the layout of the caller and callee frames. Notice how important it is
  5626. %% that we correctly compute the maximum number of arguments needed for
  5627. %% function calls; if that number is too small then the arguments and
  5628. %% local variables will smash into each other!
  5629. \subsection{Efficient Tail Calls}
  5630. \label{sec:tail-call}
  5631. In general, the amount of stack space used by a program is determined
  5632. by the longest chain of nested function calls. That is, if function
  5633. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  5634. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  5635. $n$ can grow quite large in the case of recursive or mutually
  5636. recursive functions. However, in some cases we can arrange to use only
  5637. constant space, i.e. $O(1)$, instead of $O(n)$.
  5638. If a function call is the last action in a function body, then that
  5639. call is said to be a \emph{tail call}. In such situations, the frame
  5640. of the caller is no longer needed, so we can pop the caller's frame
  5641. before making the tail call. With this approach, a recursive function
  5642. that only makes tail calls will only use $O(1)$ stack space.
  5643. Functional languages like Racket typically rely heavily on recursive
  5644. functions, so they typically guarantee that all tail calls will be
  5645. optimized in this way.
  5646. However, some care is needed with regards to argument passing in tail
  5647. calls. As mentioned above, for arguments beyond the sixth, the
  5648. convention is to use space in the caller's frame for passing
  5649. arguments. But here we've popped the caller's frame and can no longer
  5650. use it. Another alternative is to use space in the callee's frame for
  5651. passing arguments. However, this option is also problematic because
  5652. the caller and callee's frame overlap in memory. As we begin to copy
  5653. the arguments from their sources in the caller's frame, the target
  5654. locations in the callee's frame might overlap with the sources for
  5655. later arguments! We solve this problem by not using the stack for
  5656. parameter passing but instead use the heap, as we describe in the
  5657. Section~\ref{sec:limit-functions-r4}.
  5658. As mentioned above, for a tail call we pop the caller's frame prior to
  5659. making the tail call. The instructions for popping a frame are the
  5660. instructions that we usually place in the conclusion of a
  5661. function. Thus, we also need to place such code immediately before
  5662. each tail call. These instructions include restoring the callee-saved
  5663. registers, so it is good that the argument passing registers are all
  5664. caller-saved registers.
  5665. One last note regarding which instruction to use to make the tail
  5666. call. When the callee is finished, it should not return to the current
  5667. function, but it should return to the function that called the current
  5668. one. Thus, the return address that is already on the stack is the
  5669. right one, and we should not use \key{callq} to make the tail call, as
  5670. that would unnecessarily overwrite the return address. Instead we can
  5671. simply use the \key{jmp} instruction. Like the indirect function call,
  5672. we write an indirect jump with a register prefixed with an asterisk.
  5673. We recommend using \code{rax} to hold the jump target because the
  5674. preceding ``conclusion'' overwrites just about everything else.
  5675. \begin{lstlisting}
  5676. jmp *%rax
  5677. \end{lstlisting}
  5678. %% Now that we have a good understanding of functions as they appear in
  5679. %% $R_4$ and the support for functions in x86, we need to plan the
  5680. %% changes to our compiler, that is, do we need any new passes and/or do
  5681. %% we need to change any existing passes? Also, do we need to add new
  5682. %% kinds of AST nodes to any of the intermediate languages?
  5683. \section{Shrink $R_4$}
  5684. \label{sec:shrink-r4}
  5685. The \code{shrink} pass performs a couple minor modifications to the
  5686. grammar to ease the later passes. This pass adds an empty $\itm{info}$
  5687. field to each function definition:
  5688. \begin{lstlisting}
  5689. (define (|$f$| [|$x_1 : \Type_1$| ...) : |$\Type_r$| |$\Exp$|)
  5690. |$\Rightarrow$| (define (|$f$| [|$x_1 : \Type_1$| ...) : |$\Type_r$| () |$\Exp$|)
  5691. \end{lstlisting}
  5692. and introduces an explicit \code{main} function.\\
  5693. \begin{tabular}{lll}
  5694. \begin{minipage}{0.45\textwidth}
  5695. \begin{lstlisting}
  5696. (program |$\itm{info}$| |$ds$| ... |$\Exp$|)
  5697. \end{lstlisting}
  5698. \end{minipage}
  5699. &
  5700. $\Rightarrow$
  5701. &
  5702. \begin{minipage}{0.45\textwidth}
  5703. \begin{lstlisting}
  5704. (program |$\itm{info}$| |$ds'$| |$\itm{mainDef}$|)
  5705. \end{lstlisting}
  5706. \end{minipage}
  5707. \end{tabular} \\
  5708. where $\itm{mainDef}$ is
  5709. \begin{lstlisting}
  5710. (define (main) : Integer () |$\Exp'$|)
  5711. \end{lstlisting}
  5712. \section{Reveal Functions}
  5713. \label{sec:reveal-functions-r4}
  5714. Going forward, the syntax of $R_4$ is inconvenient for purposes of
  5715. compilation because it conflates the use of function names and local
  5716. variables. This is a problem because we need to compile the use of a
  5717. function name differently than the use of a local variable; we need to
  5718. use \code{leaq} to convert the function name (a label in x86) to an
  5719. address in a register. Thus, it is a good idea to create a new pass
  5720. that changes function references from just a symbol $f$ to
  5721. \code{(fun-ref $f$)}. A good name for this pass is
  5722. \code{reveal-functions} and the output language, $F_1$, is defined in
  5723. Figure~\ref{fig:f1-syntax}.
  5724. \begin{figure}[tp]
  5725. \centering
  5726. \fbox{
  5727. \begin{minipage}{0.96\textwidth}
  5728. \[
  5729. \begin{array}{lcl}
  5730. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  5731. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} \mid (\Type^{*} \; \key{->}\; \Type)} \\
  5732. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  5733. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  5734. &\mid& \gray{ \key{\#t} \mid \key{\#f} \mid
  5735. (\key{not}\;\Exp)} \mid \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5736. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5737. (\key{vector-ref}\;\Exp\;\Int)} \\
  5738. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void}) \mid
  5739. (\key{app}\; \Exp \; \Exp^{*})} \\
  5740. &\mid& (\key{fun-ref}\, \itm{label}) \\
  5741. \Def &::=& \gray{(\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5742. F_1 &::=& \gray{(\key{program}\;\itm{info} \; \Def^{*})}
  5743. \end{array}
  5744. \]
  5745. \end{minipage}
  5746. }
  5747. \caption{The $F_1$ language, an extension of $R_4$
  5748. (Figure~\ref{fig:r4-syntax}).}
  5749. \label{fig:f1-syntax}
  5750. \end{figure}
  5751. %% Distinguishing between calls in tail position and non-tail position
  5752. %% requires the pass to have some notion of context. We recommend using
  5753. %% two mutually recursive functions, one for processing expressions in
  5754. %% tail position and another for the rest.
  5755. Placing this pass after \code{uniquify} is a good idea, because it
  5756. will make sure that there are no local variables and functions that
  5757. share the same name. On the other hand, \code{reveal-functions} needs
  5758. to come before the \code{explicate-control} pass because that pass
  5759. will help us compile \code{fun-ref} into assignment statements.
  5760. \section{Limit Functions}
  5761. \label{sec:limit-functions-r4}
  5762. This pass transforms functions so that they have at most six
  5763. parameters and transforms all function calls so that they pass at most
  5764. six arguments. A simple strategy for imposing an argument limit of
  5765. length $n$ is to take all arguments $i$ where $i \geq n$ and pack them
  5766. into a vector, making that subsequent vector the $n$th argument.
  5767. \begin{tabular}{lll}
  5768. \begin{minipage}{0.2\textwidth}
  5769. \begin{lstlisting}
  5770. (|$f$| |$x_1$| |$\ldots$| |$x_n$|)
  5771. \end{lstlisting}
  5772. \end{minipage}
  5773. &
  5774. $\Rightarrow$
  5775. &
  5776. \begin{minipage}{0.4\textwidth}
  5777. \begin{lstlisting}
  5778. (|$f$| |$x_1$| |$\ldots$| |$x_5$| (vector |$x_6$| |$\ldots$| |$x_n$|))
  5779. \end{lstlisting}
  5780. \end{minipage}
  5781. \end{tabular}
  5782. In the body of the function, all occurrences of the $i$th argument in
  5783. which $i>5$ must be replaced with a \code{vector-ref}.
  5784. \section{Remove Complex Operators and Operands}
  5785. \label{sec:rco-r4}
  5786. The primary decisions to make for this pass is whether to classify
  5787. \code{fun-ref} and \code{app} as either simple or complex
  5788. expressions. Recall that a simple expression will eventually end up as
  5789. just an ``immediate'' argument of an x86 instruction. Function
  5790. application will be translated to a sequence of instructions, so
  5791. \code{app} must be classified as complex expression. Regarding
  5792. \code{fun-ref}, as discussed above, the function label needs to
  5793. be converted to an address using the \code{leaq} instruction. Thus,
  5794. even though \code{fun-ref} seems rather simple, it needs to be
  5795. classified as a complex expression so that we generate an assignment
  5796. statement with a left-hand side that can serve as the target of the
  5797. \code{leaq}.
  5798. \section{Explicate Control and the $C_3$ language}
  5799. \label{sec:explicate-control-r4}
  5800. Figure~\ref{fig:c3-syntax} defines the syntax for $C_3$, the output of
  5801. \key{explicate-control}. The three mutually recursive functions for
  5802. this pass, for assignment, tail, and predicate contexts, must all be
  5803. updated with cases for \code{fun-ref} and \code{app}. In
  5804. assignment and predicate contexts, \code{app} becomes \code{call},
  5805. whereas in tail position \code{app} becomes \code{tailcall}. We
  5806. recommend defining a new function for processing function definitions.
  5807. This code is similar to the case for \code{program} in $R_3$. The
  5808. top-level \code{explicate-control} function that handles the
  5809. \code{program} form of $R_4$ can then apply this new function to all
  5810. the function definitions.
  5811. \begin{figure}[tp]
  5812. \fbox{
  5813. \begin{minipage}{0.96\textwidth}
  5814. \[
  5815. \begin{array}{lcl}
  5816. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  5817. \\
  5818. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5819. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  5820. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  5821. &\mid& \gray{ (\key{allocate}\,\Int\,\Type)
  5822. \mid (\key{vector-ref}\, \Arg\, \Int) } \\
  5823. &\mid& \gray{ (\key{vector-set!}\,\Arg\,\Int\,\Arg) \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) } \\
  5824. &\mid& (\key{fun-ref}\,\itm{label}) \mid (\key{call} \,\Arg\,\Arg^{*}) \\
  5825. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  5826. \mid (\key{collect} \,\itm{int}) }\\
  5827. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  5828. &\mid& \gray{(\key{goto}\,\itm{label})
  5829. \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  5830. &\mid& (\key{tailcall} \,\Arg\,\Arg^{*}) \\
  5831. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; ((\itm{label}\,\key{.}\,\Tail)^{+})) \\
  5832. C_3 & ::= & (\key{program}\;\itm{info}\;\Def^{*})
  5833. \end{array}
  5834. \]
  5835. \end{minipage}
  5836. }
  5837. \caption{The $C_3$ language, extending $C_2$ (Figure~\ref{fig:c2-syntax}) with functions.}
  5838. \label{fig:c3-syntax}
  5839. \end{figure}
  5840. \section{Uncover Locals}
  5841. \label{sec:uncover-locals-r4}
  5842. The function for processing $\Tail$ should be updated with a case for
  5843. \code{tailcall}. We also recommend creating a new function for
  5844. processing function definitions. Each function definition in $C_3$ has
  5845. its own set of local variables, so the code for function definitions
  5846. should be similar to the case for the \code{program} form in $C_2$.
  5847. \section{Select Instructions}
  5848. \label{sec:select-r4}
  5849. The output of select instructions is a program in the x86$_3$
  5850. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  5851. \begin{figure}[tp]
  5852. \fbox{
  5853. \begin{minipage}{0.96\textwidth}
  5854. \[
  5855. \begin{array}{lcl}
  5856. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg}
  5857. \mid (\key{deref}\,\Reg\,\Int) } \\
  5858. &\mid& \gray{ (\key{byte-reg}\; \Reg)
  5859. \mid (\key{global-value}\; \itm{name}) } \\
  5860. &\mid& (\key{fun-ref}\; \itm{label})\\
  5861. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  5862. \Instr &::=& \gray{ (\key{addq} \; \Arg\; \Arg) \mid
  5863. (\key{subq} \; \Arg\; \Arg) \mid
  5864. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) } \\
  5865. &\mid& \gray{ (\key{callq} \; \mathit{label}) \mid
  5866. (\key{pushq}\;\Arg) \mid
  5867. (\key{popq}\;\Arg) \mid
  5868. (\key{retq}) } \\
  5869. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  5870. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  5871. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  5872. \mid (\key{jmp} \; \itm{label})
  5873. \mid (\key{j}\itm{cc} \; \itm{label})
  5874. \mid (\key{label} \; \itm{label}) } \\
  5875. &\mid& (\key{indirect-callq}\;\Arg ) \mid (\key{tail-jmp}\;\Arg) \\
  5876. &\mid& (\key{leaq}\;\Arg\;\Arg)\\
  5877. \Block &::= & \gray{(\key{block} \;\itm{info}\; \Instr^{+})} \\
  5878. \Def &::= & (\key{define} \; (\itm{label}) \;\itm{info}\; ((\itm{label} \,\key{.}\, \Block)^{+}))\\
  5879. x86_3 &::= & (\key{program} \;\itm{info} \;\Def^{*})
  5880. \end{array}
  5881. \]
  5882. \end{minipage}
  5883. }
  5884. \caption{The x86$_3$ language (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  5885. \label{fig:x86-3}
  5886. \end{figure}
  5887. An assignment of \code{fun-ref} becomes a \code{leaq} instruction
  5888. as follows: \\
  5889. \begin{tabular}{lll}
  5890. \begin{minipage}{0.45\textwidth}
  5891. \begin{lstlisting}
  5892. (assign |$\itm{lhs}$| (fun-ref |$f$|))
  5893. \end{lstlisting}
  5894. \end{minipage}
  5895. &
  5896. $\Rightarrow$
  5897. &
  5898. \begin{minipage}{0.4\textwidth}
  5899. \begin{lstlisting}
  5900. (leaq (fun-ref |$f$|) |$\itm{lhs}$|)
  5901. \end{lstlisting}
  5902. \end{minipage}
  5903. \end{tabular} \\
  5904. Regarding function definitions, we need to remove their parameters and
  5905. instead perform parameter passing in terms of the conventions
  5906. discussed in Section~\ref{sec:fun-x86}. That is, the arguments will be
  5907. in the argument passing registers, and inside the function we should
  5908. generate a \code{movq} instruction for each parameter, to move the
  5909. argument value from the appropriate register to a new local variable
  5910. with the same name as the old parameter.
  5911. Next, consider the compilation of function calls, which have the
  5912. following form upon input to \code{select-instructions}.
  5913. \begin{lstlisting}
  5914. (assign |\itm{lhs}| (call |\itm{fun}| |\itm{args}| |$\ldots$|))
  5915. \end{lstlisting}
  5916. In the mirror image of handling the parameters of function
  5917. definitions, the arguments \itm{args} need to be moved to the argument
  5918. passing registers.
  5919. %
  5920. Once the instructions for parameter passing have been generated, the
  5921. function call itself can be performed with an indirect function call,
  5922. for which I recommend creating the new instruction
  5923. \code{indirect-callq}. Of course, the return value from the function
  5924. is stored in \code{rax}, so it needs to be moved into the \itm{lhs}.
  5925. \begin{lstlisting}
  5926. (indirect-callq |\itm{fun}|)
  5927. (movq (reg rax) |\itm{lhs}|)
  5928. \end{lstlisting}
  5929. Regarding tail calls, the parameter passing is the same as non-tail
  5930. calls: generate instructions to move the arguments into to the
  5931. argument passing registers. After that we need to pop the frame from
  5932. the procedure call stack. However, we do not yet know how big the
  5933. frame is; that gets determined during register allocation. So instead
  5934. of generating those instructions here, we invent a new instruction
  5935. that means ``pop the frame and then do an indirect jump'', which we
  5936. name \code{tail-jmp}.
  5937. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  5938. using the label \code{start} for the initial block of a program, and
  5939. in Section~\ref{sec:select-r1} we recommended labeling the conclusion
  5940. of the program with \code{conclusion}, so that $(\key{return}\;\Arg)$
  5941. can be compiled to an assignment to \code{rax} followed by a jump to
  5942. \code{conclusion}. With the addition of function definitions, we will
  5943. have a starting block and conclusion for each function, but their
  5944. labels need to be unique. We recommend prepending the function's name
  5945. to \code{start} and \code{conclusion}, respectively, to obtain unique
  5946. labels. (Alternatively, one could \code{gensym} labels for the start
  5947. and conclusion and store them in the $\itm{info}$ field of the
  5948. function definition.)
  5949. \section{Uncover Live}
  5950. %% The rest of the passes need only minor modifications to handle the new
  5951. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  5952. %% \code{leaq}.
  5953. Inside \code{uncover-live}, when computing the $W$ set (written
  5954. variables) for an \code{indirect-callq} instruction, we recommend
  5955. including all the caller-saved registers, which will have the affect
  5956. of making sure that no caller-saved register actually needs to be
  5957. saved.
  5958. \section{Build Interference Graph}
  5959. With the addition of function definitions, we compute an interference
  5960. graph for each function (not just one for the whole program).
  5961. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  5962. spill vector-typed variables that are live during a call to the
  5963. \code{collect}. With the addition of functions to our language, we
  5964. need to revisit this issue. Many functions will perform allocation and
  5965. therefore have calls to the collector inside of them. Thus, we should
  5966. not only spill a vector-typed variable when it is live during a call
  5967. to \code{collect}, but we should spill the variable if it is live
  5968. during any function call. Thus, in the \code{build-interference} pass,
  5969. we recommend adding interference edges between call-live vector-typed
  5970. variables and the callee-saved registers (in addition to the usual
  5971. addition of edges between call-live variables and the caller-saved
  5972. registers).
  5973. \section{Patch Instructions}
  5974. In \code{patch-instructions}, you should deal with the x86
  5975. idiosyncrasy that the destination argument of \code{leaq} must be a
  5976. register. Additionally, you should ensure that the argument of
  5977. \code{tail-jmp} is \itm{rax}, our reserved register---this is to make
  5978. code generation more convenient, because we will be trampling many
  5979. registers before the tail call (as explained below).
  5980. \section{Print x86}
  5981. For the \code{print-x86} pass, we recommend the following translations:
  5982. \begin{lstlisting}
  5983. (fun-ref |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  5984. (indirect-callq |\itm{arg}|) |$\Rightarrow$| callq *|\itm{arg}|
  5985. \end{lstlisting}
  5986. Handling \code{tail-jmp} requires a bit more care. A straightforward
  5987. translation of \code{tail-jmp} would be \code{jmp *$\itm{arg}$}, which
  5988. is what we will want to do, but before the jump we need to pop the
  5989. current frame. So we need to restore the state of the registers to the
  5990. point they were at when the current function was called. This
  5991. sequence of instructions is the same as the code for the conclusion of
  5992. a function.
  5993. Note that your \code{print-x86} pass needs to add the code for saving
  5994. and restoring callee-saved registers, if you have not already
  5995. implemented that. This is necessary when generating code for function
  5996. definitions.
  5997. \section{An Example Translation}
  5998. Figure~\ref{fig:add-fun} shows an example translation of a simple
  5999. function in $R_4$ to x86. The figure also includes the results of the
  6000. \code{explicate-control} and \code{select-instructions} passes. We
  6001. have omitted the \code{has-type} AST nodes for readability. Can you
  6002. see any ways to improve the translation?
  6003. \begin{figure}[tbp]
  6004. \begin{tabular}{ll}
  6005. \begin{minipage}{0.45\textwidth}
  6006. % s3_2.rkt
  6007. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6008. (program
  6009. (define (add [x : Integer]
  6010. [y : Integer])
  6011. : Integer (+ x y))
  6012. (add 40 2))
  6013. \end{lstlisting}
  6014. $\Downarrow$
  6015. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6016. (program ()
  6017. (define (add86 [x87 : Integer]
  6018. [y88 : Integer]) : Integer ()
  6019. ((add86start . (return (+ x87 y88)))))
  6020. (define (main) : Integer ()
  6021. ((mainstart .
  6022. (seq (assign tmp89 (fun-ref add86))
  6023. (tailcall tmp89 40 2))))))
  6024. \end{lstlisting}
  6025. \end{minipage}
  6026. &
  6027. $\Rightarrow$
  6028. \begin{minipage}{0.5\textwidth}
  6029. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6030. (program ()
  6031. (define (add86)
  6032. ((locals (x87 . Integer) (y88 . Integer))
  6033. (num-params . 2))
  6034. ((add86start .
  6035. (block ()
  6036. (movq (reg rcx) (var x87))
  6037. (movq (reg rdx) (var y88))
  6038. (movq (var x87) (reg rax))
  6039. (addq (var y88) (reg rax))
  6040. (jmp add86conclusion)))))
  6041. (define (main)
  6042. ((locals . ((tmp89 . (Integer Integer -> Integer))))
  6043. (num-params . 0))
  6044. ((mainstart .
  6045. (block ()
  6046. (leaq (fun-ref add86) (var tmp89))
  6047. (movq (int 40) (reg rcx))
  6048. (movq (int 2) (reg rdx))
  6049. (tail-jmp (var tmp89))))))
  6050. \end{lstlisting}
  6051. $\Downarrow$
  6052. \end{minipage}
  6053. \end{tabular}
  6054. \begin{tabular}{lll}
  6055. \begin{minipage}{0.3\textwidth}
  6056. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6057. _add90start:
  6058. movq %rcx, %rsi
  6059. movq %rdx, %rcx
  6060. movq %rsi, %rax
  6061. addq %rcx, %rax
  6062. jmp _add90conclusion
  6063. .globl _add90
  6064. .align 16
  6065. _add90:
  6066. pushq %rbp
  6067. movq %rsp, %rbp
  6068. pushq %r12
  6069. pushq %rbx
  6070. pushq %r13
  6071. pushq %r14
  6072. subq $0, %rsp
  6073. jmp _add90start
  6074. _add90conclusion:
  6075. addq $0, %rsp
  6076. popq %r14
  6077. popq %r13
  6078. popq %rbx
  6079. popq %r12
  6080. subq $0, %r15
  6081. popq %rbp
  6082. retq
  6083. \end{lstlisting}
  6084. \end{minipage}
  6085. &
  6086. \begin{minipage}{0.3\textwidth}
  6087. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6088. _mainstart:
  6089. leaq _add90(%rip), %rsi
  6090. movq $40, %rcx
  6091. movq $2, %rdx
  6092. movq %rsi, %rax
  6093. addq $0, %rsp
  6094. popq %r14
  6095. popq %r13
  6096. popq %rbx
  6097. popq %r12
  6098. subq $0, %r15
  6099. popq %rbp
  6100. jmp *%rax
  6101. .globl _main
  6102. .align 16
  6103. _main:
  6104. pushq %rbp
  6105. movq %rsp, %rbp
  6106. pushq %r12
  6107. pushq %rbx
  6108. pushq %r13
  6109. pushq %r14
  6110. subq $0, %rsp
  6111. movq $16384, %rdi
  6112. movq $16, %rsi
  6113. callq _initialize
  6114. movq _rootstack_begin(%rip), %r15
  6115. jmp _mainstart
  6116. \end{lstlisting}
  6117. \end{minipage}
  6118. &
  6119. \begin{minipage}{0.3\textwidth}
  6120. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6121. _mainconclusion:
  6122. addq $0, %rsp
  6123. popq %r14
  6124. popq %r13
  6125. popq %rbx
  6126. popq %r12
  6127. subq $0, %r15
  6128. popq %rbp
  6129. retq
  6130. \end{lstlisting}
  6131. \end{minipage}
  6132. \end{tabular}
  6133. \caption{Example compilation of a simple function to x86.}
  6134. \label{fig:add-fun}
  6135. \end{figure}
  6136. \begin{exercise}\normalfont
  6137. Expand your compiler to handle $R_4$ as outlined in this chapter.
  6138. Create 5 new programs that use functions, including examples that pass
  6139. functions and return functions from other functions and including
  6140. recursive functions. Test your compiler on these new programs and all
  6141. of your previously created test programs.
  6142. \end{exercise}
  6143. \begin{figure}[p]
  6144. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6145. \node (R4) at (0,2) {\large $R_4$};
  6146. \node (R4-2) at (3,2) {\large $R_4$};
  6147. \node (R4-3) at (6,2) {\large $R_4$};
  6148. \node (F1-1) at (12,0) {\large $F_1$};
  6149. \node (F1-2) at (9,0) {\large $F_1$};
  6150. \node (F1-3) at (6,0) {\large $F_1$};
  6151. \node (F1-4) at (3,0) {\large $F_1$};
  6152. \node (C3-1) at (6,-2) {\large $C_3$};
  6153. \node (C3-2) at (3,-2) {\large $C_3$};
  6154. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  6155. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  6156. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  6157. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  6158. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  6159. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  6160. \path[->,bend left=15] (R4) edge [above] node
  6161. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  6162. \path[->,bend left=15] (R4-2) edge [above] node
  6163. {\ttfamily\footnotesize uniquify} (R4-3);
  6164. \path[->,bend left=15] (R4-3) edge [right] node
  6165. {\ttfamily\footnotesize\color{red} reveal-functions} (F1-1);
  6166. \path[->,bend left=15] (F1-1) edge [below] node
  6167. {\ttfamily\footnotesize\color{red} limit-functions} (F1-2);
  6168. \path[->,bend right=15] (F1-2) edge [above] node
  6169. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  6170. \path[->,bend right=15] (F1-3) edge [above] node
  6171. {\ttfamily\footnotesize\color{red} remove-complex.} (F1-4);
  6172. \path[->,bend left=15] (F1-4) edge [right] node
  6173. {\ttfamily\footnotesize\color{red} explicate-control} (C3-1);
  6174. \path[->,bend left=15] (C3-1) edge [below] node
  6175. {\ttfamily\footnotesize\color{red} uncover-locals} (C3-2);
  6176. \path[->,bend right=15] (C3-2) edge [left] node
  6177. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  6178. \path[->,bend left=15] (x86-2) edge [left] node
  6179. {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  6180. \path[->,bend right=15] (x86-2-1) edge [below] node
  6181. {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  6182. \path[->,bend right=15] (x86-2-2) edge [left] node
  6183. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6184. \path[->,bend left=15] (x86-3) edge [above] node
  6185. {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  6186. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  6187. \end{tikzpicture}
  6188. \caption{Diagram of the passes for $R_4$, a language with functions.}
  6189. \label{fig:R4-passes}
  6190. \end{figure}
  6191. Figure~\ref{fig:R4-passes} gives an overview of the passes needed for
  6192. the compilation of $R_4$.
  6193. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6194. \chapter{Lexically Scoped Functions}
  6195. \label{ch:lambdas}
  6196. This chapter studies lexically scoped functions as they appear in
  6197. functional languages such as Racket. By lexical scoping we mean that a
  6198. function's body may refer to variables whose binding site is outside
  6199. of the function, in an enclosing scope.
  6200. %
  6201. Consider the example in Figure~\ref{fig:lexical-scoping} featuring an
  6202. anonymous function defined using the \key{lambda} form. The body of
  6203. the \key{lambda}, refers to three variables: \code{x}, \code{y}, and
  6204. \code{z}. The binding sites for \code{x} and \code{y} are outside of
  6205. the \key{lambda}. Variable \code{y} is bound by the enclosing
  6206. \key{let} and \code{x} is a parameter of \code{f}. The \key{lambda} is
  6207. returned from the function \code{f}. Below the definition of \code{f},
  6208. we have two calls to \code{f} with different arguments for \code{x},
  6209. first \code{5} then \code{3}. The functions returned from \code{f} are
  6210. bound to variables \code{g} and \code{h}. Even though these two
  6211. functions were created by the same \code{lambda}, they are really
  6212. different functions because they use different values for
  6213. \code{x}. Finally, we apply \code{g} to \code{11} (producing
  6214. \code{20}) and apply \code{h} to \code{15} (producing \code{22}) so
  6215. the result of this program is \code{42}.
  6216. \begin{figure}[btp]
  6217. % s4_6.rkt
  6218. \begin{lstlisting}
  6219. (define (f [x : Integer]) : (Integer -> Integer)
  6220. (let ([y 4])
  6221. (lambda: ([z : Integer]) : Integer
  6222. (+ x (+ y z)))))
  6223. (let ([g (f 5)])
  6224. (let ([h (f 3)])
  6225. (+ (g 11) (h 15))))
  6226. \end{lstlisting}
  6227. \caption{Example of a lexically scoped function.}
  6228. \label{fig:lexical-scoping}
  6229. \end{figure}
  6230. \section{The $R_5$ Language}
  6231. The syntax for this language with anonymous functions and lexical
  6232. scoping, $R_5$, is defined in Figure~\ref{fig:r5-syntax}. It adds the
  6233. \key{lambda} form to the grammar for $R_4$, which already has syntax
  6234. for function application. In this chapter we shall describe how to
  6235. compile $R_5$ back into $R_4$, compiling lexically-scoped functions
  6236. into a combination of functions (as in $R_4$) and tuples (as in
  6237. $R_3$).
  6238. \begin{figure}[tp]
  6239. \centering
  6240. \fbox{
  6241. \begin{minipage}{0.96\textwidth}
  6242. \[
  6243. \begin{array}{lcl}
  6244. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6245. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}
  6246. \mid (\Type^{*} \; \key{->}\; \Type)} \\
  6247. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6248. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  6249. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}}\\
  6250. &\mid& \gray{\key{\#t} \mid \key{\#f}
  6251. \mid (\key{and}\;\Exp\;\Exp)
  6252. \mid (\key{or}\;\Exp\;\Exp)
  6253. \mid (\key{not}\;\Exp) } \\
  6254. &\mid& \gray{(\key{eq?}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6255. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  6256. (\key{vector-ref}\;\Exp\;\Int)} \\
  6257. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  6258. &\mid& \gray{(\Exp \; \Exp^{*})} \\
  6259. &\mid& (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  6260. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6261. R_5 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  6262. \end{array}
  6263. \]
  6264. \end{minipage}
  6265. }
  6266. \caption{Syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax})
  6267. with \key{lambda}.}
  6268. \label{fig:r5-syntax}
  6269. \end{figure}
  6270. To compile lexically-scoped functions to top-level function
  6271. definitions, the compiler will need to provide special treatment to
  6272. variable occurrences such as \code{x} and \code{y} in the body of the
  6273. \code{lambda} of Figure~\ref{fig:lexical-scoping}, for the functions
  6274. of $R_4$ may not refer to variables defined outside the function. To
  6275. identify such variable occurrences, we review the standard notion of
  6276. free variable.
  6277. \begin{definition}
  6278. A variable is \emph{free with respect to an expression} $e$ if the
  6279. variable occurs inside $e$ but does not have an enclosing binding in
  6280. $e$.
  6281. \end{definition}
  6282. For example, the variables \code{x}, \code{y}, and \code{z} are all
  6283. free with respect to the expression \code{(+ x (+ y z))}. On the
  6284. other hand, only \code{x} and \code{y} are free with respect to the
  6285. following expression because \code{z} is bound by the \code{lambda}.
  6286. \begin{lstlisting}
  6287. (lambda: ([z : Integer]) : Integer
  6288. (+ x (+ y z)))
  6289. \end{lstlisting}
  6290. Once we have identified the free variables of a \code{lambda}, we need
  6291. to arrange for some way to transport, at runtime, the values of those
  6292. variables from the point where the \code{lambda} was created to the
  6293. point where the \code{lambda} is applied. Referring again to
  6294. Figure~\ref{fig:lexical-scoping}, the binding of \code{x} to \code{5}
  6295. needs to be used in the application of \code{g} to \code{11}, but the
  6296. binding of \code{x} to \code{3} needs to be used in the application of
  6297. \code{h} to \code{15}. An efficient solution to the problem, due to
  6298. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  6299. free variables together with the function pointer for the lambda's
  6300. code, an arrangement called a \emph{flat closure} (which we shorten to
  6301. just ``closure'') . Fortunately, we have all the ingredients to make
  6302. closures, Chapter~\ref{ch:tuples} gave us vectors and
  6303. Chapter~\ref{ch:functions} gave us function pointers. The function
  6304. pointer shall reside at index $0$ and the values for free variables
  6305. will fill in the rest of the vector. Figure~\ref{fig:closures} depicts
  6306. the two closures created by the two calls to \code{f} in
  6307. Figure~\ref{fig:lexical-scoping}. Because the two closures came from
  6308. the same \key{lambda}, they share the same function pointer but differ
  6309. in the values for the free variable \code{x}.
  6310. \begin{figure}[tbp]
  6311. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  6312. \caption{Example closure representation for the \key{lambda}'s
  6313. in Figure~\ref{fig:lexical-scoping}.}
  6314. \label{fig:closures}
  6315. \end{figure}
  6316. \section{Interpreting $R_5$}
  6317. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  6318. $R_5$. The clause for \key{lambda} saves the current environment
  6319. inside the returned \key{lambda}. Then the clause for \key{app} uses
  6320. the environment from the \key{lambda}, the \code{lam-env}, when
  6321. interpreting the body of the \key{lambda}. The \code{lam-env}
  6322. environment is extended with the mapping of parameters to argument
  6323. values.
  6324. \begin{figure}[tbp]
  6325. \begin{lstlisting}
  6326. (define (interp-exp env)
  6327. (lambda (e)
  6328. (define recur (interp-exp env))
  6329. (match e
  6330. ...
  6331. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  6332. `(lambda ,xs ,body ,env)]
  6333. [`(app ,fun ,args ...)
  6334. (define fun-val ((interp-exp env) fun))
  6335. (define arg-vals (map (interp-exp env) args))
  6336. (match fun-val
  6337. [`(lambda (,xs ...) ,body ,lam-env)
  6338. (define new-env (append (map cons xs arg-vals) lam-env))
  6339. ((interp-exp new-env) body)]
  6340. [else (error "interp-exp, expected function, not" fun-val)])]
  6341. [else (error 'interp-exp "unrecognized expression")]
  6342. )))
  6343. \end{lstlisting}
  6344. \caption{Interpreter for $R_5$.}
  6345. \label{fig:interp-R5}
  6346. \end{figure}
  6347. \section{Type Checking $R_5$}
  6348. Figure~\ref{fig:typecheck-R5} shows how to type check the new
  6349. \key{lambda} form. The body of the \key{lambda} is checked in an
  6350. environment that includes the current environment (because it is
  6351. lexically scoped) and also includes the \key{lambda}'s parameters. We
  6352. require the body's type to match the declared return type.
  6353. \begin{figure}[tbp]
  6354. \begin{lstlisting}
  6355. (define (typecheck-R5 env)
  6356. (lambda (e)
  6357. (match e
  6358. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  6359. (define new-env (append (map cons xs Ts) env))
  6360. (define bodyT ((typecheck-R5 new-env) body))
  6361. (cond [(equal? rT bodyT)
  6362. `(,@Ts -> ,rT)]
  6363. [else
  6364. (error "mismatch in return type" bodyT rT)])]
  6365. ...
  6366. )))
  6367. \end{lstlisting}
  6368. \caption{Type checking the \key{lambda}'s in $R_5$.}
  6369. \label{fig:typecheck-R5}
  6370. \end{figure}
  6371. \section{Closure Conversion}
  6372. The compiling of lexically-scoped functions into top-level function
  6373. definitions is accomplished in the pass \code{convert-to-closures}
  6374. that comes after \code{reveal-functions} and before
  6375. \code{limit-functions}.
  6376. As usual, we shall implement the pass as a recursive function over the
  6377. AST. All of the action is in the clauses for \key{lambda} and
  6378. \key{app}. We transform a \key{lambda} expression into an expression
  6379. that creates a closure, that is, creates a vector whose first element
  6380. is a function pointer and the rest of the elements are the free
  6381. variables of the \key{lambda}. The \itm{name} is a unique symbol
  6382. generated to identify the function.
  6383. \begin{tabular}{lll}
  6384. \begin{minipage}{0.4\textwidth}
  6385. \begin{lstlisting}
  6386. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  6387. \end{lstlisting}
  6388. \end{minipage}
  6389. &
  6390. $\Rightarrow$
  6391. &
  6392. \begin{minipage}{0.4\textwidth}
  6393. \begin{lstlisting}
  6394. (vector |\itm{name}| |\itm{fvs}| ...)
  6395. \end{lstlisting}
  6396. \end{minipage}
  6397. \end{tabular} \\
  6398. %
  6399. In addition to transforming each \key{lambda} into a \key{vector}, we
  6400. must create a top-level function definition for each \key{lambda}, as
  6401. shown below.\\
  6402. \begin{minipage}{0.8\textwidth}
  6403. \begin{lstlisting}
  6404. (define (|\itm{name}| [clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps}| ...)
  6405. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  6406. ...
  6407. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  6408. |\itm{body'}|)...))
  6409. \end{lstlisting}
  6410. \end{minipage}\\
  6411. The \code{clos} parameter refers to the closure. The $\itm{ps}$
  6412. parameters are the normal parameters of the \key{lambda}. The types
  6413. $\itm{fvts}$ are the types of the free variables in the lambda and the
  6414. underscore is a dummy type because it is rather difficult to give a
  6415. type to the function in the closure's type, and it does not matter.
  6416. The sequence of \key{let} forms bind the free variables to their
  6417. values obtained from the closure.
  6418. We transform function application into code that retrieves the
  6419. function pointer from the closure and then calls the function, passing
  6420. in the closure as the first argument. We bind $e'$ to a temporary
  6421. variable to avoid code duplication.
  6422. \begin{tabular}{lll}
  6423. \begin{minipage}{0.3\textwidth}
  6424. \begin{lstlisting}
  6425. (app |$e$| |\itm{es}| ...)
  6426. \end{lstlisting}
  6427. \end{minipage}
  6428. &
  6429. $\Rightarrow$
  6430. &
  6431. \begin{minipage}{0.5\textwidth}
  6432. \begin{lstlisting}
  6433. (let ([|\itm{tmp}| |$e'$|])
  6434. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  6435. \end{lstlisting}
  6436. \end{minipage}
  6437. \end{tabular} \\
  6438. There is also the question of what to do with top-level function
  6439. definitions. To maintain a uniform translation of function
  6440. application, we turn function references into closures.
  6441. \begin{tabular}{lll}
  6442. \begin{minipage}{0.3\textwidth}
  6443. \begin{lstlisting}
  6444. (fun-ref |$f$|)
  6445. \end{lstlisting}
  6446. \end{minipage}
  6447. &
  6448. $\Rightarrow$
  6449. &
  6450. \begin{minipage}{0.5\textwidth}
  6451. \begin{lstlisting}
  6452. (vector (fun-ref |$f$|))
  6453. \end{lstlisting}
  6454. \end{minipage}
  6455. \end{tabular} \\
  6456. %
  6457. The top-level function definitions need to be updated as well to take
  6458. an extra closure parameter.
  6459. \section{An Example Translation}
  6460. \label{sec:example-lambda}
  6461. Figure~\ref{fig:lexical-functions-example} shows the result of closure
  6462. conversion for the example program demonstrating lexical scoping that
  6463. we discussed at the beginning of this chapter.
  6464. \begin{figure}[h]
  6465. \begin{minipage}{0.8\textwidth}
  6466. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6467. (program
  6468. (define (f [x : Integer]) : (Integer -> Integer)
  6469. (let ([y 4])
  6470. (lambda: ([z : Integer]) : Integer
  6471. (+ x (+ y z)))))
  6472. (let ([g (f 5)])
  6473. (let ([h (f 3)])
  6474. (+ (g 11) (h 15)))))
  6475. \end{lstlisting}
  6476. $\Downarrow$
  6477. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6478. (program (type Integer)
  6479. (define (f (x : Integer)) : (Integer -> Integer)
  6480. (let ((y 4))
  6481. (lambda: ((z : Integer)) : Integer
  6482. (+ x (+ y z)))))
  6483. (let ((g (app (fun-ref f) 5)))
  6484. (let ((h (app (fun-ref f) 3)))
  6485. (+ (app g 11) (app h 15)))))
  6486. \end{lstlisting}
  6487. $\Downarrow$
  6488. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6489. (program (type Integer)
  6490. (define (f (clos.1 : _) (x : Integer)) : (Integer -> Integer)
  6491. (let ((y 4))
  6492. (vector (fun-ref lam.1) x y)))
  6493. (define (lam.1 (clos.2 : _) (z : Integer)) : Integer
  6494. (let ((x (vector-ref clos.2 1)))
  6495. (let ((y (vector-ref clos.2 2)))
  6496. (+ x (+ y z)))))
  6497. (let ((g (let ((t.1 (vector (fun-ref f))))
  6498. (app (vector-ref t.1 0) t.1 5))))
  6499. (let ((h (let ((t.2 (vector (fun-ref f))))
  6500. (app (vector-ref t.2 0) t.2 3))))
  6501. (+ (let ((t.3 g)) (app (vector-ref t.3 0) t.3 11))
  6502. (let ((t.4 h)) (app (vector-ref t.4 0) t.4 15))))))
  6503. \end{lstlisting}
  6504. \end{minipage}
  6505. \caption{Example of closure conversion.}
  6506. \label{fig:lexical-functions-example}
  6507. \end{figure}
  6508. \begin{figure}[p]
  6509. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6510. \node (R4) at (0,2) {\large $R_4$};
  6511. \node (R4-2) at (3,2) {\large $R_4$};
  6512. \node (R4-3) at (6,2) {\large $R_4$};
  6513. \node (F1-1) at (12,0) {\large $F_1$};
  6514. \node (F1-2) at (9,0) {\large $F_1$};
  6515. \node (F1-3) at (6,0) {\large $F_1$};
  6516. \node (F1-4) at (3,0) {\large $F_1$};
  6517. \node (F1-5) at (0,0) {\large $F_1$};
  6518. \node (C3-1) at (6,-2) {\large $C_3$};
  6519. \node (C3-2) at (3,-2) {\large $C_3$};
  6520. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  6521. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  6522. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  6523. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  6524. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  6525. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  6526. \path[->,bend left=15] (R4) edge [above] node
  6527. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  6528. \path[->,bend left=15] (R4-2) edge [above] node
  6529. {\ttfamily\footnotesize uniquify} (R4-3);
  6530. \path[->] (R4-3) edge [right] node
  6531. {\ttfamily\footnotesize reveal-functions} (F1-1);
  6532. \path[->,bend left=15] (F1-1) edge [below] node
  6533. {\ttfamily\footnotesize\color{red} convert-to-clos.} (F1-2);
  6534. \path[->,bend right=15] (F1-2) edge [above] node
  6535. {\ttfamily\footnotesize limit-functions} (F1-3);
  6536. \path[->,bend right=15] (F1-3) edge [above] node
  6537. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  6538. \path[->,bend right=15] (F1-4) edge [above] node
  6539. {\ttfamily\footnotesize remove-complex.} (F1-5);
  6540. \path[->] (F1-5) edge [left] node
  6541. {\ttfamily\footnotesize explicate-control} (C3-1);
  6542. \path[->,bend left=15] (C3-1) edge [below] node
  6543. {\ttfamily\footnotesize uncover-locals} (C3-2);
  6544. \path[->,bend right=15] (C3-2) edge [left] node
  6545. {\ttfamily\footnotesize select-instr.} (x86-2);
  6546. \path[->,bend left=15] (x86-2) edge [left] node
  6547. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6548. \path[->,bend right=15] (x86-2-1) edge [below] node
  6549. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  6550. \path[->,bend right=15] (x86-2-2) edge [left] node
  6551. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6552. \path[->,bend left=15] (x86-3) edge [above] node
  6553. {\ttfamily\footnotesize patch-instr.} (x86-4);
  6554. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  6555. \end{tikzpicture}
  6556. \caption{Diagram of the passes for $R_5$, a language with lexically-scoped
  6557. functions.}
  6558. \label{fig:R5-passes}
  6559. \end{figure}
  6560. Figure~\ref{fig:R5-passes} provides an overview of all the passes needed
  6561. for the compilation of $R_5$.
  6562. \begin{exercise}\normalfont
  6563. Expand your compiler to handle $R_5$ as outlined in this chapter.
  6564. Create 5 new programs that use \key{lambda} functions and make use of
  6565. lexical scoping. Test your compiler on these new programs and all of
  6566. your previously created test programs.
  6567. \end{exercise}
  6568. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6569. \chapter{Dynamic Typing}
  6570. \label{ch:type-dynamic}
  6571. In this chapter we discuss the compilation of a dynamically typed
  6572. language, named $R_7$, that is a subset of the Racket
  6573. language. (Recall that in the previous chapters we have studied
  6574. subsets of the \emph{Typed} Racket language.) In dynamically typed
  6575. languages, an expression may produce values of differing
  6576. type. Consider the following example with a conditional expression
  6577. that may return a Boolean or an integer depending on the input to the
  6578. program.
  6579. \begin{lstlisting}
  6580. (not (if (eq? (read) 1) #f 0))
  6581. \end{lstlisting}
  6582. Languages that allow expressions to produce different kinds of values
  6583. are called \emph{polymorphic}. There are many kinds of polymorphism,
  6584. such as subtype polymorphism and parametric
  6585. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism are
  6586. talking about here does not have a special name, but it is the usual
  6587. kind that arises in dynamically typed languages.
  6588. Another characteristic of dynamically typed languages is that
  6589. primitive operations, such as \code{not}, are often defined to operate
  6590. on many different types of values. In fact, in Racket, the \code{not}
  6591. operator produces a result for any kind of value: given \code{\#f} it
  6592. returns \code{\#t} and given anything else it returns \code{\#f}.
  6593. Furthermore, even when primitive operations restrict their inputs to
  6594. values of a certain type, this restriction is enforced at runtime
  6595. instead of during compilation. For example, the following vector
  6596. reference results in a run-time contract violation.
  6597. \begin{lstlisting}
  6598. (vector-ref (vector 42) #t)
  6599. \end{lstlisting}
  6600. \begin{figure}[tp]
  6601. \centering
  6602. \fbox{
  6603. \begin{minipage}{0.97\textwidth}
  6604. \[
  6605. \begin{array}{rcl}
  6606. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  6607. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6608. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp) \\
  6609. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  6610. &\mid& \key{\#t} \mid \key{\#f}
  6611. \mid (\key{and}\;\Exp\;\Exp)
  6612. \mid (\key{or}\;\Exp\;\Exp)
  6613. \mid (\key{not}\;\Exp) \\
  6614. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  6615. &\mid& (\key{vector}\;\Exp^{+}) \mid
  6616. (\key{vector-ref}\;\Exp\;\Exp) \\
  6617. &\mid& (\key{vector-set!}\;\Exp\;\Exp\;\Exp) \mid (\key{void}) \\
  6618. &\mid& (\Exp \; \Exp^{*}) \mid (\key{lambda}\; (\Var^{*}) \; \Exp) \\
  6619. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  6620. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  6621. \Def &::=& (\key{define}\; (\Var \; \Var^{*}) \; \Exp) \\
  6622. R_7 &::=& (\key{program} \; \Def^{*}\; \Exp)
  6623. \end{array}
  6624. \]
  6625. \end{minipage}
  6626. }
  6627. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  6628. \label{fig:r7-syntax}
  6629. \end{figure}
  6630. The syntax of $R_7$, our subset of Racket, is defined in
  6631. Figure~\ref{fig:r7-syntax}.
  6632. %
  6633. The definitional interpreter for $R_7$ is given in
  6634. Figure~\ref{fig:interp-R7}.
  6635. \begin{figure}[tbp]
  6636. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6637. (define (get-tagged-type v) (match v [`(tagged ,v1 ,ty) ty]))
  6638. (define (valid-op? op) (member op '(+ - and or not)))
  6639. (define (interp-r7 env)
  6640. (lambda (ast)
  6641. (define recur (interp-r7 env))
  6642. (match ast
  6643. [(? symbol?) (lookup ast env)]
  6644. [(? integer?) `(inject ,ast Integer)]
  6645. [#t `(inject #t Boolean)]
  6646. [#f `(inject #f Boolean)]
  6647. [`(read) `(inject ,(read-fixnum) Integer)]
  6648. [`(lambda (,xs ...) ,body)
  6649. `(inject (lambda ,xs ,body ,env) (,@(map (lambda (x) 'Any) xs) -> Any))]
  6650. [`(define (,f ,xs ...) ,body)
  6651. (mcons f `(lambda ,xs ,body))]
  6652. [`(program ,ds ... ,body)
  6653. (let ([top-level (for/list ([d ds]) ((interp-r7 '()) d))])
  6654. (for/list ([b top-level])
  6655. (set-mcdr! b (match (mcdr b)
  6656. [`(lambda ,xs ,body)
  6657. `(inject (lambda ,xs ,body ,top-level)
  6658. (,@(map (lambda (x) 'Any) xs) -> Any))])))
  6659. ((interp-r7 top-level) body))]
  6660. [`(vector ,(app recur elts) ...)
  6661. (define tys (map get-tagged-type elts))
  6662. `(inject ,(apply vector elts) (Vector ,@tys))]
  6663. [`(vector-set! ,(app recur v1) ,n ,(app recur v2))
  6664. (match v1
  6665. [`(inject ,vec ,ty)
  6666. (vector-set! vec n v2)
  6667. `(inject (void) Void)])]
  6668. [`(vector-ref ,(app recur v) ,n)
  6669. (match v [`(inject ,vec ,ty) (vector-ref vec n)])]
  6670. [`(let ([,x ,(app recur v)]) ,body)
  6671. ((interp-r7 (cons (cons x v) env)) body)]
  6672. [`(,op ,es ...) #:when (valid-op? op)
  6673. (interp-r7-op op (for/list ([e es]) (recur e)))]
  6674. [`(eq? ,(app recur l) ,(app recur r))
  6675. `(inject ,(equal? l r) Boolean)]
  6676. [`(if ,(app recur q) ,t ,f)
  6677. (match q
  6678. [`(inject #f Boolean) (recur f)]
  6679. [else (recur t)])]
  6680. [`(,(app recur f-val) ,(app recur vs) ...)
  6681. (match f-val
  6682. [`(inject (lambda (,xs ...) ,body ,lam-env) ,ty)
  6683. (define new-env (append (map cons xs vs) lam-env))
  6684. ((interp-r7 new-env) body)]
  6685. [else (error "interp-r7, expected function, not" f-val)])])))
  6686. \end{lstlisting}
  6687. \caption{Interpreter for the $R_7$ language. UPDATE ME -Jeremy}
  6688. \label{fig:interp-R7}
  6689. \end{figure}
  6690. Let us consider how we might compile $R_7$ to x86, thinking about the
  6691. first example above. Our bit-level representation of the Boolean
  6692. \code{\#f} is zero and similarly for the integer \code{0}. However,
  6693. \code{(not \#f)} should produce \code{\#t} whereas \code{(not 0)}
  6694. should produce \code{\#f}. Furthermore, the behavior of \code{not}, in
  6695. general, cannot be determined at compile time, but depends on the
  6696. runtime type of its input, as in the example above that depends on the
  6697. result of \code{(read)}.
  6698. The way around this problem is to include information about a value's
  6699. runtime type in the value itself, so that this information can be
  6700. inspected by operators such as \code{not}. In particular, we shall
  6701. steal the 3 right-most bits from our 64-bit values to encode the
  6702. runtime type. We shall use $001$ to identify integers, $100$ for
  6703. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  6704. void value. We shall refer to these 3 bits as the \emph{tag} and we
  6705. define the following auxiliary function.
  6706. \begin{align*}
  6707. \itm{tagof}(\key{Integer}) &= 001 \\
  6708. \itm{tagof}(\key{Boolean}) &= 100 \\
  6709. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  6710. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  6711. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  6712. \itm{tagof}(\key{Void}) &= 101
  6713. \end{align*}
  6714. (We shall say more about the new \key{Vectorof} type shortly.)
  6715. This stealing of 3 bits comes at some
  6716. price: our integers are reduced to ranging from $-2^{60}$ to
  6717. $2^{60}$. The stealing does not adversely affect vectors and
  6718. procedures because those values are addresses, and our addresses are
  6719. 8-byte aligned so the rightmost 3 bits are unused, they are always
  6720. $000$. Thus, we do not lose information by overwriting the rightmost 3
  6721. bits with the tag and we can simply zero-out the tag to recover the
  6722. original address.
  6723. In some sense, these tagged values are a new kind of value. Indeed,
  6724. we can extend our \emph{typed} language with tagged values by adding a
  6725. new type to classify them, called \key{Any}, and with operations for
  6726. creating and using tagged values, yielding the $R_6$ language that we
  6727. define in Section~\ref{sec:r6-lang}. The $R_6$ language provides the
  6728. fundamental support for polymorphism and runtime types that we need to
  6729. support dynamic typing.
  6730. There is an interesting interaction between tagged values and garbage
  6731. collection. A variable of type \code{Any} might refer to a vector and
  6732. therefore it might be a root that needs to be inspected and copied
  6733. during garbage collection. Thus, we need to treat variables of type
  6734. \code{Any} in a similar way to variables of type \code{Vector} for
  6735. purposes of register allocation, which we discuss in
  6736. Section~\ref{sec:register-allocation-r6}. One concern is that, if a
  6737. variable of type \code{Any} is spilled, it must be spilled to the root
  6738. stack. But this means that the garbage collector needs to be able to
  6739. differentiate between (1) plain old pointers to tuples, (2) a tagged
  6740. value that points to a tuple, and (3) a tagged value that is not a
  6741. tuple. We enable this differentiation by choosing not to use the tag
  6742. $000$. Instead, that bit pattern is reserved for identifying plain old
  6743. pointers to tuples. On the other hand, if one of the first three bits
  6744. is set, then we have a tagged value, and inspecting the tag can
  6745. differentiation between vectors ($010$) and the other kinds of values.
  6746. We shall implement our untyped language $R_7$ by compiling it to $R_6$
  6747. (Section~\ref{sec:compile-r7}), but first we describe the how to
  6748. extend our compiler to handle the new features of $R_6$
  6749. (Sections~\ref{sec:shrink-r6}, \ref{sec:select-r6}, and
  6750. \ref{sec:register-allocation-r6}).
  6751. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  6752. \label{sec:r6-lang}
  6753. \begin{figure}[tp]
  6754. \centering
  6755. \fbox{
  6756. \begin{minipage}{0.97\textwidth}
  6757. \[
  6758. \begin{array}{lcl}
  6759. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6760. \mid (\key{Vector}\;\Type^{+}) \mid (\key{Vectorof}\;\Type) \mid \key{Void}} \\
  6761. &\mid& \gray{(\Type^{*} \; \key{->}\; \Type)} \mid \key{Any} \\
  6762. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void} \mid (\key{Vectorof}\;\key{Any}) \mid (\key{Vector}\; \key{Any}^{*}) \\
  6763. &\mid& (\key{Any}^{*} \; \key{->}\; \key{Any})\\
  6764. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  6765. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6766. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  6767. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  6768. &\mid& \gray{\key{\#t} \mid \key{\#f}
  6769. \mid (\key{and}\;\Exp\;\Exp)
  6770. \mid (\key{or}\;\Exp\;\Exp)
  6771. \mid (\key{not}\;\Exp)} \\
  6772. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6773. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  6774. (\key{vector-ref}\;\Exp\;\Int)} \\
  6775. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  6776. &\mid& \gray{(\Exp \; \Exp^{*})
  6777. \mid (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6778. & \mid & (\key{inject}\; \Exp \; \FType) \mid (\key{project}\;\Exp\;\FType) \\
  6779. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  6780. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  6781. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6782. R_6 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  6783. \end{array}
  6784. \]
  6785. \end{minipage}
  6786. }
  6787. \caption{Syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax})
  6788. with \key{Any}.}
  6789. \label{fig:r6-syntax}
  6790. \end{figure}
  6791. The syntax of $R_6$ is defined in Figure~\ref{fig:r6-syntax}. The
  6792. $(\key{inject}\; e\; T)$ form converts the value produced by
  6793. expression $e$ of type $T$ into a tagged value. The
  6794. $(\key{project}\;e\;T)$ form converts the tagged value produced by
  6795. expression $e$ into a value of type $T$ or else halts the program if
  6796. the type tag is equivalent to $T$. We treat
  6797. $(\key{Vectorof}\;\key{Any})$ as equivalent to
  6798. $(\key{Vector}\;\key{Any}\;\ldots)$.
  6799. Note that in both \key{inject} and
  6800. \key{project}, the type $T$ is restricted to the flat types $\FType$,
  6801. which simplifies the implementation and corresponds with what is
  6802. needed for compiling untyped Racket. The type predicates,
  6803. $(\key{boolean?}\,e)$ etc., expect a tagged value and return \key{\#t}
  6804. if the tag corresponds to the predicate, and return \key{\#t}
  6805. otherwise.
  6806. %
  6807. Selections from the type checker for $R_6$ are shown in
  6808. Figure~\ref{fig:typecheck-R6} and the interpreter for $R_6$ is in
  6809. Figure~\ref{fig:interp-R6}.
  6810. \begin{figure}[btp]
  6811. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6812. (define (flat-ty? ty) ...)
  6813. (define (typecheck-R6 env)
  6814. (lambda (e)
  6815. (define recur (typecheck-R6 env))
  6816. (match e
  6817. [`(inject ,e ,ty)
  6818. (unless (flat-ty? ty)
  6819. (error "may only inject a value of flat type, not ~a" ty))
  6820. (define-values (new-e e-ty) (recur e))
  6821. (cond
  6822. [(equal? e-ty ty)
  6823. (values `(inject ,new-e ,ty) 'Any)]
  6824. [else
  6825. (error "inject expected ~a to have type ~a" e ty)])]
  6826. [`(project ,e ,ty)
  6827. (unless (flat-ty? ty)
  6828. (error "may only project to a flat type, not ~a" ty))
  6829. (define-values (new-e e-ty) (recur e))
  6830. (cond
  6831. [(equal? e-ty 'Any)
  6832. (values `(project ,new-e ,ty) ty)]
  6833. [else
  6834. (error "project expected ~a to have type Any" e)])]
  6835. [`(vector-ref ,e ,i)
  6836. (define-values (new-e e-ty) (recur e))
  6837. (match e-ty
  6838. [`(Vector ,ts ...) ...]
  6839. [`(Vectorof ,ty)
  6840. (unless (exact-nonnegative-integer? i)
  6841. (error 'type-check "invalid index ~a" i))
  6842. (values `(vector-ref ,new-e ,i) ty)]
  6843. [else (error "expected a vector in vector-ref, not" e-ty)])]
  6844. ...
  6845. )))
  6846. \end{lstlisting}
  6847. \caption{Type checker for parts of the $R_6$ language.}
  6848. \label{fig:typecheck-R6}
  6849. \end{figure}
  6850. % to do: add rules for vector-ref, etc. for Vectorof
  6851. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  6852. \begin{figure}[btp]
  6853. \begin{lstlisting}
  6854. (define primitives (set 'boolean? ...))
  6855. (define (interp-op op)
  6856. (match op
  6857. ['boolean? (lambda (v)
  6858. (match v
  6859. [`(tagged ,v1 Boolean) #t]
  6860. [else #f]))]
  6861. ...))
  6862. ;; Equivalence of flat types
  6863. (define (tyeq? t1 t2)
  6864. (match `(,t1 ,t2)
  6865. [`((Vectorof Any) (Vector ,t2s ...))
  6866. (for/and ([t2 t2s]) (eq? t2 'Any))]
  6867. [`((Vector ,t1s ...) (Vectorof Any))
  6868. (for/and ([t1 t1s]) (eq? t1 'Any))]
  6869. [else (equal? t1 t2)]))
  6870. (define (interp-R6 env)
  6871. (lambda (ast)
  6872. (match ast
  6873. [`(inject ,e ,t)
  6874. `(tagged ,((interp-R6 env) e) ,t)]
  6875. [`(project ,e ,t2)
  6876. (define v ((interp-R6 env) e))
  6877. (match v
  6878. [`(tagged ,v1 ,t1)
  6879. (cond [(tyeq? t1 t2)
  6880. v1]
  6881. [else
  6882. (error "in project, type mismatch" t1 t2)])]
  6883. [else
  6884. (error "in project, expected tagged value" v)])]
  6885. ...)))
  6886. \end{lstlisting}
  6887. \caption{Interpreter for $R_6$.}
  6888. \label{fig:interp-R6}
  6889. \end{figure}
  6890. %\clearpage
  6891. \section{Shrinking $R_6$}
  6892. \label{sec:shrink-r6}
  6893. In the \code{shrink} pass we recommend compiling \code{project} into
  6894. an explicit \code{if} expression that uses three new operations:
  6895. \code{tag-of-any}, \code{value-of-any}, and \code{exit}. The
  6896. \code{tag-of-any} operation retrieves the type tag from a tagged value
  6897. of type \code{Any}. The \code{value-of-any} retrieves the underlying
  6898. value from a tagged value. Finally, the \code{exit} operation ends the
  6899. execution of the program by invoking the operating system's
  6900. \code{exit} function. So the translation for \code{project} is as
  6901. follows. (We have omitted the \code{has-type} AST nodes to make this
  6902. output more readable.)
  6903. \begin{tabular}{lll}
  6904. \begin{minipage}{0.3\textwidth}
  6905. \begin{lstlisting}
  6906. (project |$e$| |$\Type$|)
  6907. \end{lstlisting}
  6908. \end{minipage}
  6909. &
  6910. $\Rightarrow$
  6911. &
  6912. \begin{minipage}{0.5\textwidth}
  6913. \begin{lstlisting}
  6914. (let ([|$\itm{tmp}$| |$e'$|])
  6915. (if (eq? (tag-of-any |$\itm{tmp}$|) |$\itm{tag}$|)
  6916. (value-of-any |$\itm{tmp}$|)
  6917. (exit)))
  6918. \end{lstlisting}
  6919. \end{minipage}
  6920. \end{tabular} \\
  6921. Similarly, we recommend translating the type predicates
  6922. (\code{boolean?}, etc.) into uses of \code{tag-of-any} and \code{eq?}.
  6923. \section{Instruction Selection for $R_6$}
  6924. \label{sec:select-r6}
  6925. \paragraph{Inject}
  6926. We recommend compiling an \key{inject} as follows if the type is
  6927. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  6928. destination to the left by the number of bits specified its source
  6929. argument (in this case $3$, the length of the tag) and it preserves
  6930. the sign of the integer. We use the \key{orq} instruction to combine
  6931. the tag and the value to form the tagged value. \\
  6932. \begin{tabular}{lll}
  6933. \begin{minipage}{0.4\textwidth}
  6934. \begin{lstlisting}
  6935. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  6936. \end{lstlisting}
  6937. \end{minipage}
  6938. &
  6939. $\Rightarrow$
  6940. &
  6941. \begin{minipage}{0.5\textwidth}
  6942. \begin{lstlisting}
  6943. (movq |$e'$| |\itm{lhs}'|)
  6944. (salq (int 3) |\itm{lhs}'|)
  6945. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  6946. \end{lstlisting}
  6947. \end{minipage}
  6948. \end{tabular} \\
  6949. The instruction selection for vectors and procedures is different
  6950. because their is no need to shift them to the left. The rightmost 3
  6951. bits are already zeros as described above. So we just combine the
  6952. value and the tag using \key{orq}. \\
  6953. \begin{tabular}{lll}
  6954. \begin{minipage}{0.4\textwidth}
  6955. \begin{lstlisting}
  6956. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  6957. \end{lstlisting}
  6958. \end{minipage}
  6959. &
  6960. $\Rightarrow$
  6961. &
  6962. \begin{minipage}{0.5\textwidth}
  6963. \begin{lstlisting}
  6964. (movq |$e'$| |\itm{lhs}'|)
  6965. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  6966. \end{lstlisting}
  6967. \end{minipage}
  6968. \end{tabular}
  6969. \paragraph{Tag of Any}
  6970. Recall that the \code{tag-of-any} operation extracts the type tag from
  6971. a value of type \code{Any}. The type tag is the bottom three bits, so
  6972. we obtain the tag by taking the bitwise-and of the value with $111$
  6973. ($7$ in decimal).
  6974. \begin{tabular}{lll}
  6975. \begin{minipage}{0.4\textwidth}
  6976. \begin{lstlisting}
  6977. (assign |\itm{lhs}| (tag-of-any |$e$|))
  6978. \end{lstlisting}
  6979. \end{minipage}
  6980. &
  6981. $\Rightarrow$
  6982. &
  6983. \begin{minipage}{0.5\textwidth}
  6984. \begin{lstlisting}
  6985. (movq |$e'$| |\itm{lhs}'|)
  6986. (andq (int 7) |\itm{lhs}'|)
  6987. \end{lstlisting}
  6988. \end{minipage}
  6989. \end{tabular}
  6990. \paragraph{Value of Any}
  6991. Like \key{inject}, the instructions for \key{value-of-any} are
  6992. different depending on whether the type $T$ is a pointer (vector or
  6993. procedure) or not (Integer or Boolean). The following shows the
  6994. instruction selection for Integer and Boolean. We produce an untagged
  6995. value by shifting it to the right by 3 bits.
  6996. %
  6997. \\
  6998. \begin{tabular}{lll}
  6999. \begin{minipage}{0.4\textwidth}
  7000. \begin{lstlisting}
  7001. (assign |\itm{lhs}| (project |$e$| |$T$|))
  7002. \end{lstlisting}
  7003. \end{minipage}
  7004. &
  7005. $\Rightarrow$
  7006. &
  7007. \begin{minipage}{0.5\textwidth}
  7008. \begin{lstlisting}
  7009. (movq |$e'$| |\itm{lhs}'|)
  7010. (sarq (int 3) |\itm{lhs}'|)
  7011. \end{lstlisting}
  7012. \end{minipage}
  7013. \end{tabular} \\
  7014. %
  7015. In the case for vectors and procedures, there is no need to
  7016. shift. Instead we just need to zero-out the rightmost 3 bits. We
  7017. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  7018. decimal) and apply \code{bitwise-not} to obtain $\ldots 1000$ which we
  7019. \code{movq} into the destination $\itm{lhs}$. We then generate
  7020. \code{andq} with the tagged value to get the desired result. \\
  7021. %
  7022. \begin{tabular}{lll}
  7023. \begin{minipage}{0.4\textwidth}
  7024. \begin{lstlisting}
  7025. (assign |\itm{lhs}| (project |$e$| |$T$|))
  7026. \end{lstlisting}
  7027. \end{minipage}
  7028. &
  7029. $\Rightarrow$
  7030. &
  7031. \begin{minipage}{0.5\textwidth}
  7032. \begin{lstlisting}
  7033. (movq (int |$\ldots 1000$|) |\itm{lhs}'|)
  7034. (andq |$e'$| |\itm{lhs}'|)
  7035. \end{lstlisting}
  7036. \end{minipage}
  7037. \end{tabular}
  7038. %% \paragraph{Type Predicates} We leave it to the reader to
  7039. %% devise a sequence of instructions to implement the type predicates
  7040. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  7041. \section{Register Allocation for $R_6$}
  7042. \label{sec:register-allocation-r6}
  7043. As mentioned above, a variable of type \code{Any} might refer to a
  7044. vector. Thus, the register allocator for $R_6$ needs to treat variable
  7045. of type \code{Any} in the same way that it treats variables of type
  7046. \code{Vector} for purposes of garbage collection. In particular,
  7047. \begin{itemize}
  7048. \item If a variable of type \code{Any} is live during a function call,
  7049. then it must be spilled. One way to accomplish this is to augment
  7050. the pass \code{build-interference} to mark all variables that are
  7051. live after a \code{callq} as interfering with all the registers.
  7052. \item If a variable of type \code{Any} is spilled, it must be spilled
  7053. to the root stack instead of the normal procedure call stack.
  7054. \end{itemize}
  7055. \begin{exercise}\normalfont
  7056. Expand your compiler to handle $R_6$ as discussed in the last few
  7057. sections. Create 5 new programs that use the \code{Any} type and the
  7058. new operations (\code{inject}, \code{project}, \code{boolean?},
  7059. etc.). Test your compiler on these new programs and all of your
  7060. previously created test programs.
  7061. \end{exercise}
  7062. \section{Compiling $R_7$ to $R_6$}
  7063. \label{sec:compile-r7}
  7064. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  7065. $R_7$ forms into $R_6$. An important invariant of this pass is that
  7066. given a subexpression $e$ of $R_7$, the pass will produce an
  7067. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  7068. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  7069. the Boolean \code{\#t}, which must be injected to produce an
  7070. expression of type \key{Any}.
  7071. %
  7072. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  7073. addition, is representative of compilation for many operations: the
  7074. arguments have type \key{Any} and must be projected to \key{Integer}
  7075. before the addition can be performed.
  7076. The compilation of \key{lambda} (third row of
  7077. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  7078. produce type annotations: we simply use \key{Any}.
  7079. %
  7080. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  7081. has to account for some differences in behavior between $R_7$ and
  7082. $R_6$. The $R_7$ language is more permissive than $R_6$ regarding what
  7083. kind of values can be used in various places. For example, the
  7084. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  7085. the arguments need not be of the same type (but in that case, the
  7086. result will be \code{\#f}).
  7087. \begin{figure}[btp]
  7088. \centering
  7089. \begin{tabular}{|lll|} \hline
  7090. \begin{minipage}{0.25\textwidth}
  7091. \begin{lstlisting}
  7092. #t
  7093. \end{lstlisting}
  7094. \end{minipage}
  7095. &
  7096. $\Rightarrow$
  7097. &
  7098. \begin{minipage}{0.6\textwidth}
  7099. \begin{lstlisting}
  7100. (inject #t Boolean)
  7101. \end{lstlisting}
  7102. \end{minipage}
  7103. \\[2ex]\hline
  7104. \begin{minipage}{0.25\textwidth}
  7105. \begin{lstlisting}
  7106. (+ |$e_1$| |$e_2$|)
  7107. \end{lstlisting}
  7108. \end{minipage}
  7109. &
  7110. $\Rightarrow$
  7111. &
  7112. \begin{minipage}{0.6\textwidth}
  7113. \begin{lstlisting}
  7114. (inject
  7115. (+ (project |$e'_1$| Integer)
  7116. (project |$e'_2$| Integer))
  7117. Integer)
  7118. \end{lstlisting}
  7119. \end{minipage}
  7120. \\[2ex]\hline
  7121. \begin{minipage}{0.25\textwidth}
  7122. \begin{lstlisting}
  7123. (lambda (|$x_1 \ldots$|) |$e$|)
  7124. \end{lstlisting}
  7125. \end{minipage}
  7126. &
  7127. $\Rightarrow$
  7128. &
  7129. \begin{minipage}{0.6\textwidth}
  7130. \begin{lstlisting}
  7131. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  7132. (Any|$\ldots$|Any -> Any))
  7133. \end{lstlisting}
  7134. \end{minipage}
  7135. \\[2ex]\hline
  7136. \begin{minipage}{0.25\textwidth}
  7137. \begin{lstlisting}
  7138. (app |$e_0$| |$e_1 \ldots e_n$|)
  7139. \end{lstlisting}
  7140. \end{minipage}
  7141. &
  7142. $\Rightarrow$
  7143. &
  7144. \begin{minipage}{0.6\textwidth}
  7145. \begin{lstlisting}
  7146. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  7147. |$e'_1 \ldots e'_n$|)
  7148. \end{lstlisting}
  7149. \end{minipage}
  7150. \\[2ex]\hline
  7151. \begin{minipage}{0.25\textwidth}
  7152. \begin{lstlisting}
  7153. (vector-ref |$e_1$| |$e_2$|)
  7154. \end{lstlisting}
  7155. \end{minipage}
  7156. &
  7157. $\Rightarrow$
  7158. &
  7159. \begin{minipage}{0.6\textwidth}
  7160. \begin{lstlisting}
  7161. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  7162. (let ([tmp2 (project |$e'_2$| Integer)])
  7163. (vector-ref tmp1 tmp2)))
  7164. \end{lstlisting}
  7165. \end{minipage}
  7166. \\[2ex]\hline
  7167. \begin{minipage}{0.25\textwidth}
  7168. \begin{lstlisting}
  7169. (if |$e_1$| |$e_2$| |$e_3$|)
  7170. \end{lstlisting}
  7171. \end{minipage}
  7172. &
  7173. $\Rightarrow$
  7174. &
  7175. \begin{minipage}{0.6\textwidth}
  7176. \begin{lstlisting}
  7177. (if (eq? |$e'_1$| (inject #f Boolean))
  7178. |$e'_3$|
  7179. |$e'_2$|)
  7180. \end{lstlisting}
  7181. \end{minipage}
  7182. \\[2ex]\hline
  7183. \begin{minipage}{0.25\textwidth}
  7184. \begin{lstlisting}
  7185. (eq? |$e_1$| |$e_2$|)
  7186. \end{lstlisting}
  7187. \end{minipage}
  7188. &
  7189. $\Rightarrow$
  7190. &
  7191. \begin{minipage}{0.6\textwidth}
  7192. \begin{lstlisting}
  7193. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  7194. \end{lstlisting}
  7195. \end{minipage}
  7196. \\[2ex]\hline
  7197. \end{tabular}
  7198. \caption{Compiling $R_7$ to $R_6$.}
  7199. \label{fig:compile-r7-r6}
  7200. \end{figure}
  7201. \begin{exercise}\normalfont
  7202. Expand your compiler to handle $R_7$ as outlined in this chapter.
  7203. Create tests for $R_7$ by adapting all of your previous test programs
  7204. by removing type annotations. Add 5 more tests programs that
  7205. specifically rely on the language being dynamically typed. That is,
  7206. they should not be legal programs in a statically typed language, but
  7207. nevertheless, they should be valid $R_7$ programs that run to
  7208. completion without error.
  7209. \end{exercise}
  7210. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7211. \chapter{Gradual Typing}
  7212. \label{ch:gradual-typing}
  7213. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  7214. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7215. \chapter{Parametric Polymorphism}
  7216. \label{ch:parametric-polymorphism}
  7217. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  7218. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  7219. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7220. \chapter{High-level Optimization}
  7221. \label{ch:high-level-optimization}
  7222. This chapter will present a procedure inlining pass based on the
  7223. algorithm of \citet{Waddell:1997fk}.
  7224. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7225. \chapter{Appendix}
  7226. \section{Interpreters}
  7227. \label{appendix:interp}
  7228. We provide several interpreters in the \key{interp.rkt} file. The
  7229. \key{interp-scheme} function takes an AST in one of the Racket-like
  7230. languages considered in this book ($R_1, R_2, \ldots$) and interprets
  7231. the program, returning the result value. The \key{interp-C} function
  7232. interprets an AST for a program in one of the C-like languages ($C_0,
  7233. C_1, \ldots$), and the \code{interp-x86} function interprets an AST
  7234. for an x86 program.
  7235. \section{Utility Functions}
  7236. \label{appendix:utilities}
  7237. The utility function described in this section can be found in the
  7238. \key{utilities.rkt} file.
  7239. The \key{read-program} function takes a file path and parses that file
  7240. (it must be a Racket program) into an abstract syntax tree with a
  7241. \key{Program} node at the top.
  7242. The \key{parse-program} function takes an S-expression representation
  7243. of an AST and converts it into the struct-based representation.
  7244. The \key{assert} function displays the error message \key{msg} if the
  7245. Boolean \key{bool} is false.
  7246. \begin{lstlisting}
  7247. (define (assert msg bool) ...)
  7248. \end{lstlisting}
  7249. % remove discussion of lookup? -Jeremy
  7250. The \key{lookup} function takes a key and an alist, and returns the
  7251. first value that is associated with the given key, if there is one. If
  7252. not, an error is triggered. The alist may contain both immutable
  7253. pairs (built with \key{cons}) and mutable pairs (built with
  7254. \key{mcons}).
  7255. The \key{map2} function ...
  7256. %% \subsection{Graphs}
  7257. %% \begin{itemize}
  7258. %% \item The \code{make-graph} function takes a list of vertices
  7259. %% (symbols) and returns a graph.
  7260. %% \item The \code{add-edge} function takes a graph and two vertices and
  7261. %% adds an edge to the graph that connects the two vertices. The graph
  7262. %% is updated in-place. There is no return value for this function.
  7263. %% \item The \code{adjacent} function takes a graph and a vertex and
  7264. %% returns the set of vertices that are adjacent to the given
  7265. %% vertex. The return value is a Racket \code{hash-set} so it can be
  7266. %% used with functions from the \code{racket/set} module.
  7267. %% \item The \code{vertices} function takes a graph and returns the list
  7268. %% of vertices in the graph.
  7269. %% \end{itemize}
  7270. \subsection{Testing}
  7271. The \key{interp-tests} function takes a compiler name (a string), a
  7272. description of the passes, an interpreter for the source language, a
  7273. test family name (a string), and a list of test numbers, and runs the
  7274. compiler passes and the interpreters to check whether the passes
  7275. correct. The description of the passes is a list with one entry per
  7276. pass. An entry is a list with three things: a string giving the name
  7277. of the pass, the function that implements the pass (a translator from
  7278. AST to AST), and a function that implements the interpreter (a
  7279. function from AST to result value) for the language of the output of
  7280. the pass. The interpreters from Appendix~\ref{appendix:interp} make a
  7281. good choice. The \key{interp-tests} function assumes that the
  7282. subdirectory \key{tests} has a collection of Scheme programs whose names
  7283. all start with the family name, followed by an underscore and then the
  7284. test number, ending in \key{.scm}. Also, for each Scheme program there
  7285. is a file with the same number except that it ends with \key{.in} that
  7286. provides the input for the Scheme program.
  7287. \begin{lstlisting}
  7288. (define (interp-tests name passes test-family test-nums) ...)
  7289. \end{lstlisting}
  7290. The compiler-tests function takes a compiler name (a string) a
  7291. description of the passes (as described above for
  7292. \code{interp-tests}), a test family name (a string), and a list of
  7293. test numbers (see the comment for interp-tests), and runs the compiler
  7294. to generate x86 (a \key{.s} file) and then runs gcc to generate
  7295. machine code. It runs the machine code and checks that the output is
  7296. 42.
  7297. \begin{lstlisting}
  7298. (define (compiler-tests name passes test-family test-nums) ...)
  7299. \end{lstlisting}
  7300. The compile-file function takes a description of the compiler passes
  7301. (see the comment for \key{interp-tests}) and returns a function that,
  7302. given a program file name (a string ending in \key{.scm}), applies all
  7303. of the passes and writes the output to a file whose name is the same
  7304. as the program file name but with \key{.scm} replaced with \key{.s}.
  7305. \begin{lstlisting}
  7306. (define (compile-file passes)
  7307. (lambda (prog-file-name) ...))
  7308. \end{lstlisting}
  7309. \section{x86 Instruction Set Quick-Reference}
  7310. \label{sec:x86-quick-reference}
  7311. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  7312. do. We write $A \to B$ to mean that the value of $A$ is written into
  7313. location $B$. Address offsets are given in bytes. The instruction
  7314. arguments $A, B, C$ can be immediate constants (such as $\$4$),
  7315. registers (such as $\%rax$), or memory references (such as
  7316. $-4(\%ebp)$). Most x86 instructions only allow at most one memory
  7317. reference per instruction. Other operands must be immediates or
  7318. registers.
  7319. \begin{table}[tbp]
  7320. \centering
  7321. \begin{tabular}{l|l}
  7322. \textbf{Instruction} & \textbf{Operation} \\ \hline
  7323. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  7324. \texttt{negq} $A$ & $- A \to A$ \\
  7325. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  7326. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  7327. \texttt{callq} *$A$ & Calls the function at the address $A$. \\
  7328. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  7329. \texttt{retq} & Pops the return address and jumps to it \\
  7330. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  7331. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  7332. \texttt{leaq} $A$,$B$ & $A \to B$ ($C$ must be a register) \\
  7333. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register \\
  7334. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  7335. matches the condition code of the instruction, otherwise go to the
  7336. next instructions. The condition codes are \key{e} for ``equal'',
  7337. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  7338. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  7339. \texttt{jl} $L$ & \\
  7340. \texttt{jle} $L$ & \\
  7341. \texttt{jg} $L$ & \\
  7342. \texttt{jge} $L$ & \\
  7343. \texttt{jmp} $L$ & Jump to label $L$ \\
  7344. \texttt{movq} $A$, $B$ & $A \to B$ \\
  7345. \texttt{movzbq} $A$, $B$ &
  7346. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  7347. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  7348. and the extra bytes of $B$ are set to zero.} \\
  7349. & \\
  7350. & \\
  7351. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  7352. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  7353. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  7354. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  7355. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  7356. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  7357. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  7358. description of the condition codes. $A$ must be a single byte register
  7359. (e.g., \texttt{al} or \texttt{cl}).} \\
  7360. \texttt{setl} $A$ & \\
  7361. \texttt{setle} $A$ & \\
  7362. \texttt{setg} $A$ & \\
  7363. \texttt{setge} $A$ &
  7364. \end{tabular}
  7365. \vspace{5pt}
  7366. \caption{Quick-reference for the x86 instructions used in this book.}
  7367. \label{tab:x86-instr}
  7368. \end{table}
  7369. \bibliographystyle{plainnat}
  7370. \bibliography{all}
  7371. \end{document}
  7372. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  7373. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  7374. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  7375. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  7376. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator
  7377. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  7378. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  7379. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  7380. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs
  7381. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  7382. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  7383. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  7384. %% LocalWords: boolean typecheck notq cmpq sete movzbq jmp al xorq
  7385. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  7386. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  7387. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  7388. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  7389. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  7390. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  7391. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  7392. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  7393. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  7394. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  7395. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  7396. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  7397. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  7398. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  7399. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  7400. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  7401. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  7402. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  7403. % LocalWords: struct symtab