book.tex 268 KB

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