book.tex 229 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282
  1. \documentclass[11pt]{book}
  2. \usepackage[T1]{fontenc}
  3. \usepackage[utf8]{inputenc}
  4. \usepackage{lmodern}
  5. \usepackage{hyperref}
  6. \usepackage{graphicx}
  7. \usepackage[english]{babel}
  8. \usepackage{listings}
  9. \usepackage{amsmath}
  10. \usepackage{amsthm}
  11. \usepackage{amssymb}
  12. \usepackage{natbib}
  13. \usepackage{stmaryrd}
  14. \usepackage{xypic}
  15. \usepackage{semantic}
  16. \usepackage{wrapfig}
  17. \usepackage{multirow}
  18. \usepackage{color}
  19. \definecolor{lightgray}{gray}{1}
  20. \newcommand{\black}[1]{{\color{black} #1}}
  21. \newcommand{\gray}[1]{{\color{lightgray} #1}}
  22. %% For pictures
  23. \usepackage{tikz}
  24. \usetikzlibrary{arrows.meta}
  25. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  26. % Computer Modern is already the default. -Jeremy
  27. %\renewcommand{\ttdefault}{cmtt}
  28. \lstset{%
  29. language=Lisp,
  30. basicstyle=\ttfamily\small,
  31. escapechar=|,
  32. columns=flexible,
  33. moredelim=[is][\color{red}]{~}{~}
  34. }
  35. \newtheorem{theorem}{Theorem}
  36. \newtheorem{lemma}[theorem]{Lemma}
  37. \newtheorem{corollary}[theorem]{Corollary}
  38. \newtheorem{proposition}[theorem]{Proposition}
  39. \newtheorem{constraint}[theorem]{Constraint}
  40. \newtheorem{definition}[theorem]{Definition}
  41. \newtheorem{exercise}[theorem]{Exercise}
  42. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  43. % 'dedication' environment: To add a dedication paragraph at the start of book %
  44. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  45. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  46. \newenvironment{dedication}
  47. {
  48. \cleardoublepage
  49. \thispagestyle{empty}
  50. \vspace*{\stretch{1}}
  51. \hfill\begin{minipage}[t]{0.66\textwidth}
  52. \raggedright
  53. }
  54. {
  55. \end{minipage}
  56. \vspace*{\stretch{3}}
  57. \clearpage
  58. }
  59. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  60. % Chapter quote at the start of chapter %
  61. % Source: http://tex.stackexchange.com/a/53380 %
  62. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  63. \makeatletter
  64. \renewcommand{\@chapapp}{}% Not necessary...
  65. \newenvironment{chapquote}[2][2em]
  66. {\setlength{\@tempdima}{#1}%
  67. \def\chapquote@author{#2}%
  68. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  69. \itshape}
  70. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  71. \makeatother
  72. \input{defs}
  73. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  74. \title{\Huge \textbf{Essentials of Compilation} \\
  75. \huge An Incremental Approach}
  76. \author{\textsc{Jeremy G. Siek} \\
  77. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  78. Indiana University \\
  79. \\
  80. with contributions from: \\
  81. Carl Factora \\
  82. Andre Kuhlenschmidt \\
  83. Michael M. Vitousek \\
  84. Cameron Swords
  85. }
  86. \begin{document}
  87. \frontmatter
  88. \maketitle
  89. \begin{dedication}
  90. This book is dedicated to the programming language wonks at Indiana
  91. University.
  92. \end{dedication}
  93. \tableofcontents
  94. %\listoffigures
  95. %\listoftables
  96. \mainmatter
  97. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  98. \chapter*{Preface}
  99. The tradition of compiler writing at Indiana University goes back to
  100. programming language research and courses taught by Daniel Friedman in
  101. the 1970's and 1980's. Dan had conducted research on lazy evaluation
  102. in the context of Lisp~\citep{McCarthy:1960dz} and then studied
  103. continuations and macros in the context of the
  104. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of students of
  105. those courses, Kent Dybvig, went on to build Chez
  106. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  107. compiler for Scheme. After completing his Ph.D. at the University of
  108. North Carolina, Kent returned to teach at Indiana University.
  109. Throughout the 1990's and early 2000's, Kent continued development of
  110. Chez Scheme and rotated with Dan in teaching the compiler course.
  111. Thanks to this collaboration between Dan and Kent, the compiler course
  112. evolved to incorporate novel pedagogical ideas while also including
  113. elements of effective real-world compilers. One of Dan's ideas was to
  114. split the compiler into many small passes over the input program and
  115. subsequent intermediate representations, so that the code for each
  116. pass would be easy to understood in isolation. (In contrast, most
  117. compilers of the time were organized into only a few monolithic passes
  118. for reasons of compile-time efficiency.) Kent and his students,
  119. Dipanwita Sarkar and Andrew Keep, developed infrastructure to support
  120. this approach and evolved the course, first to use micro-sized passes
  121. and then into even smaller nano
  122. passes~\citep{Sarkar:2004fk,Keep:2012aa}. I took this compiler course
  123. in the early 2000's, as part of my Ph.D. studies at Indiana
  124. University. Needless to say, I enjoyed the course immensely.
  125. One of my classmates, Abdulaziz Ghuloum, observed that the
  126. front-to-back organization of the course made it difficult for
  127. students to understand the rationale for the compiler
  128. design. Abdulaziz proposed an incremental approach in which the
  129. students build the compiler in stages; they start by implementing a
  130. complete compiler for a very small subset of the input language, then
  131. in each subsequent stage they add a feature to the input language and
  132. add or modify passes to handle the new feature~\citep{Ghuloum:2006bh}.
  133. In this way, the students see how the language features motivate
  134. aspects of the compiler design.
  135. After graduating from Indiana University in 2005, I went on to teach
  136. at the University of Colorado. I adapted the nano pass and incremental
  137. approaches to compiling a subset of the Python
  138. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  139. on the surface but there is a large overlap in the compiler techniques
  140. required for the two languages. Thus, I was able to teach much of the
  141. same content from the Indiana compiler course. I very much enjoyed
  142. teaching the course organized in this way, and even better, many of
  143. the students learned a lot and got excited about compilers. (No, I
  144. didn't do a quantitative study to support this claim.)
  145. It is now 2016 and I too have returned to teach at Indiana University.
  146. In my absence the compiler course had switched from the front-to-back
  147. organization to a back-to-front organization. Seeing how well the
  148. incremental approach worked at Colorado, I found this unsatisfactory
  149. and have reorganized the course, porting and adapting the structure of
  150. the Colorado course back into the land of Scheme. In the meantime
  151. Scheme has been superseded by Racket (at least in Indiana), so the
  152. course is now about compiling a subset of Racket to the x86 assembly
  153. language and the compiler is implemented in Racket~\citep{plt-tr}.
  154. This is the textbook for the incremental version of the compiler
  155. course at Indiana University (Spring 2016) and it is the first
  156. textbook for an Indiana compiler course. With this book I hope to
  157. make the Indiana compiler course available to people that have not had
  158. the chance to study here in person. Many of the compiler design
  159. decisions in this book are drawn from the assignment descriptions of
  160. \cite{Dybvig:2010aa}. I have captured what I think are the most
  161. important topics from \cite{Dybvig:2010aa} but have omitted topics
  162. that I think are less interesting conceptually and I have made
  163. simplifications to reduce complexity. In this way, this book leans
  164. more towards pedagogy than towards absolute efficiency. Also, the book
  165. differs in places where I saw the opportunity to make the topics more
  166. fun, such as in relating register allocation to Sudoku
  167. (Chapter~\ref{ch:register-allocation}).
  168. \section*{Prerequisites}
  169. The material in this book is challenging but rewarding. It is meant to
  170. prepare students for a lifelong career in programming languages. I do
  171. not recommend this book for students who want to dabble in programming
  172. languages. Because the book uses the Racket language both for the
  173. implementation of the compiler and for the language that is compiled,
  174. a student should be proficient with Racket (or Scheme) prior to
  175. reading this book. There are many other excellent resources for
  176. learning Scheme and
  177. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. It
  178. is helpful but not necessary for the student to have prior exposure to
  179. x86 (or x86-64) assembly language~\citep{Intel:2015aa}, as one might
  180. obtain from a computer systems
  181. course~\citep{Bryant:2005aa,Bryant:2010aa}. This book introduces the
  182. parts of x86-64 assembly language that are needed.
  183. %\section*{Structure of book}
  184. % You might want to add short description about each chapter in this book.
  185. %\section*{About the companion website}
  186. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  187. %\begin{itemize}
  188. % \item A link to (freely downlodable) latest version of this document.
  189. % \item Link to download LaTeX source for this document.
  190. % \item Miscellaneous material (e.g. suggested readings etc).
  191. %\end{itemize}
  192. \section*{Acknowledgments}
  193. Need to give thanks to
  194. \begin{itemize}
  195. \item Bor-Yuh Evan Chang
  196. \item Kent Dybvig
  197. \item Daniel P. Friedman
  198. \item Ronald Garcia
  199. \item Abdulaziz Ghuloum
  200. \item Ryan Newton
  201. \item Dipanwita Sarkar
  202. \item Andrew Keep
  203. \item Oscar Waddell
  204. \end{itemize}
  205. \mbox{}\\
  206. \noindent Jeremy G. Siek \\
  207. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  208. \noindent Spring 2016
  209. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  210. \chapter{Preliminaries}
  211. \label{ch:trees-recur}
  212. In this chapter, we review the basic tools that are needed for
  213. implementing a compiler. We use abstract syntax trees (ASTs) in the
  214. form of S-expressions to represent programs (Section~\ref{sec:ast})
  215. and pattern matching to inspect individual nodes in an AST
  216. (Section~\ref{sec:pattern-matching}). We use recursion to construct
  217. and deconstruct entire ASTs (Section~\ref{sec:recursion}).
  218. \section{Abstract Syntax Trees}
  219. \label{sec:ast}
  220. The primary data structure that is commonly used for representing
  221. programs is the \emph{abstract syntax tree} (AST). When considering
  222. some part of a program, a compiler needs to ask what kind of part it
  223. is and what sub-parts it has. For example, the program on the left is
  224. represented by the AST on the right.
  225. \begin{center}
  226. \begin{minipage}{0.4\textwidth}
  227. \begin{lstlisting}
  228. (+ (read) (- 8))
  229. \end{lstlisting}
  230. \end{minipage}
  231. \begin{minipage}{0.4\textwidth}
  232. \begin{equation}
  233. \begin{tikzpicture}
  234. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  235. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  236. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  237. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  238. \draw[->] (plus) to (read);
  239. \draw[->] (plus) to (minus);
  240. \draw[->] (minus) to (8);
  241. \end{tikzpicture}
  242. \label{eq:arith-prog}
  243. \end{equation}
  244. \end{minipage}
  245. \end{center}
  246. We shall use the standard terminology for trees: each circle above is
  247. called a \emph{node}. The arrows connect a node to its \emph{children}
  248. (which are also nodes). The top-most node is the \emph{root}. Every
  249. node except for the root has a \emph{parent} (the node it is the child
  250. of). If a node has no children, it is a \emph{leaf} node. Otherwise
  251. it is an \emph{internal} node.
  252. When deciding how to compile the above program, we need to know that
  253. the root node operation is addition and that it has two children:
  254. \texttt{read} and a negation. The abstract syntax tree data structure
  255. directly supports these queries and hence is a good choice. In this
  256. book, we will often write down the textual representation of a program
  257. even when we really have in mind the AST because the textual
  258. representation is more concise. We recommend that, in your mind, you
  259. always interpret programs as abstract syntax trees.
  260. \section{Grammars}
  261. \label{sec:grammar}
  262. A programming language can be thought of as a \emph{set} of programs.
  263. The set is typically infinite (one can always create larger and larger
  264. programs), so one cannot simply describe a language by listing all of
  265. the programs in the language. Instead we write down a set of rules, a
  266. \emph{grammar}, for building programs. We shall write our rules in a
  267. variant of Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  268. As an example, we describe a small language, named $R_0$, of
  269. integers and arithmetic operations. The first rule says that any
  270. integer is an expression, $\Exp$, in the language:
  271. \begin{equation}
  272. \Exp ::= \Int \label{eq:arith-int}
  273. \end{equation}
  274. Each rule has a left-hand-side and a right-hand-side. The way to read
  275. a rule is that if you have all the program parts on the
  276. right-hand-side, then you can create an AST node and categorize it
  277. according to the left-hand-side. (We do not define $\Int$ because the
  278. reader already knows what an integer is.) We make the simplifying
  279. design decision that all of the languages in this book only handle
  280. machine-representable integers (those representable with 64-bits,
  281. i.e., the range $-2^{63}$ to $2^{63}$) which corresponds to the
  282. \texttt{fixnum} datatype in Racket. A name such as $\Exp$ that is
  283. defined by the grammar rules is a \emph{non-terminal}.
  284. The second grammar rule is the \texttt{read} operation that receives
  285. an input integer from the user of the program.
  286. \begin{equation}
  287. \Exp ::= (\key{read}) \label{eq:arith-read}
  288. \end{equation}
  289. The third rule says that, given an $\Exp$ node, you can build another
  290. $\Exp$ node by negating it.
  291. \begin{equation}
  292. \Exp ::= (\key{-} \; \Exp) \label{eq:arith-neg}
  293. \end{equation}
  294. Symbols such as \key{-} in typewriter font are \emph{terminal} symbols
  295. and must literally appear in the program for the rule to be
  296. applicable.
  297. We can apply the rules to build ASTs in the $R_0$
  298. language. For example, by rule \eqref{eq:arith-int}, \texttt{8} is an
  299. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  300. an $\Exp$.
  301. \begin{center}
  302. \begin{minipage}{0.25\textwidth}
  303. \begin{lstlisting}
  304. (- 8)
  305. \end{lstlisting}
  306. \end{minipage}
  307. \begin{minipage}{0.25\textwidth}
  308. \begin{equation}
  309. \begin{tikzpicture}
  310. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  311. \node[draw, circle] (8) at (0, -1.2) {$8$};
  312. \draw[->] (minus) to (8);
  313. \end{tikzpicture}
  314. \label{eq:arith-neg8}
  315. \end{equation}
  316. \end{minipage}
  317. \end{center}
  318. The following grammar rule defines addition expressions:
  319. \begin{equation}
  320. \Exp ::= (\key{+} \; \Exp \; \Exp) \label{eq:arith-add}
  321. \end{equation}
  322. Now we can see that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  323. $R_0$. We know that \lstinline{(read)} is an $\Exp$ by rule
  324. \eqref{eq:arith-read} and we have shown that \texttt{(- 8)} is an
  325. $\Exp$, so we can apply rule \eqref{eq:arith-add} to show that
  326. \texttt{(+ (read) (- 8))} is an $\Exp$ in the $R_0$ language.
  327. If you have an AST for which the above rules do not apply, then the
  328. AST is not in $R_0$. For example, the AST \texttt{(- (read) (+ 8))} is
  329. not in $R_0$ because there are no rules for \key{+} with only one
  330. argument, nor for \key{-} with two arguments. Whenever we define a
  331. language with a grammar, we implicitly mean for the language to be the
  332. smallest set of programs that are justified by the rules. That is, the
  333. language only includes those programs that the rules allow.
  334. The last grammar for $R_0$ states that there is a \key{program} node
  335. to mark the top of the whole program:
  336. \[
  337. R_0 ::= (\key{program} \; \Exp)
  338. \]
  339. The \code{read-program} function provided in \code{utilities.rkt}
  340. reads programs in from a file (the sequence of characters in the
  341. concrete syntax of Racket) and parses them into the abstract syntax
  342. tree. The concrete syntax does not include a \key{program} form; that
  343. is added by the \code{read-program} function as it creates the
  344. AST. See the description of \code{read-program} in
  345. Appendix~\ref{appendix:utilities} for more details.
  346. It is common to have many rules with the same left-hand side, such as
  347. $\Exp$ in the grammar for $R_0$, so there is a vertical bar notation
  348. for gathering several rules, as shown in
  349. Figure~\ref{fig:r0-syntax}. Each clause between a vertical bar is
  350. called an {\em alternative}.
  351. \begin{figure}[tp]
  352. \fbox{
  353. \begin{minipage}{0.96\textwidth}
  354. \[
  355. \begin{array}{rcl}
  356. \Exp &::=& \Int \mid ({\tt \key{read}}) \mid (\key{-} \; \Exp) \mid
  357. (\key{+} \; \Exp \; \Exp) \\
  358. R_0 &::=& (\key{program} \; \Exp)
  359. \end{array}
  360. \]
  361. \end{minipage}
  362. }
  363. \caption{The syntax of the $R_0$ language.}
  364. \label{fig:r0-syntax}
  365. \end{figure}
  366. \section{S-Expressions}
  367. \label{sec:s-expr}
  368. Racket, as a descendant of Lisp, has
  369. convenient support for creating and manipulating abstract syntax trees
  370. with its \emph{symbolic expression} feature, or S-expression for
  371. short. We can create an S-expression simply by writing a backquote
  372. followed by the textual representation of the AST. (Technically
  373. speaking, this is called a \emph{quasiquote} in Racket.) For example,
  374. an S-expression to represent the AST \eqref{eq:arith-prog} is created
  375. by the following Racket expression:
  376. \begin{center}
  377. \texttt{`(+ (read) (- 8))}
  378. \end{center}
  379. To build larger S-expressions one often needs to splice together
  380. several smaller S-expressions. Racket provides the comma operator to
  381. splice an S-expression into a larger one. For example, instead of
  382. creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  383. we could have first created an S-expression for AST
  384. \eqref{eq:arith-neg8} and then spliced that into the addition
  385. S-expression.
  386. \begin{lstlisting}
  387. (define ast1.4 `(- 8))
  388. (define ast1.1 `(+ (read) ,ast1.4))
  389. \end{lstlisting}
  390. In general, the Racket expression that follows the comma (splice)
  391. can be any expression that computes an S-expression.
  392. \section{Pattern Matching}
  393. \label{sec:pattern-matching}
  394. As mentioned above, one of the operations that a compiler needs to
  395. perform on an AST is to access the children of a node. Racket
  396. provides the \texttt{match} form to access the parts of an
  397. S-expression. Consider the following example and the output on the
  398. right.
  399. \begin{center}
  400. \begin{minipage}{0.5\textwidth}
  401. \begin{lstlisting}
  402. (match ast1.1
  403. [`(,op ,child1 ,child2)
  404. (print op) (newline)
  405. (print child1) (newline)
  406. (print child2)])
  407. \end{lstlisting}
  408. \end{minipage}
  409. \vrule
  410. \begin{minipage}{0.25\textwidth}
  411. \begin{lstlisting}
  412. '+
  413. '(read)
  414. '(- 8)
  415. \end{lstlisting}
  416. \end{minipage}
  417. \end{center}
  418. The \texttt{match} form takes AST \eqref{eq:arith-prog} and binds its
  419. parts to the three variables \texttt{op}, \texttt{child1}, and
  420. \texttt{child2}. In general, a match clause consists of a
  421. \emph{pattern} and a \emph{body}. The pattern is a quoted S-expression
  422. that may contain pattern-variables (preceded by a comma). The body
  423. may contain any Racket code.
  424. A \texttt{match} form may contain several clauses, as in the following
  425. function \texttt{leaf?} that recognizes when an $R_0$ node is
  426. a leaf. The \texttt{match} proceeds through the clauses in order,
  427. checking whether the pattern can match the input S-expression. The
  428. body of the first clause that matches is executed. The output of
  429. \texttt{leaf?} for several S-expressions is shown on the right. In the
  430. below \texttt{match}, we see another form of pattern: the \texttt{(?
  431. fixnum?)} applies the predicate \texttt{fixnum?} to the input
  432. S-expression to see if it is a machine-representable integer.
  433. \begin{center}
  434. \begin{minipage}{0.5\textwidth}
  435. \begin{lstlisting}
  436. (define (leaf? arith)
  437. (match arith
  438. [(? fixnum?) #t]
  439. [`(read) #t]
  440. [`(- ,c1) #f]
  441. [`(+ ,c1 ,c2) #f]))
  442. (leaf? `(read))
  443. (leaf? `(- 8))
  444. (leaf? `(+ (read) (- 8)))
  445. \end{lstlisting}
  446. \end{minipage}
  447. \vrule
  448. \begin{minipage}{0.25\textwidth}
  449. \begin{lstlisting}
  450. #t
  451. #f
  452. #f
  453. \end{lstlisting}
  454. \end{minipage}
  455. \end{center}
  456. \section{Recursion}
  457. \label{sec:recursion}
  458. Programs are inherently recursive in that an $R_0$ AST is made
  459. up of smaller $R_0$ ASTs. Thus, the natural way to process in
  460. entire program is with a recursive function. As a first example of
  461. such a function, we define \texttt{R0?} below, which takes an
  462. arbitrary S-expression, {\tt sexp}, and determines whether or not {\tt
  463. sexp} is in {\tt arith}. Note that each match clause corresponds to
  464. one grammar rule for $R_0$ and the body of each clause makes a
  465. recursive call for each child node. This pattern of recursive function
  466. is so common that it has a name, \emph{structural recursion}. In
  467. general, when a recursive function is defined using a sequence of
  468. match clauses that correspond to a grammar, and each clause body makes
  469. a recursive call on each child node, then we say the function is
  470. defined by structural recursion.
  471. \begin{center}
  472. \begin{minipage}{0.7\textwidth}
  473. \begin{lstlisting}
  474. (define (R0? sexp)
  475. (match sexp
  476. [(? fixnum?) #t]
  477. [`(read) #t]
  478. [`(- ,e) (R0? e)]
  479. [`(+ ,e1 ,e2)
  480. (and (R0? e1) (R0? e2))]
  481. [`(program ,e) (R0? e)]
  482. [else #f]))
  483. (R0? `(+ (read) (- 8)))
  484. (R0? `(- (read) (+ 8)))
  485. \end{lstlisting}
  486. \end{minipage}
  487. \vrule
  488. \begin{minipage}{0.25\textwidth}
  489. \begin{lstlisting}
  490. #t
  491. #f
  492. \end{lstlisting}
  493. \end{minipage}
  494. \end{center}
  495. \section{Interpreters}
  496. \label{sec:interp-R0}
  497. The meaning, or semantics, of a program is typically defined in the
  498. specification of the language. For example, the Scheme language is
  499. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  500. defined in its reference manual~\citep{plt-tr}. In this book we use an
  501. interpreter to define the meaning of each language that we consider,
  502. following Reynold's advice in this
  503. regard~\citep{reynolds72:_def_interp}. Here we will warm up by writing
  504. an interpreter for the $R_0$ language, which will also serve
  505. as a second example of structural recursion. The \texttt{interp-R0}
  506. function is defined in Figure~\ref{fig:interp-R0}. The body of the
  507. function is a match on the input expression \texttt{e} and there is
  508. one clause per grammar rule for $R_0$. The clauses for
  509. internal AST nodes make recursive calls to \texttt{interp-R0} on
  510. each child node.
  511. \begin{figure}[tbp]
  512. \begin{lstlisting}
  513. (define (interp-R0 e)
  514. (match e
  515. [(? fixnum?) e]
  516. [`(read)
  517. (define r (read))
  518. (cond [(fixnum? r) r]
  519. [else (error 'interp-R0 "expected an integer" r)])]
  520. [`(- ,e)
  521. (fx- 0 (interp-R0 e))]
  522. [`(+ ,e1 ,e2)
  523. (fx+ (interp-R0 e1) (interp-R0 e2))]
  524. [`(program ,e) (interp-R0 e)]
  525. ))
  526. \end{lstlisting}
  527. \caption{Interpreter for the $R_0$ language.}
  528. \label{fig:interp-R0}
  529. \end{figure}
  530. Let us consider the result of interpreting some example $R_0$
  531. programs. The following program simply adds two integers.
  532. \begin{lstlisting}
  533. (+ 10 32)
  534. \end{lstlisting}
  535. The result is \key{42}, as you might have expected.
  536. %
  537. The next example demonstrates that expressions may be nested within
  538. each other, in this case nesting several additions and negations.
  539. \begin{lstlisting}
  540. (+ 10 (- (+ 12 20)))
  541. \end{lstlisting}
  542. What is the result of the above program?
  543. If we interpret the AST \eqref{eq:arith-prog} and give it the input
  544. \texttt{50}
  545. \begin{lstlisting}
  546. (interp-R0 ast1.1)
  547. \end{lstlisting}
  548. we get the answer to life, the universe, and everything:
  549. \begin{lstlisting}
  550. 42
  551. \end{lstlisting}
  552. Moving on, the \key{read} operation prompts the user of the program
  553. for an integer. Given an input of \key{10}, the following program
  554. produces \key{42}.
  555. \begin{lstlisting}
  556. (+ (read) 32)
  557. \end{lstlisting}
  558. We include the \key{read} operation in $R_1$ so that a compiler for
  559. $R_1$ cannot be implemented simply by running the interpreter at
  560. compilation time to obtain the output and then generating the trivial
  561. code to return the output. (A clever student at Colorado did this the
  562. first time I taught the course.)
  563. The job of a compiler is to translate a program in one language into a
  564. program in another language so that the output program behaves the
  565. same way as the input program. This idea is depicted in the following
  566. diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  567. $\mathcal{L}_2$, and an interpreter for each language. Suppose that
  568. the compiler translates program $P_1$ in language $\mathcal{L}_1$ into
  569. program $P_2$ in language $\mathcal{L}_2$. Then interpreting $P_1$
  570. and $P_2$ on their respective interpreters with input $i$ should yield
  571. the same output $o$.
  572. \begin{equation} \label{eq:compile-correct}
  573. \begin{tikzpicture}[baseline=(current bounding box.center)]
  574. \node (p1) at (0, 0) {$P_1$};
  575. \node (p2) at (3, 0) {$P_2$};
  576. \node (o) at (3, -2.5) {$o$};
  577. \path[->] (p1) edge [above] node {compile} (p2);
  578. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  579. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  580. \end{tikzpicture}
  581. \end{equation}
  582. In the next section we see our first example of a compiler, which is
  583. another example of structural recursion.
  584. \section{Partial Evaluation}
  585. \label{sec:partial-evaluation}
  586. In this section we consider a compiler that translates $R_0$
  587. programs into $R_0$ programs that are more efficient, that is,
  588. this compiler is an optimizer. Our optimizer will accomplish this by
  589. trying to eagerly compute the parts of the program that do not depend
  590. on any inputs. For example, given the following program
  591. \begin{lstlisting}
  592. (+ (read) (- (+ 5 3)))
  593. \end{lstlisting}
  594. our compiler will translate it into the program
  595. \begin{lstlisting}
  596. (+ (read) -8)
  597. \end{lstlisting}
  598. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  599. evaluator for the $R_0$ language. The output of the partial evaluator
  600. is an $R_0$ program, which we build up using a combination of
  601. quasiquotes and commas. (Though no quasiquote is necessary for
  602. integers.) In Figure~\ref{fig:pe-arith}, the normal structural
  603. recursion is captured in the main \texttt{pe-arith} function whereas
  604. the code for partially evaluating negation and addition is factored
  605. into two separate helper functions: \texttt{pe-neg} and
  606. \texttt{pe-add}. The input to these helper functions is the output of
  607. partially evaluating the children nodes.
  608. \begin{figure}[tbp]
  609. \begin{lstlisting}
  610. (define (pe-neg r)
  611. (cond [(fixnum? r) (fx- 0 r)]
  612. [else `(- ,r)]))
  613. (define (pe-add r1 r2)
  614. (cond [(and (fixnum? r1) (fixnum? r2)) (fx+ r1 r2)]
  615. [else `(+ ,r1 ,r2)]))
  616. (define (pe-arith e)
  617. (match e
  618. [(? fixnum?) e]
  619. [`(read) `(read)]
  620. [`(- ,e1) (pe-neg (pe-arith e1))]
  621. [`(+ ,e1 ,e2) (pe-add (pe-arith e1) (pe-arith e2))]))
  622. \end{lstlisting}
  623. \caption{A partial evaluator for the $R_0$ language.}
  624. \label{fig:pe-arith}
  625. \end{figure}
  626. Our code for \texttt{pe-neg} and \texttt{pe-add} implements the simple
  627. idea of checking whether the inputs are integers and if they are, to
  628. go ahead and perform the arithmetic. Otherwise, we use quasiquote to
  629. create an AST node for the appropriate operation (either negation or
  630. addition) and use comma to splice in the child nodes.
  631. To gain some confidence that the partial evaluator is correct, we can
  632. test whether it produces programs that get the same result as the
  633. input program. That is, we can test whether it satisfies Diagram
  634. \eqref{eq:compile-correct}. The following code runs the partial
  635. evaluator on several examples and tests the output program. The
  636. \texttt{assert} function is defined in Appendix~\ref{appendix:utilities}.
  637. \begin{lstlisting}
  638. (define (test-pe p)
  639. (assert "testing pe-arith"
  640. (equal? (interp-R0 p) (interp-R0 (pe-arith p)))))
  641. (test-pe `(+ (read) (- (+ 5 3))))
  642. (test-pe `(+ 1 (+ (read) 1)))
  643. (test-pe `(- (+ (read) (- 5))))
  644. \end{lstlisting}
  645. \begin{exercise}
  646. \normalfont % I don't like the italics for exercises. -Jeremy
  647. We challenge the reader to improve on the simple partial evaluator in
  648. Figure~\ref{fig:pe-arith} by replacing the \texttt{pe-neg} and
  649. \texttt{pe-add} helper functions with functions that know more about
  650. arithmetic. For example, your partial evaluator should translate
  651. \begin{lstlisting}
  652. (+ 1 (+ (read) 1))
  653. \end{lstlisting}
  654. into
  655. \begin{lstlisting}
  656. (+ 2 (read))
  657. \end{lstlisting}
  658. To accomplish this, we recommend that your partial evaluator produce
  659. output that takes the form of the $\itm{residual}$ non-terminal in the
  660. following grammar.
  661. \[
  662. \begin{array}{lcl}
  663. \Exp &::=& (\key{read}) \mid (\key{-} \;(\key{read})) \mid (\key{+} \; \Exp \; \Exp)\\
  664. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \Exp) \mid \Exp
  665. \end{array}
  666. \]
  667. \end{exercise}
  668. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  669. \chapter{Compiling Integers and Variables}
  670. \label{ch:int-exp}
  671. This chapter concerns the challenge of compiling a subset of Racket,
  672. which we name $R_1$, to x86-64 assembly code~\citep{Intel:2015aa}.
  673. (Hence force we shall refer to x86-64 simply as x86). The chapter
  674. begins with a description of the $R_1$ language (Section~\ref{sec:s0})
  675. and then a description of x86 (Section~\ref{sec:x86}). The
  676. x86 assembly language is quite large, so we only discuss what is
  677. needed for compiling $R_1$. We introduce more of x86 in later
  678. chapters. Once we have introduced $R_1$ and x86, we reflect on
  679. their differences and come up with a plan breaking down the
  680. translation from $R_1$ to x86 into a handful of steps
  681. (Section~\ref{sec:plan-s0-x86}). The rest of the sections in this
  682. Chapter give detailed hints regarding each step
  683. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  684. to give enough hints that the well-prepared reader can implement a
  685. compiler from $R_1$ to x86 while at the same time leaving room for
  686. some fun and creativity.
  687. \section{The $R_1$ Language}
  688. \label{sec:s0}
  689. The $R_1$ language extends the $R_0$ language
  690. (Figure~\ref{fig:r0-syntax}) with variable definitions. The syntax of
  691. the $R_1$ language is defined by the grammar in
  692. Figure~\ref{fig:r1-syntax}. As in $R_0$, \key{read} is a nullary
  693. operator, \key{-} is a unary operator, and \key{+} is a binary
  694. operator. In addition to variable definitions, the $R_1$ language
  695. includes the \key{program} form to mark the top of the program, which
  696. is helpful in some of the compiler passes. The $R_1$ language is rich
  697. enough to exhibit several compilation techniques but simple enough so
  698. that the reader can implement a compiler for it in a week of part-time
  699. work. To give the reader a feeling for the scale of this first
  700. compiler, the instructor solution for the $R_1$ compiler consists of 6
  701. recursive functions and a few small helper functions that together
  702. span 256 lines of code.
  703. \begin{figure}[btp]
  704. \centering
  705. \fbox{
  706. \begin{minipage}{0.96\textwidth}
  707. \[
  708. \begin{array}{rcl}
  709. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \\
  710. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  711. R_1 &::=& (\key{program} \; \Exp)
  712. \end{array}
  713. \]
  714. \end{minipage}
  715. }
  716. \caption{The syntax of the $R_1$ language.
  717. The non-terminal \Var{} may be any Racket identifier.}
  718. \label{fig:r1-syntax}
  719. \end{figure}
  720. The \key{let} construct defines a variable for use within its body
  721. and initializes the variable with the value of an expression. So the
  722. following program initializes \code{x} to \code{32} and then evaluates
  723. the body \code{(+ 10 x)}, producing \code{42}.
  724. \begin{lstlisting}
  725. (program
  726. (let ([x (+ 12 20)]) (+ 10 x)))
  727. \end{lstlisting}
  728. When there are multiple \key{let}'s for the same variable, the closest
  729. enclosing \key{let} is used. That is, variable definitions overshadow
  730. prior definitions. Consider the following program with two \key{let}'s
  731. that define variables named \code{x}. Can you figure out the result?
  732. \begin{lstlisting}
  733. (program
  734. (let ([x 32]) (+ (let ([x 10]) x) x)))
  735. \end{lstlisting}
  736. For the purposes of showing which variable uses correspond to which
  737. definitions, the following shows the \code{x}'s annotated with subscripts
  738. to distinguish them. Double check that your answer for the above is
  739. the same as your answer for this annotated version of the program.
  740. \begin{lstlisting}
  741. (program
  742. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|)))
  743. \end{lstlisting}
  744. The initializing expression is always evaluated before the body of the
  745. \key{let}, so in the following, the \key{read} for \code{x} is
  746. performed before the \key{read} for \code{y}. Given the input
  747. \code{52} then \code{10}, the following produces \code{42} (and not
  748. \code{-42}).
  749. \begin{lstlisting}
  750. (program
  751. (let ([x (read)]) (let ([y (read)]) (- x y))))
  752. \end{lstlisting}
  753. Figure~\ref{fig:interp-R1} shows the interpreter for the $R_1$
  754. language. It extends the interpreter for $R_0$ with two new
  755. \key{match} clauses for variables and for \key{let}. For \key{let},
  756. we will need a way to communicate the initializing value of a variable
  757. to all the uses of a variable. To accomplish this, we maintain a
  758. mapping from variables to values, which is traditionally called an
  759. \emph{environment}. For simplicity, here we use an association list to
  760. represent the environment. The \code{interp-R1} function takes the
  761. current environment, \code{env}, as an extra parameter. When the
  762. interpreter encounters a variable, it finds the corresponding value
  763. using the \code{lookup} function (Appendix~\ref{appendix:utilities}).
  764. When the interpreter encounters a \key{let}, it evaluates the
  765. initializing expression, extends the environment with the result bound
  766. to the variable, then evaluates the body of the \key{let}.
  767. \begin{figure}[tbp]
  768. \begin{lstlisting}
  769. (define (interp-R1 env e)
  770. (match e
  771. [(? symbol?) (lookup e env)]
  772. [`(let ([,x ,e]) ,body)
  773. (define v (interp-R1 env e))
  774. (define new-env (cons (cons x v) env))
  775. (interp-R1 new-env body)]
  776. [(? fixnum?) e]
  777. [`(read)
  778. (define r (read))
  779. (cond [(fixnum? r) r]
  780. [else (error 'interp-R1 "expected an integer" r)])]
  781. [`(- ,e)
  782. (fx- 0 (interp-R1 env e))]
  783. [`(+ ,e1 ,e2)
  784. (fx+ (interp-R1 env e1) (interp-R1 env e2))]
  785. [`(program ,e) (interp-R1 '() e)]
  786. ))
  787. \end{lstlisting}
  788. \caption{Interpreter for the $R_1$ language.}
  789. \label{fig:interp-R1}
  790. \end{figure}
  791. The goal for this chapter is to implement a compiler that translates
  792. any program $P_1$ in the $R_1$ language into an x86 assembly
  793. program $P_2$ such that $P_2$ exhibits the same behavior on an x86
  794. computer as the $R_1$ program running in a Racket implementation.
  795. That is, they both output the same integer $n$.
  796. \[
  797. \begin{tikzpicture}[baseline=(current bounding box.center)]
  798. \node (p1) at (0, 0) {$P_1$};
  799. \node (p2) at (4, 0) {$P_2$};
  800. \node (o) at (4, -2) {$n$};
  801. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  802. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  803. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  804. \end{tikzpicture}
  805. \]
  806. In the next section we introduce enough of the x86 assembly
  807. language to compile $R_1$.
  808. \section{The x86 Assembly Language}
  809. \label{sec:x86}
  810. An x86 program is a sequence of instructions. The instructions may
  811. refer to integer constants (called \emph{immediate values}), variables
  812. called \emph{registers}, and instructions may load and store values
  813. into \emph{memory}. Memory is a mapping of 64-bit addresses to 64-bit
  814. values. Figure~\ref{fig:x86-a} defines the syntax for the subset of
  815. the x86 assembly language needed for this chapter. (We use the
  816. AT\&T syntax expected by the GNU assembler inside \key{gcc}.)
  817. \begin{figure}[tp]
  818. \fbox{
  819. \begin{minipage}{0.96\textwidth}
  820. \[
  821. \begin{array}{lcl}
  822. \Reg &::=& \key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  823. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  824. && \key{r8} \mid \key{r9} \mid \key{r10}
  825. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  826. \mid \key{r14} \mid \key{r15} \\
  827. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int(\key{\%}\Reg) \\
  828. \Instr &::=& \key{addq} \; \Arg, \Arg \mid
  829. \key{subq} \; \Arg, \Arg \mid
  830. % \key{imulq} \; \Arg,\Arg \mid
  831. \key{negq} \; \Arg \mid \key{movq} \; \Arg, \Arg \mid \\
  832. && \key{callq} \; \mathit{label} \mid
  833. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \\
  834. \Prog &::= & \key{.globl main}\\
  835. & & \key{main:} \; \Instr^{+}
  836. \end{array}
  837. \]
  838. \end{minipage}
  839. }
  840. \caption{A subset of the x86 assembly language (AT\&T syntax).}
  841. \label{fig:x86-a}
  842. \end{figure}
  843. An immediate value is written using the notation \key{\$}$n$ where $n$
  844. is an integer.
  845. %
  846. A register is written with a \key{\%} followed by the register name,
  847. such as \key{\%rax}.
  848. %
  849. An access to memory is specified using the syntax $n(\key{\%}r)$,
  850. which reads register $r$ and then offsets the address by $n$ bytes
  851. (8 bits). The address is then used to either load or store to memory
  852. depending on whether it occurs as a source or destination argument of
  853. an instruction.
  854. An arithmetic instruction, such as $\key{addq}\,s,\,d$, reads from the
  855. source $s$ and destination $d$, applies the arithmetic operation, then
  856. writes the result in $d$.
  857. %
  858. The move instruction, $\key{movq}\,s\,d$ reads from $s$ and stores the
  859. result in $d$.
  860. %
  861. The $\key{callq}\,\mathit{label}$ instruction executes the procedure
  862. specified by the label.
  863. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  864. to \code{(+ 10 32)}. The \key{globl} directive says that the
  865. \key{main} procedure is externally visible, which is necessary so
  866. that the operating system can call it. The label \key{main:}
  867. indicates the beginning of the \key{main} procedure which is where
  868. the operating system starts executing this program. The instruction
  869. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  870. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  871. $10$ in \key{rax} and puts the result, $42$, back into
  872. \key{rax}. The instruction \lstinline{movq %rax, %rdi} moves the value
  873. in \key{rax} into another register, \key{rdi}, and
  874. \lstinline{callq print_int} calls the external function \code{print\_int}, which
  875. prints the value in \key{rdi}.
  876. The instruction \key{retq} finishes the \key{main}
  877. function by returning the integer in \key{rax} to the
  878. operating system.
  879. %\begin{wrapfigure}{r}{2.25in}
  880. \begin{figure}[tbp]
  881. \begin{lstlisting}
  882. .globl main
  883. main:
  884. movq $10, %rax
  885. addq $32, %rax
  886. movq %rax, %rdi
  887. callq print_int
  888. retq
  889. \end{lstlisting}
  890. \caption{An x86 program equivalent to $\BINOP{+}{10}{32}$.}
  891. \label{fig:p0-x86}
  892. %\end{wrapfigure}
  893. \end{figure}
  894. %% \marginpar{Consider using italics for the texts in these figures.
  895. %% It can get confusing to differentiate them from the main text.}
  896. %% It looks pretty ugly in italics.-Jeremy
  897. Unfortunately, x86 varies in a couple ways depending on what
  898. operating system it is assembled in. The code examples shown here are
  899. correct on the Unix platform, but when assembled on Mac OS X, labels
  900. like \key{main} must be prefixed with an underscore. So the correct
  901. output for the above program on Mac would begin with:
  902. \begin{lstlisting}
  903. .globl _main
  904. _main:
  905. ...
  906. \end{lstlisting}
  907. The next example exhibits the use of memory. Figure~\ref{fig:p1-x86}
  908. lists an x86 program that is equivalent to $\BINOP{+}{52}{
  909. \UNIOP{-}{10} }$. To understand how this x86 program works, we
  910. need to explain a region of memory called the \emph{procedure call
  911. stack} (or \emph{stack} for short). The stack consists of a separate
  912. \emph{frame} for each procedure call. The memory layout for an
  913. individual frame is shown in Figure~\ref{fig:frame}. The register
  914. \key{rsp} is called the \emph{stack pointer} and points to the item at
  915. the top of the stack. The stack grows downward in memory, so we
  916. increase the size of the stack by subtracting from the stack
  917. pointer. The frame size is required to be a multiple of 16 bytes. The
  918. register \key{rbp} is the \emph{base pointer} which serves two
  919. purposes: 1) it saves the location of the stack pointer for the
  920. procedure that called the current one and 2) it is used to access
  921. variables associated with the current procedure. We number the
  922. variables from $1$ to $n$. Variable $1$ is stored at address
  923. $-8\key{(\%rbp)}$, variable $2$ at $-16\key{(\%rbp)}$, etc.
  924. %\begin{wrapfigure}{r}{2.1in}
  925. \begin{figure}[tbp]
  926. \begin{lstlisting}
  927. .globl main
  928. main:
  929. pushq %rbp
  930. movq %rsp, %rbp
  931. subq $16, %rsp
  932. movq $10, -8(%rbp)
  933. negq -8(%rbp)
  934. movq $52, %rax
  935. addq -8(%rbp), %rax
  936. movq %rax, %rdi
  937. callq print_int
  938. addq $16, %rsp
  939. popq %rbp
  940. retq
  941. \end{lstlisting}
  942. \caption{An x86 program equivalent to $\BINOP{+}{52}{\UNIOP{-}{10} }$.}
  943. \label{fig:p1-x86}
  944. \end{figure}
  945. %\end{wrapfigure}
  946. \begin{figure}[tbp]
  947. \centering
  948. \begin{tabular}{|r|l|} \hline
  949. Position & Contents \\ \hline
  950. 8(\key{\%rbp}) & return address \\
  951. 0(\key{\%rbp}) & old \key{rbp} \\
  952. -8(\key{\%rbp}) & variable $1$ \\
  953. -16(\key{\%rbp}) & variable $2$ \\
  954. \ldots & \ldots \\
  955. 0(\key{\%rsp}) & variable $n$\\ \hline
  956. \end{tabular}
  957. \caption{Memory layout of a frame.}
  958. \label{fig:frame}
  959. \end{figure}
  960. Getting back to the program in Figure~\ref{fig:p1-x86}, the first
  961. three instructions are the typical \emph{prelude} for a procedure.
  962. The instruction \key{pushq \%rbp} saves the base pointer for the
  963. procedure that called the current one onto the stack and subtracts $8$
  964. from the stack pointer. The second instruction \key{movq \%rsp, \%rbp}
  965. changes the base pointer to the top of the stack. The instruction
  966. \key{subq \$16, \%rsp} moves the stack pointer down to make enough
  967. room for storing variables. This program just needs one variable ($8$
  968. bytes) but because the frame size is required to be a multiple of 16
  969. bytes, it rounds to 16 bytes.
  970. The next four instructions carry out the work of computing
  971. $\BINOP{+}{52}{\UNIOP{-}{10} }$. The first instruction \key{movq \$10,
  972. -8(\%rbp)} stores $10$ in variable $1$. The instruction \key{negq
  973. -8(\%rbp)} changes variable $1$ to $-10$. The \key{movq \$52, \%rax}
  974. places $52$ in the register \key{rax} and \key{addq -8(\%rbp), \%rax}
  975. adds the contents of variable $1$ to \key{rax}, at which point
  976. \key{rax} contains $42$.
  977. The last five instructions are the typical \emph{conclusion} of a
  978. procedure. The first two print the final result of the program. The
  979. latter three are necessary to get the state of the machine back to
  980. where it was before the current procedure was called. The \key{addq
  981. \$16, \%rsp} instruction moves the stack pointer back to point at
  982. the old base pointer. The amount added here needs to match the amount
  983. that was subtracted in the prelude of the procedure. Then \key{popq
  984. \%rbp} returns the old base pointer to \key{rbp} and adds $8$ to the
  985. stack pointer. The \key{retq} instruction jumps back to the procedure
  986. that called this one and subtracts 8 from the stack pointer.
  987. The compiler will need a convenient representation for manipulating
  988. x86 programs, so we define an abstract syntax for x86 in
  989. Figure~\ref{fig:x86-ast-a}. The $\Int$ field of the \key{program} AST
  990. node is number of bytes of stack space needed for variables in the
  991. program. (Some of the intermediate languages will store other
  992. information in that location for the purposes of communicating
  993. auxiliary data from one step of the compiler to the next. )
  994. \begin{figure}[tp]
  995. \fbox{
  996. \begin{minipage}{0.96\textwidth}
  997. \[
  998. \begin{array}{lcl}
  999. \Arg &::=& \INT{\Int} \mid \REG{\itm{register}}
  1000. \mid (\key{deref}\,\itm{register}\,\Int) \\
  1001. \Instr &::=& (\key{addq} \; \Arg\; \Arg) \mid
  1002. (\key{subq} \; \Arg\; \Arg) \mid
  1003. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) \\
  1004. &\mid& (\key{callq} \; \mathit{label}) \mid
  1005. (\key{pushq}\;\Arg) \mid
  1006. (\key{popq}\;\Arg) \mid
  1007. (\key{retq}) \\
  1008. x86_0 &::= & (\key{program} \;\Int \; \Instr^{+})
  1009. \end{array}
  1010. \]
  1011. \end{minipage}
  1012. }
  1013. \caption{Abstract syntax for x86 assembly.}
  1014. \label{fig:x86-ast-a}
  1015. \end{figure}
  1016. \section{Planning the trip to x86 via the $C_0$ language}
  1017. \label{sec:plan-s0-x86}
  1018. To compile one language to another it helps to focus on the
  1019. differences between the two languages. It is these differences that
  1020. the compiler will need to bridge. What are the differences between
  1021. $R_1$ and x86 assembly? Here we list some of the most important the
  1022. differences.
  1023. \begin{enumerate}
  1024. \item x86 arithmetic instructions typically take two arguments and
  1025. update the second argument in place. In contrast, $R_1$ arithmetic
  1026. operations only read their arguments and produce a new value.
  1027. \item An argument to an $R_1$ operator can be any expression, whereas
  1028. x86 instructions restrict their arguments to integers, registers,
  1029. and memory locations.
  1030. \item An $R_1$ program can have any number of variables whereas x86
  1031. has only 16 registers.
  1032. \item Variables in $R_1$ can overshadow other variables with the same
  1033. name. The registers and memory locations of x86 all have unique
  1034. names.
  1035. \end{enumerate}
  1036. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1037. the problem into several steps, dealing with the above differences one
  1038. at a time. The main question then becomes: in what order do we tackle
  1039. these differences? This is often one of the most challenging questions
  1040. that a compiler writer must answer because some orderings may be much
  1041. more difficult to implement than others. It is difficult to know ahead
  1042. of time which orders will be better so often some trial-and-error is
  1043. involved. However, we can try to plan ahead and choose the orderings
  1044. based on this planning.
  1045. For example, to handle difference \#2 (nested expressions), we shall
  1046. introduce new variables and pull apart the nested expressions into a
  1047. sequence of assignment statements. To deal with difference \#3 we
  1048. will be replacing variables with registers and/or stack
  1049. locations. Thus, it makes sense to deal with \#2 before \#3 so that
  1050. \#3 can replace both the original variables and the new ones. Next,
  1051. consider where \#1 should fit in. Because it has to do with the format
  1052. of x86 instructions, it makes more sense after we have flattened the
  1053. nested expressions (\#2). Finally, when should we deal with \#4
  1054. (variable overshadowing)? We shall solve this problem by renaming
  1055. variables to make sure they have unique names. Recall that our plan
  1056. for \#2 involves moving nested expressions, which could be problematic
  1057. if it changes the shadowing of variables. However, if we deal with \#4
  1058. first, then it will not be an issue. Thus, we arrive at the following
  1059. ordering.
  1060. \[
  1061. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1062. \foreach \i/\p in {4/1,2/2,1/3,3/4}
  1063. {
  1064. \node (\i) at (\p*1.5,0) {$\i$};
  1065. }
  1066. \foreach \x/\y in {4/2,2/1,1/3}
  1067. {
  1068. \draw[->] (\x) to (\y);
  1069. }
  1070. \end{tikzpicture}
  1071. \]
  1072. We further simplify the translation from $R_1$ to x86 by identifying
  1073. an intermediate language named $C_0$, roughly half-way between $R_1$
  1074. and x86, to provide a rest stop along the way. We name the language
  1075. $C_0$ because it is vaguely similar to the $C$
  1076. language~\citep{Kernighan:1988nx}. The differences \#4 and \#1,
  1077. regarding variables and nested expressions, will be handled by two
  1078. steps, \key{uniquify} and \key{flatten}, which bring us to
  1079. $C_0$.
  1080. \[
  1081. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1082. \foreach \i/\p in {R_1/1,R_1/2,C_0/3}
  1083. {
  1084. \node (\p) at (\p*3,0) {\large $\i$};
  1085. }
  1086. \foreach \x/\y/\lbl in {1/2/uniquify,2/3/flatten}
  1087. {
  1088. \path[->,bend left=15] (\x) edge [above] node {\ttfamily\footnotesize \lbl} (\y);
  1089. }
  1090. \end{tikzpicture}
  1091. \]
  1092. Each of these steps in the compiler is implemented by a function,
  1093. typically a structurally recursive function that translates an input
  1094. AST into an output AST. We refer to such a function as a \emph{pass}
  1095. because it makes a pass over, i.e. it traverses the entire AST.
  1096. The syntax for $C_0$ is defined in Figure~\ref{fig:c0-syntax}. The
  1097. $C_0$ language supports the same operators as $R_1$ but the arguments
  1098. of operators are now restricted to just variables and integers. The
  1099. \key{let} construct of $R_1$ is replaced by an assignment statement
  1100. and there is a \key{return} construct to specify the return value of
  1101. the program. A program consists of a sequence of statements that
  1102. include at least one \key{return} statement. Each program is also
  1103. annotated with a list of variables (viz. {\tt (var*)}). At the start
  1104. of the program, these variables are uninitialized (they contain garbage)
  1105. and each variable becomes initialized on its first assignment. All of
  1106. the variables used in the program must be present in this list.
  1107. \begin{figure}[tp]
  1108. \fbox{
  1109. \begin{minipage}{0.96\textwidth}
  1110. \[
  1111. \begin{array}{lcl}
  1112. \Arg &::=& \Int \mid \Var \\
  1113. \Exp &::=& \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)\\
  1114. \Stmt &::=& \ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg} \\
  1115. C_0 & ::= & (\key{program}\;(\Var^{*})\;\Stmt^{+})
  1116. \end{array}
  1117. \]
  1118. \end{minipage}
  1119. }
  1120. \caption{The $C_0$ intermediate language.}
  1121. \label{fig:c0-syntax}
  1122. \end{figure}
  1123. To get from $C_0$ to x86 assembly it remains for us to handle
  1124. difference \#1 (the format of instructions) and difference \#3
  1125. (variables versus registers). These two differences are intertwined,
  1126. creating a bit of a Gordian Knot. To handle difference \#3, we need to
  1127. map some variables to registers (there are only 16 registers) and the
  1128. remaining variables to locations on the stack (which is unbounded). To
  1129. make good decisions regarding this mapping, we need the program to be
  1130. close to its final form (in x86 assembly) so we know exactly when
  1131. which variables are used. After all, variables that are used in
  1132. disjoint parts of the program can be assigned to the same register.
  1133. However, our choice of x86 instructions depends on whether the
  1134. variables are mapped to registers or stack locations, so we have a
  1135. circular dependency. We cut this knot by doing an optimistic selection
  1136. of instructions in the \key{select-instructions} pass, followed by the
  1137. \key{assign-homes} pass to map variables to registers or stack
  1138. locations, and conclude by finalizing the instruction selection in the
  1139. \key{patch-instructions} pass.
  1140. \[
  1141. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1142. \node (1) at (0,0) {\large $C_0$};
  1143. \node (2) at (3,0) {\large $\text{x86}^{*}$};
  1144. \node (3) at (6,0) {\large $\text{x86}^{*}$};
  1145. \node (4) at (9,0) {\large $\text{x86}$};
  1146. \path[->,bend left=15] (1) edge [above] node {\ttfamily\footnotesize select-instr.} (2);
  1147. \path[->,bend left=15] (2) edge [above] node {\ttfamily\footnotesize assign-homes} (3);
  1148. \path[->,bend left=15] (3) edge [above] node {\ttfamily\footnotesize patch-instr.} (4);
  1149. \end{tikzpicture}
  1150. \]
  1151. The \key{select-instructions} pass is optimistic in the sense that it
  1152. treats variables as if they were all mapped to registers. The
  1153. \key{select-instructions} pass generates a program that consists of
  1154. x86 instructions but that still uses variables, so it is an
  1155. intermediate language that is technically different than x86, which
  1156. explains the asterisks in the diagram above.
  1157. In this Chapter we shall take the easy road to implementing
  1158. \key{assign-homes} and simply map all variables to stack locations.
  1159. The topic of Chapter~\ref{ch:register-allocation} is implementing a
  1160. smarter approach in which we make a best-effort to map variables to
  1161. registers, resorting to the stack only when necessary.
  1162. %% \marginpar{\scriptsize I'm confused: shouldn't `select instructions' do this?
  1163. %% After all, that selects the x86 instructions. Even if it is separate,
  1164. %% if we perform `patching' before register allocation, we aren't forced to rely on
  1165. %% \key{rax} as much. This can ultimately make a more-performant result. --
  1166. %% Cam}
  1167. Once variables have been assigned to their homes, we can finalize the
  1168. instruction selection by dealing with an idiosyncrasy of x86
  1169. assembly. Many x86 instructions have two arguments but only one of the
  1170. arguments may be a memory reference (and the stack is a part of
  1171. memory). Because some variables may get mapped to stack locations,
  1172. some of our generated instructions may violate this restriction. The
  1173. purpose of the \key{patch-instructions} pass is to fix this problem by
  1174. replacing every violating instruction with a short sequence of
  1175. instructions that use the \key{rax} register. Once we have implemented
  1176. a good register allocator (Chapter~\ref{ch:register-allocation}), the
  1177. need to patch instructions will be relatively rare.
  1178. \section{Uniquify Variables}
  1179. \label{sec:uniquify-s0}
  1180. The purpose of this pass is to make sure that each \key{let} uses a
  1181. unique variable name. For example, the \code{uniquify} pass should
  1182. translate the program on the left into the program on the right. \\
  1183. \begin{tabular}{lll}
  1184. \begin{minipage}{0.4\textwidth}
  1185. \begin{lstlisting}
  1186. (program
  1187. (let ([x 32])
  1188. (+ (let ([x 10]) x) x)))
  1189. \end{lstlisting}
  1190. \end{minipage}
  1191. &
  1192. $\Rightarrow$
  1193. &
  1194. \begin{minipage}{0.4\textwidth}
  1195. \begin{lstlisting}
  1196. (program
  1197. (let ([x.1 32])
  1198. (+ (let ([x.2 10]) x.2) x.1)))
  1199. \end{lstlisting}
  1200. \end{minipage}
  1201. \end{tabular} \\
  1202. %
  1203. The following is another example translation, this time of a program
  1204. with a \key{let} nested inside the initializing expression of another
  1205. \key{let}.\\
  1206. \begin{tabular}{lll}
  1207. \begin{minipage}{0.4\textwidth}
  1208. \begin{lstlisting}
  1209. (program
  1210. (let ([x (let ([x 4])
  1211. (+ x 1))])
  1212. (+ x 2)))
  1213. \end{lstlisting}
  1214. \end{minipage}
  1215. &
  1216. $\Rightarrow$
  1217. &
  1218. \begin{minipage}{0.4\textwidth}
  1219. \begin{lstlisting}
  1220. (program
  1221. (let ([x.2 (let ([x.1 4])
  1222. (+ x.1 1))])
  1223. (+ x.2 2)))
  1224. \end{lstlisting}
  1225. \end{minipage}
  1226. \end{tabular}
  1227. We recommend implementing \code{uniquify} as a structurally recursive
  1228. function that mostly copies the input program. However, when
  1229. encountering a \key{let}, it should generate a unique name for the
  1230. variable (the Racket function \code{gensym} is handy for this) and
  1231. associate the old name with the new unique name in an association
  1232. list. The \code{uniquify} function will need to access this
  1233. association list when it gets to a variable reference, so we add
  1234. another parameter to \code{uniquify} for the association list. It is
  1235. quite common for a compiler pass to need a map to store extra
  1236. information about variables. Such maps are often called \emph{symbol
  1237. tables}.
  1238. The skeleton of the \code{uniquify} function is shown in
  1239. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1240. convenient to partially apply it to an association list and then apply
  1241. it to different expressions, as in the last clause for primitive
  1242. operations in Figure~\ref{fig:uniquify-s0}. In the last \key{match}
  1243. clause for the primitive operators, note the use of the comma-@
  1244. operator to splice a list of S-expressions into an enclosing
  1245. S-expression.
  1246. \begin{exercise}
  1247. \normalfont % I don't like the italics for exercises. -Jeremy
  1248. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1249. implement the clauses for variables and for the \key{let} construct.
  1250. \end{exercise}
  1251. \begin{figure}[tbp]
  1252. \begin{lstlisting}
  1253. (define uniquify
  1254. (lambda (alist)
  1255. (lambda (e)
  1256. (match e
  1257. [(? symbol?) ___]
  1258. [(? integer?) e]
  1259. [`(let ([,x ,e]) ,body) ___]
  1260. [`(program ,e)
  1261. `(program ,((uniquify alist) e))]
  1262. [`(,op ,es ...)
  1263. `(,op ,@(map (uniquify alist) es))]
  1264. ))))
  1265. \end{lstlisting}
  1266. \caption{Skeleton for the \key{uniquify} pass.}
  1267. \label{fig:uniquify-s0}
  1268. \end{figure}
  1269. \begin{exercise}
  1270. \normalfont % I don't like the italics for exercises. -Jeremy
  1271. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1272. and checking whether the output programs produce the same result as
  1273. the input programs. The $R_1$ programs should be designed to test the
  1274. most interesting parts of the \key{uniquify} pass, that is, the
  1275. programs should include \key{let} constructs, variables, and variables
  1276. that overshadow each other. The five programs should be in a
  1277. subdirectory named \key{tests} and they should have the same file name
  1278. except for a different integer at the end of the name, followed by the
  1279. ending \key{.rkt}. Use the \key{interp-tests} function
  1280. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1281. your \key{uniquify} pass on the example programs.
  1282. \end{exercise}
  1283. \section{Flatten Expressions}
  1284. \label{sec:flatten-r1}
  1285. The \code{flatten} pass will transform $R_1$ programs into $C_0$
  1286. programs. In particular, the purpose of the \code{flatten} pass is to
  1287. get rid of nested expressions, such as the \code{(- 10)} in the program
  1288. below. This can be accomplished by introducing a new variable,
  1289. assigning the nested expression to the new variable, and then using
  1290. the new variable in place of the nested expressions, as shown in the
  1291. output of \code{flatten} on the right.\\
  1292. \begin{tabular}{lll}
  1293. \begin{minipage}{0.4\textwidth}
  1294. \begin{lstlisting}
  1295. (program
  1296. (+ 52 (- 10)))
  1297. \end{lstlisting}
  1298. \end{minipage}
  1299. &
  1300. $\Rightarrow$
  1301. &
  1302. \begin{minipage}{0.4\textwidth}
  1303. \begin{lstlisting}
  1304. (program (tmp.1 tmp.2)
  1305. (assign tmp.1 (- 10))
  1306. (assign tmp.2 (+ 52 tmp.1))
  1307. (return tmp.2))
  1308. \end{lstlisting}
  1309. \end{minipage}
  1310. \end{tabular}
  1311. The clause of \code{flatten} for \key{let} is straightforward to
  1312. implement as it just requires the generation of an assignment
  1313. statement for the \key{let}-bound variable. The following shows the
  1314. result of \code{flatten} for a \key{let}. \\
  1315. \begin{tabular}{lll}
  1316. \begin{minipage}{0.4\textwidth}
  1317. \begin{lstlisting}
  1318. (program
  1319. (let ([x (+ (- 10) 11)])
  1320. (+ x 41)))
  1321. \end{lstlisting}
  1322. \end{minipage}
  1323. &
  1324. $\Rightarrow$
  1325. &
  1326. \begin{minipage}{0.4\textwidth}
  1327. \begin{lstlisting}
  1328. (program (tmp.1 x tmp.2)
  1329. (assign tmp.1 (- 10))
  1330. (assign x (+ tmp.1 11))
  1331. (assign tmp.2 (+ x 41))
  1332. (return tmp.2))
  1333. \end{lstlisting}
  1334. \end{minipage}
  1335. \end{tabular}
  1336. We recommend implementing \key{flatten} as a structurally recursive
  1337. function that returns two things, 1) the newly flattened expression,
  1338. and 2) a list of assignment statements, one for each of the new
  1339. variables introduced during the flattening the expression. The newly
  1340. flattened expression should be an $\Arg$ in the $C_0$ syntax
  1341. (Figure~\ref{fig:c0-syntax}), that is, it should be an integer or a
  1342. variable. You can return multiple things from a function using the
  1343. \key{values} form and you can receive multiple things from a function
  1344. call using the \key{define-values} form. If you are not familiar with
  1345. these constructs, the Racket documentation will be of help. Also, the
  1346. \key{map2} function (Appendix~\ref{appendix:utilities}) is useful for
  1347. applying a function to each element of a list, in the case where the
  1348. function returns two values. The result of \key{map2} is two lists.
  1349. The clause of \key{flatten} for the \key{program} node needs to
  1350. recursively flatten the body of the program and the newly flattened
  1351. expression should be placed in a \key{return} statement. The
  1352. \key{flatten} pass should also compute the list of variables used in
  1353. the program. I recommend traversing the statements in the body of the
  1354. program (after it has been flattened) and collect all variables that
  1355. appear on the left-hand-side of an assignment. Note that each variable
  1356. should only occur once in the list of variables that you place in the
  1357. \key{program} form.
  1358. Take special care for programs such as the following that initialize
  1359. variables with integers or other variables. It should be translated
  1360. to the program on the right \\
  1361. \begin{tabular}{lll}
  1362. \begin{minipage}{0.4\textwidth}
  1363. \begin{lstlisting}
  1364. (let ([a 42])
  1365. (let ([b a])
  1366. b))
  1367. \end{lstlisting}
  1368. \end{minipage}
  1369. &
  1370. $\Rightarrow$
  1371. &
  1372. \begin{minipage}{0.4\textwidth}
  1373. \begin{lstlisting}
  1374. (program (a b)
  1375. (assign a 42)
  1376. (assign b a)
  1377. (return b))
  1378. \end{lstlisting}
  1379. \end{minipage}
  1380. \end{tabular} \\
  1381. and not to the following, which could result from a naive
  1382. implementation of \key{flatten}.
  1383. \begin{lstlisting}
  1384. (program (tmp.1 a tmp.2 b)
  1385. (assign tmp.1 42)
  1386. (assign a tmp.1)
  1387. (assign tmp.2 a)
  1388. (assign b tmp.2)
  1389. (return b))
  1390. \end{lstlisting}
  1391. \begin{exercise}
  1392. \normalfont
  1393. Implement the \key{flatten} pass and test it on all of the example
  1394. programs that you created to test the \key{uniquify} pass and create
  1395. three new example programs that are designed to exercise all of the
  1396. interesting code in the \key{flatten} pass. Use the \key{interp-tests}
  1397. function (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to
  1398. test your passes on the example programs.
  1399. \end{exercise}
  1400. \section{Select Instructions}
  1401. \label{sec:select-s0}
  1402. In the \key{select-instructions} pass we begin the work of translating
  1403. from $C_0$ to x86. The target language of this pass is a pseudo-x86
  1404. language that still uses variables, so we add an AST node of the form
  1405. $\VAR{\itm{var}}$ to the x86 abstract syntax. Also, the \key{program}
  1406. form should still list the variables (similar to $C_0$):
  1407. \[
  1408. (\key{program}\;(\Var^{*})\;\Instr^{+})
  1409. \]
  1410. The \key{select-instructions} pass deals with the differing format of
  1411. arithmetic operations. For example, in $C_0$ an addition operation can
  1412. take the form below. To translate to x86, we need to use the
  1413. \key{addq} instruction which does an in-place update. So we must first
  1414. move \code{10} to \code{x}. \\
  1415. \begin{tabular}{lll}
  1416. \begin{minipage}{0.4\textwidth}
  1417. \begin{lstlisting}
  1418. (assign x (+ 10 32))
  1419. \end{lstlisting}
  1420. \end{minipage}
  1421. &
  1422. $\Rightarrow$
  1423. &
  1424. \begin{minipage}{0.4\textwidth}
  1425. \begin{lstlisting}
  1426. (movq (int 10) (var x))
  1427. (addq (int 32) (var x))
  1428. \end{lstlisting}
  1429. \end{minipage}
  1430. \end{tabular} \\
  1431. There are some cases that require special care to avoid generating
  1432. needlessly complicated code. If one of the arguments is the same as
  1433. the left-hand side of the assignment, then there is no need for the
  1434. extra move instruction. For example, the following assignment
  1435. statement can be translated into a single \key{addq} instruction.\\
  1436. \begin{tabular}{lll}
  1437. \begin{minipage}{0.4\textwidth}
  1438. \begin{lstlisting}
  1439. (assign x (+ 10 x))
  1440. \end{lstlisting}
  1441. \end{minipage}
  1442. &
  1443. $\Rightarrow$
  1444. &
  1445. \begin{minipage}{0.4\textwidth}
  1446. \begin{lstlisting}
  1447. (addq (int 10) (var x))
  1448. \end{lstlisting}
  1449. \end{minipage}
  1450. \end{tabular} \\
  1451. The \key{read} operation does not have a direct counterpart in x86
  1452. assembly, so we have instead implemented this functionality in the C
  1453. language, with the function \code{read\_int} in the file
  1454. \code{runtime.c}. In general, we refer to all of the functionality in
  1455. this file as the \emph{runtime system}, or simply the \emph{runtime}
  1456. for short. When compiling your generated x86 assembly code, you
  1457. will need to compile \code{runtime.c} to \code{runtime.o} (an ``object
  1458. file'', using \code{gcc} option \code{-c}) and link it into the final
  1459. executable. For our purposes of code generation, all you need to do is
  1460. translate an assignment of \key{read} to some variable $\itm{lhs}$
  1461. (for left-hand side) into a call to the \code{read\_int} function
  1462. followed by a move from \code{rax} to the left-hand side. The move
  1463. from \code{rax} is needed because the return value from
  1464. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  1465. \begin{tabular}{lll}
  1466. \begin{minipage}{0.4\textwidth}
  1467. \begin{lstlisting}
  1468. (assign |$\itm{lhs}$| (read))
  1469. \end{lstlisting}
  1470. \end{minipage}
  1471. &
  1472. $\Rightarrow$
  1473. &
  1474. \begin{minipage}{0.4\textwidth}
  1475. \begin{lstlisting}
  1476. (callq read_int)
  1477. (movq (reg rax) (var |$\itm{lhs}$|))
  1478. \end{lstlisting}
  1479. \end{minipage}
  1480. \end{tabular} \\
  1481. Regarding the \RETURN{\Arg} statement of $C_0$, we recommend treating it
  1482. as an assignment to the \key{rax} register and let the procedure
  1483. conclusion handle the transfer of control back to the calling
  1484. procedure.
  1485. \begin{exercise}
  1486. \normalfont
  1487. Implement the \key{select-instructions} pass and test it on all of the
  1488. example programs that you created for the previous passes and create
  1489. three new example programs that are designed to exercise all of the
  1490. interesting code in this pass. Use the \key{interp-tests} function
  1491. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1492. your passes on the example programs.
  1493. \end{exercise}
  1494. \section{Assign Homes}
  1495. \label{sec:assign-s0}
  1496. As discussed in Section~\ref{sec:plan-s0-x86}, the
  1497. \key{assign-homes} pass places all of the variables on the stack.
  1498. Consider again the example $R_1$ program \code{(+ 52 (- 10))},
  1499. which after \key{select-instructions} looks like the following.
  1500. \begin{lstlisting}
  1501. (movq (int 10) (var x))
  1502. (negq (var x))
  1503. (movq (int 52) (reg rax))
  1504. (addq (var x) (reg rax))
  1505. \end{lstlisting}
  1506. The one and only variable \code{x} is assigned to stack location
  1507. \code{-8(\%rbp)}, so the \code{assign-homes} pass translates the
  1508. above to
  1509. \begin{lstlisting}
  1510. (movq (int 10) (stack -8))
  1511. (negq (stack -8))
  1512. (movq (int 52) (reg rax))
  1513. (addq (stack -8) (reg rax))
  1514. \end{lstlisting}
  1515. In the process of assigning stack locations to variables, it is
  1516. convenient to compute and store the size of the frame in the first
  1517. field of the \key{program} node which will be needed later to generate
  1518. the procedure conclusion.
  1519. \[
  1520. (\key{program}\;\Int\;\Instr^{+})
  1521. \]
  1522. Some operating systems place restrictions on
  1523. the frame size. For example, Mac OS X requires the frame size to be a
  1524. multiple of 16 bytes.
  1525. \begin{exercise}
  1526. \normalfont Implement the \key{assign-homes} pass and test it on all
  1527. of the example programs that you created for the previous passes pass.
  1528. I recommend that \key{assign-homes} take an extra parameter that is a
  1529. mapping of variable names to homes (stack locations for now). Use the
  1530. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  1531. \key{utilities.rkt} to test your passes on the example programs.
  1532. \end{exercise}
  1533. \section{Patch Instructions}
  1534. \label{sec:patch-s0}
  1535. The purpose of this pass is to make sure that each instruction adheres
  1536. to the restrictions regarding which arguments can be memory
  1537. references. For most instructions, the rule is that at most one
  1538. argument may be a memory reference.
  1539. Consider again the following example.
  1540. \begin{lstlisting}
  1541. (let ([a 42])
  1542. (let ([b a])
  1543. b))
  1544. \end{lstlisting}
  1545. After \key{assign-homes} pass, the above has been translated to
  1546. \begin{lstlisting}
  1547. (movq (int 42) (stack -8))
  1548. (movq (stack -8) (stack -16))
  1549. (movq (stack -16) (reg rax))
  1550. \end{lstlisting}
  1551. The second \key{movq} instruction is problematic because both arguments
  1552. are stack locations. We suggest fixing this problem by moving from the
  1553. source to \key{rax} and then from \key{rax} to the destination, as
  1554. follows.
  1555. \begin{lstlisting}
  1556. (movq (int 42) (stack -8))
  1557. (movq (stack -8) (reg rax))
  1558. (movq (reg rax) (stack -16))
  1559. (movq (stack -16) (reg rax))
  1560. \end{lstlisting}
  1561. \begin{exercise}
  1562. \normalfont
  1563. Implement the \key{patch-instructions} pass and test it on all of the
  1564. example programs that you created for the previous passes and create
  1565. three new example programs that are designed to exercise all of the
  1566. interesting code in this pass. Use the \key{interp-tests} function
  1567. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1568. your passes on the example programs.
  1569. \end{exercise}
  1570. \section{Print x86}
  1571. \label{sec:print-x86}
  1572. The last step of the compiler from $R_1$ to x86 is to convert the
  1573. x86 AST (defined in Figure~\ref{fig:x86-ast-a}) to the string
  1574. representation (defined in Figure~\ref{fig:x86-a}). The Racket
  1575. \key{format} and \key{string-append} functions are useful in this
  1576. regard. The main work that this step needs to perform is to create the
  1577. \key{main} function and the standard instructions for its prelude
  1578. and conclusion, as shown in Figure~\ref{fig:p1-x86} of
  1579. Section~\ref{sec:x86}. You need to know the number of
  1580. stack-allocated variables, for which it is suggest that you compute in
  1581. the \key{assign-homes} pass (Section~\ref{sec:assign-s0}) and store in
  1582. the $\itm{info}$ field of the \key{program} node.
  1583. Your compiled code should print the result of the program's execution by using the
  1584. \code{print\_int} function provided in \code{runtime.c}. If your compiler has been implemented correctly so far, this final result should be stored in the \key{rax} register.
  1585. We'll talk more about
  1586. how to perform function calls with arguments in general later on, but
  1587. for now, make sure that your x86 printer includes the following code as part of the conclusion:
  1588. \begin{lstlisting}
  1589. movq %rax, %rdi
  1590. callq print_int
  1591. \end{lstlisting}
  1592. These lines move the value in \key{rax} into the \key{rdi} register, which
  1593. stores the first argument to be passed into \key{print\_int}.
  1594. If you want your program to run on Mac OS X, your code needs to
  1595. determine whether or not it is running on a Mac, and prefix
  1596. underscores to labels like \key{main}. You can determine the platform
  1597. with the Racket call \code{(system-type 'os)}, which returns
  1598. \code{'macosx}, \code{'unix}, or \code{'windows}. In addition to
  1599. placing underscores on \key{main}, you need to put them in front of
  1600. \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  1601. \_print\_int}).
  1602. \begin{exercise}
  1603. \normalfont Implement the \key{print-x86} pass and test it on all of
  1604. the example programs that you created for the previous passes. Use the
  1605. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  1606. \key{utilities.rkt} to test your complete compiler on the example
  1607. programs.
  1608. % The following is specific to P423/P523. -Jeremy
  1609. %Mac support is optional, but your compiler has to output
  1610. %valid code for Unix machines.
  1611. \end{exercise}
  1612. \begin{figure}[p]
  1613. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1614. \node (R1) at (0,2) {\large $R_1$};
  1615. \node (R1-2) at (3,2) {\large $R_1$};
  1616. \node (C0-1) at (3,0) {\large $C_0$};
  1617. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  1618. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  1619. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  1620. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  1621. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1622. \path[->,bend left=15] (R1-2) edge [right] node {\ttfamily\footnotesize flatten} (C0-1);
  1623. \path[->,bend right=15] (C0-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1624. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1625. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1626. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1627. \end{tikzpicture}
  1628. \caption{Overview of the passes for compiling $R_1$. The x86$^{*}$
  1629. language extends x86 with variables and looser rules regarding
  1630. instruction arguments. The x86$^{\dagger}$ language is the concrete
  1631. syntax (string) for x86.}
  1632. \label{fig:R1-passes}
  1633. \end{figure}
  1634. Figure~\ref{fig:R1-passes} provides an overview of all the compiler
  1635. passes described in this Chapter.
  1636. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1637. \chapter{Register Allocation}
  1638. \label{ch:register-allocation}
  1639. In Chapter~\ref{ch:int-exp} we simplified the generation of x86
  1640. assembly by placing all variables on the stack. We can improve the
  1641. performance of the generated code considerably if we instead try to
  1642. place as many variables as possible into registers. The CPU can
  1643. access a register in a single cycle, whereas accessing the stack can
  1644. take from several cycles (to go to cache) to hundreds of cycles (to go
  1645. to main memory). Figure~\ref{fig:reg-eg} shows a program with four
  1646. variables that serves as a running example. We show the source program
  1647. and also the output of instruction selection. At that point the
  1648. program is almost x86 assembly but not quite; it still contains
  1649. variables instead of stack locations or registers.
  1650. \begin{figure}
  1651. \begin{minipage}{0.45\textwidth}
  1652. Source program:
  1653. \begin{lstlisting}
  1654. (program
  1655. (let ([v 1])
  1656. (let ([w 46])
  1657. (let ([x (+ v 7)])
  1658. (let ([y (+ 4 x)])
  1659. (let ([z (+ x w)])
  1660. (+ z (- y))))))))
  1661. \end{lstlisting}
  1662. \end{minipage}
  1663. \begin{minipage}{0.45\textwidth}
  1664. After instruction selection:
  1665. \begin{lstlisting}
  1666. (program (v w x y z t.1 t.2)
  1667. (movq (int 1) (var v))
  1668. (movq (int 46) (var w))
  1669. (movq (var v) (var x))
  1670. (addq (int 7) (var x))
  1671. (movq (var x) (var y))
  1672. (addq (int 4) (var y))
  1673. (movq (var x) (var z))
  1674. (addq (var w) (var z))
  1675. (movq (var y) (var t.1))
  1676. (negq (var t.1))
  1677. (movq (var z) (var t.2))
  1678. (addq (var t.1) (var t.2))
  1679. (movq (var t.2) (reg rax)))
  1680. \end{lstlisting}
  1681. \end{minipage}
  1682. \caption{Running example for this chapter.}
  1683. \label{fig:reg-eg}
  1684. \end{figure}
  1685. The goal of register allocation is to fit as many variables into
  1686. registers as possible. It is often the case that we have more
  1687. variables than registers, so we cannot naively map each variable to a
  1688. register. Fortunately, it is also common for different variables to be
  1689. needed during different periods of time, and in such cases the
  1690. variables can be mapped to the same register. Consider variables
  1691. \code{x} and \code{y} in Figure~\ref{fig:reg-eg}. After the variable
  1692. \code{x} is moved to \code{z} it is no longer needed. Variable
  1693. \code{y}, on the other hand, is used only after this point, so
  1694. \code{x} and \code{y} could share the same register. The topic of the
  1695. next section is how we compute where a variable is needed.
  1696. \section{Liveness Analysis}
  1697. \label{sec:liveness-analysis}
  1698. A variable is \emph{live} if the variable is used at some later point
  1699. in the program and there is not an intervening assignment to the
  1700. variable.
  1701. %
  1702. To understand the latter condition, consider the following code
  1703. fragment in which there are two writes to \code{b}. Are \code{a} and
  1704. \code{b} both live at the same time?
  1705. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  1706. (movq (int 5) (var a))
  1707. (movq (int 30) (var b))
  1708. (movq (var a) (var c))
  1709. (movq (int 10) (var b))
  1710. (addq (var b) (var c))
  1711. \end{lstlisting}
  1712. The answer is no because the value \code{30} written to \code{b} on
  1713. line 2 is never used. The variable \code{b} is read on line 5 and
  1714. there is an intervening write to \code{b} on line 4, so the read on
  1715. line 5 receives the value written on line 4, not line 2.
  1716. The live variables can be computed by traversing the instruction
  1717. sequence back to front (i.e., backwards in execution order). Let
  1718. $I_1,\ldots, I_n$ be the instruction sequence. We write
  1719. $L_{\mathsf{after}}(k)$ for the set of live variables after
  1720. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  1721. variables before instruction $I_k$. The live variables after an
  1722. instruction are always the same as the live variables before the next
  1723. instruction.
  1724. \begin{equation*}
  1725. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  1726. \end{equation*}
  1727. To start things off, there are no live variables after the last
  1728. instruction, so
  1729. \begin{equation*}
  1730. L_{\mathsf{after}}(n) = \emptyset
  1731. \end{equation*}
  1732. We then apply the following rule repeatedly, traversing the
  1733. instruction sequence back to front.
  1734. \begin{equation*}
  1735. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  1736. \end{equation*}
  1737. where $W(k)$ are the variables written to by instruction $I_k$ and
  1738. $R(k)$ are the variables read by instruction $I_k$.
  1739. Figure~\ref{fig:live-eg} shows the results of live variables analysis
  1740. for the running example, with each instruction aligned with its
  1741. $L_{\mathtt{after}}$ set to make the figure easy to read.
  1742. \begin{figure}[tbp]
  1743. \hspace{20pt}
  1744. \begin{minipage}{0.45\textwidth}
  1745. \begin{lstlisting}[numbers=left]
  1746. (program (v w x y z t.1 t.2)
  1747. (movq (int 1) (var v))
  1748. (movq (int 46) (var w))
  1749. (movq (var v) (var x))
  1750. (addq (int 7) (var x))
  1751. (movq (var x) (var y))
  1752. (addq (int 4) (var y))
  1753. (movq (var x) (var z))
  1754. (addq (var w) (var z))
  1755. (movq (var y) (var t.1))
  1756. (negq (var t.1))
  1757. (movq (var z) (var t.2))
  1758. (addq (var t.1) (var t.2))
  1759. (movq (var t.2) (reg rax)))
  1760. \end{lstlisting}
  1761. \end{minipage}
  1762. \vrule\hspace{10pt}
  1763. \begin{minipage}{0.45\textwidth}
  1764. \begin{lstlisting}
  1765. |$\{ v \}$|
  1766. |$\{ v, w \}$|
  1767. |$\{ w, x \}$|
  1768. |$\{ w, x \}$|
  1769. |$\{ w, x, y\}$|
  1770. |$\{ w, x, y \}$|
  1771. |$\{ w, y, z \}$|
  1772. |$\{ y, z \}$|
  1773. |$\{ t.1, z \}$|
  1774. |$\{ t.1, z \}$|
  1775. |$\{t.1,t.2\}$|
  1776. |$\{t.2\}$|
  1777. |$\{\}$|
  1778. \end{lstlisting}
  1779. \end{minipage}
  1780. \caption{The running example and its live-after sets.}
  1781. \label{fig:live-eg}
  1782. \end{figure}
  1783. \begin{exercise}\normalfont
  1784. Implement the compiler pass named \code{uncover-live} that computes
  1785. the live-after sets. We recommend storing the live-after sets (a list
  1786. of lists of variables) in the $\itm{info}$ field of the \key{program}
  1787. node alongside the list of variables as follows.
  1788. \begin{lstlisting}
  1789. (program (|$\Var^{*}$| |$\itm{live{-}afters}$|) |$\Instr^{+}$|)
  1790. \end{lstlisting}
  1791. I recommend organizing your code to use a helper function that takes a
  1792. list of statements and an initial live-after set (typically empty) and
  1793. returns the list of statements and the list of live-after sets. For
  1794. this chapter, returning the list of statements is unnecessary, as they
  1795. will be unchanged, but in Chapter~\ref{ch:bool-types} we introduce
  1796. \key{if} statements and will need to annotate them with the live-after
  1797. sets of the two branches.
  1798. I recommend creating helper functions to 1) compute the set of
  1799. variables that appear in an argument (of an instruction), 2) compute
  1800. the variables read by an instruction which corresponds to the $R$
  1801. function discussed above, and 3) the variables written by an
  1802. instruction which corresponds to $W$.
  1803. \end{exercise}
  1804. \section{Building the Interference Graph}
  1805. Based on the liveness analysis, we know where each variable is needed.
  1806. However, during register allocation, we need to answer questions of
  1807. the specific form: are variables $u$ and $v$ live at the same time?
  1808. (And therefore cannot be assigned to the same register.) To make this
  1809. question easier to answer, we create an explicit data structure, an
  1810. \emph{interference graph}. An interference graph is an undirected
  1811. graph that has an edge between two variables if they are live at the
  1812. same time, that is, if they interfere with each other.
  1813. The most obvious way to compute the interference graph is to look at
  1814. the set of live variables between each statement in the program, and
  1815. add an edge to the graph for every pair of variables in the same set.
  1816. This approach is less than ideal for two reasons. First, it can be
  1817. rather expensive because it takes $O(n^2)$ time to look at every pair
  1818. in a set of $n$ live variables. Second, there is a special case in
  1819. which two variables that are live at the same time do not actually
  1820. interfere with each other: when they both contain the same value
  1821. because we have assigned one to the other.
  1822. A better way to compute the interference graph is given by the
  1823. following.
  1824. \begin{itemize}
  1825. \item If instruction $I_k$ is a move: (\key{movq} $s$\, $d$), then add
  1826. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  1827. d$ or $v = s$.
  1828. \item If instruction $I_k$ is not a move but some other arithmetic
  1829. instruction such as (\key{addq} $s$\, $d$), then add the edge $(d,v)$
  1830. for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  1831. \item If instruction $I_k$ is of the form (\key{callq}
  1832. $\mathit{label}$), then add an edge $(r,v)$ for every caller-save
  1833. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  1834. \end{itemize}
  1835. Working from the top to bottom of Figure~\ref{fig:live-eg}, we obtain
  1836. the following interference for the instruction at the specified line
  1837. number.
  1838. \begin{quote}
  1839. Line 2: no interference,\\
  1840. Line 3: $w$ interferes with $v$,\\
  1841. Line 4: $x$ interferes with $w$,\\
  1842. Line 5: $x$ interferes with $w$,\\
  1843. Line 6: $y$ interferes with $w$,\\
  1844. Line 7: $y$ interferes with $w$ and $x$,\\
  1845. Line 8: $z$ interferes with $w$ and $y$,\\
  1846. Line 9: $z$ interferes with $y$, \\
  1847. Line 10: $t.1$ interferes with $z$, \\
  1848. Line 11: $t.1$ interferes with $z$, \\
  1849. Line 12: $t.2$ interferes with $t.1$, \\
  1850. Line 13: no interference. \\
  1851. Line 14: no interference.
  1852. \end{quote}
  1853. The resulting interference graph is shown in
  1854. Figure~\ref{fig:interfere}.
  1855. \begin{figure}[tbp]
  1856. \large
  1857. \[
  1858. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1859. \node (v) at (0,0) {$v$};
  1860. \node (w) at (2,0) {$w$};
  1861. \node (x) at (4,0) {$x$};
  1862. \node (t1) at (6,0) {$t.1$};
  1863. \node (y) at (2,-2) {$y$};
  1864. \node (z) at (4,-2) {$z$};
  1865. \node (t2) at (6,-2) {$t.2$};
  1866. \draw (v) to (w);
  1867. \foreach \i in {w,x,y}
  1868. {
  1869. \foreach \j in {w,x,y}
  1870. {
  1871. \draw (\i) to (\j);
  1872. }
  1873. }
  1874. \draw (z) to (w);
  1875. \draw (z) to (y);
  1876. \draw (t1) to (z);
  1877. \draw (t2) to (t1);
  1878. \end{tikzpicture}
  1879. \]
  1880. \caption{Interference graph for the running example.}
  1881. \label{fig:interfere}
  1882. \end{figure}
  1883. Our next concern is to choose a data structure for representing the
  1884. interference graph. There are many standard choices for how to
  1885. represent a graph: \emph{adjacency matrix}, \emph{adjacency list}, and
  1886. \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a data
  1887. structure is to study the algorithm that uses the data structure,
  1888. determine what operations need to be performed, and then choose the
  1889. data structure that provide the most efficient implementations of
  1890. those operations. Often times the choice of data structure can have an
  1891. affect on the time complexity of the algorithm, as it does here. If
  1892. you skim the next section, you will see that the register allocation
  1893. algorithm needs to ask the graph for all of its vertices and, given a
  1894. vertex, it needs to known all of the adjacent vertices. Thus, the
  1895. correct choice of graph representation is that of an adjacency
  1896. list. There are helper functions in \code{utilities.rkt} for
  1897. representing graphs using the adjacency list representation:
  1898. \code{make-graph}, \code{add-edge}, and \code{adjacent}
  1899. (Appendix~\ref{appendix:utilities}). In particular, those functions
  1900. use a hash table to map each vertex to the set of adjacent vertices,
  1901. and the sets are represented using Racket's \key{set}, which is also a
  1902. hash table.
  1903. \begin{exercise}\normalfont
  1904. Implement the compiler pass named \code{build-interference} according
  1905. to the algorithm suggested above. The output of this pass should
  1906. replace the live-after sets with the interference $\itm{graph}$ as
  1907. follows.
  1908. \begin{lstlisting}
  1909. (program (|$\Var^{*}$| |$\itm{graph}$|) |$\Instr^{+}$|)
  1910. \end{lstlisting}
  1911. \end{exercise}
  1912. \section{Graph Coloring via Sudoku}
  1913. We now come to the main event, mapping variables to registers (or to
  1914. stack locations in the event that we run out of registers). We need
  1915. to make sure not to map two variables to the same register if the two
  1916. variables interfere with each other. In terms of the interference
  1917. graph, this means we cannot map adjacent nodes to the same register.
  1918. If we think of registers as colors, the register allocation problem
  1919. becomes the widely-studied graph coloring
  1920. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  1921. The reader may be more familiar with the graph coloring problem then he
  1922. or she realizes; the popular game of Sudoku is an instance of the
  1923. graph coloring problem. The following describes how to build a graph
  1924. out of an initial Sudoku board.
  1925. \begin{itemize}
  1926. \item There is one node in the graph for each Sudoku square.
  1927. \item There is an edge between two nodes if the corresponding squares
  1928. are in the same row, in the same column, or if the squares are in
  1929. the same $3\times 3$ region.
  1930. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  1931. \item Based on the initial assignment of numbers to squares in the
  1932. Sudoku board, assign the corresponding colors to the corresponding
  1933. nodes in the graph.
  1934. \end{itemize}
  1935. If you can color the remaining nodes in the graph with the nine
  1936. colors, then you have also solved the corresponding game of Sudoku.
  1937. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  1938. the corresponding graph with colored vertices.
  1939. \begin{figure}[tbp]
  1940. \includegraphics[width=0.45\textwidth]{sudoku}
  1941. \includegraphics[width=0.5\textwidth]{sudoku-graph}
  1942. \caption{A Sudoku game board and the corresponding colored graph. We
  1943. map the Sudoku number 1 to blue, 2 to yellow, and 3 to red. We only
  1944. show edges for a sampling of the vertices (those that are colored)
  1945. because showing edges for all of the vertices would make the graph
  1946. unreadable.}
  1947. \label{fig:sudoku-graph}
  1948. \end{figure}
  1949. Given that Sudoku is graph coloring, one can use Sudoku strategies to
  1950. come up with an algorithm for allocating registers. For example, one
  1951. of the basic techniques for Sudoku is called Pencil Marks. The idea is
  1952. that you use a process of elimination to determine what numbers no
  1953. longer make sense for a square, and write down those numbers in the
  1954. square (writing very small). For example, if the number $1$ is
  1955. assigned to a square, then by process of elimination, you can write
  1956. the pencil mark $1$ in all the squares in the same row, column, and
  1957. region. Many Sudoku computer games provide automatic support for
  1958. Pencil Marks. This heuristic also reduces the degree of branching in
  1959. the search tree.
  1960. The Pencil Marks technique corresponds to the notion of color
  1961. \emph{saturation} due to \cite{Brelaz:1979eu}. The saturation of a
  1962. node, in Sudoku terms, is the set of colors that are no longer
  1963. available. In graph terminology, we have the following definition:
  1964. \begin{equation*}
  1965. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  1966. \text{ and } \mathrm{color}(v) = c \}
  1967. \end{equation*}
  1968. where $\mathrm{adjacent}(u)$ is the set of nodes adjacent to $u$.
  1969. Using the Pencil Marks technique leads to a simple strategy for
  1970. filling in numbers: if there is a square with only one possible number
  1971. left, then write down that number! But what if there are no squares
  1972. with only one possibility left? One brute-force approach is to just
  1973. make a guess. If that guess ultimately leads to a solution, great. If
  1974. not, backtrack to the guess and make a different guess. Of course,
  1975. backtracking can be horribly time consuming. One standard way to
  1976. reduce the amount of backtracking is to use the most-constrained-first
  1977. heuristic. That is, when making a guess, always choose a square with
  1978. the fewest possibilities left (the node with the highest saturation).
  1979. The idea is that choosing highly constrained squares earlier rather
  1980. than later is better because later there may not be any possibilities.
  1981. In some sense, register allocation is easier than Sudoku because we
  1982. can always cheat and add more numbers by mapping variables to the
  1983. stack. We say that a variable is \emph{spilled} when we decide to map
  1984. it to a stack location. We would like to minimize the time needed to
  1985. color the graph, and backtracking is expensive. Thus, it makes sense
  1986. to keep the most-constrained-first heuristic but drop the backtracking
  1987. in favor of greedy search (guess and just keep going).
  1988. Figure~\ref{fig:satur-algo} gives the pseudo-code for this simple
  1989. greedy algorithm for register allocation based on saturation and the
  1990. most-constrained-first heuristic, which is roughly equivalent to the
  1991. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  1992. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just
  1993. as in Sudoku, the algorithm represents colors with integers, with the
  1994. first $k$ colors corresponding to the $k$ registers in a given machine
  1995. and the rest of the integers corresponding to stack locations.
  1996. \begin{figure}[btp]
  1997. \centering
  1998. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  1999. Algorithm: DSATUR
  2000. Input: a graph |$G$|
  2001. Output: an assignment |$\mathrm{color}[v]$| for each node |$v \in G$|
  2002. |$W \gets \mathit{vertices}(G)$|
  2003. while |$W \neq \emptyset$| do
  2004. pick a node |$u$| from |$W$| with the highest saturation,
  2005. breaking ties randomly
  2006. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(v)\}$|
  2007. |$\mathrm{color}[u] \gets c$|
  2008. |$W \gets W - \{u\}$|
  2009. \end{lstlisting}
  2010. \caption{Saturation-based greedy graph coloring algorithm.}
  2011. \label{fig:satur-algo}
  2012. \end{figure}
  2013. With this algorithm in hand, let us return to the running example and
  2014. consider how to color the interference graph in
  2015. Figure~\ref{fig:interfere}. We shall not use register \key{rax} for
  2016. register allocation because we use it to patch instructions, so we
  2017. remove that vertex from the graph. Initially, all of the nodes are
  2018. not yet colored and they are unsaturated, so we annotate each of them
  2019. with a dash for their color and an empty set for the saturation.
  2020. \[
  2021. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2022. \node (v) at (0,0) {$v:-,\{\}$};
  2023. \node (w) at (3,0) {$w:-,\{\}$};
  2024. \node (x) at (6,0) {$x:-,\{\}$};
  2025. \node (y) at (3,-1.5) {$y:-,\{\}$};
  2026. \node (z) at (6,-1.5) {$z:-,\{\}$};
  2027. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2028. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2029. \draw (v) to (w);
  2030. \foreach \i in {w,x,y}
  2031. {
  2032. \foreach \j in {w,x,y}
  2033. {
  2034. \draw (\i) to (\j);
  2035. }
  2036. }
  2037. \draw (z) to (w);
  2038. \draw (z) to (y);
  2039. \draw (t1) to (z);
  2040. \draw (t2) to (t1);
  2041. \end{tikzpicture}
  2042. \]
  2043. We select a maximally saturated node and color it $0$. In this case we
  2044. have a 7-way tie, so we arbitrarily pick $y$. The then mark color $0$
  2045. as no longer available for $w$, $x$, and $z$ because they interfere
  2046. with $y$.
  2047. \[
  2048. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2049. \node (v) at (0,0) {$v:-,\{\}$};
  2050. \node (w) at (3,0) {$w:-,\{0\}$};
  2051. \node (x) at (6,0) {$x:-,\{0\}$};
  2052. \node (y) at (3,-1.5) {$y:0,\{\}$};
  2053. \node (z) at (6,-1.5) {$z:-,\{0\}$};
  2054. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2055. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2056. \draw (v) to (w);
  2057. \foreach \i in {w,x,y}
  2058. {
  2059. \foreach \j in {w,x,y}
  2060. {
  2061. \draw (\i) to (\j);
  2062. }
  2063. }
  2064. \draw (z) to (w);
  2065. \draw (z) to (y);
  2066. \draw (t1) to (z);
  2067. \draw (t2) to (t1);
  2068. \end{tikzpicture}
  2069. \]
  2070. Now we repeat the process, selecting another maximally saturated node.
  2071. This time there is a three-way tie between $w$, $x$, and $z$. We color
  2072. $w$ with $1$.
  2073. \[
  2074. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2075. \node (v) at (0,0) {$v:-,\{1\}$};
  2076. \node (w) at (3,0) {$w:1,\{0\}$};
  2077. \node (x) at (6,0) {$x:-,\{0,1\}$};
  2078. \node (y) at (3,-1.5) {$y:0,\{1\}$};
  2079. \node (z) at (6,-1.5) {$z:-,\{0,1\}$};
  2080. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2081. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2082. \draw (t1) to (z);
  2083. \draw (t2) to (t1);
  2084. \draw (v) to (w);
  2085. \foreach \i in {w,x,y}
  2086. {
  2087. \foreach \j in {w,x,y}
  2088. {
  2089. \draw (\i) to (\j);
  2090. }
  2091. }
  2092. \draw (z) to (w);
  2093. \draw (z) to (y);
  2094. \end{tikzpicture}
  2095. \]
  2096. The most saturated nodes are now $x$ and $z$. We color $x$ with the
  2097. next available color which is $2$.
  2098. \[
  2099. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2100. \node (v) at (0,0) {$v:-,\{1\}$};
  2101. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2102. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2103. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2104. \node (z) at (6,-1.5) {$z:-,\{0,1\}$};
  2105. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2106. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2107. \draw (t1) to (z);
  2108. \draw (t2) to (t1);
  2109. \draw (v) to (w);
  2110. \foreach \i in {w,x,y}
  2111. {
  2112. \foreach \j in {w,x,y}
  2113. {
  2114. \draw (\i) to (\j);
  2115. }
  2116. }
  2117. \draw (z) to (w);
  2118. \draw (z) to (y);
  2119. \end{tikzpicture}
  2120. \]
  2121. Node $z$ is the next most highly saturated, so we color $z$ with $2$.
  2122. \[
  2123. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2124. \node (v) at (0,0) {$v:-,\{1\}$};
  2125. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2126. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2127. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2128. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2129. \node (t1) at (9,0) {$t.1:-,\{2\}$};
  2130. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2131. \draw (t1) to (z);
  2132. \draw (t2) to (t1);
  2133. \draw (v) to (w);
  2134. \foreach \i in {w,x,y}
  2135. {
  2136. \foreach \j in {w,x,y}
  2137. {
  2138. \draw (\i) to (\j);
  2139. }
  2140. }
  2141. \draw (z) to (w);
  2142. \draw (z) to (y);
  2143. \end{tikzpicture}
  2144. \]
  2145. We have a 2-way tie between $v$ and $t.1$. We choose to color $v$ with
  2146. $0$.
  2147. \[
  2148. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2149. \node (v) at (0,0) {$v:0,\{1\}$};
  2150. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2151. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2152. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2153. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2154. \node (t1) at (9,0) {$t.1:-,\{2\}$};
  2155. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2156. \draw (t1) to (z);
  2157. \draw (t2) to (t1);
  2158. \draw (v) to (w);
  2159. \foreach \i in {w,x,y}
  2160. {
  2161. \foreach \j in {w,x,y}
  2162. {
  2163. \draw (\i) to (\j);
  2164. }
  2165. }
  2166. \draw (z) to (w);
  2167. \draw (z) to (y);
  2168. \end{tikzpicture}
  2169. \]
  2170. In the last two steps of the algorithm, we color $t.1$ with $0$
  2171. then $t.2$ with $1$.
  2172. \[
  2173. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2174. \node (v) at (0,0) {$v:0,\{1\}$};
  2175. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2176. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2177. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2178. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2179. \node (t1) at (9,0) {$t.1:0,\{2,1\}$};
  2180. \node (t2) at (9,-1.5) {$t.2:1,\{0\}$};
  2181. \draw (t1) to (z);
  2182. \draw (t2) to (t1);
  2183. \draw (v) to (w);
  2184. \foreach \i in {w,x,y}
  2185. {
  2186. \foreach \j in {w,x,y}
  2187. {
  2188. \draw (\i) to (\j);
  2189. }
  2190. }
  2191. \draw (z) to (w);
  2192. \draw (z) to (y);
  2193. \end{tikzpicture}
  2194. \]
  2195. With the coloring complete, we can finalize the assignment of
  2196. variables to registers and stack locations. Recall that if we have $k$
  2197. registers, we map the first $k$ colors to registers and the rest to
  2198. stack locations. Suppose for the moment that we just have one extra
  2199. register to use for register allocation, just \key{rbx}. Then the
  2200. following is the mapping of colors to registers and stack allocations.
  2201. \[
  2202. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)}, \ldots \}
  2203. \]
  2204. Putting this mapping together with the above coloring of the variables, we
  2205. arrive at the assignment:
  2206. \begin{gather*}
  2207. \{ v \mapsto \key{\%rbx}, \,
  2208. w \mapsto \key{-8(\%rbp)}, \,
  2209. x \mapsto \key{-16(\%rbp)}, \,
  2210. y \mapsto \key{\%rbx}, \,
  2211. z\mapsto \key{-16(\%rbp)}, \\
  2212. t.1\mapsto \key{\%rbx} ,\,
  2213. t.2\mapsto \key{-8(\%rbp)} \}
  2214. \end{gather*}
  2215. Applying this assignment to our running example
  2216. (Figure~\ref{fig:reg-eg}) yields the program on the right.
  2217. % why frame size of 32? -JGS
  2218. \begin{minipage}{0.45\textwidth}
  2219. \begin{lstlisting}
  2220. (program (v w x y z)
  2221. (movq (int 1) (var v))
  2222. (movq (int 46) (var w))
  2223. (movq (var v) (var x))
  2224. (addq (int 7) (var x))
  2225. (movq (var x) (var y))
  2226. (addq (int 4) (var y))
  2227. (movq (var x) (var z))
  2228. (addq (var w) (var z))
  2229. (movq (var y) (var t.1))
  2230. (negq (var t.1))
  2231. (movq (var z) (var t.2))
  2232. (addq (var t.1) (var t.2))
  2233. (movq (var t.2) (reg rax)))
  2234. \end{lstlisting}
  2235. \end{minipage}
  2236. $\Rightarrow$
  2237. \begin{minipage}{0.45\textwidth}
  2238. \begin{lstlisting}
  2239. (program 16
  2240. (movq (int 1) (reg rbx))
  2241. (movq (int 46) (stack -8))
  2242. (movq (reg rbx) (stack -16))
  2243. (addq (int 7) (stack -16))
  2244. (movq (stack -16) (reg rbx))
  2245. (addq (int 4) (reg rbx))
  2246. (movq (stack -16) (stack -16))
  2247. (addq (stack -8) (stack -16))
  2248. (movq (reg rbx) (reg rbx))
  2249. (negq (reg rbx))
  2250. (movq (stack -16) (stack -8))
  2251. (addq (reg rbx) (stack -8))
  2252. (movq (stack -8) (reg rax)))
  2253. \end{lstlisting}
  2254. \end{minipage}
  2255. The resulting program is almost an x86 program. The remaining step
  2256. is to apply the patch instructions pass. In this example, the trivial
  2257. move of \code{-16(\%rbp)} to itself is deleted and the addition of
  2258. \code{-8(\%rbp)} to \key{-16(\%rbp)} is fixed by going through
  2259. \code{rax}. The following shows the portion of the program that
  2260. changed.
  2261. \begin{lstlisting}
  2262. (addq (int 4) (reg rbx))
  2263. (movq (stack -8) (reg rax)
  2264. (addq (reg rax) (stack -16))
  2265. \end{lstlisting}
  2266. An overview of all of the passes involved in register allocation is
  2267. shown in Figure~\ref{fig:reg-alloc-passes}.
  2268. \begin{figure}[p]
  2269. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2270. \node (R1) at (0,2) {\large $R_1$};
  2271. \node (R1-2) at (3,2) {\large $R_1$};
  2272. \node (C0-1) at (3,0) {\large $C_0$};
  2273. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  2274. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  2275. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  2276. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  2277. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  2278. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  2279. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  2280. \path[->,bend left=15] (R1-2) edge [right] node {\ttfamily\footnotesize flatten} (C0-1);
  2281. \path[->,bend right=15] (C0-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  2282. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  2283. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  2284. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  2285. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  2286. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  2287. \end{tikzpicture}
  2288. \caption{Diagram of the passes for compiling $R_1$, including the
  2289. three new passes for register allocation.}
  2290. \label{fig:reg-alloc-passes}
  2291. \end{figure}
  2292. \begin{exercise}\normalfont
  2293. Implement the pass \code{allocate-registers} and test it by creating
  2294. new example programs that exercise all of the register allocation
  2295. algorithm, such as forcing variables to be spilled to the stack.
  2296. I recommend organizing our code by creating a helper function named
  2297. \code{allocate-homes} that takes an interference graph, a list of all
  2298. the variables in the program, and the list of statements. This
  2299. function should return a mapping of variables to their homes
  2300. (registers or stack locations) and the total size needed for the
  2301. stack. By creating this helper function, we will be able to reuse it
  2302. in Chapter~\ref{ch:functions} when we add support for functions.
  2303. Once you have obtained the mapping from \code{allocate-homes}, you can
  2304. use the \code{assign-homes} function from Section~\ref{sec:assign-s0}
  2305. to replace the variables with their homes.
  2306. \end{exercise}
  2307. \section{Print x86 and Conventions for Registers}
  2308. \label{sec:print-x86-reg-alloc}
  2309. Recall the the \code{print-x86} pass generates the prelude and
  2310. conclusion instructions for the \code{main} function. The prelude
  2311. saved the values in \code{rbp} and \code{rsp} and the conclusion
  2312. returned those values to \code{rbp} and \code{rsp}. The reason for
  2313. this is that there are agreed-upon conventions for how different
  2314. functions share the same fixed set of registers. There is a function
  2315. inside the operating system (OS) that calls our \code{main} function,
  2316. and that OS function uses the same registers that we use in
  2317. \code{main}. The convention for x86 is that the caller is responsible
  2318. for freeing up some registers, the \emph{caller save registers}, prior
  2319. to the function call, and the callee is responsible for saving and
  2320. restoring some other registers, the \emph{callee save registers},
  2321. before and after using them. The caller save registers are
  2322. \begin{lstlisting}
  2323. rax rdx rcx rsi rdi r8 r9 r10 r11
  2324. \end{lstlisting}
  2325. while the callee save registers are
  2326. \begin{lstlisting}
  2327. rsp rbp rbx r12 r13 r14 r15
  2328. \end{lstlisting}
  2329. Another way to think about this caller/callee convention is the
  2330. following. The caller should assume that all the caller save registers
  2331. get overwritten with arbitrary values by the callee. On the other
  2332. hand, the caller can safely assume that all the callee save registers
  2333. contain the same values after the call that they did before the call.
  2334. The callee can freely use any of the caller save registers. However,
  2335. if the callee wants to use a callee save register, the callee must
  2336. arrange to put the original value back in the register prior to
  2337. returning to the caller, which is usually accomplished by saving and
  2338. restoring the value from the stack.
  2339. The upshot of these conventions is that the \code{main} function needs
  2340. to save (in the prelude) and restore (in the conclusion) any callee
  2341. save registers that get used during register allocation. The simplest
  2342. approach is to save and restore all the callee save registers. The
  2343. more efficient approach is to keep track of which callee save
  2344. registers were used and only save and restore them. Either way, make
  2345. sure to take this use of stack space into account when you round up
  2346. the size of the frame to make sure it is a multiple of 16 bytes.
  2347. \section{Challenge: Move Biasing$^{*}$}
  2348. \label{sec:move-biasing}
  2349. This section describes an optional enhancement to register allocation
  2350. for those students who are looking for an extra challenge or who have
  2351. a deeper interest in register allocation.
  2352. We return to the running example, but we remove the supposition that
  2353. we only have one register to use. So we have the following mapping of
  2354. color numbers to registers.
  2355. \[
  2356. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx}, \ldots \}
  2357. \]
  2358. Using the same assignment that was produced by register allocator
  2359. described in the last section, we get the following program.
  2360. \begin{minipage}{0.45\textwidth}
  2361. \begin{lstlisting}
  2362. (program (v w x y z)
  2363. (movq (int 1) (var v))
  2364. (movq (int 46) (var w))
  2365. (movq (var v) (var x))
  2366. (addq (int 7) (var x))
  2367. (movq (var x) (var y))
  2368. (addq (int 4) (var y))
  2369. (movq (var x) (var z))
  2370. (addq (var w) (var z))
  2371. (movq (var y) (var t.1))
  2372. (negq (var t.1))
  2373. (movq (var z) (var t.2))
  2374. (addq (var t.1) (var t.2))
  2375. (movq (var t.2) (reg rax)))
  2376. \end{lstlisting}
  2377. \end{minipage}
  2378. $\Rightarrow$
  2379. \begin{minipage}{0.45\textwidth}
  2380. \begin{lstlisting}
  2381. (program 0
  2382. (movq (int 1) (reg rbx))
  2383. (movq (int 46) (reg rcx))
  2384. (movq (reg rbx) (reg rdx))
  2385. (addq (int 7) (reg rdx))
  2386. (movq (reg rdx) (reg rbx))
  2387. (addq (int 4) (reg rbx))
  2388. (movq (reg rdx) (reg rdx))
  2389. (addq (reg rcx) (reg rdx))
  2390. (movq (reg rbx) (reg rbx))
  2391. (negq (reg rbx))
  2392. (movq (reg rdx) (reg rcx))
  2393. (addq (reg rbx) (reg rcx))
  2394. (movq (reg rcx) (reg rax)))
  2395. \end{lstlisting}
  2396. \end{minipage}
  2397. While this allocation is quite good, we could do better. For example,
  2398. the variables \key{v} and \key{x} ended up in different registers, but
  2399. if they had been placed in the same register, then the move from
  2400. \key{v} to \key{x} could be removed.
  2401. We say that two variables $p$ and $q$ are \emph{move related} if they
  2402. participate together in a \key{movq} instruction, that is, \key{movq
  2403. p, q} or \key{movq q, p}. When the register allocator chooses a
  2404. color for a variable, it should prefer a color that has already been
  2405. used for a move-related variable (assuming that they do not
  2406. interfere). Of course, this preference should not override the
  2407. preference for registers over stack locations, but should only be used
  2408. as a tie breaker when choosing between registers or when choosing
  2409. between stack locations.
  2410. We recommend that you represent the move relationships in a graph,
  2411. similar to how we represented interference. The following is the
  2412. \emph{move graph} for our running example.
  2413. \[
  2414. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2415. \node (v) at (0,0) {$v$};
  2416. \node (w) at (3,0) {$w$};
  2417. \node (x) at (6,0) {$x$};
  2418. \node (y) at (3,-1.5) {$y$};
  2419. \node (z) at (6,-1.5) {$z$};
  2420. \node (t1) at (9,0) {$t.1$};
  2421. \node (t2) at (9,-1.5) {$t.2$};
  2422. \draw (t1) to (y);
  2423. \draw (t2) to (z);
  2424. \draw[bend left=20] (v) to (x);
  2425. \draw (x) to (y);
  2426. \draw (x) to (z);
  2427. \end{tikzpicture}
  2428. \]
  2429. Now we replay the graph coloring, pausing to see the coloring of $z$
  2430. and $v$. So we have the following coloring so far and the most
  2431. saturated vertex is $z$.
  2432. \[
  2433. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2434. \node (v) at (0,0) {$v:-,\{1\}$};
  2435. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2436. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2437. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2438. \node (z) at (6,-1.5) {$z:-,\{0,1\}$};
  2439. \node (t1) at (9,0) {$t.1:-,\{\}$};
  2440. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2441. \draw (t1) to (z);
  2442. \draw (t2) to (t1);
  2443. \draw (v) to (w);
  2444. \foreach \i in {w,x,y}
  2445. {
  2446. \foreach \j in {w,x,y}
  2447. {
  2448. \draw (\i) to (\j);
  2449. }
  2450. }
  2451. \draw (z) to (w);
  2452. \draw (z) to (y);
  2453. \end{tikzpicture}
  2454. \]
  2455. Last time we chose to color $z$ with $2$, which so happens to be the
  2456. color of $x$, and $z$ is move related to $x$. This was rather lucky,
  2457. and if the program had been a little different, and say $x$ had been
  2458. already assigned to $3$, then $z$ would still get $2$ and our luck
  2459. would have run out. With move biasing, we use the fact that $z$ and
  2460. $x$ are move related to influence the choice of color for $z$, in this
  2461. case choosing $2$ because that's the color of $x$.
  2462. \[
  2463. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2464. \node (v) at (0,0) {$v:-,\{1\}$};
  2465. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2466. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2467. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2468. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2469. \node (t1) at (9,0) {$t.1:-,\{2\}$};
  2470. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2471. \draw (t1) to (z);
  2472. \draw (t2) to (t1);
  2473. \draw (v) to (w);
  2474. \foreach \i in {w,x,y}
  2475. {
  2476. \foreach \j in {w,x,y}
  2477. {
  2478. \draw (\i) to (\j);
  2479. }
  2480. }
  2481. \draw (z) to (w);
  2482. \draw (z) to (y);
  2483. \end{tikzpicture}
  2484. \]
  2485. Next we consider coloring the variable $v$, and we just need to avoid
  2486. choosing $1$ because of the interference with $w$. Last time we choose
  2487. the color $0$, simply because it was the lowest, but this time we know
  2488. that $v$ is move related to $x$, so we choose the color $2$.
  2489. \[
  2490. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2491. \node (v) at (0,0) {$v:2,\{1\}$};
  2492. \node (w) at (3,0) {$w:1,\{0,2\}$};
  2493. \node (x) at (6,0) {$x:2,\{0,1\}$};
  2494. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2495. \node (z) at (6,-1.5) {$z:2,\{0,1\}$};
  2496. \node (t1) at (9,0) {$t.1:-,\{2\}$};
  2497. \node (t2) at (9,-1.5) {$t.2:-,\{\}$};
  2498. \draw (t1) to (z);
  2499. \draw (t2) to (t1);
  2500. \draw (v) to (w);
  2501. \foreach \i in {w,x,y}
  2502. {
  2503. \foreach \j in {w,x,y}
  2504. {
  2505. \draw (\i) to (\j);
  2506. }
  2507. }
  2508. \draw (z) to (w);
  2509. \draw (z) to (y);
  2510. \end{tikzpicture}
  2511. \]
  2512. We apply this register assignment to the running example, on the left,
  2513. to obtain the code on right.
  2514. \begin{minipage}{0.45\textwidth}
  2515. \begin{lstlisting}
  2516. (program (v w x y z)
  2517. (movq (int 1) (var v))
  2518. (movq (int 46) (var w))
  2519. (movq (var v) (var x))
  2520. (addq (int 7) (var x))
  2521. (movq (var x) (var y))
  2522. (addq (int 4) (var y))
  2523. (movq (var x) (var z))
  2524. (addq (var w) (var z))
  2525. (movq (var y) (var t.1))
  2526. (negq (var t.1))
  2527. (movq (var z) (var t.2))
  2528. (addq (var t.1) (var t.2))
  2529. (movq (var t.2) (reg rax)))
  2530. \end{lstlisting}
  2531. \end{minipage}
  2532. $\Rightarrow$
  2533. \begin{minipage}{0.45\textwidth}
  2534. \begin{lstlisting}
  2535. (program 0
  2536. (movq (int 1) (reg rdx))
  2537. (movq (int 46) (reg rcx))
  2538. (movq (reg rdx) (reg rdx))
  2539. (addq (int 7) (reg rdx))
  2540. (movq (reg rdx) (reg rbx))
  2541. (addq (int 4) (reg rbx))
  2542. (movq (reg rdx) (reg rdx))
  2543. (addq (reg rcx) (reg rdx))
  2544. (movq (reg rbx) (reg rbx))
  2545. (negq (reg rbx))
  2546. (movq (reg rdx) (reg rcx))
  2547. (addq (reg rbx) (reg rcx))
  2548. (movq (reg rcx) (reg rax)))
  2549. \end{lstlisting}
  2550. \end{minipage}
  2551. The \code{patch-instructions} then removes the trivial moves from
  2552. \key{v} to \key{x}, from \key{x} to \key{z}, and from \key{y} to
  2553. \key{t.1}, to obtain the following result.
  2554. \begin{lstlisting}
  2555. (program 0
  2556. (movq (int 1) (reg rdx))
  2557. (movq (int 46) (reg rcx))
  2558. (addq (int 7) (reg rdx))
  2559. (movq (reg rdx) (reg rbx))
  2560. (addq (int 4) (reg rbx))
  2561. (addq (reg rcx) (reg rdx))
  2562. (negq (reg rbx))
  2563. (movq (reg rdx) (reg rcx))
  2564. (addq (reg rbx) (reg rcx))
  2565. (movq (reg rcx) (reg rax)))
  2566. \end{lstlisting}
  2567. \begin{exercise}\normalfont
  2568. Change your implementation of \code{allocate-registers} to take move
  2569. biasing into account. Make sure that your compiler still passes all of
  2570. the previous tests. Create two new tests that include at least one
  2571. opportunity for move biasing and visually inspect the output x86
  2572. programs to make sure that your move biasing is working properly.
  2573. \end{exercise}
  2574. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2575. \chapter{Booleans, Control Flow, and Type Checking}
  2576. \label{ch:bool-types}
  2577. Up until now the input languages have only included a single kind of
  2578. value, the integers. In this Chapter we add a second kind of value,
  2579. the Booleans (true and false), together with some new operations
  2580. (\key{and}, \key{not}, \key{eq?}) and conditional expressions to create
  2581. the $R_2$ language. With the addition of conditional expressions,
  2582. programs can have non-trivial control flow which has an impact on
  2583. several parts of the compiler. Also, because we now have two kinds of
  2584. values, we need to worry about programs that apply an operation to the
  2585. wrong kind of value, such as \code{(not 1)}.
  2586. There are two language design options for such situations. One option
  2587. is to signal an error and the other is to provide a wider
  2588. interpretation of the operation. The Racket language uses a mixture of
  2589. these two options, depending on the operation and on the kind of
  2590. value. For example, the result of \code{(not 1)} in Racket is
  2591. \code{\#f} (that is, false) because Racket treats non-zero integers as
  2592. true. On the other hand, \code{(car 1)} results in a run-time error in
  2593. Racket, which states that \code{car} expects a pair.
  2594. The Typed Racket language makes similar design choices as Racket,
  2595. except much of the error detection happens at compile time instead of
  2596. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  2597. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  2598. reports a compile-time error because the type of the argument is
  2599. expected to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  2600. For the $R_2$ language we choose to be more like Typed Racket in that
  2601. we shall perform type checking during compilation. However, we shall
  2602. take a narrower interpretation of the operations, rejecting
  2603. \code{(not 1)}. Despite this difference in design,
  2604. $R_2$ is literally a subset of Typed Racket. Every $R_2$
  2605. program is a Typed Racket program.
  2606. This chapter is organized as follows. We begin by defining the syntax
  2607. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  2608. then introduce the idea of type checking and build a type checker for
  2609. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  2610. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  2611. Section~\ref{sec:c1}. The remaining sections of this Chapter discuss
  2612. how our compiler passes need to change to accommodate Booleans and
  2613. conditional control flow.
  2614. \section{The $R_2$ Language}
  2615. \label{sec:r2-lang}
  2616. The syntax of the $R_2$ language is defined in
  2617. Figure~\ref{fig:r2-syntax}. It includes all of $R_1$, so we only show
  2618. the new operators and expressions. We add the Boolean literals
  2619. \code{\#t} and \code{\#f} for true and false and the conditional
  2620. expression. The operators are expanded to include the \key{and} and
  2621. \key{not} operations on Booleans and the \key{eq?} operation for
  2622. comparing two integers and for comparing two Booleans.
  2623. \begin{figure}[tp]
  2624. \centering
  2625. \fbox{
  2626. \begin{minipage}{0.96\textwidth}
  2627. \[
  2628. \begin{array}{lcl}
  2629. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  2630. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  2631. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  2632. &\mid& \key{\#t} \mid \key{\#f} \mid
  2633. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp) \\
  2634. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  2635. R_2 &::=& (\key{program} \; \Exp)
  2636. \end{array}
  2637. \]
  2638. \end{minipage}
  2639. }
  2640. \caption{The $R_2$ language, an extension of $R_1$
  2641. (Figure~\ref{fig:r1-syntax}).}
  2642. \label{fig:r2-syntax}
  2643. \end{figure}
  2644. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  2645. the parts that are the same as the interpreter for $R_1$
  2646. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  2647. simply evaluate to themselves. The conditional expression \code{(if
  2648. cnd thn els)} evaluates the Boolean expression \code{cnd} and then
  2649. either evaluates \code{thn} or \code{els} depending on whether
  2650. \code{cnd} produced \code{\#t} or \code{\#f}. The logical operations
  2651. \code{not} and \code{and} behave as you might expect, but note that
  2652. the \code{and} operation is short-circuiting. That is, the second
  2653. expression \code{e2} is not evaluated if \code{e1} evaluates to
  2654. \code{\#f}.
  2655. With the addition of the comparison operations, there are quite a few
  2656. primitive operations and the interpreter code for them is somewhat
  2657. repetitive. In Figure~\ref{fig:interp-R2} we factor out the different
  2658. parts into the \code{interp-op} function and the similar parts into
  2659. the one match clause shown in Figure~\ref{fig:interp-R2}. It is
  2660. important for that match clause to come last because it matches
  2661. \emph{any} compound S-expression. We do not use \code{interp-op} for
  2662. the \code{and} operation because of the short-circuiting behavior in
  2663. the order of evaluation of its arguments.
  2664. \begin{figure}[tbp]
  2665. \begin{lstlisting}
  2666. (define primitives (set '+ '- 'eq? '< '<= '> '>= 'not 'read))
  2667. (define (interp-op op)
  2668. (match op
  2669. ['+ fx+]
  2670. ['- (lambda (n) (fx- 0 n))]
  2671. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  2672. ['read read-fixnum]
  2673. ['eq? (lambda (v1 v2)
  2674. (cond [(or (and (fixnum? v1) (fixnum? v2))
  2675. (and (boolean? v1) (boolean? v2))
  2676. (and (vector? v1) (vector? v2)))
  2677. (eq? v1 v2)]))]
  2678. ['< (lambda (v1 v2)
  2679. (cond [(and (fixnum? v1) (fixnum? v2))
  2680. (< v1 v2)]))]
  2681. ['<= (lambda (v1 v2)
  2682. (cond [(and (fixnum? v1) (fixnum? v2))
  2683. (<= v1 v2)]))]
  2684. ['> (lambda (v1 v2)
  2685. (cond [(and (fixnum? v1) (fixnum? v2))
  2686. (<= v1 v2)]))]
  2687. ['>= (lambda (v1 v2)
  2688. (cond [(and (fixnum? v1) (fixnum? v2))
  2689. (<= v1 v2)]))]
  2690. [else (error 'interp-op "unknown operator")]))
  2691. (define (interp-R2 env e)
  2692. (match e
  2693. ...
  2694. [(? boolean?) e]
  2695. [`(if ,cnd ,thn ,els)
  2696. (match (interp-R2 env cnd)
  2697. [#t (interp-R2 env thn)]
  2698. [#f (interp-R2 env els)])]
  2699. [`(not ,e)
  2700. (match (interp-R2 env e) [#t #f] [#f #t])]
  2701. [`(and ,e1 ,e2)
  2702. (match (interp-R2 env e1)
  2703. [#t (match (interp-R2 env e2) [#t #t] [#f #f])]
  2704. [#f #f])]
  2705. [`(,op ,args ...) #:when (set-member? primitives op)
  2706. (apply (interp-op op) (map (interp-R2 env) args))]
  2707. ))
  2708. \end{lstlisting}
  2709. \caption{Interpreter for the $R_2$ language.}
  2710. \label{fig:interp-R2}
  2711. \end{figure}
  2712. \section{Type Checking $R_2$ Programs}
  2713. \label{sec:type-check-r2}
  2714. It is helpful to think about type checking into two complementary
  2715. ways. A type checker predicts the \emph{type} of value that will be
  2716. produced by each expression in the program. For $R_2$, we have just
  2717. two types, \key{Integer} and \key{Boolean}. So a type checker should
  2718. predict that
  2719. \begin{lstlisting}
  2720. (+ 10 (- (+ 12 20)))
  2721. \end{lstlisting}
  2722. produces an \key{Integer} while
  2723. \begin{lstlisting}
  2724. (and (not #f) #t)
  2725. \end{lstlisting}
  2726. produces a \key{Boolean}.
  2727. As mentioned at the beginning of this chapter, a type checker also
  2728. rejects programs that apply operators to the wrong type of value. Our
  2729. type checker for $R_2$ will signal an error for the following because,
  2730. as we have seen above, the expression \code{(+ 10 ...)} has type
  2731. \key{Integer}, and we shall require an argument of \code{not} to have
  2732. type \key{Boolean}.
  2733. \begin{lstlisting}
  2734. (not (+ 10 (- (+ 12 20))))
  2735. \end{lstlisting}
  2736. The type checker for $R_2$ is best implemented as a structurally
  2737. recursive function over the AST. Figure~\ref{fig:type-check-R2} shows
  2738. many of the clauses for the \code{typecheck-R2} function. Given an
  2739. input expression \code{e}, the type checker either returns the type
  2740. (\key{Integer} or \key{Boolean}) or it signals an error. Of course,
  2741. the type of an integer literal is \code{Integer} and the type of a
  2742. Boolean literal is \code{Boolean}. To handle variables, the type
  2743. checker, like the interpreter, uses an association list. However, in
  2744. this case the association list maps variables to types instead of
  2745. values. Consider the clause for \key{let}. We type check the
  2746. initializing expression to obtain its type \key{T} and then map the
  2747. variable \code{x} to \code{T}. When the type checker encounters the
  2748. use of a variable, it can lookup its type in the association list.
  2749. \begin{figure}[tbp]
  2750. \begin{lstlisting}
  2751. (define (typecheck-R2 env e)
  2752. (match e
  2753. [(? fixnum?) 'Integer]
  2754. [(? boolean?) 'Boolean]
  2755. [(? symbol?) (lookup e env)]
  2756. [`(let ([,x ,e]) ,body)
  2757. (define T (typecheck-R2 env e))
  2758. (define new-env (cons (cons x T) env))
  2759. (typecheck-R2 new-env body)]
  2760. ...
  2761. [`(not ,e)
  2762. (match (typecheck-R2 env e)
  2763. ['Boolean 'Boolean]
  2764. [else (error 'typecheck-R2 "'not' expects a Boolean" e)])]
  2765. ...
  2766. [`(program ,body)
  2767. (let ([ty (typecheck-R2 '() body)])
  2768. `(program (type ,ty) ,body))]
  2769. ))
  2770. \end{lstlisting}
  2771. \caption{Skeleton of a type checker for the $R_2$ language.}
  2772. \label{fig:type-check-R2}
  2773. \end{figure}
  2774. To print the resulting value correctly, the overall type of the
  2775. program must be threaded through the remainder of the passes. We can
  2776. store the type within the \key{program} form as shown in Figure
  2777. \ref{fig:type-check-R2}. The syntax for post-typechecking $R_2$
  2778. programs is below:
  2779. \fbox{
  2780. \begin{minipage}{0.87\textwidth}
  2781. \[
  2782. \begin{array}{lcl}
  2783. R_2 &::=& (\key{program}\;(\key{type}\;\textit{type})\; \Exp)
  2784. \end{array}
  2785. \]
  2786. \end{minipage}
  2787. }
  2788. \begin{exercise}\normalfont
  2789. Complete the implementation of \code{typecheck-R2} and test it on 10
  2790. new example programs in $R_2$ that you choose based on how thoroughly
  2791. they test the type checking algorithm. Half of the example programs
  2792. should have a type error, to make sure that your type checker properly
  2793. rejects them. The other half of the example programs should not have
  2794. type errors. Your testing should check that the result of the type
  2795. checker agrees with the value returned by the interpreter, that is, if
  2796. the type checker returns \key{Integer}, then the interpreter should
  2797. return an integer. Likewise, if the type checker returns
  2798. \key{Boolean}, then the interpreter should return \code{\#t} or
  2799. \code{\#f}. Note that if your type checker does not signal an error
  2800. for a program, then interpreting that program should not encounter an
  2801. error. If it does, there is something wrong with your type checker.
  2802. \end{exercise}
  2803. \section{The $C_1$ Language}
  2804. \label{sec:c1}
  2805. The $R_2$ language adds Booleans and conditional expressions to $R_1$.
  2806. As with $R_1$, we shall compile to a C-like intermediate language, but
  2807. we need to grow that intermediate language to handle the new features
  2808. in $R_2$. Figure~\ref{fig:c1-syntax} shows the new features of $C_1$;
  2809. we add logic and comparison operators to the $\Exp$ non-terminal, the
  2810. literals \key{\#t} and \key{\#f} to the $\Arg$ non-terminal, and we
  2811. add an \key{if} statement. The \key{if} statement of $C_1$ includes an
  2812. \key{eq?} test, which is needed for improving code generation in
  2813. Section~\ref{sec:opt-if}. We do not include \key{and} in $C_1$
  2814. because it is not needed in the translation of the \key{and} of $R_2$.
  2815. \begin{figure}[tp]
  2816. \fbox{
  2817. \begin{minipage}{0.96\textwidth}
  2818. \[
  2819. \begin{array}{lcl}
  2820. \Arg &::=& \gray{\Int \mid \Var} \mid \key{\#t} \mid \key{\#f} \\
  2821. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  2822. \Exp &::= & \gray{\Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)}
  2823. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) \\
  2824. \Stmt &::=& \gray{\ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg}} \\
  2825. &\mid& \IF{(\itm{cmp}\, \Arg\,\Arg)}{\Stmt^{*}}{\Stmt^{*}} \\
  2826. C_1 & ::= & (\key{program}\;(\Var^{*})\;(\key{type}\;\textit{type})\;\Stmt^{+})
  2827. \end{array}
  2828. \]
  2829. \end{minipage}
  2830. }
  2831. \caption{The $C_1$ intermediate language, an extension of $C_0$
  2832. (Figure~\ref{fig:c0-syntax}).}
  2833. \label{fig:c1-syntax}
  2834. \end{figure}
  2835. \section{Flatten Expressions}
  2836. \label{sec:flatten-r2}
  2837. The \code{flatten} pass needs to be expanded to handle the Boolean
  2838. literals \key{\#t} and \key{\#f}, the new logic and comparison
  2839. operations, and \key{if} expressions. We shall start with a simple
  2840. example of translating a \key{if} expression, shown below on the
  2841. left. \\
  2842. \begin{tabular}{lll}
  2843. \begin{minipage}{0.4\textwidth}
  2844. \begin{lstlisting}
  2845. (program (if #f 0 42))
  2846. \end{lstlisting}
  2847. \end{minipage}
  2848. &
  2849. $\Rightarrow$
  2850. &
  2851. \begin{minipage}{0.4\textwidth}
  2852. \begin{lstlisting}
  2853. (program (if.1)
  2854. (if (eq? #t #f)
  2855. ((assign if.1 0))
  2856. ((assign if.1 42)))
  2857. (return if.1))
  2858. \end{lstlisting}
  2859. \end{minipage}
  2860. \end{tabular} \\
  2861. The value of the \key{if} expression is the value of the branch that
  2862. is selected. Recall that in the \code{flatten} pass we need to replace
  2863. arbitrary expressions with $\Arg$'s (variables or literals). In the
  2864. translation above, on the right, we have translated the \key{if}
  2865. expression into a new variable \key{if.1} and we have produced code
  2866. that will assign the appropriate value to \key{if.1}. For $R_1$, the
  2867. \code{flatten} pass returned a list of assignment statements. Here,
  2868. for $R_2$, we return a list of statements that can include both
  2869. \key{if} statements and assignment statements.
  2870. The next example is a bit more involved, showing what happens when
  2871. there are complex expressions (not variables or literals) in the
  2872. condition and branch expressions of an \key{if}, including nested
  2873. \key{if} expressions.
  2874. \begin{tabular}{lll}
  2875. \begin{minipage}{0.4\textwidth}
  2876. \begin{lstlisting}
  2877. (program
  2878. (if (eq? (read) 0)
  2879. 777
  2880. (+ 2 (if (eq? (read) 0)
  2881. 40
  2882. 444))))
  2883. \end{lstlisting}
  2884. \end{minipage}
  2885. &
  2886. $\Rightarrow$
  2887. &
  2888. \begin{minipage}{0.4\textwidth}
  2889. \begin{lstlisting}
  2890. (program (t.1 t.2 if.1 t.3 t.4
  2891. if.2 t.5)
  2892. (assign t.1 (read))
  2893. (assign t.2 (eq? t.1 0))
  2894. (if (eq? #t t.2)
  2895. ((assign if.1 777))
  2896. ((assign t.3 (read))
  2897. (assign t.4 (eq? t.3 0))
  2898. (if (eq? #t t.4)
  2899. ((assign if.2 40))
  2900. ((assign if.2 444)))
  2901. (assign t.5 (+ 2 if.2))
  2902. (assign if.1 t.5)))
  2903. (return if.1))
  2904. \end{lstlisting}
  2905. \end{minipage}
  2906. \end{tabular} \\
  2907. The \code{flatten} clauses for the Boolean literals and the operations
  2908. \key{not} and \key{eq?} are straightforward. However, the
  2909. \code{flatten} clause for \key{and} requires some care to properly
  2910. imitate the order of evaluation of the interpreter for $R_2$
  2911. (Figure~\ref{fig:interp-R2}). We recommend using an \key{if} statement
  2912. in the code you generate for \key{and}.
  2913. The \code{flatten} clause for \key{if} requires some care because the
  2914. condition of the \key{if} can be an arbitrary expression in $R_2$ but
  2915. in $C_1$ the condition must be an equality predicate. We recommend
  2916. flattening the condition into an $\Arg$ and then comparing it with
  2917. \code{\#t}.
  2918. \begin{exercise}\normalfont
  2919. Expand your \code{flatten} pass to handle $R_2$, that is, handle the
  2920. Boolean literals, the new logic and comparison operations, and the
  2921. \key{if} expressions. Create 4 more test cases that expose whether
  2922. your flattening code is correct. Test your \code{flatten} pass by
  2923. running the output programs with \code{interp-C}
  2924. (Appendix~\ref{appendix:interp}).
  2925. \end{exercise}
  2926. \section{XOR, Comparisons, and Control Flow in x86}
  2927. \label{sec:x86-1}
  2928. To implement the new logical operations, the comparison operations,
  2929. and the \key{if} statement, we need to delve further into the x86
  2930. language. Figure~\ref{fig:x86-2} defines the abstract syntax for a
  2931. larger subset of x86 that includes instructions for logical
  2932. operations, comparisons, and jumps.
  2933. In addition to its arithmetic operations, x86 provides bitwise
  2934. operators that perform an operation on every bit of their
  2935. arguments. For example, the \key{xorq} instruction takes two
  2936. arguments, performs a pairwise exclusive-or (XOR) operation on the
  2937. bits of its arguments, and writes the result into its second argument.
  2938. Recall the truth table for XOR:
  2939. \begin{center}
  2940. \begin{tabular}{l|cc}
  2941. & 0 & 1 \\ \hline
  2942. 0 & 0 & 1 \\
  2943. 1 & 1 & 0
  2944. \end{tabular}
  2945. \end{center}
  2946. So $0011 \mathrel{\mathrm{XOR}} 0101 = 0110$.
  2947. \begin{figure}[tp]
  2948. \fbox{
  2949. \begin{minipage}{0.96\textwidth}
  2950. \[
  2951. \begin{array}{lcl}
  2952. \Arg &::=& \gray{\INT{\Int} \mid \REG{\itm{register}}
  2953. \mid (\key{deref}\,\itm{register}\,\Int)} \\
  2954. &\mid& (\key{byte-reg}\; \itm{register}) \\
  2955. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  2956. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  2957. (\key{subq} \; \Arg\; \Arg) \mid
  2958. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  2959. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  2960. (\key{pushq}\;\Arg) \mid
  2961. (\key{popq}\;\Arg) \mid
  2962. (\key{retq})} \\
  2963. &\mid& (\key{xorq} \; \Arg\;\Arg)
  2964. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\;\itm{cc} \; \Arg) \\
  2965. &\mid& (\key{movzbq}\;\Arg\;\Arg)
  2966. \mid (\key{jmp} \; \itm{label})
  2967. \mid (\key{jmp-if}\; \itm{cc} \; \itm{label}) \\
  2968. &\mid& (\key{label} \; \itm{label}) \\
  2969. x86_1 &::= & (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+})
  2970. \end{array}
  2971. \]
  2972. \end{minipage}
  2973. }
  2974. \caption{The x86$_1$ language (extends x86$_0$ of Figure~\ref{fig:x86-ast-a}).}
  2975. \label{fig:x86-1}
  2976. \end{figure}
  2977. The \key{cmpq} instruction is somewhat unusual in that its arguments
  2978. are the two things to be compared and the result (less than, greater
  2979. than, equal, not equal, etc.) is placed in the special EFLAGS
  2980. register. This register cannot be accessed directly but it can be
  2981. queried by a number of instructions, including the \key{set}
  2982. instruction. The \key{set} instruction puts a \key{1} or \key{0} into
  2983. its destination depending on whether the comparison came out according
  2984. to the condition code \itm{cc} ('e' for equal, 'l' for less, 'le' for
  2985. less-or-equal, 'g' for greater, 'ge' for greater-or-equal). The
  2986. \key{set} instruction has an annoying quirk in that its destination
  2987. argument must be single byte register, such as \code{al}, which is
  2988. part of the \code{rax} register. Thankfully, the \key{movzbq}
  2989. instruction can then be used to move from a single byte register to a
  2990. normal 64-bit register.
  2991. The \key{jmp} instruction jumps to the instruction after the indicated
  2992. label. The \key{jmp-if} instruction jumps to the instruction after
  2993. the indicated label depending whether the result in the EFLAGS
  2994. register matches the condition code \itm{cc}, otherwise the
  2995. \key{jmp-if} instruction falls through to the next instruction.
  2996. \section{Select Instructions}
  2997. \label{sec:select-r2}
  2998. The \code{select-instructions} pass needs to lower from $C_1$ to an
  2999. intermediate representation suitable for conducting register
  3000. allocation, i.e., close to x86$_1$.
  3001. We can take the usual approach of encoding Booleans as integers, with
  3002. true as 1 and false as 0.
  3003. \[
  3004. \key{\#t} \Rightarrow \key{1}
  3005. \qquad
  3006. \key{\#f} \Rightarrow \key{0}
  3007. \]
  3008. The \code{not} operation can be implemented in terms of \code{xorq}.
  3009. Can you think of a bit pattern that, when XOR'd with the bit
  3010. representation of 0 produces 1, and when XOR'd with the bit
  3011. representation of 1 produces 0?
  3012. Translating the \code{eq?} operation to x86 is slightly involved due
  3013. to the unusual nature of the \key{cmpq} instruction discussed above.
  3014. We recommend translating an assignment from \code{eq?} into the
  3015. following sequence of three instructions. \\
  3016. \begin{tabular}{lll}
  3017. \begin{minipage}{0.4\textwidth}
  3018. \begin{lstlisting}
  3019. (assign |$\itm{lhs}$| (eq? |$\Arg_1$| |$\Arg_2$|))
  3020. \end{lstlisting}
  3021. \end{minipage}
  3022. &
  3023. $\Rightarrow$
  3024. &
  3025. \begin{minipage}{0.4\textwidth}
  3026. \begin{lstlisting}
  3027. (cmpq |$\Arg_1$| |$\Arg_2$|)
  3028. (set e (byte-reg al))
  3029. (movzbq (byte-reg al) |$\itm{lhs}$|)
  3030. \end{lstlisting}
  3031. \end{minipage}
  3032. \end{tabular} \\
  3033. % The translation of the \code{not} operator is not quite as simple
  3034. % as it seems. Recall that \key{notq} is a bitwise operator, not a boolean
  3035. % one. For example, the following program performs bitwise negation on
  3036. % the integer 1:
  3037. %
  3038. % \begin{tabular}{lll}
  3039. % \begin{minipage}{0.4\textwidth}
  3040. % \begin{lstlisting}
  3041. % (movq (int 1) (reg rax))
  3042. % (notq (reg rax))
  3043. % \end{lstlisting}
  3044. % \end{minipage}
  3045. % \end{tabular}
  3046. %
  3047. % After the program is run, \key{rax} does not contain 0, as you might
  3048. % hope -- it contains the binary value $111\ldots10$, which is the
  3049. % two's complement representation of $-2$. We recommend implementing boolean
  3050. % not by using \key{notq} and then masking the upper bits of the result with
  3051. % the \key{andq} instruction.
  3052. Regarding \key{if} statements, we recommend that you not lower them in
  3053. \code{select-instructions} but instead lower them in
  3054. \code{patch-instructions}. The reason is that for purposes of
  3055. liveness analysis, \key{if} statements are easier to deal with than
  3056. jump instructions.
  3057. \begin{exercise}\normalfont
  3058. Expand your \code{select-instructions} pass to handle the new features
  3059. of the $R_2$ language. Test the pass on all the examples you have
  3060. created and make sure that you have some test programs that use the
  3061. \code{eq?} operator, creating some if necessary. Test the output of
  3062. \code{select-instructions} using the \code{interp-x86} interpreter
  3063. (Appendix~\ref{appendix:interp}).
  3064. \end{exercise}
  3065. \section{Register Allocation}
  3066. \label{sec:register-allocation-r2}
  3067. The changes required for $R_2$ affect the liveness analysis, building
  3068. the interference graph, and assigning homes, but the graph coloring
  3069. algorithm itself should not need to change.
  3070. \subsection{Liveness Analysis}
  3071. \label{sec:liveness-analysis-r2}
  3072. The addition of \key{if} statements brings up an interesting issue in
  3073. liveness analysis. Recall that liveness analysis works backwards
  3074. through the program, for each instruction computing the variables that
  3075. are live before the instruction based on which variables are live
  3076. after the instruction. Now consider the situation for \code{(\key{if}
  3077. (\key{eq?} $e_1$ $e_2$) $\itm{thns}$ $\itm{elss}$)}, where we know the
  3078. $L_{\mathsf{after}}$ set and need to produce the $L_{\mathsf{before}}$
  3079. set. We can recursively perform liveness analysis on the $\itm{thns}$
  3080. and $\itm{elss}$ branches, using $L_{\mathsf{after}}$ as the starting
  3081. point, to obtain $L^{\mathsf{thns}}_{\mathsf{before}}$ and
  3082. $L^{\mathsf{elss}}_{\mathsf{before}}$ respectively. However, we do not
  3083. know, during compilation, which way the branch will go, so we do not
  3084. know whether to use $L^{\mathsf{thns}}_{\mathsf{before}}$ or
  3085. $L^{\mathsf{elss}}_{\mathsf{before}}$ as the $L_{\mathsf{before}}$ for
  3086. the entire \key{if} statement. The solution comes from the observation
  3087. that there is no harm in identifying more variables as live than
  3088. absolutely necessary. Thus, we can take the union of the live
  3089. variables from the two branches to be the live set for the whole
  3090. \key{if}, as shown below. Of course, we also need to include the
  3091. variables that are read in the $\itm{cnd}$ argument.
  3092. \[
  3093. L_{\mathsf{before}} = L^{\mathsf{thns}}_{\mathsf{before}} \cup
  3094. L^{\mathsf{elss}}_{\mathsf{before}} \cup
  3095. \mathit{Vars}(e_1) \cup \mathit{Vars}(e_2)
  3096. \]
  3097. We need the live-after sets for all the instructions in both branches
  3098. of the \key{if} when we build the interference graph, so I recommend
  3099. storing that data in the \key{if} statement AST as follows:
  3100. \begin{lstlisting}
  3101. (if (eq? |$\itm{arg}$| |$\itm{arg}$|) |$\itm{thns}$| |$\itm{thn{-}lives}$| |$\itm{elss}$| |$\itm{els{-}lives}$|)
  3102. \end{lstlisting}
  3103. If you wrote helper functions for computing the variables in an
  3104. argument and the variables read-from ($R$) or written-to ($W$) by an
  3105. instruction, you need to be update them to handle the new kinds of
  3106. arguments and instructions in x86$_1$.
  3107. \subsection{Build Interference}
  3108. \label{sec:build-interference-r2}
  3109. Many of the new instructions, such as the logical operations, can be
  3110. handled in the same way as the arithmetic instructions. Thus, if your
  3111. code was already quite general, it will not need to be changed to
  3112. handle the logical operations. If not, I recommend that you change
  3113. your code to be more general. The \key{movzbq} instruction should be
  3114. handled like the \key{movq} instruction. The \key{if} statement is
  3115. straightforward to handle because we stored the live-after sets for the
  3116. two branches in the AST node as described above. Here we just need to
  3117. recursively process the two branches. The output of this pass can
  3118. discard the live after sets, as they are no longer needed.
  3119. \subsection{Assign Homes}
  3120. \label{sec:assign-homes-r2}
  3121. The \code{assign-homes} function (Section~\ref{sec:assign-s0}) needs
  3122. to be updated to handle the \key{if} statement, simply by recursively
  3123. processing the child nodes. Hopefully your code already handles the
  3124. other new instructions, but if not, you can generalize your code.
  3125. \begin{exercise}\normalfont
  3126. Implement the additions to the \code{register-allocation} pass so that
  3127. it works for $R_2$ and test your compiler using your previously
  3128. created programs on the \code{interp-x86} interpreter
  3129. (Appendix~\ref{appendix:interp}).
  3130. \end{exercise}
  3131. \section{Lower Conditionals (New Pass)}
  3132. \label{sec:lower-conditionals}
  3133. In the \code{select-instructions} pass we decided to procrastinate in
  3134. the lowering of the \key{if} statement (thereby making liveness
  3135. analysis easier). Now we need to make up for that and turn the
  3136. \key{if} statement into the appropriate instruction sequence. The
  3137. following translation gives the general idea. If $e_1$ and $e_2$ are
  3138. equal we need to execute the $\itm{thns}$ branch and otherwise we need
  3139. to execute the $\itm{elss}$ branch. So use \key{cmpq} and do a
  3140. conditional jump to the $\itm{thenlabel}$ (which we can generate with
  3141. \code{gensym}). Otherwise we fall through to the $\itm{elss}$
  3142. branch. At the end of the $\itm{elss}$ branch we need to take care to
  3143. not fall through to the $\itm{thns}$ branch. So we jump to the
  3144. $\itm{endlabel}$ (also generated with \code{gensym}).
  3145. \begin{tabular}{lll}
  3146. \begin{minipage}{0.4\textwidth}
  3147. \begin{lstlisting}
  3148. (if (eq? |$e_1$| |$e_2$|) |$\itm{thns}$| |$\itm{elss}$|)
  3149. \end{lstlisting}
  3150. \end{minipage}
  3151. &
  3152. $\Rightarrow$
  3153. &
  3154. \begin{minipage}{0.4\textwidth}
  3155. \begin{lstlisting}
  3156. (cmpq |$e_1$| |$e_2$|)
  3157. (jmp-if e |$\itm{thenlabel}$|)
  3158. |$\itm{elss}$|
  3159. (jmp |$\itm{endlabel}$|)
  3160. (label |$\itm{thenlabel}$|)
  3161. |$\itm{thns}$|
  3162. (label |$\itm{endlabel}$|)
  3163. \end{lstlisting}
  3164. \end{minipage}
  3165. \end{tabular}
  3166. \begin{exercise}\normalfont
  3167. Implement the \code{lower-conditionals} pass. Test your compiler using
  3168. your previously created programs on the \code{interp-x86} interpreter
  3169. (Appendix~\ref{appendix:interp}).
  3170. \end{exercise}
  3171. \section{Patch Instructions}
  3172. There are no special restrictions on the instructions \key{jmp-if},
  3173. \key{jmp}, and \key{label}, but there is an unusual restriction on
  3174. \key{cmpq}. The second argument is not allowed to be an immediate
  3175. value (such as a literal integer). If you are comparing two
  3176. immediates, you must insert another \key{movq} instruction to put the
  3177. second argument in \key{rax}.
  3178. \begin{exercise}\normalfont
  3179. Update \code{patch-instructions} to handle the new x86 instructions.
  3180. Test your compiler using your previously created programs on the
  3181. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  3182. \end{exercise}
  3183. \section{An Example Translation}
  3184. Figure~\ref{fig:if-example-x86} shows a simple example program in
  3185. $R_2$ translated to x86, showing the results of \code{flatten},
  3186. \code{select-instructions}, and the final x86 assembly.
  3187. \begin{figure}[tbp]
  3188. \begin{tabular}{lll}
  3189. \begin{minipage}{0.5\textwidth}
  3190. \begin{lstlisting}
  3191. (program
  3192. (if (eq? (read) 1) 42 0))
  3193. \end{lstlisting}
  3194. $\Downarrow$
  3195. \begin{lstlisting}
  3196. (program (t.1 t.2 if.1)
  3197. (assign t.1 (read))
  3198. (assign t.2 (eq? t.1 1))
  3199. (if (eq? #t t.2)
  3200. ((assign if.1 42))
  3201. ((assign if.1 0)))
  3202. (return if.1))
  3203. \end{lstlisting}
  3204. $\Downarrow$
  3205. \begin{lstlisting}
  3206. (program (t.1 t.2 if.1)
  3207. (callq read_int)
  3208. (movq (reg rax) (var t.1))
  3209. (cmpq (int 1) (var t.1))
  3210. (set e (byte-reg al))
  3211. (movzbq (byte-reg al) (var t.2))
  3212. (if (eq? (int 1) (var t.2))
  3213. ((movq (int 42) (var if.1)))
  3214. ((movq (int 0) (var if.1))))
  3215. (movq (var if.1) (reg rax)))
  3216. \end{lstlisting}
  3217. \end{minipage}
  3218. &
  3219. $\Rightarrow$
  3220. \begin{minipage}{0.4\textwidth}
  3221. \begin{lstlisting}
  3222. .globl _main
  3223. _main:
  3224. pushq %rbp
  3225. movq %rsp, %rbp
  3226. pushq %r15
  3227. pushq %r14
  3228. pushq %r13
  3229. pushq %r12
  3230. pushq %rbx
  3231. subq $8, %rsp
  3232. callq _read_int
  3233. movq %rax, %rcx
  3234. cmpq $1, %rcx
  3235. sete %al
  3236. movzbq %al, %rcx
  3237. cmpq $1, %rcx
  3238. je then21288
  3239. movq $0, %rbx
  3240. jmp if_end21289
  3241. then21288:
  3242. movq $42, %rbx
  3243. if_end21289:
  3244. movq %rbx, %rax
  3245. movq %rax, %rdi
  3246. callq _print_int
  3247. movq $0, %rax
  3248. addq $8, %rsp
  3249. popq %rbx
  3250. popq %r12
  3251. popq %r13
  3252. popq %r14
  3253. popq %r15
  3254. popq %rbp
  3255. retq
  3256. \end{lstlisting}
  3257. \end{minipage}
  3258. \end{tabular}
  3259. \caption{Example compilation of an \key{if} expression to x86.}
  3260. \label{fig:if-example-x86}
  3261. \end{figure}
  3262. \begin{figure}[p]
  3263. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3264. \node (R1) at (0,2) {\large $R_1$};
  3265. \node (R1-2) at (3,2) {\large $R_1$};
  3266. \node (R1-3) at (6,2) {\large $R_1$};
  3267. \node (C0-1) at (3,0) {\large $C_0$};
  3268. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  3269. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  3270. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}$};
  3271. \node (x86-5) at (12,-2) {\large $\text{x86}$};
  3272. \node (x86-6) at (12,-4) {\large $\text{x86}^{\dagger}$};
  3273. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  3274. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  3275. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize typecheck} (R1-2);
  3276. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize uniquify} (R1-3);
  3277. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize flatten} (C0-1);
  3278. \path[->,bend right=15] (C0-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  3279. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  3280. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  3281. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  3282. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize lower-cond.} (x86-4);
  3283. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-5);
  3284. \path[->,bend right=15] (x86-5) edge [left] node {\ttfamily\footnotesize print-x86} (x86-6);
  3285. \end{tikzpicture}
  3286. \caption{Diagram of the passes for compiling $R_2$, including the
  3287. new type checking pass.}
  3288. \label{fig:R2-passes}
  3289. \end{figure}
  3290. Figure~\ref{fig:R2-passes} gives an overview of all the passes needed
  3291. for the compilation of $R_2$.
  3292. \section{Challenge: Optimizing Conditions$^{*}$}
  3293. \label{sec:opt-if}
  3294. A close inspection of the x86 code generated in
  3295. Figure~\ref{fig:if-example-x86} reveals some redundant computation
  3296. regarding the condition of the \key{if}. We compare \key{rcx} to $1$
  3297. twice using \key{cmpq} as follows.
  3298. \begin{lstlisting}
  3299. cmpq $1, %rcx
  3300. sete %al
  3301. movzbq %al, %rcx
  3302. cmpq $1, %rcx
  3303. je then21288
  3304. \end{lstlisting}
  3305. The reason for this non-optimal code has to do with the \code{flatten}
  3306. pass earlier in this Chapter. We recommended flattening the condition
  3307. to an $\Arg$ and then comparing with \code{\#t}. But if the condition
  3308. is already an \code{eq?} test, then we would like to use that
  3309. directly. In fact, for many of the expressions of Boolean type, we can
  3310. generate more optimized code. For example, if the condition is
  3311. \code{\#t} or \code{\#f}, we do not need to generate an \code{if} at
  3312. all. If the condition is a \code{let}, we can optimize based on the
  3313. form of its body. If the condition is a \code{not}, then we can flip
  3314. the two branches.
  3315. %
  3316. \marginpar{\tiny We could do even better by converting to basic
  3317. blocks.\\ --Jeremy}
  3318. %
  3319. On the other hand, if the condition is a \code{and}
  3320. or another \code{if}, we should flatten them into an $\Arg$ to avoid
  3321. code duplication.
  3322. Figure~\ref{fig:opt-if} shows an example program and the result of
  3323. applying the above suggested optimizations.
  3324. \begin{exercise}\normalfont
  3325. Change the \code{flatten} pass to improve the code that gets
  3326. generated for \code{if} expressions. We recommend writing a helper
  3327. function that recursively traverses the condition of the \code{if}.
  3328. \end{exercise}
  3329. \begin{figure}[tbp]
  3330. \begin{tabular}{lll}
  3331. \begin{minipage}{0.5\textwidth}
  3332. \begin{lstlisting}
  3333. (program
  3334. (if (let ([x 1])
  3335. (not (eq? 2 x)))
  3336. 42
  3337. 777))
  3338. \end{lstlisting}
  3339. $\Downarrow$
  3340. \begin{lstlisting}
  3341. (program (x.1 t.1 if.1)
  3342. (assign x.1 1)
  3343. (assign t.1 (read))
  3344. (if (eq? x.1 t.1)
  3345. ((assign if.1 42))
  3346. ((assign if.1 777)))
  3347. (return if.1))
  3348. \end{lstlisting}
  3349. $\Downarrow$
  3350. \begin{lstlisting}
  3351. (program (x.1 t.1 if.1)
  3352. (movq (int 1) (var x.1))
  3353. (callq read_int)
  3354. (movq (reg rax) (var t.1))
  3355. (if (eq? (var x.1) (var t.1))
  3356. ((movq (int 42) (var if.1)))
  3357. ((movq (int 777) (var if.1))))
  3358. (movq (var if.1) (reg rax)))
  3359. \end{lstlisting}
  3360. \end{minipage}
  3361. &
  3362. $\Rightarrow$
  3363. \begin{minipage}{0.4\textwidth}
  3364. \begin{lstlisting}
  3365. .globl _main
  3366. _main:
  3367. pushq %rbp
  3368. movq %rsp, %rbp
  3369. pushq %r15
  3370. pushq %r14
  3371. pushq %r13
  3372. pushq %r12
  3373. pushq %rbx
  3374. subq $8, %rsp
  3375. movq $1, %rbx
  3376. callq _read_int
  3377. movq %rax, %rcx
  3378. cmpq %rbx, %rcx
  3379. je then21288
  3380. movq $777, %r12
  3381. jmp if_end21289
  3382. then21288:
  3383. movq $42, %r12
  3384. if_end21289:
  3385. movq %r12, %rax
  3386. movq %rax, %rdi
  3387. callq _print_int
  3388. movq $0, %rax
  3389. addq $8, %rsp
  3390. popq %rbx
  3391. popq %r12
  3392. popq %r13
  3393. popq %r14
  3394. popq %r15
  3395. popq %rbp
  3396. retq
  3397. \end{lstlisting}
  3398. \end{minipage}
  3399. \end{tabular}
  3400. \caption{Example program with optimized conditionals.}
  3401. \label{fig:opt-if}
  3402. \end{figure}
  3403. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3404. \chapter{Tuples and Garbage Collection}
  3405. \label{ch:tuples}
  3406. \marginpar{\scriptsize To do: look through Andre's code comments for extra
  3407. things to discuss in this chapter. \\ --Jeremy}
  3408. \marginpar{\scriptsize To do: Flesh out this chapter, e.g., make sure
  3409. all the IR grammars are spelled out! \\ --Jeremy}
  3410. \marginpar{\scriptsize Introduce has-type, but after flatten, remove it,
  3411. but keep type annotations on vector creation and local variables, function
  3412. parameters, etc. \\ --Jeremy}
  3413. In this chapter we study the implementation of mutable tuples (called
  3414. ``vectors'' in Racket). This language feature is the first to require
  3415. use of the ``heap'' because the lifetime of a Racket tuple is
  3416. indefinite, that is, the lifetime of a tuple does not follow a stack
  3417. (FIFO) discipline but they instead live forever from the programmer's
  3418. viewpoint. Of course, from an implementor's viewpoint, it is important
  3419. to recycle the space associated with tuples that will no longer be
  3420. used by the program, which is why we also study \emph{garbage
  3421. collection} techniques in this chapter.
  3422. \section{The $R_3$ Language}
  3423. Figure~\ref{fig:r3-syntax} defines the syntax
  3424. for $R_3$, which includes three new forms for creating a tuple,
  3425. reading an element of a tuple, and writing an element into a
  3426. tuple. The following program shows the usage of tuples in Racket. We
  3427. create a 3-tuple \code{t} and a 1-tuple. The 1-tuple is stored at
  3428. index $2$ of the 3-tuple, showing that tuples are first-class values.
  3429. The element at index $1$ of \code{t} is \code{\#t}, so the ``then''
  3430. branch is taken. The element at index $0$ of \code{t} is $40$, to
  3431. which we add the $2$, the element at index $0$ of the 1-tuple.
  3432. \begin{lstlisting}
  3433. (let ([t (vector 40 #t (vector 2))])
  3434. (if (vector-ref t 1)
  3435. (+ (vector-ref t 0)
  3436. (vector-ref (vector-ref t 2) 0))
  3437. 44))
  3438. \end{lstlisting}
  3439. \marginpar{\tiny to do: propagate the use of 'app' to earlier in the book
  3440. and explain it. \\ --Jeremy}
  3441. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  3442. $R_3$ language and Figure~\ref{fig:typecheck-R3} shows the type
  3443. checker.
  3444. \begin{figure}[tp]
  3445. \centering
  3446. \fbox{
  3447. \begin{minipage}{0.96\textwidth}
  3448. \[
  3449. \begin{array}{lcl}
  3450. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  3451. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}\\
  3452. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  3453. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) } \\
  3454. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  3455. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  3456. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp) }\\
  3457. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} } \\
  3458. &\mid& (\key{vector}\;\Exp^{+}) \mid
  3459. (\key{vector-ref}\;\Exp\;\Int) \\
  3460. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)\\
  3461. &\mid& (\key{void}) \\
  3462. R_3 &::=& (\key{program} \;(\key{type}\;\itm{type})\; \Exp)
  3463. \end{array}
  3464. \]
  3465. \end{minipage}
  3466. }
  3467. \caption{Syntax of the $R_3$ language, an extension of $R_2$
  3468. (Figure~\ref{fig:r2-syntax}).}
  3469. \label{fig:r3-syntax}
  3470. \end{figure}
  3471. \begin{figure}[tbp]
  3472. \begin{lstlisting}
  3473. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  3474. (define (interp-op op)
  3475. (match op
  3476. ...
  3477. ['vector vector]
  3478. ['vector-ref vector-ref]
  3479. ['vector-set! vector-set!]
  3480. [else (error 'interp-op "unknown operator")]))
  3481. (define (interp-R3 env)
  3482. (lambda (e)
  3483. (match e
  3484. ...
  3485. [else (error 'interp-R3 "unrecognized expression")]
  3486. )))
  3487. \end{lstlisting}
  3488. \caption{Definitional interpreter for the $R_3$ language.}
  3489. \label{fig:interp-R3}
  3490. \end{figure}
  3491. \begin{figure}[tbp]
  3492. \begin{lstlisting}
  3493. (define (typecheck-R3 env)
  3494. (lambda (e)
  3495. (match e
  3496. ...
  3497. ['(void) (values '(has-type (void) Void) 'Void)]
  3498. [`(vector ,(app (type-check env) e* t*) ...)
  3499. (let ([t `(Vector ,@t*)])
  3500. (values `(has-type (vector ,@e*) ,t) t))]
  3501. [`(vector-ref ,(app (type-check env) e t) ,i)
  3502. (match t
  3503. [`(Vector ,ts ...)
  3504. (unless (and (exact-nonnegative-integer? i)
  3505. (i . < . (length ts)))
  3506. (error 'type-check "invalid index ~a" i))
  3507. (let ([t (list-ref ts i)])
  3508. (values `(has-type (vector-ref ,e (has-type ,i Integer)) ,t)
  3509. t))]
  3510. [else (error "expected a vector in vector-ref, not" t)])]
  3511. [`(vector-set! ,(app (type-check env) e-vec^ t-vec) ,i
  3512. ,(app (type-check env) e-arg^ t-arg))
  3513. (match t-vec
  3514. [`(Vector ,ts ...)
  3515. (unless (and (exact-nonnegative-integer? i)
  3516. (i . < . (length ts)))
  3517. (error 'type-check "invalid index ~a" i))
  3518. (unless (equal? (list-ref ts i) t-arg)
  3519. (error 'type-check "type mismatch in vector-set! ~a ~a"
  3520. (list-ref ts i) t-arg))
  3521. (values `(has-type (vector-set! ,e-vec^
  3522. (has-type ,i Integer)
  3523. ,e-arg^) Void) 'Void)]
  3524. [else (error 'type-check
  3525. "expected a vector in vector-set!, not ~a" t-vec)])]
  3526. [`(eq? ,(app (type-check env) e1 t1)
  3527. ,(app (type-check env) e2 t2))
  3528. (match* (t1 t2)
  3529. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  3530. (values `(has-type (eq? ,e1 ,e2) Boolean) 'Boolean)]
  3531. [(other wise) ((super type-check env) e)])]
  3532. )))
  3533. \end{lstlisting}
  3534. \caption{Type checker for the $R_3$ language.}
  3535. \label{fig:typecheck-R3}
  3536. \end{figure}
  3537. Tuples are our first encounter with heap-allocated data, which raises
  3538. several interesting issues. First, variable binding performs a
  3539. shallow-copy when dealing with tuples, which means that different
  3540. variables can refer to the same tuple, i.e., the variables can be
  3541. \emph{aliases} for the same thing. Consider the following example in
  3542. which both \code{t1} and \code{t2} refer to the same tuple. Thus, the
  3543. mutation through \code{t2} is visible when referencing the tuple from
  3544. \code{t1} and the result of the program is therefore \code{42}.
  3545. \begin{lstlisting}
  3546. (let ([t1 (vector 3 7)])
  3547. (let ([t2 t1])
  3548. (let ([_ (vector-set! t2 0 42)])
  3549. (vector-ref t1 0))))
  3550. \end{lstlisting}
  3551. The next issue concerns the lifetime of tuples. Of course, they are
  3552. created by the \code{vector} form, but when does their lifetime end?
  3553. Notice that the grammar in Figure~\ref{fig:r3-syntax} does not include
  3554. an operation for deallocating tuples. Furthermore, the lifetime of a
  3555. tuple is not tied to any notion of static scoping. For example, the
  3556. following program returns \code{3} even though the variable \code{t}
  3557. goes out of scope prior to the reference.
  3558. \begin{lstlisting}
  3559. (vector-ref
  3560. (let ([t (vector 3 7)])
  3561. t)
  3562. 0)
  3563. \end{lstlisting}
  3564. From the perspective of programmer-observable behavior, tuples live
  3565. forever. Of course, if they really lived forever, then many programs
  3566. would run out of memory.\footnote{The $R_3$ language does not have
  3567. looping or recursive function, so it is nigh impossible to write a
  3568. program in $R_3$ that will run out of memory. However, we add
  3569. recursive functions in the next Chapter!} A Racket implementation
  3570. must therefore perform automatic garbage collection.
  3571. \section{Garbage Collection}
  3572. \label{sec:GC}
  3573. \marginpar{\tiny Need to add comment somewhere about the goodness
  3574. of copying collection, especially that it doesn't touch
  3575. the garbage, so its time complexity only depends on the
  3576. amount of live data.\\ --Jeremy}
  3577. %
  3578. Here we study a relatively simple algorithm for garbage collection
  3579. that is the basis of state-of-the-art garbage
  3580. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  3581. particular, we describe a two-space copying
  3582. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  3583. perform the
  3584. copy~\citep{Cheney:1970aa}. Figure~\ref{fig:copying-collector} gives a
  3585. coarse-grained depiction of what happens in a two-space collector,
  3586. showing two time steps, prior to garbage collection on the top and
  3587. after garbage collection on the bottom. In a two-space collector, the
  3588. heap is segmented into two parts, the FromSpace and the
  3589. ToSpace. Initially, all allocations go to the FromSpace until there is
  3590. not enough room for the next allocation request. At that point, the
  3591. garbage collector goes to work to make more room.
  3592. A running program has direct access to registers and the procedure
  3593. call stack, and those may contain pointers into the heap. Those
  3594. pointers are called the \emph{root set}. In
  3595. Figure~\ref{fig:copying-collector} there are three pointers in the
  3596. root set, one in a register and two on the stack.
  3597. %
  3598. \marginpar{\tiny We can't actually write a program that produces
  3599. the heap structure in the Figure because there is no recursion. Once we
  3600. have the dynamic type, we will be able to.\\ --Jeremy}
  3601. %
  3602. The goal of the
  3603. garbage collector is to 1) preserve all objects that are reachable
  3604. from the root set via a path of pointers, i.e., the \emph{live}
  3605. objects and 2) reclaim the storage of everything else, i.e., the
  3606. \emph{garbage}. A copying collector accomplished this by copying all
  3607. of the live objects into the ToSpace and then performs a slight of
  3608. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  3609. as the new ToSpace. In the bottom of
  3610. Figure~\ref{fig:copying-collector} you can see the result of the copy.
  3611. All of the live objects have been copied to the ToSpace in a way that
  3612. preserves the pointer relationships. For example, the pointer in the
  3613. register still points to a 2-tuple whose first element is a 3-tuple
  3614. and second element is a 2-tuple.
  3615. \begin{figure}[tbp]
  3616. \centering
  3617. \includegraphics[width=\textwidth]{copy-collect-1} \\[5ex]
  3618. \includegraphics[width=\textwidth]{copy-collect-2}
  3619. \caption{A copying collector in action.}
  3620. \label{fig:copying-collector}
  3621. \end{figure}
  3622. \subsection{Graph Copying via Cheney's Algorithm}
  3623. Let us take a closer look at how the copy works. The allocated objects
  3624. and pointers essentially form a graph and we need to copy the part of
  3625. the graph that is reachable from the root set. To make sure we copy
  3626. all of the reachable nodes, we need an exhaustive traversal algorithm,
  3627. such as depth-first search or breadth-first
  3628. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  3629. take into account the possibility of cycles by marking which objects
  3630. have already been visited, so as to ensure termination of the
  3631. algorithm. These search algorithms also use a data structure such as a
  3632. stack or queue as a to-do list to keep track of the objects that need
  3633. to be visited. Here we shall use breadth-first search and a trick due
  3634. to Cheney~\citep{Cheney:1970aa} for simultaneously representing the
  3635. queue and compacting the objects as they are copied into the ToSpace.
  3636. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  3637. copy progresses. The queue is represented by a chunk of contiguous
  3638. memory at the beginning of the ToSpace, using two pointers to track
  3639. the front and the back of the queue. The algorithm starts by copying
  3640. all objects that are immediately reachable from the root set into the
  3641. ToSpace to form the initial queue. When we copy an object, we mark
  3642. the old object to indicate that it has been visited. (We discuss the
  3643. marking in Section~\ref{sec:data-rep-gc}.) Note that any pointers
  3644. inside the copied objects in the queue still point back to the
  3645. FromSpace. The algorithm then pops the object at the front of the
  3646. queue and copies all the objects that are directly reachable from it
  3647. to the ToSpace, at the back of the queue. The algorithm then updates
  3648. the pointers in the popped object so they point to the newly copied
  3649. objects. So getting back to Figure~\ref{fig:cheney}, in the first step
  3650. we copy the tuple whose second element is $42$ to the back of the
  3651. queue. The other pointer goes to a tuple that has already been copied,
  3652. so we do not need to copy it again, but we do need to update the
  3653. pointer to the new location. This can be accomplished by storing a
  3654. \emph{forwarding} pointer to the new location in the old object, back
  3655. when we initially copied the object into the ToSpace. This completes
  3656. one step of the algorithm. The algorithm continues in this way until
  3657. the front of the queue is empty, that is, until the front catches up
  3658. with the back.
  3659. \begin{figure}[tbp]
  3660. \centering \includegraphics[width=0.9\textwidth]{cheney}
  3661. \caption{Depiction of the ToSpace as the Cheney algorithm copies and
  3662. compacts the live objects.}
  3663. \label{fig:cheney}
  3664. \end{figure}
  3665. \section{Data Representation}
  3666. \label{sec:data-rep-gc}
  3667. The garbage collector places some requirements on the data
  3668. representations used by our compiler. First, the garbage collector
  3669. needs to distinguish between pointers and other kinds of data. There
  3670. are several ways to accomplish this.
  3671. \begin{enumerate}
  3672. \item Attached a tag to each object that says what kind of object it
  3673. is~\citep{Jones:1996aa}.
  3674. \item Store different kinds of objects in different regions of
  3675. memory~\citep{Jr.:1977aa}.
  3676. \item Use type information from the program to either generate
  3677. type-specific code for collecting or to generate tables that can
  3678. guide the
  3679. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  3680. \end{enumerate}
  3681. Dynamically typed languages, such as Lisp, need to tag objects
  3682. anyways, so option 1 is a natural choice for those languages.
  3683. However, $R_3$ is a statically typed language, so it would be
  3684. unfortunate to require tags on every object, especially small and
  3685. pervasive objects like integers and Booleans. Option 3 is the
  3686. best-performing choice for statically typed languages, but comes with
  3687. a relatively high implementation complexity. To keep this chapter to a
  3688. 2-week time budget, we recommend a combination of options 1 and 2,
  3689. with separate strategies used for the stack and the heap.
  3690. Regarding the stack, we recommend using a separate stack for
  3691. pointers~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa} (i.e., a
  3692. ``shadow stack''), which we call a \emph{root stack}. That is, when a
  3693. local variable needs to be spilled and is of type \code{(Vector
  3694. $\Type_1 \ldots \Type_n$)}, then we put it on the root stack
  3695. instead of the normal procedure call stack.
  3696. Figure~\ref{fig:shadow-stack} reproduces the example from
  3697. Figure~\ref{fig:copying-collector} and contrasts it with the data
  3698. layout using a root stack. The root stack contains the two
  3699. pointers from the regular stack and also the pointer in the second
  3700. register. Prior to invoking the garbage collector, we shall push all
  3701. pointers in local variables (resident in registers or spilled to the
  3702. stack) onto the root stack. After the collection, the pointers must
  3703. be popped back into the local variables because the locations of the
  3704. pointed-to objects will have changed.
  3705. \begin{figure}[tbp]
  3706. \centering \includegraphics[width=0.7\textwidth]{root-stack}
  3707. \caption{Maintaining a root stack for pointers to facilitate garbage collection.}
  3708. \label{fig:shadow-stack}
  3709. \end{figure}
  3710. The problem of distinguishing between pointers and other kinds of data
  3711. also arises inside of each tuple. We solve this problem by attaching a
  3712. tag, an extra 64-bits, to each tuple. Figure~\ref{fig:tuple-rep} zooms
  3713. in on the tags for two of the tuples in the example from
  3714. Figure~\ref{fig:copying-collector}. Part of each tag is dedicated to
  3715. specifying which elements of the tuple are pointers, the part labeled
  3716. ``pointer mask''. Within the pointer mask, a 1 bit indicates there is
  3717. a pointer and a 0 bit indicates some other kind of data. The pointer
  3718. mask starts at bit location 7. We have limited tuples to a maximum
  3719. size of 50 elements, so we just need 50 bits for the pointer mask. The
  3720. tag also contains two other pieces of information. The length of the
  3721. tuple (number of elements) is stored in bits location 1 through
  3722. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  3723. to be copied to the FromSpace. If the bit has value 1, then this
  3724. tuple has not yet been copied. If the bit has value 0 then the entire
  3725. tag is in fact a forwarding pointer. (The lower 3 bits of an pointer
  3726. are always zero anyways because our tuples are 8-byte aligned.)
  3727. \begin{figure}[tbp]
  3728. \centering \includegraphics[width=0.8\textwidth]{tuple-rep}
  3729. \caption{Representation for tuples in the heap.}
  3730. \label{fig:tuple-rep}
  3731. \end{figure}
  3732. \section{Implementation of the Garbage Collector}
  3733. \label{sec:organize-gz}
  3734. The implementation of the garbage collector needs to do a lot of
  3735. bit-level data manipulation and we will need to link it with our
  3736. compiler-generated x86 code. Thus, we recommend implementing the
  3737. garbage collector in C~\citep{Kernighan:1988nx} and putting the code
  3738. in the \code{runtime.c} file. Figure~\ref{fig:gc-header} shows the
  3739. interface to the garbage collector. The function \code{initialize}
  3740. should create the FromSpace, ToSpace, and root stack. The
  3741. \code{initialize} function is meant to be called near the beginning of
  3742. \code{main}, before the body of the program executes. The
  3743. \code{initialize} function should put the address of the beginning of
  3744. the FromSpace into the global variable \code{free\_ptr}. The global
  3745. \code{fromspace\_end} should point to the address that is 1-past the
  3746. last element of the FromSpace. (We use half-open intervals to
  3747. represent chunks of memory.) The \code{rootstack\_begin} global
  3748. should point to the first element of the root stack.
  3749. As long as there is room left in the FromSpace, your generated code
  3750. can allocate tuples simply by moving the \code{free\_ptr} forward.
  3751. The amount of room left in FromSpace is the difference between the
  3752. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  3753. function should be called when there is not enough room left in the
  3754. FromSpace for the next allocation. The \code{collect} function takes
  3755. a pointer to the current top of the root stack (one past the last item
  3756. that was pushed) and the number of bytes that need to be
  3757. allocated. The \code{collect} should perform the copying collection
  3758. and leave the heap in a state such that the next allocation will
  3759. succeed.
  3760. \begin{figure}[tbp]
  3761. \begin{lstlisting}
  3762. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  3763. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  3764. int64_t* free_ptr;
  3765. int64_t* fromspace_end;
  3766. int64_t** rootstack_begin;
  3767. \end{lstlisting}
  3768. \caption{Interface to the garbage collector.}
  3769. \label{fig:gc-header}
  3770. \end{figure}
  3771. \section{Compiler Passes}
  3772. \label{sec:code-generation-gc}
  3773. The introduction of garbage collection has a non-trivial impact on our
  3774. compiler passes. We introduce two new compiler passes and make
  3775. non-trivial changes to \code{flatten} and \code{select-instructions}.
  3776. The following program will serve as our running example. It creates
  3777. two tuples, one nested inside the other. Both tuples have length
  3778. one. The example then accesses the element in the inner tuple tuple
  3779. via two vector references.
  3780. % tests/s2_17.rkt
  3781. \begin{lstlisting}
  3782. (vector-ref (vector-ref (vector (vector 42)) 0) 0))
  3783. \end{lstlisting}
  3784. \subsection{Flatten and the $C_2$ intermediate language}
  3785. \begin{figure}[tp]
  3786. \fbox{
  3787. \begin{minipage}{0.96\textwidth}
  3788. \[
  3789. \begin{array}{lcl}
  3790. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }\\
  3791. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  3792. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  3793. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  3794. &\mid& (\key{vector}\, \Arg^{+})
  3795. \mid (\key{vector-ref}\, \Arg\, \Int) \\
  3796. &\mid& (\key{vector-set!}\,\Arg\,\Int\,\Arg) \\
  3797. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg} } \\
  3798. &\mid& \gray{ \IF{(\itm{cmp}\, \Arg\,\Arg)}{\Stmt^{*}}{\Stmt^{*}} } \\
  3799. &\mid& (\key{initialize}\,\itm{int}\,\itm{int}) \\
  3800. &\mid& \IF{(\key{collection-needed?}\,\itm{int})}{\Stmt^{*}}{\Stmt^{*}} \\
  3801. &\mid& (\key{collect} \,\itm{int}) \\
  3802. &\mid& (\key{allocate} \,\itm{int}) \\
  3803. &\mid& (\key{call-live-roots}\,(\Var^{*}) \,\Stmt^{*}) \\
  3804. C_2 & ::= & \gray{ (\key{program}\;(\Var^{*})\;(\key{type}\;\textit{type})\;\Stmt^{+}) }
  3805. \end{array}
  3806. \]
  3807. \end{minipage}
  3808. }
  3809. \caption{The $C_2$ intermediate language, an extension of $C_1$
  3810. (Figure~\ref{fig:c1-syntax}).}
  3811. \label{fig:c2-syntax}
  3812. \end{figure}
  3813. \marginpar{\tiny I don't like the collection-needed form.
  3814. Would it make sense to instead expose the free-ptr here?\\--Jeremy}
  3815. The impact on \code{flatten} is straightforward. We add several $\Exp$
  3816. forms for vectors. The output of \code{flatten} is a program in the
  3817. intermediate language $C_2$, whose syntax is defined in
  3818. Figure~\ref{fig:c2-syntax}. Some of the forms in $C_2$ do not get
  3819. used in \code{flatten}, but get used in upcoming passes. The
  3820. \code{flatten} pass should treat the new forms much like the other
  3821. kinds of expressions. The output on our running example is shown in
  3822. Figure~\ref{fig:flatten-gc}.
  3823. \begin{figure}[tbp]
  3824. \begin{lstlisting}
  3825. (program (t.1 t.2 t.3 t.4) (type Integer)
  3826. (assign t.1 (vector 42))
  3827. (assign t.2 (vector t.1))
  3828. (assign t.3 (vector-ref t.2 0))
  3829. (assign t.4 (vector-ref t.3 0))
  3830. (return t.4))
  3831. \end{lstlisting}
  3832. \caption{Output of \code{flatten} for the running example.}
  3833. \label{fig:flatten-gc}
  3834. \end{figure}
  3835. \subsection{Expose Allocation (New)}
  3836. \label{sec:expose-allocation}
  3837. The pass \code{expose-allocation} lowers the vector creation form into
  3838. a conditional call to the collector followed by the allocation. In
  3839. the following, we show the transformation for the \code{vector} form.
  3840. The $\itm{len}$ is the length of the vector and $\itm{bytes}$ is how
  3841. many total bytes need to be allocated for the vector, which is 8 (for
  3842. the tag) plus $\itm{len}$ times 8.
  3843. \begin{lstlisting}
  3844. (assign |$\itm{lhs}$| (vector |$e_0 \ldots e_{n-1}$|))
  3845. |$\Longrightarrow$|
  3846. (if (collection-needed? |$\itm{bytes}$|)
  3847. ((collect |$\itm{bytes}$|))
  3848. ())
  3849. (assign |$\itm{lhs}$| (allocate |$\itm{len}$|))
  3850. (vector-set! |$\itm{lhs}$| |$0$| |$e_0$|)
  3851. |$\ldots$|
  3852. (vector-set! |$\itm{lhs}$| |$n{-}1$| |$e_{n-1}$|)
  3853. \end{lstlisting}
  3854. The \code{expose-allocation} inserts an \code{initialize} statement at
  3855. the beginning of the program which will instruct the garbage collector
  3856. to set up the FromSpace, ToSpace, and all the global variables. The
  3857. two arguments of \code{initialize} specify the initial allocated space
  3858. for the root stack and for the heap.
  3859. %
  3860. Finally, the \code{expose-allocation} pass
  3861. annotates all of the local variables in the \code{program} form with
  3862. their type.
  3863. Figure~\ref{fig:expose-alloc-output} shows the output of the
  3864. \code{expose-allocation} pass on our running example. We highlight in
  3865. red the parts of the program that were changed by the pass.
  3866. \begin{figure}[tbp]
  3867. \begin{lstlisting}
  3868. (program (~(t.1 . (Vector Integer))
  3869. (t.2 . (Vector (Vector Integer)))
  3870. (t.3 . (Vector Integer))
  3871. (t.4 . Integer)
  3872. (void.1 . Void)
  3873. (void.2 . Void)~) (type Integer)
  3874. ~(initialize 10000 10000)~
  3875. ~(if (collection-needed? 16)
  3876. ((collect 16))
  3877. ())
  3878. (assign t.1 (allocate 1 (Vector Integer)))
  3879. (assign void.1 (vector-set! t.1 0 42))~
  3880. ~(if (collection-needed? 16)
  3881. ((collect 16))
  3882. ())
  3883. (assign t.2 (allocate 1 (Vector (Vector Integer))))
  3884. (assign void.2 (vector-set! t.2 0 t.1))~
  3885. (assign t.3 (vector-ref t.2 0))
  3886. (assign t.4 (vector-ref t.3 0))
  3887. (return t.4))
  3888. \end{lstlisting}
  3889. \caption{Output of the \code{expose-allocation} pass.}
  3890. \label{fig:expose-alloc-output}
  3891. \end{figure}
  3892. \subsection{Uncover Call-Live Roots (New)}
  3893. \label{sec:call-live-roots}
  3894. The goal of this pass is to discover which roots (variables of type
  3895. \code{Vector}) are live during calls to the collector. We recommend
  3896. using an algorithm similar to the liveness analysis used in the
  3897. register allocator. In the next pass we shall copy these roots to and
  3898. from the root stack. We extend $C_2$ again, adding a new statement
  3899. form for recording the live variables that are roots.
  3900. \[
  3901. \begin{array}{lcl}
  3902. \Stmt &::=& \ldots \mid (\key{call-live-roots}\, (\Var^{*}) \, \Stmt^{*})
  3903. \end{array}
  3904. \]
  3905. Figure~\ref{fig:call-live-roots-output} shows the output of
  3906. \code{uncover-call-live-roots} on the running example. The only
  3907. changes to the program are wrapping the two \code{collect} forms with
  3908. the \code{call-live-roots}. For the first \code{collect} there are no
  3909. live roots. For the second \code{collect}, the variable \code{t.1} is
  3910. a root and it is live at that point.
  3911. \begin{figure}[tbp]
  3912. \begin{lstlisting}
  3913. (program (t.1 t.2 t.3 t.4 void.1 void.2) (type Integer)
  3914. (initialize 10000 10000)
  3915. (if (collection-needed? 16)
  3916. (~(call-live-roots () (collect 16))~)
  3917. ())
  3918. (assign t.1 (allocate 1 (Vector Integer)))
  3919. (assign void.1 (vector-set! t.1 0 42))
  3920. (if (collection-needed? 16)
  3921. (~(call-live-roots (t.1) (collect 16))~)
  3922. ())
  3923. (assign t.2 (allocate 1 (Vector (Vector Integer))))
  3924. (assign void.2 (vector-set! t.2 0 t.1))
  3925. (assign t.3 (vector-ref t.2 0))
  3926. (assign t.4 (vector-ref t.3 0))
  3927. (return t.4))
  3928. \end{lstlisting}
  3929. \caption{Output of the \code{uncover-call-live-roots} pass.}
  3930. \label{fig:call-live-roots-output}
  3931. \end{figure}
  3932. \marginpar{\tiny mention that we discard type information
  3933. for the local variables.\\--Jeremy}
  3934. \subsection{Select Instructions}
  3935. \label{sec:select-instructions-gc}
  3936. In this pass we generate the code for explicitly manipulating the root
  3937. stack, lower the forms needed for garbage collection, and also lower
  3938. the \code{vector-ref} and \code{vector-set!} forms. We shall use a
  3939. register, \code{r15}, to store the pointer to the top of the root
  3940. stack. (So \code{r15} is no longer available for use by the register
  3941. allocator.) For readability, we shall refer to this register as the
  3942. \emph{rootstack}.
  3943. %
  3944. We shall obtain the top of the root stack to begin with from the
  3945. global variable \code{rootstack\_begin}.
  3946. The translation of the \code{call-live-roots} introduces the code that
  3947. manipulates the root stack. We push all of the call-live roots onto
  3948. the root stack prior to the call to \code{collect} and we move them
  3949. back afterwards.
  3950. %
  3951. \marginpar{\tiny I would prefer to instead have roots live solely on
  3952. the root stack and in registers, not on the normal stack. Then we
  3953. would only need to push the roots in registers, decreasing memory
  3954. traffic for function calls. (to do: next year)\\ --Jeremy}
  3955. %
  3956. \begin{lstlisting}
  3957. (call-live-roots (|$x_0 \ldots x_{n-1}$|) (collect |$\itm{bytes}$|))
  3958. |$\Longrightarrow$|
  3959. (movq (var |$x_0$|) (deref |$\itm{rootstack}$| |$0$|))
  3960. |$\ldots$|
  3961. (movq (var |$x_{n-1}$|) (deref |$\itm{rootstack}$| |$8(n-1)$|))
  3962. (addq |$n$| (reg |$\itm{rootstack}$|))
  3963. (movq (reg |$\itm{rootstack}$|) (reg rdi))
  3964. (movq (int |$\itm{bytes}$|) (reg rsi))
  3965. (callq collect)
  3966. (subq |$n$| (reg |$\itm{rootstack}$|))
  3967. (movq (deref |$\itm{rootstack}$| |$0$|) (var |$x_0$|))
  3968. |$\ldots$|
  3969. (movq (deref |$\itm{rootstack}$| |$8(n-1)$|) (var |$x_{n-1}$|))
  3970. \end{lstlisting}
  3971. \noindent We simply translate \code{initialize} into a call to the
  3972. function in \code{runtime.c}.
  3973. \begin{lstlisting}
  3974. (initialize |$\itm{rootlen}\;\itm{heaplen}$|)
  3975. |$\Longrightarrow$|
  3976. (movq (int |\itm{rootlen}|) (reg rdi))
  3977. (movq (int |\itm{heaplen}|) (reg rsi))
  3978. (callq initialize)
  3979. (movq (global-value rootstack_begin) (reg |\itm{rootstack}|))
  3980. \end{lstlisting}
  3981. %
  3982. We translate the special \code{collection-needed?} predicate into code
  3983. that compares the \code{free\_ptr} to the \code{fromspace\_end}.
  3984. %
  3985. \begin{lstlisting}
  3986. (if (collection-needed? |$\itm{bytes}$|) |$\itm{thn}$| |$\itm{els}$|)
  3987. |$\Longrightarrow$|
  3988. (movq (global-value free_ptr) (var end-data.1))
  3989. (addq (int |$\itm{bytes}$|) (var end-data.1))
  3990. (if (< (var end-data.1) (global-value fromspace_end))
  3991. |$\itm{thn}'$|
  3992. |$\itm{els}'$|)
  3993. \end{lstlisting}
  3994. The \code{allocate} form translates to operations on the
  3995. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  3996. is the next free address in the FromSpace, so we move it into the
  3997. \itm{lhs} and then move it forward by enough space for the vector
  3998. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  3999. is 8 bytes (64 bits) and we use 8 bytes for the tag. Last but not
  4000. least, we need to initialize the \itm{tag}. Refer to
  4001. Figure~\ref{fig:tuple-rep} to see how the tag is organized. We
  4002. recommend using the Racket operations \code{bitwise-ior} and
  4003. \code{arithmetic-shift} to compute the tag. The \itm{types} in the
  4004. \code{has-type } annotation can be used to determine
  4005. the pointer mask region of the tag. The move of $ \itm{lhs}^\prime $ to
  4006. register \code{r11}, before the move to the offset of \code{r11}
  4007. ensures that if $ \itm{lhs}^\prime $ offsets are only performed with
  4008. register operands.
  4009. \begin{lstlisting}
  4010. (assign |$\itm{lhs}$| (hash-type (allocate |$\itm{len}$|) (Vector |$\itm{types}$|)))
  4011. |$\Longrightarrow$|
  4012. (movq (global-value free_ptr) |$\itm{lhs}'$|)
  4013. (addq (int |$8(\itm{len}+1)$|) (global-value free_ptr))
  4014. (movq |$\itm{lhs}'$| (reg r11))
  4015. (movq (int |$\itm{tag}$|) (deref r11 0))
  4016. \end{lstlisting}
  4017. The \code{vector-ref} and \code{vector-set!} forms translate into
  4018. \code{movq} instructions with the appropriate \key{deref}. (The
  4019. plus one is to get past the tag at the beginning of the tuple
  4020. representation.)
  4021. \begin{lstlisting}
  4022. (assign |$\itm{lhs}$| (vector-ref |$\itm{vec}$| |$n$|))
  4023. |$\Longrightarrow$|
  4024. (movq |$\itm{vec}'$| (reg r11))
  4025. (movq (deref r11 |$8(n+1)$|) |$\itm{lhs}$|)
  4026. (assign |$\itm{lhs}$| (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|))
  4027. |$\Longrightarrow$|
  4028. (movq |$\itm{vec}'$| (reg r11))
  4029. (movq |$\itm{arg}'$| (deref r11 |$8(n+1)$|))
  4030. (movq (int 0) |$\itm{lhs}$|)
  4031. \end{lstlisting}
  4032. The $\itm{vec}'$ and $\itm{arg}'$ are obtained by recursively
  4033. processing $\itm{vec}$ and $\itm{arg}$.
  4034. \begin{figure}[tp]
  4035. \fbox{
  4036. \begin{minipage}{0.96\textwidth}
  4037. \[
  4038. \begin{array}{lcl}
  4039. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\itm{register}}
  4040. \mid (\key{deref}\,\itm{register}\,\Int) } \\
  4041. &\mid& \gray{ (\key{byte-reg}\; \itm{register}) }
  4042. \mid (\key{global-value}\; \itm{name}) \\
  4043. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  4044. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  4045. (\key{subq} \; \Arg\; \Arg) \mid
  4046. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  4047. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  4048. (\key{pushq}\;\Arg) \mid
  4049. (\key{popq}\;\Arg) \mid
  4050. (\key{retq})} \\
  4051. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  4052. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  4053. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  4054. \mid (\key{jmp} \; \itm{label})
  4055. \mid (\key{j}\itm{cc} \; \itm{label})
  4056. \mid (\key{label} \; \itm{label}) } \\
  4057. x86_2 &::= & \gray{ (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+}) }
  4058. \end{array}
  4059. \]
  4060. \end{minipage}
  4061. }
  4062. \caption{The x86$_2$ language (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  4063. \label{fig:x86-2}
  4064. \end{figure}
  4065. The syntax of the $x86_2$ language is defined in
  4066. Figure~\ref{fig:x86-2}. It differs from $x86_1$ just in the addition
  4067. of the form for global variables.
  4068. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  4069. \code{select-instructions} pass on the running example.
  4070. \begin{figure}[tbp]
  4071. \centering
  4072. \begin{minipage}{0.75\textwidth}
  4073. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4074. (program (lt28655 end-data28654 lt28652 end-data28651 tmp28644
  4075. tmp28645 tmp28646 tmp28647 void28649 void28648)
  4076. (type Integer)
  4077. (movq (int 16384) (reg rdi))
  4078. (movq (int 16) (reg rsi))
  4079. (callq initialize)
  4080. (movq (global-value rootstack_begin) (reg r15))
  4081. (movq (global-value free_ptr) (var end-data28651))
  4082. (addq (int 16) (var end-data28651))
  4083. (cmpq (global-value fromspace_end) (var end-data28651))
  4084. (set l (byte-reg al))
  4085. (movzbq (byte-reg al) (var lt28652))
  4086. (if (eq? (int 0) (var lt28652))
  4087. ((movq (reg r15) (reg rdi))
  4088. (movq (int 16) (reg rsi))
  4089. (callq collect))
  4090. ())
  4091. (movq (global-value free_ptr) (var tmp28644))
  4092. (addq (int 16) (global-value free_ptr))
  4093. (movq (var tmp28644) (reg r11))
  4094. (movq (int 3) (deref r11 0))
  4095. (movq (var tmp28644) (reg r11))
  4096. (movq (int 42) (deref r11 8))
  4097. (movq (global-value free_ptr) (var end-data28654))
  4098. (addq (int 16) (var end-data28654))
  4099. (cmpq (global-value fromspace_end) (var end-data28654))
  4100. (set l (byte-reg al))
  4101. (movzbq (byte-reg al) (var lt28655))
  4102. (if (eq? (int 0) (var lt28655))
  4103. ((movq (var tmp28644) (deref r15 0))
  4104. (addq (int 8) (reg r15))
  4105. (movq (reg r15) (reg rdi))
  4106. (movq (int 16) (reg rsi))
  4107. (callq collect)
  4108. (subq (int 8) (reg r15))
  4109. (movq (deref r15 0) (var tmp28644)))
  4110. ())
  4111. (movq (global-value free_ptr) (var tmp28645))
  4112. (addq (int 16) (global-value free_ptr))
  4113. (movq (var tmp28645) (reg r11))
  4114. (movq (int 131) (deref r11 0))
  4115. (movq (var tmp28645) (reg r11))
  4116. (movq (var tmp28644) (deref r11 8))
  4117. (movq (var tmp28645) (reg r11))
  4118. (movq (deref r11 8) (var tmp28646))
  4119. (movq (var tmp28646) (reg r11))
  4120. (movq (deref r11 8) (var tmp28647))
  4121. (movq (var tmp28647) (reg rax)))
  4122. \end{lstlisting}
  4123. \end{minipage}
  4124. \caption{Output of the \code{select-instructions} pass.}
  4125. \label{fig:select-instr-output-gc}
  4126. \end{figure}
  4127. \subsection{Print x86}
  4128. \label{sec:print-x86-gc}
  4129. \marginpar{\scriptsize We need to show the translation to x86 and what
  4130. to do about global-value. \\ --Jeremy}
  4131. \begin{figure}[tbp]
  4132. \begin{minipage}[t]{0.5\textwidth}
  4133. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4134. .globl _main
  4135. _main:
  4136. pushq %rbp
  4137. movq %rsp, %rbp
  4138. pushq %r14
  4139. pushq %r13
  4140. pushq %r12
  4141. pushq %rbx
  4142. subq $0, %rsp
  4143. movq $16384, %rdi
  4144. movq $16, %rsi
  4145. callq _initialize
  4146. movq _rootstack_begin(%rip), %r15
  4147. movq _free_ptr(%rip), %rbx
  4148. addq $16, %rbx
  4149. cmpq _fromspace_end(%rip), %rbx
  4150. setl %al
  4151. movzbq %al, %rbx
  4152. cmpq $0, %rbx
  4153. je then30964
  4154. jmp if_end30965
  4155. then30964:
  4156. movq %r15, %rdi
  4157. movq $16, %rsi
  4158. callq _collect
  4159. if_end30965:
  4160. movq _free_ptr(%rip), %rbx
  4161. addq $16, _free_ptr(%rip)
  4162. movq %rbx, %r11
  4163. movq $3, 0(%r11)
  4164. movq %rbx, %r11
  4165. movq $42, 8(%r11)
  4166. movq _free_ptr(%rip), %rcx
  4167. addq $16, %rcx
  4168. cmpq _fromspace_end(%rip), %rcx
  4169. setl %al
  4170. movzbq %al, %rcx
  4171. cmpq $0, %rcx
  4172. je then30966
  4173. jmp if_end30967
  4174. \end{lstlisting}
  4175. \end{minipage}
  4176. \begin{minipage}[t]{0.45\textwidth}
  4177. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4178. then30966:
  4179. movq %rbx, 0(%r15)
  4180. addq $8, %r15
  4181. movq %r15, %rdi
  4182. movq $16, %rsi
  4183. callq _collect
  4184. subq $8, %r15
  4185. movq 0(%r15), %rbx
  4186. if_end30967:
  4187. movq _free_ptr(%rip), %rcx
  4188. addq $16, _free_ptr(%rip)
  4189. movq %rcx, %r11
  4190. movq $131, 0(%r11)
  4191. movq %rcx, %r11
  4192. movq %rbx, 8(%r11)
  4193. movq %rcx, %r11
  4194. movq 8(%r11), %rbx
  4195. movq %rbx, %r11
  4196. movq 8(%r11), %rbx
  4197. movq %rbx, %rax
  4198. movq %rax, %rdi
  4199. callq _print_int
  4200. movq $0, %rax
  4201. addq $0, %rsp
  4202. popq %rbx
  4203. popq %r12
  4204. popq %r13
  4205. popq %r14
  4206. popq %rbp
  4207. retq
  4208. \end{lstlisting}
  4209. \end{minipage}
  4210. \caption{Output of the \code{print-x86} pass.}
  4211. \label{fig:print-x86-output-gc}
  4212. \end{figure}
  4213. \marginpar{\scriptsize Suggest an implementation strategy
  4214. in which the students first do the code gen and test that
  4215. without GC (just use a big heap), then after that is debugged,
  4216. implement the GC. \\ --Jeremy}
  4217. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4218. \chapter{Functions}
  4219. \label{ch:functions}
  4220. This chapter studies the compilation of functions (aka. procedures) at
  4221. the level of abstraction of the C language. This corresponds to a
  4222. subset of Typed Racket in which only top-level function definitions
  4223. are allowed. This abstraction level is an important stepping stone to
  4224. implementing lexically-scoped functions in the form of \key{lambda}
  4225. abstractions (Chapter~\ref{ch:lambdas}).
  4226. \section{The $R_4$ Language}
  4227. The syntax for function definitions and function application
  4228. (aka. function call) is shown in Figure~\ref{fig:r4-syntax}, where we
  4229. define the $R_4$ language. Programs in $R_4$ start with zero or more
  4230. function definitions. The function names from these definitions are
  4231. in-scope for the entire program, including all other function
  4232. definitions (so the ordering of function definitions does not matter).
  4233. Functions are first-class in the sense that a function pointer is data
  4234. and can be stored in memory or passed as a parameter to another
  4235. function. Thus, we introduce a function type, written
  4236. \begin{lstlisting}
  4237. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  4238. \end{lstlisting}
  4239. for a function whose $n$ parameters have the types $\Type_1$ through
  4240. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  4241. these functions (with respect to Racket functions) is that they are
  4242. not lexically scoped. That is, the only external entities that can be
  4243. referenced from inside a function body are other globally-defined
  4244. functions. The syntax of $R_4$ prevents functions from being nested
  4245. inside each other; they can only be defined at the top level.
  4246. \begin{figure}[tp]
  4247. \centering
  4248. \fbox{
  4249. \begin{minipage}{0.96\textwidth}
  4250. \[
  4251. \begin{array}{lcl}
  4252. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  4253. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} } \mid (\Type^{*} \; \key{->}\; \Type) \\
  4254. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4255. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  4256. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  4257. &\mid& \gray{ \key{\#t} \mid \key{\#f} \mid
  4258. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp)} \\
  4259. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  4260. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  4261. (\key{vector-ref}\;\Exp\;\Int)} \\
  4262. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  4263. &\mid& (\Exp \; \Exp^{*}) \\
  4264. \Def &::=& (\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  4265. R_4 &::=& (\key{program} \; \Def^{*} \; \Exp)
  4266. \end{array}
  4267. \]
  4268. \end{minipage}
  4269. }
  4270. \caption{The $R_4$ language, an extension of $R_3$
  4271. (Figure~\ref{fig:r3-syntax}).}
  4272. \label{fig:r4-syntax}
  4273. \end{figure}
  4274. The program in Figure~\ref{fig:r4-function-example} is a
  4275. representative example of defining and using functions in $R_4$. We
  4276. define a function \code{map-vec} that applies some other function
  4277. \code{f} to both elements of a vector (a 2-tuple) and returns a new
  4278. vector containing the results. We also define a function \code{add1}
  4279. that does what its name suggests. The program then applies
  4280. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  4281. \code{(vector 1 42)}, from which we return the \code{42}.
  4282. \begin{figure}[tbp]
  4283. \begin{lstlisting}
  4284. (program
  4285. (define (map-vec [f : (Integer -> Integer)]
  4286. [v : (Vector Integer Integer)])
  4287. : (Vector Integer Integer)
  4288. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  4289. (define (add1 [x : Integer]) : Integer
  4290. (+ x 1))
  4291. (vector-ref (map-vec add1 (vector 0 41)) 1)
  4292. )
  4293. \end{lstlisting}
  4294. \caption{Example of using functions in $R_4$.}
  4295. \label{fig:r4-function-example}
  4296. \end{figure}
  4297. The definitional interpreter for $R_4$ is in
  4298. Figure~\ref{fig:interp-R4}.
  4299. \begin{figure}[tp]
  4300. \begin{lstlisting}
  4301. (define (interp-R4 env)
  4302. (lambda (e)
  4303. (match e
  4304. ....
  4305. [`(define (,f [,xs : ,ps] ...) : ,rt ,body)
  4306. (cons f `(lambda ,xs ,body))]
  4307. [`(program ,ds ... ,body)
  4308. (let ([top-level (map (interp-R4 '()) ds)])
  4309. ((interp-R4 top-level) body))]
  4310. [`(,fun ,args ...)
  4311. (define arg-vals (map (interp-R4 env) args))
  4312. (define fun-val ((interp-R4 env) fun))
  4313. (match fun-val
  4314. [`(lambda (,xs ...) ,body)
  4315. (define new-env (append (map cons xs arg-vals) env))
  4316. ((interp-R4 new-env) body)]
  4317. [else (error "interp-R4, expected function, not" fun-val)]))]
  4318. [else (error 'interp-R4 "unrecognized expression")]
  4319. )))
  4320. \end{lstlisting}
  4321. \caption{Interpreter for the $R_4$ language.}
  4322. \label{fig:interp-R4}
  4323. \end{figure}
  4324. \section{Functions in x86}
  4325. \label{sec:fun-x86}
  4326. The x86 architecture provides a few features to support the
  4327. implementation of functions. We have already seen that x86 provides
  4328. labels so that one can refer to the location of an instruction, as is
  4329. needed for jump instructions. Labels can also be used to mark the
  4330. beginning of the instructions for a function. Going further, we can
  4331. obtain the address of a label by using the \key{leaq} instruction and
  4332. \key{rip}-relative addressing. For example, the following puts the
  4333. address of the \code{add1} label into the \code{rbx} register.
  4334. \begin{lstlisting}
  4335. leaq add1(%rip), %rbx
  4336. \end{lstlisting}
  4337. In Sections~\ref{sec:x86} and \ref{sec:select-s0} we saw the use of
  4338. the \code{callq} instruction for jumping to a function as specified by
  4339. a label. The use of the instruction changes slightly if the function
  4340. is specified by an address in a register, that is, an \emph{indirect
  4341. function call}. The x86 syntax is to give the register name prefixed
  4342. with an asterisk.
  4343. \begin{lstlisting}
  4344. callq *%rbx
  4345. \end{lstlisting}
  4346. The x86 architecture does not directly support passing arguments to
  4347. functions; instead we use a combination of registers and stack
  4348. locations for passing arguments, following the conventions used by
  4349. \code{gcc} as described by \cite{Matz:2013aa}. Up to six arguments may
  4350. be passed in registers, using the registers \code{rdi}, \code{rsi},
  4351. \code{rdx}, \code{rcx}, \code{r8}, and \code{r9}, in that order. If
  4352. there are more than six arguments, then the rest must be placed on the
  4353. stack, which we call \emph{stack arguments}, which we discuss in later
  4354. paragraphs. The register \code{rax} is for the return value of the
  4355. function.
  4356. Recall from Section~\ref{sec:x86} that the stack is also used for
  4357. local variables and for storing the values of callee-save registers
  4358. (we shall refer to all of these collectively as ``locals''), and that
  4359. at the beginning of a function we move the stack pointer \code{rsp}
  4360. down to make room for them.
  4361. %% We recommend storing the local variables
  4362. %% first and then the callee-save registers, so that the local variables
  4363. %% can be accessed using \code{rbp} the same as before the addition of
  4364. %% functions.
  4365. To make additional room for passing arguments, we shall
  4366. move the stack pointer even further down. We count how many stack
  4367. arguments are needed for each function call that occurs inside the
  4368. body of the function and find their maximum. Adding this number to the
  4369. number of locals gives us how much the \code{rsp} should be moved at
  4370. the beginning of the function. In preparation for a function call, we
  4371. offset from \code{rsp} to set up the stack arguments. We put the first
  4372. stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  4373. so on.
  4374. Upon calling the function, the stack arguments are retrieved by the
  4375. callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  4376. is the location of the first stack argument, \code{24(\%rbp)} is the
  4377. address of the second, and so on. Figure~\ref{fig:call-frames} shows
  4378. the layout of the caller and callee frames. Notice how important it is
  4379. that we correctly compute the maximum number of arguments needed for
  4380. function calls; if that number is too small then the arguments and
  4381. local variables will smash into each other!
  4382. As discussed in Section~\ref{sec:print-x86-reg-alloc}, an x86 function
  4383. is responsible for following conventions regarding the use of
  4384. registers: the caller should assume that all the caller save registers
  4385. get overwritten with arbitrary values by the callee. Thus, the caller
  4386. should either 1) not put values that are live across a call in caller
  4387. save registers, or 2) save and restore values that are live across
  4388. calls. We shall recommend option 1). On the flip side, if the callee
  4389. wants to use a callee save register, the callee must arrange to put
  4390. the original value back in the register prior to returning to the
  4391. caller.
  4392. \begin{figure}[tbp]
  4393. \centering
  4394. \begin{tabular}{r|r|l|l} \hline
  4395. Caller View & Callee View & Contents & Frame \\ \hline
  4396. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  4397. 0(\key{\%rbp}) & & old \key{rbp} \\
  4398. -8(\key{\%rbp}) & & local $1$ \\
  4399. \ldots & & \ldots \\
  4400. $-8k$(\key{\%rbp}) & & local $k$ \\
  4401. & & \\
  4402. $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  4403. & \ldots & \ldots \\
  4404. 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\ \hline
  4405. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  4406. & 0(\key{\%rbp}) & old \key{rbp} \\
  4407. & -8(\key{\%rbp}) & local $1$ \\
  4408. & \ldots & \ldots \\
  4409. & $-8m$(\key{\%rsp}) & local $m$\\ \hline
  4410. \end{tabular}
  4411. \caption{Memory layout of caller and callee frames.}
  4412. \label{fig:call-frames}
  4413. \end{figure}
  4414. \section{The compilation of functions}
  4415. \marginpar{\scriptsize To do: discuss the need to push and
  4416. pop call-live pointers (vectors and functions)
  4417. to the root stack \\ --Jeremy}
  4418. Now that we have a good understanding of functions as they appear in
  4419. $R_4$ and the support for functions in x86, we need to plan the
  4420. changes to our compiler, that is, do we need any new passes and/or do
  4421. we need to change any existing passes? Also, do we need to add new
  4422. kinds of AST nodes to any of the intermediate languages?
  4423. \begin{figure}[tp]
  4424. \centering
  4425. \fbox{
  4426. \begin{minipage}{0.96\textwidth}
  4427. \[
  4428. \begin{array}{lcl}
  4429. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  4430. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} } \mid (\Type^{*} \; \key{->}\; \Type) \\
  4431. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  4432. &\mid& (\key{function-ref}\, \itm{label})
  4433. \mid \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  4434. &\mid& \gray{ \key{\#t} \mid \key{\#f} \mid
  4435. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp)} \\
  4436. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  4437. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  4438. (\key{vector-ref}\;\Exp\;\Int)} \\
  4439. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  4440. &\mid& (\key{app}\, \Exp \; \Exp^{*}) \\
  4441. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  4442. F_1 &::=& (\key{program} \; \Def^{*} \; \Exp)
  4443. \end{array}
  4444. \]
  4445. \end{minipage}
  4446. }
  4447. \caption{The $F_1$ language, an extension of $R_3$
  4448. (Figure~\ref{fig:r3-syntax}).}
  4449. \label{fig:f1-syntax}
  4450. \end{figure}
  4451. To begin with, the syntax of $R_4$ is inconvenient for purposes of
  4452. compilation because it conflates the use of function names and local
  4453. variables and it conflates the application of primitive operations and
  4454. the application of functions. This is a problem because we need to
  4455. compile the use of a function name differently than the use of a local
  4456. variable; we need to use \code{leaq} to move the function name to a
  4457. register. Similarly, the application of a function is going to require
  4458. a complex sequence of instructions, unlike the primitive
  4459. operations. Thus, it is a good idea to create a new pass that changes
  4460. function references from just a symbol $f$ to \code{(function-ref
  4461. $f$)} and that changes function application from \code{($e_0$ $e_1$
  4462. $\ldots$ $e_n$)} to the explicitly tagged AST \code{(app $e_0$ $e_1$
  4463. $\ldots$ $e_n$)}. A good name for this pass is
  4464. \code{reveal-functions} and the output language, $F_1$, is defined in
  4465. Figure~\ref{fig:f1-syntax}. Placing this pass after \code{uniquify} is
  4466. a good idea, because it will make sure that there are no local
  4467. variables and functions that share the same name. On the other hand,
  4468. \code{reveal-functions} needs to come before the \code{flatten} pass
  4469. because \code{flatten} will help us compile \code{function-ref}.
  4470. Figure~\ref{fig:c3-syntax} defines the syntax for $C_3$, the output of
  4471. \key{flatten}.
  4472. \begin{figure}[tp]
  4473. \fbox{
  4474. \begin{minipage}{0.96\textwidth}
  4475. \[
  4476. \begin{array}{lcl}
  4477. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  4478. \mid (\key{function-ref}\,\itm{label})\\
  4479. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4480. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  4481. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  4482. &\mid& \gray{ (\key{vector}\, \Arg^{+})
  4483. \mid (\key{vector-ref}\, \Arg\, \Int) } \\
  4484. &\mid& \gray{ (\key{vector-set!}\,\Arg\,\Int\,\Arg) } \\
  4485. &\mid& (\key{app} \,\Arg\,\Arg^{*}) \\
  4486. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Arg} } \\
  4487. &\mid& \gray{ \IF{(\itm{cmp}\, \Arg\,\Arg)}{\Stmt^{*}}{\Stmt^{*}} } \\
  4488. &\mid& \gray{ (\key{initialize}\,\itm{int}\,\itm{int}) }\\
  4489. &\mid& \gray{ \IF{(\key{collection-needed?}\,\itm{int})}{\Stmt^{*}}{\Stmt^{*}} } \\
  4490. &\mid& \gray{ (\key{collect} \,\itm{int}) }
  4491. \mid \gray{ (\key{allocate} \,\itm{int}) }\\
  4492. &\mid& \gray{ (\key{call-live-roots}\,(\Var^{*}) \,\Stmt^{*}) } \\
  4493. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Stmt^{+}) \\
  4494. C_3 & ::= & (\key{program}\;(\Var^{*})\;(\key{type}\;\textit{type})\;(\key{defines}\,\Def^{*})\;\Stmt^{+})
  4495. \end{array}
  4496. \]
  4497. \end{minipage}
  4498. }
  4499. \caption{The $C_3$ intermediate language, an extension of $C_2$
  4500. (Figure~\ref{fig:c2-syntax}).}
  4501. \label{fig:c3-syntax}
  4502. \end{figure}
  4503. Because each \code{function-ref} needs to eventually become an
  4504. \code{leaq} instruction, it first needs to become an assignment
  4505. statement so there is a left-hand side in which to put the
  4506. result. This can be handled easily in the \code{flatten} pass by
  4507. categorizing \code{function-ref} as a complex expression. Then, in
  4508. the \code{select-instructions} pass, an assignment of
  4509. \code{function-ref} becomes a \code{leaq} instruction as follows: \\
  4510. \begin{tabular}{lll}
  4511. \begin{minipage}{0.45\textwidth}
  4512. \begin{lstlisting}
  4513. (assign |$\itm{lhs}$| (function-ref |$f$|))
  4514. \end{lstlisting}
  4515. \end{minipage}
  4516. &
  4517. $\Rightarrow$
  4518. &
  4519. \begin{minipage}{0.4\textwidth}
  4520. \begin{lstlisting}
  4521. (leaq (function-ref |$f$|) |$\itm{lhs}$|)
  4522. \end{lstlisting}
  4523. \end{minipage}
  4524. \end{tabular} \\
  4525. %
  4526. The output of select instructions is a program in the x86$_3$
  4527. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  4528. \begin{figure}[tp]
  4529. \fbox{
  4530. \begin{minipage}{0.96\textwidth}
  4531. \[
  4532. \begin{array}{lcl}
  4533. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\itm{register}}
  4534. \mid (\key{deref}\,\itm{register}\,\Int) \mid (\key{byte-reg}\; \itm{register}) } \\
  4535. &\mid& \gray{ (\key{global-value}\; \itm{name}) } \\
  4536. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  4537. \Instr &::=& \gray{ (\key{addq} \; \Arg\; \Arg) \mid
  4538. (\key{subq} \; \Arg\; \Arg) \mid
  4539. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) } \\
  4540. &\mid& \gray{ (\key{callq} \; \mathit{label}) \mid
  4541. (\key{pushq}\;\Arg) \mid
  4542. (\key{popq}\;\Arg) \mid
  4543. (\key{retq}) } \\
  4544. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  4545. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  4546. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  4547. \mid (\key{jmp} \; \itm{label})
  4548. \mid (\key{j}\itm{cc} \; \itm{label})
  4549. \mid (\key{label} \; \itm{label}) } \\
  4550. &\mid& (\key{indirect-callq}\;\Arg ) \mid (\key{leaq}\;\Arg\;\Arg)\\
  4551. \Def &::= & (\key{define} \; (\itm{label}) \;\itm{int} \;\itm{info}\; \Stmt^{+})\\
  4552. x86_3 &::= & (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\;
  4553. (\key{defines}\,\Def^{*}) \; \Instr^{+})
  4554. \end{array}
  4555. \]
  4556. \end{minipage}
  4557. }
  4558. \caption{The x86$_3$ language (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  4559. \label{fig:x86-3}
  4560. \end{figure}
  4561. Next we consider compiling function definitions. The \code{flatten}
  4562. pass should handle function definitions a lot like a \code{program}
  4563. node; after all, the \code{program} node represents the \code{main}
  4564. function. So the \code{flatten} pass, in addition to flattening the
  4565. body of the function into a sequence of statements, should record the
  4566. local variables in the $\Var^{*}$ field as shown below.
  4567. \begin{lstlisting}
  4568. (define (|$f$| [|\itm{xs}| : |\itm{ts}|]|$^{*}$|) : |\itm{rt}| (|$\Var^{*}$|) |$\Stmt^{+}$|)
  4569. \end{lstlisting}
  4570. In the \code{select-instructions} pass, we need to encode the
  4571. parameter passing in terms of the conventions discussed in
  4572. Section~\ref{sec:fun-x86}. So depending on the length of the parameter
  4573. list \itm{xs}, some of them may be in registers and some of them may
  4574. be on the stack. I recommend generating \code{movq} instructions to
  4575. move the parameters from their registers and stack locations into the
  4576. variables \itm{xs}, then let register allocation handle the assignment
  4577. of those variables to homes. After this pass, the \itm{xs} can be
  4578. added to the list of local variables. As mentioned in
  4579. Section~\ref{sec:fun-x86}, we need to find out how far to move the
  4580. stack pointer to ensure we have enough space for stack arguments in
  4581. all the calls inside the body of this function. This pass is a good
  4582. place to do this and store the result in the \itm{maxStack} field of
  4583. the output \code{define} shown below.
  4584. \begin{lstlisting}
  4585. (define (|$f$|) |\itm{numParams}| (|$\Var^{*}$| |\itm{maxStack}|) |$\Instr^{+}$|)
  4586. \end{lstlisting}
  4587. Next, consider the compilation of function applications, which have
  4588. the following form at the start of \code{select-instructions}.
  4589. \begin{lstlisting}
  4590. (assign |\itm{lhs}| (app |\itm{fun}| |\itm{args}| |$\ldots$|))
  4591. \end{lstlisting}
  4592. In the mirror image of handling the parameters of function
  4593. definitions, some of the arguments \itm{args} need to be moved to the
  4594. argument passing registers and the rest should be moved to the
  4595. appropriate stack locations, as discussed in
  4596. Section~\ref{sec:fun-x86}. You might want to introduce a new kind of
  4597. AST node for stack arguments, \code{(stack-arg $i$)} where $i$ is the
  4598. index of this argument with respect to the other stack arguments. As
  4599. you're generating this code for parameter passing, take note of how many
  4600. stack arguments are needed for purposes of computing the
  4601. \itm{maxStack} discussed above.
  4602. Once the instructions for parameter passing have been generated, the
  4603. function call itself can be performed with an indirect function call,
  4604. for which I recommend creating the new instruction
  4605. \code{indirect-callq}. Of course, the return value from the function
  4606. is stored in \code{rax}, so it needs to be moved into the \itm{lhs}.
  4607. \begin{lstlisting}
  4608. (indirect-callq |\itm{fun}|)
  4609. (movq (reg rax) |\itm{lhs}|)
  4610. \end{lstlisting}
  4611. The rest of the passes need only minor modifications to handle the new
  4612. kinds of AST nodes: \code{function-ref}, \code{indirect-callq}, and
  4613. \code{leaq}. Inside \code{uncover-live}, when computing the $W$ set
  4614. (written variables) for an \code{indirect-callq} instruction, I
  4615. recommend including all the caller save registers, which will have the
  4616. affect of making sure that no caller save register actually needs to be
  4617. saved. In \code{patch-instructions}, you should deal with the x86
  4618. idiosyncrasy that the destination argument of \code{leaq} must be a
  4619. register.
  4620. For the \code{print-x86} pass, I recommend the following translations:
  4621. \begin{lstlisting}
  4622. (function-ref |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  4623. (indirect-callq |\itm{arg}|) |$\Rightarrow$| callq *|\itm{arg}|
  4624. (stack-arg |$i$|) |$\Rightarrow$| |$i$|(%rsp)
  4625. \end{lstlisting}
  4626. For function definitions, the \code{print-x86} pass should add the
  4627. code for saving and restoring the callee save registers, if you
  4628. haven't already done that.
  4629. \section{An Example Translation}
  4630. Figure~\ref{fig:add-fun} shows an example translation of a simple
  4631. function in $R_4$ to x86. The figure includes the results of the
  4632. \code{flatten} and \code{select-instructions} passes. Can you see any
  4633. obvious ways to improve the translation?
  4634. \begin{figure}[tbp]
  4635. \begin{tabular}{lll}
  4636. \begin{minipage}{0.5\textwidth}
  4637. \begin{lstlisting}
  4638. (program
  4639. (define (add [x : Integer]
  4640. [y : Integer])
  4641. : Integer (+ x y))
  4642. (add 40 2))
  4643. \end{lstlisting}
  4644. $\Downarrow$
  4645. \begin{lstlisting}
  4646. (program (t.1 t.2)
  4647. (defines
  4648. (define (add.1 [x.1 : Integer]
  4649. [y.1 : Integer])
  4650. : Integer (t.3)
  4651. (assign t.3 (+ x.1 y.1))
  4652. (return t.3)))
  4653. (assign t.1 (function-ref add.1))
  4654. (assign t.2 (app t.1 40 2))
  4655. (return t.2))
  4656. \end{lstlisting}
  4657. $\Downarrow$
  4658. \begin{lstlisting}
  4659. (program ((rs.1 t.1 t.2) 0)
  4660. (type Integer)
  4661. (defines
  4662. (define (add28545) 3
  4663. ((rs.2 x.2 y.3 t.4) 0)
  4664. (movq (reg rdi) (var rs.2))
  4665. (movq (reg rsi) (var x.2))
  4666. (movq (reg rdx) (var y.3))
  4667. (movq (var x.2) (var t.4))
  4668. (addq (var y.3) (var t.4))
  4669. (movq (var t.4) (reg rax))))
  4670. (movq (int 16384) (reg rdi))
  4671. (movq (int 16) (reg rsi))
  4672. (callq initialize)
  4673. (movq (global-value rootstack_begin)
  4674. (var rs.1))
  4675. (leaq (function-ref add28545) (var t.1))
  4676. (movq (var rs.1) (reg rdi))
  4677. (movq (int 40) (reg rsi))
  4678. (movq (int 2) (reg rdx))
  4679. (indirect-callq (var t.1))
  4680. (movq (reg rax) (var t.2))
  4681. (movq (var t.2) (reg rax)))
  4682. \end{lstlisting}
  4683. \end{minipage}
  4684. &
  4685. \begin{minipage}{0.4\textwidth}
  4686. $\Downarrow$
  4687. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4688. .globl add28545
  4689. add28545:
  4690. pushq %rbp
  4691. movq %rsp, %rbp
  4692. pushq %r15
  4693. pushq %r14
  4694. pushq %r13
  4695. pushq %r12
  4696. pushq %rbx
  4697. subq $8, %rsp
  4698. movq %rdi, %rbx
  4699. movq %rsi, %rbx
  4700. movq %rdx, %rcx
  4701. addq %rcx, %rbx
  4702. movq %rbx, %rax
  4703. addq $8, %rsp
  4704. popq %rbx
  4705. popq %r12
  4706. popq %r13
  4707. popq %r14
  4708. popq %r15
  4709. popq %rbp
  4710. retq
  4711. .globl _main
  4712. _main:
  4713. pushq %rbp
  4714. movq %rsp, %rbp
  4715. pushq %r15
  4716. pushq %r14
  4717. pushq %r13
  4718. pushq %r12
  4719. pushq %rbx
  4720. subq $8, %rsp
  4721. movq $16384, %rdi
  4722. movq $16, %rsi
  4723. callq _initialize
  4724. movq _rootstack_begin(%rip), %rcx
  4725. leaq add28545(%rip), %rbx
  4726. movq %rcx, %rdi
  4727. movq $40, %rsi
  4728. movq $2, %rdx
  4729. callq *%rbx
  4730. movq %rax, %rbx
  4731. movq %rbx, %rax
  4732. movq %rax, %rdi
  4733. callq _print_int
  4734. movq $0, %rax
  4735. addq $8, %rsp
  4736. popq %rbx
  4737. popq %r12
  4738. popq %r13
  4739. popq %r14
  4740. popq %r15
  4741. popq %rbp
  4742. retq
  4743. \end{lstlisting}
  4744. \end{minipage}
  4745. \end{tabular}
  4746. \caption{Example compilation of a simple function to x86.}
  4747. \label{fig:add-fun}
  4748. \end{figure}
  4749. \begin{exercise}\normalfont
  4750. Expand your compiler to handle $R_4$ as outlined in this section.
  4751. Create 5 new programs that use functions, including examples that pass
  4752. functions and return functions from other functions, and test your
  4753. compiler on these new programs and all of your previously created test
  4754. programs.
  4755. \end{exercise}
  4756. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4757. \chapter{Lexically Scoped Functions}
  4758. \label{ch:lambdas}
  4759. This chapter studies lexically scoped functions as they appear in
  4760. functional languages such as Racket. By lexical scoping we mean that a
  4761. function's body may refer to variables whose binding site is outside
  4762. of the function, in an enclosing scope.
  4763. %
  4764. Consider the example in Figure~\ref{fig:lexical-scoping} featuring an
  4765. anonymous function defined using the \key{lambda} form. The body of
  4766. the \key{lambda}, refers to three variables: \code{x}, \code{y}, and
  4767. \code{z}. The binding sites for \code{x} and \code{y} are outside of
  4768. the \key{lambda}. Variable \code{y} is bound by the enclosing
  4769. \key{let} and \code{x} is a parameter of \code{f}. The \key{lambda} is
  4770. returned from the function \code{f}. Below the definition of \code{f},
  4771. we have two calls to \code{f} with different arguments for \code{x},
  4772. first \code{5} then \code{3}. The functions returned from \code{f} are
  4773. bound to variables \code{g} and \code{h}. Even though these two
  4774. functions were created by the same \code{lambda}, they are really
  4775. different functions because they use different values for
  4776. \code{x}. Finally, we apply \code{g} to \code{11} (producing
  4777. \code{20}) and apply \code{h} to \code{15} (producing \code{22}) so
  4778. the result of this program is \code{42}.
  4779. \begin{figure}[btp]
  4780. \begin{lstlisting}
  4781. (define (f [x : Integer]) : (Integer -> Integer)
  4782. (let ([y 4])
  4783. (lambda: ([z : Integer]) : Integer
  4784. (+ x (+ y z)))))
  4785. (let ([g (f 5)])
  4786. (let ([h (f 3)])
  4787. (+ (g 11) (h 15))))
  4788. \end{lstlisting}
  4789. \caption{Example of a lexically scoped function.}
  4790. \label{fig:lexical-scoping}
  4791. \end{figure}
  4792. \section{The $R_5$ Language}
  4793. The syntax for this language with anonymous functions and lexical
  4794. scoping, $R_5$, is defined in Figure~\ref{fig:r5-syntax}. It adds the
  4795. \key{lambda} form to the grammar for $R_4$, which already has syntax
  4796. for function application. In this chapter we shall descibe how to
  4797. compile $R_5$ back into $R_4$, compiling lexically-scoped functions
  4798. into a combination of functions (as in $R_4$) and tuples (as in
  4799. $R_3$).
  4800. \begin{figure}[tp]
  4801. \centering
  4802. \fbox{
  4803. \begin{minipage}{0.96\textwidth}
  4804. \[
  4805. \begin{array}{lcl}
  4806. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  4807. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}
  4808. \mid (\Type^{*} \; \key{->}\; \Type)} \\
  4809. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  4810. \mid (\key{+} \; \Exp\;\Exp)} \\
  4811. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}
  4812. \mid \key{\#t} \mid \key{\#f} \mid
  4813. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp)} \\
  4814. &\mid& \gray{(\key{eq?}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  4815. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  4816. (\key{vector-ref}\;\Exp\;\Int)} \\
  4817. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  4818. &\mid& \gray{(\Exp \; \Exp^{*})} \\
  4819. &\mid& (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  4820. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  4821. R_5 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  4822. \end{array}
  4823. \]
  4824. \end{minipage}
  4825. }
  4826. \caption{The $R_5$ language, an extension of $R_4$
  4827. (Figure~\ref{fig:r4-syntax}).}
  4828. \label{fig:r5-syntax}
  4829. \end{figure}
  4830. We shall describe how to compile $R_5$ to $R_4$, replacing anonymous
  4831. functions with top-level function definitions. However, our compiler
  4832. must provide special treatment to variable occurences such as \code{x}
  4833. and \code{y} in the body of the \code{lambda} of
  4834. Figure~\ref{fig:lexical-scoping}, for the functions of $R_4$ may not
  4835. refer to variables defined outside the function. To identify such
  4836. variable occurences, we review the standard notion of free variable.
  4837. \begin{definition}
  4838. A variable is \emph{free with respect to an expression} $e$ if the
  4839. variable occurs inside $e$ but does not have an enclosing binding in
  4840. $e$.
  4841. \end{definition}
  4842. For example, the variables \code{x}, \code{y}, and \code{z} are all
  4843. free with respect to the expression \code{(+ x (+ y z))}. On the
  4844. other hand, only \code{x} and \code{y} are free with respect to the
  4845. following expression becuase \code{z} is bound by the \code{lambda}.
  4846. \begin{lstlisting}
  4847. (lambda: ([z : Integer]) : Integer
  4848. (+ x (+ y z)))
  4849. \end{lstlisting}
  4850. Once we have identified the free variables of a \code{lambda}, we need
  4851. to arrange for some way to transport, at runtime, the values of those
  4852. variables from the point where the \code{lambda} was created to the
  4853. point where the \code{lambda} is applied. Referring again to
  4854. Figure~\ref{fig:lexical-scoping}, the binding of \code{x} to \code{5}
  4855. needs to be used in the application of \code{g} to \code{11}, but the
  4856. binding of \code{x} to \code{3} needs to be used in the application of
  4857. \code{h} to \code{15}. The solution is to bundle the values of the
  4858. free variables together with the function pointer for the lambda's
  4859. code into a data structure called a \emph{closure}. Fortunately, we
  4860. already have the appropriate ingredients to make closures,
  4861. Chapter~\ref{ch:tuples} gave us tuples and Chapter~\ref{ch:functions}
  4862. gave us function pointers. The function pointer shall reside at index
  4863. $0$ and the values for free variables will fill in the rest of the
  4864. tuple. Figure~\ref{fig:closures} depicts the two closures created by
  4865. the two calls to \code{f} in Figure~\ref{fig:lexical-scoping}.
  4866. Because the two closures came from the same \key{lambda}, they share
  4867. the same code but differ in the values for free variable \code{x}.
  4868. \begin{figure}[tbp]
  4869. \centering \includegraphics[width=0.6\textwidth]{closures}
  4870. \caption{Example closure representation for the \key{lambda}'s
  4871. in Figure~\ref{fig:lexical-scoping}.}
  4872. \label{fig:closures}
  4873. \end{figure}
  4874. \section{Interpreting $R_5$}
  4875. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  4876. $R_5$. There are several things to worth noting. First, and most
  4877. importantly, the match clause for \key{lambda} saves the current
  4878. environment inside the returned \key{lambda}. Then the clause for
  4879. \key{app} uses the environment from the \key{lambda}, the
  4880. \code{lam-env}, when interpreting the body of the \key{lambda}. Of
  4881. course, the \code{lam-env} environment is extending with the mapping
  4882. parameters to argument values. To enable mutual recursion and allow a
  4883. unified handling of functions created with \key{lambda} and with
  4884. \key{define}, the match clause for \key{program} includes a second
  4885. pass over the top-level functions to set their environments to be the
  4886. top-level environment.
  4887. \begin{figure}[tbp]
  4888. \begin{lstlisting}
  4889. (define (interp-R5 env)
  4890. (lambda (ast)
  4891. (match ast
  4892. ...
  4893. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  4894. `(lambda ,xs ,body ,env)]
  4895. [`(define (,f [,xs : ,ps] ...) : ,rt ,body)
  4896. (mcons f `(lambda ,xs ,body))]
  4897. [`(program ,defs ... ,body)
  4898. (let ([top-level (map (interp-R5 '()) defs)])
  4899. (for/list ([b top-level])
  4900. (set-mcdr! b (match (mcdr b)
  4901. [`(lambda ,xs ,body)
  4902. `(lambda ,xs ,body ,top-level)])))
  4903. ((interp-R5 top-level) body))]
  4904. [`(,fun ,args ...)
  4905. (define arg-vals (map (interp-R5 env) args))
  4906. (define fun-val ((interp-R5 env) fun))
  4907. (match fun-val
  4908. [`(lambda (,xs ...) ,body ,lam-env)
  4909. (define new-env (append (map cons xs arg-vals) lam-env))
  4910. ((interp-R5 new-env) body)]
  4911. [else (error "interp-R5, expected function, not" fun-val)])]
  4912. )))
  4913. \end{lstlisting}
  4914. \caption{Definitional interpreter for $R_5$.}
  4915. \label{fig:interp-R5}
  4916. \end{figure}
  4917. \section{Type Checking $R_5$}
  4918. Figure~\ref{fig:typecheck-R5} shows how to type check the new
  4919. \key{lambda} form. The body of the \key{lambda} is checked in an
  4920. environment that includes the current environment (because it is
  4921. lexically scoped) and also includes the \key{lambda}'s parameters. We
  4922. require the body's type to match the declared return type.
  4923. \begin{figure}[tbp]
  4924. \begin{lstlisting}
  4925. (define (typecheck-R5 env)
  4926. (lambda (e)
  4927. (match e
  4928. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  4929. (define new-env (append (map cons xs Ts) env))
  4930. (define bodyT ((typecheck-R5 new-env) body))
  4931. (cond [(equal? rT bodyT)
  4932. `(,@Ts -> ,rT)]
  4933. [else
  4934. (error "mismatch in return type" bodyT rT)])]
  4935. ...
  4936. )))
  4937. \end{lstlisting}
  4938. \caption{Type checking the \key{lambda}'s in $R_5$.}
  4939. \label{fig:typecheck-R5}
  4940. \end{figure}
  4941. \section{Closure Conversion}
  4942. The compiling of lexically-scoped functions into C-style functions is
  4943. accomplished in the pass \code{convert-to-closures} that comes after
  4944. \code{reveal-functions} and before flatten. This pass needs to treat
  4945. regular function calls differently from applying primitive operators,
  4946. and \code{reveal-functions} differentiates those two cases for us.
  4947. As usual, we shall implement the pass as a recursive function over the
  4948. AST. All of the action is in the clauses for \key{lambda} and
  4949. \key{app} (function application). We transform a \key{lambda}
  4950. expression into an expression that creates a closure, that is, creates
  4951. a vector whose first element is a function pointer and the rest of the
  4952. elements are the free variables of the \key{lambda}. The \itm{name}
  4953. is a unique symbol generated to identify the function.
  4954. \begin{tabular}{lll}
  4955. \begin{minipage}{0.4\textwidth}
  4956. \begin{lstlisting}
  4957. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  4958. \end{lstlisting}
  4959. \end{minipage}
  4960. &
  4961. $\Rightarrow$
  4962. &
  4963. \begin{minipage}{0.4\textwidth}
  4964. \begin{lstlisting}
  4965. (vector |\itm{name}| |\itm{fvs}| ...)
  4966. \end{lstlisting}
  4967. \end{minipage}
  4968. \end{tabular} \\
  4969. %
  4970. In addition to transforming each \key{lambda} into a \key{vector}, we
  4971. must create a top-level function definition for each \key{lambda}, as
  4972. shown below.
  4973. \begin{lstlisting}
  4974. (define (|\itm{name}| [clos : _] |\itm{ps}| ...)
  4975. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  4976. ...
  4977. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  4978. |\itm{body'}|)...))
  4979. \end{lstlisting}
  4980. The \code{clos} parameter refers to the closure whereas $\itm{ps}$ are
  4981. the normal parameters of the \key{lambda}. The sequence of \key{let}
  4982. forms being the free variables to their values obtained from the
  4983. closure.
  4984. We transform function application into code that retreives the
  4985. function pointer from the closure and then calls the function, passing
  4986. in the closure as the first argument. We bind $e'$ to a temporary
  4987. variable to avoid code duplication.
  4988. \begin{tabular}{lll}
  4989. \begin{minipage}{0.3\textwidth}
  4990. \begin{lstlisting}
  4991. (app |$e$| |\itm{es}| ...)
  4992. \end{lstlisting}
  4993. \end{minipage}
  4994. &
  4995. $\Rightarrow$
  4996. &
  4997. \begin{minipage}{0.5\textwidth}
  4998. \begin{lstlisting}
  4999. (let ([|\itm{tmp}| |$e'$|])
  5000. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  5001. \end{lstlisting}
  5002. \end{minipage}
  5003. \end{tabular} \\
  5004. There is also the question of what to do with top-level function
  5005. definitions. To maintain a uniform translation of function
  5006. application, we turn function references into closures.
  5007. \begin{tabular}{lll}
  5008. \begin{minipage}{0.3\textwidth}
  5009. \begin{lstlisting}
  5010. (function-ref |$f$|)
  5011. \end{lstlisting}
  5012. \end{minipage}
  5013. &
  5014. $\Rightarrow$
  5015. &
  5016. \begin{minipage}{0.5\textwidth}
  5017. \begin{lstlisting}
  5018. (vector (function-ref |$f$|))
  5019. \end{lstlisting}
  5020. \end{minipage}
  5021. \end{tabular} \\
  5022. %
  5023. The top-level function definitions need to be updated as well to take
  5024. an extra closure parameter.
  5025. \section{An Example Translation}
  5026. \label{sec:example-lambda}
  5027. Figure~\ref{fig:lexical-functions-example} shows the result of closure
  5028. conversion for the example program demonstrating lexical scoping that
  5029. we discussed at the beginning of this chapter.
  5030. \begin{figure}[h]
  5031. \begin{minipage}{0.8\textwidth}
  5032. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  5033. (program
  5034. (define (f [x : Integer]) : (Integer -> Integer)
  5035. (let ([y 4])
  5036. (lambda: ([z : Integer]) : Integer
  5037. (+ x (+ y z)))))
  5038. (let ([g (f 5)])
  5039. (let ([h (f 3)])
  5040. (+ (g 11) (h 15)))))
  5041. \end{lstlisting}
  5042. $\Downarrow$
  5043. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  5044. (program (type Integer)
  5045. (define (f (x : Integer)) : (Integer -> Integer)
  5046. (let ((y 4))
  5047. (lambda: ((z : Integer)) : Integer
  5048. (+ x (+ y z)))))
  5049. (let ((g (app (function-ref f) 5)))
  5050. (let ((h (app (function-ref f) 3)))
  5051. (+ (app g 11) (app h 15)))))
  5052. \end{lstlisting}
  5053. $\Downarrow$
  5054. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  5055. (program (type Integer)
  5056. (define (f (clos.1 : _) (x : Integer)) : (Integer -> Integer)
  5057. (let ((y 4))
  5058. (vector (function-ref lam.1) x y)))
  5059. (define (lam.1 (clos.2 : _) (z : Integer)) : Integer
  5060. (let ((x (vector-ref clos.2 1)))
  5061. (let ((y (vector-ref clos.2 2)))
  5062. (+ x (+ y z)))))
  5063. (let ((g (let ((t.1 (vector (function-ref f))))
  5064. (app (vector-ref t.1 0) t.1 5))))
  5065. (let ((h (let ((t.2 (vector (function-ref f))))
  5066. (app (vector-ref t.2 0) t.2 3))))
  5067. (+ (let ((t.3 g)) (app (vector-ref t.3 0) t.3 11))
  5068. (let ((t.4 h)) (app (vector-ref t.4 0) t.4 15))))))
  5069. \end{lstlisting}
  5070. \end{minipage}
  5071. \caption{Example showing the result of \code{reveal-functions}
  5072. and \code{convert-to-closures}.}
  5073. \label{fig:lexical-functions-example}
  5074. \end{figure}
  5075. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5076. \chapter{Dynamic Typing}
  5077. \label{ch:type-dynamic}
  5078. In this chapter we discuss the compilation of a dynamically typed
  5079. language, named $R_7$, that is a subset of the Racket language. (In
  5080. the previous chapters we have studied subsets of the \emph{Typed}
  5081. Racket language.) In dynamically typed languages, an expression may
  5082. produce values of differing type. Consider the following example with
  5083. a conditional expression that may return a Boolean or an integer
  5084. depending on the input to the program.
  5085. \begin{lstlisting}
  5086. (not (if (eq? (read) 1) #f 0))
  5087. \end{lstlisting}
  5088. Languages that allow expressions to produce different kinds of values
  5089. are called \emph{polymorphic}, and there are many kinds of
  5090. polymorphism, such as subtype polymorphism~\citep{Cardelli:1985kx} and
  5091. parametric polymorphism (Chapter~\ref{ch:parametric-polymorphism}).
  5092. Another characteristic of dynamically typed languages is that
  5093. primitive operations, such as \code{not}, are often defined to operate
  5094. on many different types of values. In fact, in Racket, the \code{not}
  5095. operator produces a result for any kind of value: given \code{\#f} it
  5096. returns \code{\#t} and given anything else it returns \code{\#f}.
  5097. Furthermore, even when primitive operations restrict their inputs to
  5098. values of a certain type, this restriction is enforced at runtime
  5099. instead of during compilation. For example, the following vector
  5100. reference results in a run-time contract violation.
  5101. \begin{lstlisting}
  5102. (vector-ref (vector 42) #t)
  5103. \end{lstlisting}
  5104. Let us consider how we might compile untyped Racket to x86, thinking
  5105. about the first example above. Our bit-level representation of the
  5106. Boolean \code{\#f} is zero and similarly for the integer \code{0}.
  5107. However, \code{(not \#f)} should produce \code{\#t} whereas \code{(not
  5108. 0)} should produce \code{\#f}. Furthermore, the behavior of
  5109. \code{not}, in general, cannot be determined at compile time, but
  5110. depends on the runtime type of its input, as in the example above that
  5111. depends on the result of \code{(read)}.
  5112. The way around this problem is to include information about a value's
  5113. runtime type in the value itself, so that this information can be
  5114. inspected by operators such as \code{not}. In particular, we shall
  5115. steal the 3 right-most bits from our 64-bit values to encode the
  5116. runtime type. We shall use $000$ to identify integers, $001$ for
  5117. Booleans, $010$ for vectors, $011$ for procedures, and $100$ for the
  5118. void value. We shall refer to these 3 bits as the \emph{tag} and we
  5119. define the following auxilliary function.
  5120. \begin{align*}
  5121. \itm{tagof}(\key{Integer}) &= 000 \\
  5122. \itm{tagof}(\key{Boolean}) &= 001 \\
  5123. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  5124. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  5125. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  5126. \itm{tagof}(\key{Void}) &= 100
  5127. \end{align*}
  5128. (We shall say more about the new \key{Vectorof} type shortly.)
  5129. This stealing of 3 bits comes at some
  5130. price: our integers are reduced to ranging from $-2^{60}$ to
  5131. $2^{60}$. The stealing does not adversely affect vectors and
  5132. procedures because those values are addresses, and our addresses are
  5133. 8-byte aligned so the rightmost 3 bits are unused, they are always
  5134. $000$. Thus, we do not lose information by overwriting the rightmost 3
  5135. bits with the tag and we can simply zero-out the tag to recover the
  5136. original address.
  5137. In some sense, these tagged values are a new kind of value. Indeed,
  5138. we can extend our \emph{typed} language with tagged values by adding a
  5139. new type to classify them, called \key{Any}, and with operations for
  5140. creating and using tagged values, creating the $R_6$ language defined
  5141. in Section~\ref{sec:r6-lang}. Thus, $R_6$ provides the fundamental
  5142. support for polymorphism and runtime types that we need to support
  5143. dynamic typing.
  5144. We shall implement our untyped language $R_7$ by compiling it to
  5145. $R_6$. We define $R_7$ in Section~\ref{sec:r7-lang} and describe the
  5146. compilation of $R_6$ and $R_7$ in the remainder of this chapter.
  5147. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  5148. \label{sec:r6-lang}
  5149. \begin{figure}[tp]
  5150. \centering
  5151. \fbox{
  5152. \begin{minipage}{0.97\textwidth}
  5153. \[
  5154. \begin{array}{lcl}
  5155. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  5156. \mid (\key{Vector}\;\Type^{+}) \mid (\key{Vectorof}\;\Type) \mid \key{Void}} \\
  5157. &\mid& \gray{(\Type^{*} \; \key{->}\; \Type)} \mid \key{Any} \\
  5158. \FType &::=& \key{Integer} \mid \key{Boolean} \mid (\key{Vectorof}\;\key{Any})
  5159. \mid (\key{Any}^{*} \; \key{->}\; \key{Any})\\
  5160. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  5161. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  5162. \mid (\key{+} \; \Exp\;\Exp)} \\
  5163. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  5164. &\mid& \gray{\key{\#t} \mid \key{\#f} \mid
  5165. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp)} \\
  5166. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5167. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5168. (\key{vector-ref}\;\Exp\;\Int)} \\
  5169. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  5170. &\mid& \gray{(\Exp \; \Exp^{*})
  5171. \mid (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5172. & \mid & (\key{inject}\; \Exp \; \FType) \mid (\key{project}\;\Exp\;\FType) \\
  5173. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  5174. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \\
  5175. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5176. R_6 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  5177. \end{array}
  5178. \]
  5179. \end{minipage}
  5180. }
  5181. \caption{The syntax of the $R_6$ language, an extension of $R_5$
  5182. (Figure~\ref{fig:r5-syntax}).}
  5183. \label{fig:r6-syntax}
  5184. \end{figure}
  5185. The syntax of $R_6$ is defined in Figure~\ref{fig:r6-syntax}. The
  5186. $(\key{inject}\; e\; T)$ form converts the value produced by
  5187. expression $e$ of type $T$ into a tagged value. The
  5188. $(\key{project}\;e\;T)$ form converts the tagged value produced by
  5189. expression $e$ into a value of type $T$ or else halts the program if
  5190. the type tag does not match $T$. Note that in both \key{inject} and
  5191. \key{project}, the type $T$ is restricted to the flat types $\FType$,
  5192. which simplifies the implementation and corresponds with what is
  5193. needed for compiling untyped Racket. The type predicates,
  5194. $(\key{boolean?}\,e)$ etc., expect a tagged value and return \key{\#t}
  5195. if the tag corresponds to the predicate, and return \key{\#t}
  5196. otherwise.
  5197. %
  5198. The type checker for $R_6$ is given in Figure~\ref{fig:typecheck-R6}.
  5199. \begin{figure}[tbp]
  5200. \begin{lstlisting}
  5201. (define type-predicates (set 'boolean? 'integer? 'vector? 'procedure?))
  5202. (define (typecheck-R6 env)
  5203. (lambda (e)
  5204. (match e
  5205. [`(inject ,e ,ty)
  5206. (define-values (new-e e-ty) ((typecheck-R6 env) e))
  5207. (cond
  5208. [(equal? e-ty ty)
  5209. (values `(has-type (inject ,new-e ,ty) Any) 'Any)]
  5210. [else
  5211. (error "inject expected ~a to have type ~a" e ty)])]
  5212. [`(project ,e ,ty)
  5213. (define-values (new-e e-ty) ((typecheck-R6 env) e))
  5214. (cond
  5215. [(equal? e-ty 'Any)
  5216. (values `(has-type (project ,new-e ,ty) ,ty) ty)]
  5217. [else
  5218. (error "project expected ~a to have type Any" e)])]
  5219. [`(,pred ,e) #:when (set-member? type-predicates pred)
  5220. (define-values (new-e e-ty) ((typecheck-R6 env) e))
  5221. (cond
  5222. [(equal? e-ty 'Any)
  5223. (values `(has-type (,pred ,new-e) Boolean) 'Boolean)]
  5224. [else
  5225. (error "~a expected arg. of type Any, not ~a" pred e-ty)])]
  5226. ...
  5227. )))
  5228. \end{lstlisting}
  5229. \caption{Type checker for the $R_6$ language.}
  5230. \label{fig:typecheck-R6}
  5231. \end{figure}
  5232. % to do: add rules for vector-ref, etc. for Vectorof
  5233. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  5234. Figure~\ref{fig:interp-R6} shows the definitional interpreter
  5235. for $R_6$.
  5236. \begin{figure}[tbp]
  5237. \begin{lstlisting}
  5238. (define primitives (set 'boolean? ...))
  5239. (define (interp-op op)
  5240. (match op
  5241. ['boolean? (lambda (v)
  5242. (match v
  5243. [`(tagged ,v1 Boolean) #t]
  5244. [else #f]))]
  5245. ...))
  5246. (define (interp-R6 env)
  5247. (lambda (ast)
  5248. (match ast
  5249. [`(inject ,e ,t)
  5250. `(tagged ,((interp-R6 env) e) ,t)]
  5251. [`(project ,e ,t2)
  5252. (define v ((interp-R6 env) e))
  5253. (match v
  5254. [`(tagged ,v1 ,t1)
  5255. (cond [(equal? t1 t2)
  5256. v1]
  5257. [else
  5258. (error "in project, type mismatch" t1 t2)])]
  5259. [else
  5260. (error "in project, expected tagged value" v)])]
  5261. ...)))
  5262. \end{lstlisting}
  5263. \caption{Definitional interpreter for $R_6$.}
  5264. \label{fig:interp-R6}
  5265. \end{figure}
  5266. \section{The $R_7$ Language: Untyped Racket}
  5267. \label{sec:r7-lang}
  5268. \begin{figure}[btp]
  5269. \centering
  5270. \fbox{
  5271. \begin{minipage}{0.97\textwidth}
  5272. \[
  5273. \begin{array}{rcl}
  5274. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  5275. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \\
  5276. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  5277. &\mid& \key{\#t} \mid \key{\#f} \mid
  5278. (\key{and}\;\Exp\;\Exp) \mid (\key{not}\;\Exp) \\
  5279. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  5280. &\mid& (\key{vector}\;\Exp^{+}) \mid
  5281. (\key{vector-ref}\;\Exp\;\Exp) \\
  5282. &\mid& (\key{vector-set!}\;\Exp\;\Exp\;\Exp) \mid (\key{void}) \\
  5283. &\mid& (\Exp \; \Exp^{*}) \mid (\key{lambda}\; (\Var^{*}) \; \Exp) \\
  5284. \Def &::=& (\key{define}\; (\Var \; \Var^{*}) \; \Exp) \\
  5285. R_7 &::=& (\key{program} \; \Def^{*}\; \Exp)
  5286. \end{array}
  5287. \]
  5288. \end{minipage}
  5289. }
  5290. \caption{The syntax of the $R_7$ language.}
  5291. \label{fig:r7-syntax}
  5292. \end{figure}
  5293. Figure~\ref{fig:r7-syntax}
  5294. UNDER CONSTRUCTION
  5295. \section{Compiling $R_6$}
  5296. \label{sec:compile-r6}
  5297. Most of the compiler passes only require obvious changes. The
  5298. interesting part is in instruction selection.
  5299. \paragraph{Inject}
  5300. We recommend compiling an \key{inject} as follows if the type is
  5301. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  5302. destination to the left by the number of bits specified by the source
  5303. ($2$) and it preserves the sign of the integer. We use the \key{orq}
  5304. instruction to combine the tag and the value to form the tagged value.
  5305. \\
  5306. \begin{tabular}{lll}
  5307. \begin{minipage}{0.4\textwidth}
  5308. \begin{lstlisting}
  5309. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  5310. \end{lstlisting}
  5311. \end{minipage}
  5312. &
  5313. $\Rightarrow$
  5314. &
  5315. \begin{minipage}{0.5\textwidth}
  5316. \begin{lstlisting}
  5317. (movq |$e'$| |\itm{lhs}'|)
  5318. (salq (int 2) |\itm{lhs}'|)
  5319. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  5320. \end{lstlisting}
  5321. \end{minipage}
  5322. \end{tabular} \\
  5323. The instruction selection for vectors and procedures is different
  5324. because their is no need to shift them to the left. The rightmost 3
  5325. bits are already zeros as described above. So we combine the value and
  5326. the tag using
  5327. \key{orq}. \\
  5328. \begin{tabular}{lll}
  5329. \begin{minipage}{0.4\textwidth}
  5330. \begin{lstlisting}
  5331. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  5332. \end{lstlisting}
  5333. \end{minipage}
  5334. &
  5335. $\Rightarrow$
  5336. &
  5337. \begin{minipage}{0.5\textwidth}
  5338. \begin{lstlisting}
  5339. (movq |$e'$| |\itm{lhs}'|)
  5340. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  5341. \end{lstlisting}
  5342. \end{minipage}
  5343. \end{tabular} \\
  5344. \paragraph{Project}
  5345. The instruction selection for \key{project} is a bit more involved.
  5346. Like \key{inject}, the instructions are different depending on whether
  5347. the type $T$ is a pointer (vector or procedure) or not (Integer or
  5348. Boolean). The following shows the instruction selection for Integer
  5349. and Boolean. We first check to see if the tag on the tagged value
  5350. matches the tag of the target type $T$. If not, we halt the program by
  5351. calling the \code{exit} function. If we have a match, we need to
  5352. produce an untagged value by shifting it to the right by 2 bits.
  5353. %
  5354. \\
  5355. \begin{tabular}{lll}
  5356. \begin{minipage}{0.4\textwidth}
  5357. \begin{lstlisting}
  5358. (assign |\itm{lhs}| (project |$e$| |$T$|))
  5359. \end{lstlisting}
  5360. \end{minipage}
  5361. &
  5362. $\Rightarrow$
  5363. &
  5364. \begin{minipage}{0.5\textwidth}
  5365. \begin{lstlisting}
  5366. (movq |$e'$| |\itm{lhs}'|)
  5367. (andq (int 3) |\itm{lhs}'|)
  5368. (if (eq? |\itm{lhs}'| (int |$\itm{tagof}(T)$|))
  5369. ((movq |$e'$| |\itm{lhs}'|)
  5370. (sarq (int 2) |\itm{lhs}'|))
  5371. ((callq exit)))
  5372. \end{lstlisting}
  5373. \end{minipage}
  5374. \end{tabular} \\
  5375. %
  5376. The case for vectors and procedures begins in a similar way, checking
  5377. that the runtime tag matches the target type $T$ and exiting if there
  5378. is a mismatch. However, the way in which we convert the tagged value
  5379. to a value is different, as there is no need to shift. Instead we need
  5380. to zero-out the rightmost 2 bits. We accomplish this by creating the
  5381. bit pattern $\ldots 0011$, applying \code{notq} to obtain $\ldots
  5382. 1100$, and then applying \code{andq} with the tagged value get the
  5383. desired result. \\
  5384. %
  5385. \begin{tabular}{lll}
  5386. \begin{minipage}{0.4\textwidth}
  5387. \begin{lstlisting}
  5388. (assign |\itm{lhs}| (project |$e$| |$T$|))
  5389. \end{lstlisting}
  5390. \end{minipage}
  5391. &
  5392. $\Rightarrow$
  5393. &
  5394. \begin{minipage}{0.5\textwidth}
  5395. \begin{lstlisting}
  5396. (movq |$e'$| |\itm{lhs}'|)
  5397. (andq (int 3) |\itm{lhs}'|)
  5398. (if (eq? |\itm{lhs}'| (int |$\itm{tagof}(T)$|))
  5399. ((movq (int 3) |\itm{lhs}'|)
  5400. (notq |\itm{lhs}'|)
  5401. (andq |$e'$| |\itm{lhs}'|))
  5402. ((callq exit)))
  5403. \end{lstlisting}
  5404. \end{minipage}
  5405. \end{tabular} \\
  5406. \paragraph{Type Predicates} We leave it to the reader to
  5407. devise a sequence of instructions to implement the type predicates
  5408. \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  5409. \section{Compiling $R_7$ to $R_6$}
  5410. \label{sec:compile-r7}
  5411. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  5412. $R_7$ forms into $R_6$. An important invariant of this pass is that
  5413. given a subexpression $e$ of $R_7$, the pass will produce an
  5414. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  5415. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  5416. the Boolean \code{\#t}, which must be injected to produce an
  5417. expression of type \key{Any}.
  5418. %
  5419. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  5420. addition, is representative of compilation for many operations: the
  5421. arguments have type \key{Any} and must be projected to \key{Integer}
  5422. before the addition can be performed.
  5423. %
  5424. The compilation of \key{lambda} (third row of
  5425. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  5426. produce type annotations, we simply use \key{Any}.
  5427. %
  5428. The compilation of \code{if}, \code{eq?}, and \code{and} all
  5429. demonstrate how this pass has to account for some differences in
  5430. behavior between $R_7$ and $R_6$. The $R_7$ language is more
  5431. permissive than $R_6$ regarding what kind of values can be used in
  5432. various places. For example, the condition of an \key{if} does not
  5433. have to be a Boolean. Similarly, the arguments of \key{and} do not
  5434. need to be Boolean. For \key{eq?}, the arguments need not be of the
  5435. same type.
  5436. \begin{figure}[tbp]
  5437. \centering
  5438. \begin{tabular}{|lll|} \hline
  5439. \begin{minipage}{0.25\textwidth}
  5440. \begin{lstlisting}
  5441. #t
  5442. \end{lstlisting}
  5443. \end{minipage}
  5444. &
  5445. $\Rightarrow$
  5446. &
  5447. \begin{minipage}{0.6\textwidth}
  5448. \begin{lstlisting}
  5449. (inject #t Boolean)
  5450. \end{lstlisting}
  5451. \end{minipage}
  5452. \\[2ex]\hline
  5453. \begin{minipage}{0.25\textwidth}
  5454. \begin{lstlisting}
  5455. (+ |$e_1$| |$e_2$|)
  5456. \end{lstlisting}
  5457. \end{minipage}
  5458. &
  5459. $\Rightarrow$
  5460. &
  5461. \begin{minipage}{0.6\textwidth}
  5462. \begin{lstlisting}
  5463. (inject
  5464. (+ (project |$e'_1$| Integer)
  5465. (project |$e'_2$| Integer))
  5466. Integer)
  5467. \end{lstlisting}
  5468. \end{minipage}
  5469. \\[2ex]\hline
  5470. \begin{minipage}{0.25\textwidth}
  5471. \begin{lstlisting}
  5472. (lambda (|$x_1 \ldots$|) |$e$|)
  5473. \end{lstlisting}
  5474. \end{minipage}
  5475. &
  5476. $\Rightarrow$
  5477. &
  5478. \begin{minipage}{0.6\textwidth}
  5479. \begin{lstlisting}
  5480. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  5481. (Any|$\ldots$|Any -> Any))
  5482. \end{lstlisting}
  5483. \end{minipage}
  5484. \\[2ex]\hline
  5485. \begin{minipage}{0.25\textwidth}
  5486. \begin{lstlisting}
  5487. (app |$e_0$| |$e_1 \ldots e_n$|)
  5488. \end{lstlisting}
  5489. \end{minipage}
  5490. &
  5491. $\Rightarrow$
  5492. &
  5493. \begin{minipage}{0.6\textwidth}
  5494. \begin{lstlisting}
  5495. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  5496. |$e'_1 \ldots e'_n$|)
  5497. \end{lstlisting}
  5498. \end{minipage}
  5499. \\[2ex]\hline
  5500. \begin{minipage}{0.25\textwidth}
  5501. \begin{lstlisting}
  5502. (vector-ref |$e_1$| |$e_2$|)
  5503. \end{lstlisting}
  5504. \end{minipage}
  5505. &
  5506. $\Rightarrow$
  5507. &
  5508. \begin{minipage}{0.6\textwidth}
  5509. \begin{lstlisting}
  5510. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  5511. (let ([tmp2 (project |$e'_2$| Integer)])
  5512. (vector-ref tmp1 tmp2)))
  5513. \end{lstlisting}
  5514. \end{minipage}
  5515. \\[2ex]\hline
  5516. \begin{minipage}{0.25\textwidth}
  5517. \begin{lstlisting}
  5518. (if |$e_1$| |$e_2$| |$e_3$|)
  5519. \end{lstlisting}
  5520. \end{minipage}
  5521. &
  5522. $\Rightarrow$
  5523. &
  5524. \begin{minipage}{0.6\textwidth}
  5525. \begin{lstlisting}
  5526. (if (eq? |$e'_1$| (inject #f Boolean))
  5527. |$e'_3$|
  5528. |$e'_2$|)
  5529. \end{lstlisting}
  5530. \end{minipage}
  5531. \\[2ex]\hline
  5532. \begin{minipage}{0.25\textwidth}
  5533. \begin{lstlisting}
  5534. (eq? |$e_1$| |$e_2$|)
  5535. \end{lstlisting}
  5536. \end{minipage}
  5537. &
  5538. $\Rightarrow$
  5539. &
  5540. \begin{minipage}{0.6\textwidth}
  5541. \begin{lstlisting}
  5542. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  5543. \end{lstlisting}
  5544. \end{minipage}
  5545. \\[2ex]\hline
  5546. \begin{minipage}{0.25\textwidth}
  5547. \begin{lstlisting}
  5548. (and |$e_1$| |$e_2$|)
  5549. \end{lstlisting}
  5550. \end{minipage}
  5551. &
  5552. $\Rightarrow$
  5553. &
  5554. \begin{minipage}{0.6\textwidth}
  5555. \begin{lstlisting}
  5556. (let ([tmp |$e'_1$|])
  5557. (if (eq? tmp (inject #f Boolean))
  5558. tmp
  5559. |$e'_2$|))
  5560. \end{lstlisting}
  5561. \end{minipage} \\\hline
  5562. \end{tabular} \\
  5563. \caption{Compiling $R_7$ (Untyped Racket) to $R_6$.}
  5564. \label{fig:compile-r7-r6}
  5565. \end{figure}
  5566. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5567. \chapter{Gradual Typing}
  5568. \label{ch:gradual-typing}
  5569. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  5570. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5571. \chapter{Parametric Polymorphism}
  5572. \label{ch:parametric-polymorphism}
  5573. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  5574. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  5575. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5576. \chapter{High-level Optimization}
  5577. \label{ch:high-level-optimization}
  5578. This chapter will present a procedure inlining pass based on the
  5579. algorithm of \citet{Waddell:1997fk}.
  5580. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5581. \chapter{Appendix}
  5582. \section{Interpreters}
  5583. \label{appendix:interp}
  5584. We provide several interpreters in the \key{interp.rkt} file. The
  5585. \key{interp-scheme} function takes an AST in one of the Racket-like
  5586. languages considered in this book ($R_1, R_2, \ldots$) and interprets
  5587. the program, returning the result value. The \key{interp-C} function
  5588. interprets an AST for a program in one of the C-like languages ($C_0,
  5589. C_1, \ldots$), and the \code{interp-x86} function interprets an AST
  5590. for an x86 program.
  5591. \section{Utility Functions}
  5592. \label{appendix:utilities}
  5593. The utility function described in this section can be found in the
  5594. \key{utilities.rkt} file.
  5595. The \key{read-program} function takes a file path and parses that file
  5596. (it must be a Racket program) into an abstract syntax tree (as an
  5597. S-expression) with a \key{program} AST at the top.
  5598. The \key{assert} function displays the error message \key{msg} if the
  5599. Boolean \key{bool} is false.
  5600. \begin{lstlisting}
  5601. (define (assert msg bool) ...)
  5602. \end{lstlisting}
  5603. The \key{lookup} function ...
  5604. The \key{map2} function ...
  5605. \subsection{Graphs}
  5606. \begin{itemize}
  5607. \item The \code{make-graph} function takes a list of vertices
  5608. (symbols) and returns a graph.
  5609. \item The \code{add-edge} function takes a graph and two vertices and
  5610. adds an edge to the graph that connects the two vertices. The graph
  5611. is updated in-place. There is no return value for this function.
  5612. \item The \code{adjacent} function takes a graph and a vertex and
  5613. returns the set of vertices that are adjacent to the given
  5614. vertex. The return value is a Racket \code{hash-set} so it can be
  5615. used with functions from the \code{racket/set} module.
  5616. \item The \code{vertices} function takes a graph and returns the list
  5617. of vertices in the graph.
  5618. \end{itemize}
  5619. \subsection{Testing}
  5620. The \key{interp-tests} function takes a compiler name (a string), a
  5621. description of the passes, an interpreter for the source language, a
  5622. test family name (a string), and a list of test numbers, and runs the
  5623. compiler passes and the interpreters to check whether the passes
  5624. correct. The description of the passes is a list with one entry per
  5625. pass. An entry is a list with three things: a string giving the name
  5626. of the pass, the function that implements the pass (a translator from
  5627. AST to AST), and a function that implements the interpreter (a
  5628. function from AST to result value) for the language of the output of
  5629. the pass. The interpreters from Appendix~\ref{appendix:interp} make a
  5630. good choice. The \key{interp-tests} function assumes that the
  5631. subdirectory \key{tests} has a bunch of Scheme programs whose names
  5632. all start with the family name, followed by an underscore and then the
  5633. test number, ending in \key{.scm}. Also, for each Scheme program there
  5634. is a file with the same number except that it ends with \key{.in} that
  5635. provides the input for the Scheme program.
  5636. \begin{lstlisting}
  5637. (define (interp-tests name passes test-family test-nums) ...
  5638. \end{lstlisting}
  5639. The compiler-tests function takes a compiler name (a string) a
  5640. description of the passes (see the comment for \key{interp-tests}) a
  5641. test family name (a string), and a list of test numbers (see the
  5642. comment for interp-tests), and runs the compiler to generate x86 (a
  5643. \key{.s} file) and then runs gcc to generate machine code. It runs
  5644. the machine code and checks that the output is 42.
  5645. \begin{lstlisting}
  5646. (define (compiler-tests name passes test-family test-nums) ...)
  5647. \end{lstlisting}
  5648. The compile-file function takes a description of the compiler passes
  5649. (see the comment for \key{interp-tests}) and returns a function that,
  5650. given a program file name (a string ending in \key{.scm}), applies all
  5651. of the passes and writes the output to a file whose name is the same
  5652. as the program file name but with \key{.scm} replaced with \key{.s}.
  5653. \begin{lstlisting}
  5654. (define (compile-file passes)
  5655. (lambda (prog-file-name) ...))
  5656. \end{lstlisting}
  5657. \section{x86 Instruction Set Quick-Reference}
  5658. \label{sec:x86-quick-reference}
  5659. UNDER CONSTRUCTION
  5660. \bibliographystyle{plainnat}
  5661. \bibliography{all}
  5662. \end{document}
  5663. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  5664. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  5665. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  5666. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  5667. %% LocalWords: ast sexp Reynold's reynolds interp cond fx evaluator
  5668. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  5669. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  5670. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  5671. %% LocalWords: allocator gensym alist subdirectory scm rkt tmp lhs
  5672. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  5673. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  5674. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  5675. %% LocalWords: boolean typecheck notq cmpq sete movzbq jmp al xorq
  5676. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  5677. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  5678. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  5679. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  5680. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  5681. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  5682. %% LocalWords: len prev rootlen heaplen setl lt