book.tex 288 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602
  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. \fi
  38. \lstset{%
  39. language=Lisp,
  40. basicstyle=\ttfamily\small,
  41. escapechar=|,
  42. columns=flexible,
  43. moredelim=[is][\color{red}]{~}{~}
  44. }
  45. \newtheorem{theorem}{Theorem}
  46. \newtheorem{lemma}[theorem]{Lemma}
  47. \newtheorem{corollary}[theorem]{Corollary}
  48. \newtheorem{proposition}[theorem]{Proposition}
  49. \newtheorem{constraint}[theorem]{Constraint}
  50. \newtheorem{definition}[theorem]{Definition}
  51. \newtheorem{exercise}[theorem]{Exercise}
  52. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  53. % 'dedication' environment: To add a dedication paragraph at the start of book %
  54. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  55. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  56. \newenvironment{dedication}
  57. {
  58. \cleardoublepage
  59. \thispagestyle{empty}
  60. \vspace*{\stretch{1}}
  61. \hfill\begin{minipage}[t]{0.66\textwidth}
  62. \raggedright
  63. }
  64. {
  65. \end{minipage}
  66. \vspace*{\stretch{3}}
  67. \clearpage
  68. }
  69. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  70. % Chapter quote at the start of chapter %
  71. % Source: http://tex.stackexchange.com/a/53380 %
  72. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  73. \makeatletter
  74. \renewcommand{\@chapapp}{}% Not necessary...
  75. \newenvironment{chapquote}[2][2em]
  76. {\setlength{\@tempdima}{#1}%
  77. \def\chapquote@author{#2}%
  78. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  79. \itshape}
  80. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  81. \makeatother
  82. \input{defs}
  83. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  84. \title{\Huge \textbf{Essentials of Compilation} \\
  85. \huge An Incremental Approach}
  86. \author{\textsc{Jeremy G. Siek, Ryan R. Newton} \\
  87. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  88. Indiana University \\
  89. \\
  90. with contributions from: \\
  91. Carl Factora \\
  92. Andre Kuhlenschmidt \\
  93. Michael M. Vitousek \\
  94. Michael Vollmer \\
  95. Ryan Scott \\
  96. Cameron Swords
  97. }
  98. \begin{document}
  99. \frontmatter
  100. \maketitle
  101. \begin{dedication}
  102. This book is dedicated to the programming language wonks at Indiana
  103. University.
  104. \end{dedication}
  105. \tableofcontents
  106. \listoffigures
  107. %\listoftables
  108. \mainmatter
  109. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  110. \chapter*{Preface}
  111. The tradition of compiler writing at Indiana University goes back to
  112. research and courses about programming languages by Daniel Friedman in
  113. the 1970's and 1980's. Dan had conducted research on lazy
  114. evaluation~\citep{Friedman:1976aa} in the context of
  115. Lisp~\citep{McCarthy:1960dz} and then studied
  116. continuations~\citep{Felleisen:kx} and
  117. macros~\citep{Kohlbecker:1986dk} in the context of the
  118. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  119. of those courses, Kent Dybvig, went on to build Chez
  120. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  121. compiler for Scheme. After completing his Ph.D. at the University of
  122. North Carolina, Kent returned to teach at Indiana University.
  123. Throughout the 1990's and 2000's, Kent continued development of Chez
  124. Scheme and taught the compiler course.
  125. The compiler course evolved to incorporate novel pedagogical ideas
  126. while also including elements of effective real-world compilers. One
  127. of Dan's ideas was to split the compiler into many small ``passes'' so
  128. that the code for each pass would be easy to understood in isolation.
  129. (In contrast, most compilers of the time were organized into only a
  130. few monolithic passes for reasons of compile-time efficiency.) Kent,
  131. with later help from his students Dipanwita Sarkar and Andrew Keep,
  132. developed infrastructure to support this approach and evolved the
  133. course, first to use micro-sized passes and then into even smaller
  134. nano passes~\citep{Sarkar:2004fk,Keep:2012aa}. Jeremy Siek was a
  135. student in this compiler course in the early 2000's, as part of his
  136. Ph.D. studies at Indiana University. Needless to say, Jeremy enjoyed
  137. the course immensely!
  138. One of Jeremy's classmates, Abdulaziz Ghuloum, observed that the
  139. front-to-back organization of the course made it difficult for
  140. students to understand the rationale for the compiler
  141. design. Abdulaziz proposed an incremental approach in which the
  142. students build the compiler in stages; they start by implementing a
  143. complete compiler for a very small subset of the input language, then
  144. in each subsequent stage they add a feature to the input language and
  145. add or modify passes to handle the new feature~\citep{Ghuloum:2006bh}.
  146. In this way, the students see how the language features motivate
  147. aspects of the compiler design.
  148. After graduating from Indiana University in 2005, Jeremy went on to
  149. teach at the University of Colorado. He adapted the nano pass and
  150. incremental approaches to compiling a subset of the Python
  151. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  152. on the surface but there is a large overlap in the compiler techniques
  153. required for the two languages. Thus, Jeremy was able to teach much of
  154. the same content from the Indiana compiler course. He very much
  155. enjoyed teaching the course organized in this way, and even better,
  156. many of the students learned a lot and got excited about compilers.
  157. Jeremy returned to teach at Indiana University in 2013. In his
  158. absence the compiler course had switched from the front-to-back
  159. organization to a back-to-front organization. Seeing how well the
  160. incremental approach worked at Colorado, he started porting and
  161. adapting the structure of the Colorado course back into the land of
  162. Scheme. In the meantime Indiana had moved on from Scheme to Racket, so
  163. the course is now about compiling a subset of Racket (and Typed
  164. Racket) to the x86 assembly language. The compiler is implemented in
  165. Racket 7.1~\citep{plt-tr}.
  166. This is the textbook for the incremental version of the compiler
  167. course at Indiana University (Spring 2016 - present) and it is the
  168. first open textbook for an Indiana compiler course. With this book we
  169. hope to make the Indiana compiler course available to people that have
  170. not had the chance to study in Bloomington in person. Many of the
  171. compiler design decisions in this book are drawn from the assignment
  172. descriptions of \cite{Dybvig:2010aa}. We have captured what we think are
  173. the most important topics from \cite{Dybvig:2010aa} but we have omitted
  174. topics that we think are less interesting conceptually and we have made
  175. simplifications to reduce complexity. In this way, this book leans
  176. more towards pedagogy than towards the absolute efficiency of the
  177. generated code. Also, the book differs in places where we saw the
  178. opportunity to make the topics more fun, such as in relating register
  179. allocation to Sudoku (Chapter~\ref{ch:register-allocation-r1}).
  180. \section*{Prerequisites}
  181. The material in this book is challenging but rewarding. It is meant to
  182. prepare students for a lifelong career in programming languages. We do
  183. not recommend this book for students who want to dabble in programming
  184. languages.
  185. The book uses the Racket language both for the implementation of the
  186. compiler and for the language that is compiled, so a student should be
  187. proficient with Racket (or Scheme) prior to reading this book. There
  188. are many other excellent resources for learning Scheme and
  189. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. It
  190. is helpful but not necessary for the student to have prior exposure to
  191. x86 (or x86-64) assembly language~\citep{Intel:2015aa}, as one might
  192. obtain from a computer systems
  193. course~\citep{Bryant:2005aa,Bryant:2010aa}. This book introduces the
  194. parts of x86-64 assembly language that are needed.
  195. %\section*{Structure of book}
  196. % You might want to add short description about each chapter in this book.
  197. %\section*{About the companion website}
  198. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  199. %\begin{itemize}
  200. % \item A link to (freely downlodable) latest version of this document.
  201. % \item Link to download LaTeX source for this document.
  202. % \item Miscellaneous material (e.g. suggested readings etc).
  203. %\end{itemize}
  204. \section*{Acknowledgments}
  205. Many people have contributed to the ideas, techniques, organization,
  206. and teaching of the materials in this book. We especially thank the
  207. following people.
  208. \begin{itemize}
  209. \item Bor-Yuh Evan Chang
  210. \item Kent Dybvig
  211. \item Daniel P. Friedman
  212. \item Ronald Garcia
  213. \item Abdulaziz Ghuloum
  214. \item Jay McCarthy
  215. \item Dipanwita Sarkar
  216. \item Andrew Keep
  217. \item Oscar Waddell
  218. \item Michael Wollowski
  219. \end{itemize}
  220. \mbox{}\\
  221. \noindent Jeremy G. Siek \\
  222. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  223. %\noindent Spring 2016
  224. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  225. \chapter{Preliminaries}
  226. \label{ch:trees-recur}
  227. In this chapter, we review the basic tools that are needed for implementing a
  228. compiler. We use abstract syntax trees (ASTs), which refer to data structures in
  229. the compilers memory, rather than programs as they are stored on disk, in
  230. \emph{concrete syntax}.
  231. %
  232. ASTs can be represented in many different ways, depending on the programming
  233. language used to write the compiler.
  234. %
  235. Because this book uses Racket (\url{http://racket-lang.org}), a
  236. descendant of Lisp, we use S-expressions to represent programs
  237. (Section~\ref{sec:ast}). We use grammars to defined programming languages
  238. (Section~\ref{sec:grammar}) and pattern matching to inspect
  239. individual nodes in an AST (Section~\ref{sec:pattern-matching}). We
  240. use recursion to construct and deconstruct entire ASTs
  241. (Section~\ref{sec:recursion}). This chapter provides an brief
  242. introduction to these ideas.
  243. \section{Abstract Syntax Trees and S-expressions}
  244. \label{sec:ast}
  245. The primary data structure that is commonly used for representing
  246. programs is the \emph{abstract syntax tree} (AST). When considering
  247. some part of a program, a compiler needs to ask what kind of part it
  248. is and what sub-parts it has. For example, the program on the left,
  249. represented by an S-expression, corresponds to the AST on the right.
  250. \begin{center}
  251. \begin{minipage}{0.4\textwidth}
  252. \begin{lstlisting}
  253. (+ (read) (- 8))
  254. \end{lstlisting}
  255. \end{minipage}
  256. \begin{minipage}{0.4\textwidth}
  257. \begin{equation}
  258. \begin{tikzpicture}
  259. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  260. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  261. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  262. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  263. \draw[->] (plus) to (read);
  264. \draw[->] (plus) to (minus);
  265. \draw[->] (minus) to (8);
  266. \end{tikzpicture}
  267. \label{eq:arith-prog}
  268. \end{equation}
  269. \end{minipage}
  270. \end{center}
  271. We shall use the standard terminology for trees: each circle above is
  272. called a \emph{node}. The arrows connect a node to its \emph{children}
  273. (which are also nodes). The top-most node is the \emph{root}. Every
  274. node except for the root has a \emph{parent} (the node it is the child
  275. of). If a node has no children, it is a \emph{leaf} node. Otherwise
  276. it is an \emph{internal} node.
  277. Recall that an \emph{symbolic expression} (S-expression) is either
  278. \begin{enumerate}
  279. \item an atom, or
  280. \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  281. where $e_1$ and $e_2$ are each an S-expression.
  282. \end{enumerate}
  283. An \emph{atom} can be a symbol, such as \code{`hello}, a number, the null
  284. value \code{'()}, etc.
  285. We can create an S-expression in Racket simply by writing a backquote
  286. (called a quasi-quote in Racket).
  287. followed by the textual representation of the S-expression.
  288. It is quite common to use S-expressions
  289. to represent a list, such as $a, b ,c$ in the following way:
  290. \begin{lstlisting}
  291. `(a . (b . (c . ())))
  292. \end{lstlisting}
  293. Each element of the list is in the first slot of a pair, and the
  294. second slot is either the rest of the list or the null value, to mark
  295. the end of the list. Such lists are so common that Racket provides
  296. special notation for them that removes the need for the periods
  297. and so many parenthesis:
  298. \begin{lstlisting}
  299. `(a b c)
  300. \end{lstlisting}
  301. For another example,
  302. an S-expression to represent the AST \eqref{eq:arith-prog} is created
  303. by the following Racket expression:
  304. \begin{center}
  305. \texttt{`(+ (read) (- 8))}
  306. \end{center}
  307. When using S-expressions to represent ASTs, the convention is to
  308. represent each AST node as a list and to put the operation symbol at
  309. the front of the list. The rest of the list contains the children. So
  310. in the above case, the root AST node has operation \code{`+} and its
  311. two children are \code{`(read)} and \code{`(- 8)}, just as in the
  312. diagram \eqref{eq:arith-prog}.
  313. To build larger S-expressions one often needs to splice together
  314. several smaller S-expressions. Racket provides the comma operator to
  315. splice an S-expression into a larger one. For example, instead of
  316. creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  317. we could have first created an S-expression for AST
  318. \eqref{eq:arith-neg8} and then spliced that into the addition
  319. S-expression.
  320. \begin{lstlisting}
  321. (define ast1.4 `(- 8))
  322. (define ast1.1 `(+ (read) ,ast1.4))
  323. \end{lstlisting}
  324. In general, the Racket expression that follows the comma (splice)
  325. can be any expression that computes an S-expression.
  326. When deciding how to compile program \eqref{eq:arith-prog}, we need to
  327. know that the operation associated with the root node is addition and
  328. that it has two children: \texttt{read} and a negation. The AST data
  329. structure directly supports these queries, as we shall see in
  330. Section~\ref{sec:pattern-matching}, and hence is a good choice for use
  331. in compilers. In this book, we will often write down the S-expression
  332. representation of a program even when we really have in mind the AST
  333. because the S-expression is more concise. We recommend that, in your
  334. mind, you always think of programs as abstract syntax trees.
  335. \section{Grammars}
  336. \label{sec:grammar}
  337. A programming language can be thought of as a \emph{set} of programs.
  338. The set is typically infinite (one can always create larger and larger
  339. programs), so one cannot simply describe a language by listing all of
  340. the programs in the language. Instead we write down a set of rules, a
  341. \emph{grammar}, for building programs. We shall write our rules in a
  342. variant of Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  343. As an example, we describe a small language, named $R_0$, of
  344. integers and arithmetic operations. The first rule says that any
  345. integer is an expression, $\Exp$, in the language:
  346. \begin{equation}
  347. \Exp ::= \Int \label{eq:arith-int}
  348. \end{equation}
  349. %
  350. Each rule has a left-hand-side and a right-hand-side. The way to read
  351. a rule is that if you have all the program parts on the
  352. right-hand-side, then you can create an AST node and categorize it
  353. according to the left-hand-side.
  354. %
  355. A name such as $\Exp$ that is
  356. defined by the grammar rules is a \emph{non-terminal}.
  357. %
  358. The name $\Int$ is a also a non-terminal, however,
  359. we do not define $\Int$ because the
  360. reader already knows what an integer is.
  361. %
  362. Further, we make the simplifying design decision that all of the languages in
  363. this book only handle machine-representable integers. On most modern machines
  364. this corresponds to integers represented with 64-bits, i.e., the in range
  365. $-2^{63}$ to $2^{63}-1$.
  366. %
  367. However, we restrict this range further to match the Racket \texttt{fixnum}
  368. datatype, which allows 63-bit integers on a 64-bit machine.
  369. The second grammar rule is the \texttt{read} operation that receives
  370. an input integer from the user of the program.
  371. \begin{equation}
  372. \Exp ::= (\key{read}) \label{eq:arith-read}
  373. \end{equation}
  374. The third rule says that, given an $\Exp$ node, you can build another
  375. $\Exp$ node by negating it.
  376. \begin{equation}
  377. \Exp ::= (\key{-} \; \Exp) \label{eq:arith-neg}
  378. \end{equation}
  379. Symbols such as \key{-} in typewriter font are \emph{terminal} symbols
  380. and must literally appear in the program for the rule to be
  381. applicable.
  382. We can apply the rules to build ASTs in the $R_0$
  383. language. For example, by rule \eqref{eq:arith-int}, \texttt{8} is an
  384. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  385. an $\Exp$.
  386. \begin{center}
  387. \begin{minipage}{0.25\textwidth}
  388. \begin{lstlisting}
  389. (- 8)
  390. \end{lstlisting}
  391. \end{minipage}
  392. \begin{minipage}{0.25\textwidth}
  393. \begin{equation}
  394. \begin{tikzpicture}
  395. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  396. \node[draw, circle] (8) at (0, -1.2) {$8$};
  397. \draw[->] (minus) to (8);
  398. \end{tikzpicture}
  399. \label{eq:arith-neg8}
  400. \end{equation}
  401. \end{minipage}
  402. \end{center}
  403. The following grammar rule defines addition expressions:
  404. \begin{equation}
  405. \Exp ::= (\key{+} \; \Exp \; \Exp) \label{eq:arith-add}
  406. \end{equation}
  407. Now we can see that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  408. $R_0$. We know that \lstinline{(read)} is an $\Exp$ by rule
  409. \eqref{eq:arith-read} and we have shown that \texttt{(- 8)} is an
  410. $\Exp$, so we can apply rule \eqref{eq:arith-add} to show that
  411. \texttt{(+ (read) (- 8))} is an $\Exp$ in the $R_0$ language.
  412. If you have an AST for which the above rules do not apply, then the
  413. AST is not in $R_0$. For example, the AST \texttt{(- (read) (+ 8))} is
  414. not in $R_0$ because there are no rules for \key{+} with only one
  415. argument, nor for \key{-} with two arguments. Whenever we define a
  416. language with a grammar, we implicitly mean for the language to be the
  417. smallest set of programs that are justified by the rules. That is, the
  418. language only includes those programs that the rules allow.
  419. The last grammar rule for $R_0$ states that there is a \key{program}
  420. node to mark the top of the whole program:
  421. \[
  422. R_0 ::= (\key{program} \; \Exp)
  423. \]
  424. The \code{read-program} function provided in \code{utilities.rkt}
  425. reads programs in from a file (the sequence of characters in the
  426. concrete syntax of Racket) and parses them into the abstract syntax
  427. tree. The concrete syntax does not include a \key{program} form; that
  428. is added by the \code{read-program} function as it creates the
  429. AST. See the description of \code{read-program} in
  430. Appendix~\ref{appendix:utilities} for more details.
  431. It is common to have many rules with the same left-hand side, such as
  432. $\Exp$ in the grammar for $R_0$, so there is a vertical bar notation
  433. for gathering several rules, as shown in
  434. Figure~\ref{fig:r0-syntax}. Each clause between a vertical bar is
  435. called an {\em alternative}.
  436. \begin{figure}[tp]
  437. \fbox{
  438. \begin{minipage}{0.96\textwidth}
  439. \[
  440. \begin{array}{rcl}
  441. \Exp &::=& \Int \mid ({\tt \key{read}}) \mid (\key{-} \; \Exp) \mid
  442. (\key{+} \; \Exp \; \Exp) \\
  443. R_0 &::=& (\key{program} \; \Exp)
  444. \end{array}
  445. \]
  446. \end{minipage}
  447. }
  448. \caption{The syntax of $R_0$, a language of integer arithmetic.}
  449. \label{fig:r0-syntax}
  450. \end{figure}
  451. \section{Pattern Matching}
  452. \label{sec:pattern-matching}
  453. As mentioned above, one of the operations that a compiler needs to
  454. perform on an AST is to access the children of a node. Racket
  455. provides the \texttt{match} form to access the parts of an
  456. S-expression. Consider the following example and the output on the
  457. right.
  458. \begin{center}
  459. \begin{minipage}{0.5\textwidth}
  460. \begin{lstlisting}
  461. (match ast1.1
  462. [`(,op ,child1 ,child2)
  463. (print op) (newline)
  464. (print child1) (newline)
  465. (print child2)])
  466. \end{lstlisting}
  467. \end{minipage}
  468. \vrule
  469. \begin{minipage}{0.25\textwidth}
  470. \begin{lstlisting}
  471. '+
  472. '(read)
  473. '(- 8)
  474. \end{lstlisting}
  475. \end{minipage}
  476. \end{center}
  477. The \texttt{match} form takes AST \eqref{eq:arith-prog} and binds its
  478. parts to the three variables \texttt{op}, \texttt{child1}, and
  479. \texttt{child2}. In general, a match clause consists of a
  480. \emph{pattern} and a \emph{body}. The pattern is a quoted S-expression
  481. that may contain pattern-variables (each one preceded by a comma).
  482. %
  483. The pattern is not the same thing as a quasiquote expression used to
  484. \emph{construct} ASTs, however, the similarity is intentional: constructing and
  485. deconstructing ASTs uses similar syntax.
  486. %
  487. While the pattern uses a restricted syntax,
  488. the body of the match clause may contain any Racket code whatsoever.
  489. A \texttt{match} form may contain several clauses, as in the following
  490. function \texttt{leaf?} that recognizes when an $R_0$ node is
  491. a leaf. The \texttt{match} proceeds through the clauses in order,
  492. checking whether the pattern can match the input S-expression. The
  493. body of the first clause that matches is executed. The output of
  494. \texttt{leaf?} for several S-expressions is shown on the right. In the
  495. below \texttt{match}, we see another form of pattern: the \texttt{(?
  496. fixnum?)} applies the predicate \texttt{fixnum?} to the input
  497. S-expression to see if it is a machine-representable integer.
  498. \begin{center}
  499. \begin{minipage}{0.5\textwidth}
  500. \begin{lstlisting}
  501. (define (leaf? arith)
  502. (match arith
  503. [(? fixnum?) #t]
  504. [`(read) #t]
  505. [`(- ,c1) #f]
  506. [`(+ ,c1 ,c2) #f]))
  507. (leaf? `(read))
  508. (leaf? `(- 8))
  509. (leaf? `(+ (read) (- 8)))
  510. \end{lstlisting}
  511. \end{minipage}
  512. \vrule
  513. \begin{minipage}{0.25\textwidth}
  514. \begin{lstlisting}
  515. #t
  516. #f
  517. #f
  518. \end{lstlisting}
  519. \end{minipage}
  520. \end{center}
  521. \section{Recursion}
  522. \label{sec:recursion}
  523. Programs are inherently recursive in that an $R_0$ expression ($\Exp$)
  524. is made up of smaller expressions. Thus, the natural way to process an
  525. entire program is with a recursive function. As a first example of
  526. such a function, we define \texttt{exp?} below, which takes an
  527. arbitrary S-expression, {\tt sexp}, and determines whether or not {\tt
  528. sexp} is an $R_0$ expression. Note that each match clause
  529. corresponds to one grammar rule the body of each clause makes a
  530. recursive call for each child node. This pattern of recursive function
  531. is so common that it has a name, \emph{structural recursion}. In
  532. general, when a recursive function is defined using a sequence of
  533. match clauses that correspond to a grammar, and each clause body makes
  534. a recursive call on each child node, then we say the function is
  535. defined by structural recursion. Below we also define a second
  536. function, named \code{R0?}, determines whether an S-expression is an
  537. $R_0$ program.
  538. %
  539. \begin{center}
  540. \begin{minipage}{0.7\textwidth}
  541. \begin{lstlisting}
  542. (define (exp? sexp)
  543. (match sexp
  544. [(? fixnum?) #t]
  545. [`(read) #t]
  546. [`(- ,e) (exp? e)]
  547. [`(+ ,e1 ,e2)
  548. (and (exp? e1) (exp? e2))]
  549. [else #f]))
  550. (define (R0? sexp)
  551. (match sexp
  552. [`(program ,e) (exp? e)]
  553. [else #f]))
  554. (R0? `(program (+ (read) (- 8))))
  555. (R0? `(program (- (read) (+ 8))))
  556. \end{lstlisting}
  557. \end{minipage}
  558. \vrule
  559. \begin{minipage}{0.25\textwidth}
  560. \begin{lstlisting}
  561. #t
  562. #f
  563. \end{lstlisting}
  564. \end{minipage}
  565. \end{center}
  566. Indeed, the structural recursion follows the grammar itself. We can
  567. generally expect to write a recursive function to handle each
  568. non-terminal in the grammar.\footnote{This principle of structuring
  569. code according to the data definition is advocated in the book
  570. \emph{How to Design Programs}
  571. \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}
  572. You may be tempted to write the program with just one function, like this:
  573. \begin{center}
  574. \begin{minipage}{0.5\textwidth}
  575. \begin{lstlisting}
  576. (define (R0? sexp)
  577. (match sexp
  578. [(? fixnum?) #t]
  579. [`(read) #t]
  580. [`(- ,e) (R0? e)]
  581. [`(+ ,e1 ,e2) (and (R0? e1) (R0? e2))]
  582. [`(program ,e) (R0? e)]
  583. [else #f]))
  584. \end{lstlisting}
  585. \end{minipage}
  586. \end{center}
  587. %
  588. Sometimes such a trick will save a few lines of code, especially when it comes
  589. to the {\tt program} wrapper. Yet this style is generally \emph{not}
  590. recommended because it can get you into trouble.
  591. %
  592. For instance, the above function is subtly wrong:
  593. \lstinline{(R0? `(program (program 3)))} will return true, when it
  594. should return false.
  595. %% NOTE FIXME - must check for consistency on this issue throughout.
  596. \section{Interpreters}
  597. \label{sec:interp-R0}
  598. The meaning, or semantics, of a program is typically defined in the
  599. specification of the language. For example, the Scheme language is
  600. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  601. defined in its reference manual~\citep{plt-tr}. In this book we use an
  602. interpreter to define the meaning of each language that we consider,
  603. following Reynold's advice in this
  604. regard~\citep{reynolds72:_def_interp}. Here we warm up by writing an
  605. interpreter for the $R_0$ language, which serves as a second example
  606. of structural recursion. The \texttt{interp-R0} function is defined in
  607. Figure~\ref{fig:interp-R0}. The body of the function is a match on the
  608. input program \texttt{p} and then a call to the \lstinline{interp-exp}
  609. helper function, which in turn has one match clause per grammar rule
  610. for $R_0$ expressions.
  611. \begin{figure}[tbp]
  612. \begin{lstlisting}
  613. (define (interp-exp e)
  614. (match e
  615. [(? fixnum?) e]
  616. [`(read)
  617. (let ([r (read)])
  618. (cond [(fixnum? r) r]
  619. [else (error 'interp-R0 "input not an integer" r)]))]
  620. [`(- ,e1) (fx- 0 (interp-exp e1))]
  621. [`(+ ,e1 ,e2) (fx+ (interp-exp e1) (interp-exp e2))]
  622. ))
  623. (define (interp-R0 p)
  624. (match p
  625. [`(program ,e) (interp-exp e)]))
  626. \end{lstlisting}
  627. \caption{Interpreter for the $R_0$ language.}
  628. \label{fig:interp-R0}
  629. \end{figure}
  630. Let us consider the result of interpreting a few $R_0$ programs. The
  631. following program simply adds two integers.
  632. \begin{lstlisting}
  633. (+ 10 32)
  634. \end{lstlisting}
  635. The result is \key{42}, as you might have expected. Here we have written the
  636. program in concrete syntax, whereas the parsed abstract syntax would be the
  637. slightly different: \lstinline{(program (+ 10 32))}.
  638. The next example demonstrates that expressions may be nested within
  639. each other, in this case nesting several additions and negations.
  640. \begin{lstlisting}
  641. (+ 10 (- (+ 12 20)))
  642. \end{lstlisting}
  643. What is the result of the above program?
  644. As mentioned previously, the $R0$ language does not support
  645. arbitrarily-large integers, but only $63$-bit integers, so we
  646. interpret the arithmetic operations of $R0$ using fixnum arithmetic.
  647. What happens when we run the following program?
  648. \begin{lstlisting}
  649. (define large 999999999999999999)
  650. (interp-R0 `(program (+ (+ (+ ,large ,large) (+ ,large ,large))
  651. (+ (+ ,large ,large) (+ ,large ,large)))))
  652. \end{lstlisting}
  653. It produces an error:
  654. \begin{lstlisting}
  655. fx+: result is not a fixnum
  656. \end{lstlisting}
  657. We shall use the convention that if the interpreter for a language
  658. produces an error when run on a program, then the meaning of the
  659. program is unspecified. The compiler for the language is under no
  660. obligation for such a program; it can produce an executable that does
  661. anything.
  662. \noindent
  663. Moving on, the \key{read} operation prompts the user of the program
  664. for an integer. If we interpret the AST \eqref{eq:arith-prog} and give
  665. it the input \texttt{50}
  666. \begin{lstlisting}
  667. (interp-R0 ast1.1)
  668. \end{lstlisting}
  669. we get the answer to life, the universe, and everything:
  670. \begin{lstlisting}
  671. 42
  672. \end{lstlisting}
  673. We include the \key{read} operation in $R_0$ so a clever student
  674. cannot implement a compiler for $R_0$ simply by running the
  675. interpreter at compilation time to obtain the output and then
  676. generating the trivial code to return the output. (A clever student
  677. did this in a previous version of the course.)
  678. The job of a compiler is to translate a program in one language into a
  679. program in another language so that the output program behaves the
  680. same way as the input program. This idea is depicted in the following
  681. diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  682. $\mathcal{L}_2$, and an interpreter for each language. Suppose that
  683. the compiler translates program $P_1$ in language $\mathcal{L}_1$ into
  684. program $P_2$ in language $\mathcal{L}_2$. Then interpreting $P_1$
  685. and $P_2$ on their respective interpreters with input $i$ should yield
  686. the same output $o$.
  687. \begin{equation} \label{eq:compile-correct}
  688. \begin{tikzpicture}[baseline=(current bounding box.center)]
  689. \node (p1) at (0, 0) {$P_1$};
  690. \node (p2) at (3, 0) {$P_2$};
  691. \node (o) at (3, -2.5) {$o$};
  692. \path[->] (p1) edge [above] node {compile} (p2);
  693. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  694. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  695. \end{tikzpicture}
  696. \end{equation}
  697. In the next section we see our first example of a compiler, which is
  698. another example of structural recursion.
  699. \section{Example Compiler: a Partial Evaluator}
  700. \label{sec:partial-evaluation}
  701. In this section we consider a compiler that translates $R_0$
  702. programs into $R_0$ programs that are more efficient, that is,
  703. this compiler is an optimizer. Our optimizer will accomplish this by
  704. trying to eagerly compute the parts of the program that do not depend
  705. on any inputs. For example, given the following program
  706. \begin{lstlisting}
  707. (+ (read) (- (+ 5 3)))
  708. \end{lstlisting}
  709. our compiler will translate it into the program
  710. \begin{lstlisting}
  711. (+ (read) -8)
  712. \end{lstlisting}
  713. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  714. evaluator for the $R_0$ language. The output of the partial evaluator
  715. is an $R_0$ program, which we build up using a combination of
  716. quasiquotes and commas. (Though no quasiquote is necessary for
  717. integers.) In Figure~\ref{fig:pe-arith}, the normal structural
  718. recursion is captured in the main \texttt{pe-arith} function whereas
  719. the code for partially evaluating negation and addition is factored
  720. into two separate helper functions: \texttt{pe-neg} and
  721. \texttt{pe-add}. The input to these helper functions is the output of
  722. partially evaluating the children nodes.
  723. \begin{figure}[tbp]
  724. \begin{lstlisting}
  725. (define (pe-neg r)
  726. (cond [(fixnum? r) (fx- 0 r)]
  727. [else `(- ,r)]))
  728. (define (pe-add r1 r2)
  729. (cond [(and (fixnum? r1) (fixnum? r2)) (fx+ r1 r2)]
  730. [else `(+ ,r1 ,r2)]))
  731. (define (pe-arith e)
  732. (match e
  733. [(? fixnum?) e]
  734. [`(read) `(read)]
  735. [`(- ,e1)
  736. (pe-neg (pe-arith e1))]
  737. [`(+ ,e1 ,e2)
  738. (pe-add (pe-arith e1) (pe-arith e2))]))
  739. \end{lstlisting}
  740. \caption{A partial evaluator for $R_0$ expressions.}
  741. \label{fig:pe-arith}
  742. \end{figure}
  743. Our code for \texttt{pe-neg} and \texttt{pe-add} implements the simple
  744. idea of checking whether their arguments are integers and if they are,
  745. to go ahead and perform the arithmetic. Otherwise, we use quasiquote
  746. to create an AST node for the appropriate operation (either negation
  747. or addition) and use comma to splice in the child nodes.
  748. To gain some confidence that the partial evaluator is correct, we can
  749. test whether it produces programs that get the same result as the
  750. input program. That is, we can test whether it satisfies Diagram
  751. \eqref{eq:compile-correct}. The following code runs the partial
  752. evaluator on several examples and tests the output program. The
  753. \texttt{assert} function is defined in Appendix~\ref{appendix:utilities}.
  754. \begin{lstlisting}
  755. (define (test-pe p)
  756. (assert "testing pe-arith"
  757. (equal? (interp-R0 p) (interp-R0 (pe-arith p)))))
  758. (test-pe `(+ (read) (- (+ 5 3))))
  759. (test-pe `(+ 1 (+ (read) 1)))
  760. (test-pe `(- (+ (read) (- 5))))
  761. \end{lstlisting}
  762. \rn{Do we like the explicit whitespace? I've never been fond of it, in part
  763. because it breaks copy/pasting. But, then again, so do most of the quotes.}
  764. \begin{exercise}
  765. \normalfont % I don't like the italics for exercises. -Jeremy
  766. We challenge the reader to improve on the simple partial evaluator in
  767. Figure~\ref{fig:pe-arith} by replacing the \texttt{pe-neg} and
  768. \texttt{pe-add} helper functions with functions that know more about
  769. arithmetic. For example, your partial evaluator should translate
  770. \begin{lstlisting}
  771. (+ 1 (+ (read) 1))
  772. \end{lstlisting}
  773. into
  774. \begin{lstlisting}
  775. (+ 2 (read))
  776. \end{lstlisting}
  777. To accomplish this, we recommend that your partial evaluator produce
  778. output that takes the form of the $\itm{residual}$ non-terminal in the
  779. following grammar.
  780. \[
  781. \begin{array}{lcl}
  782. \Exp &::=& (\key{read}) \mid (\key{-} \;(\key{read})) \mid (\key{+} \; \Exp \; \Exp)\\
  783. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \Exp) \mid \Exp
  784. \end{array}
  785. \]
  786. \end{exercise}
  787. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  788. \chapter{Integers and Variables}
  789. \label{ch:int-exp}
  790. This chapter concerns the challenge of compiling a subset of Racket
  791. that includes integer arithmetic and local variable binding, which we
  792. name $R_1$, to x86-64 assembly code~\citep{Intel:2015aa}. Henceforth
  793. we shall refer to x86-64 simply as x86. The chapter begins with a
  794. description of the $R_1$ language (Section~\ref{sec:s0}) followed by a
  795. description of x86 (Section~\ref{sec:x86}). The x86 assembly language
  796. is quite large, so we only discuss what is needed for compiling
  797. $R_1$. We introduce more of x86 in later chapters. Once we have
  798. introduced $R_1$ and x86, we reflect on their differences and come up
  799. with a plan to break down the translation from $R_1$ to x86 into a
  800. handful of steps (Section~\ref{sec:plan-s0-x86}). The rest of the
  801. sections in this Chapter give detailed hints regarding each step
  802. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  803. to give enough hints that the well-prepared reader can implement a
  804. compiler from $R_1$ to x86 while at the same time leaving room for
  805. some fun and creativity.
  806. \section{The $R_1$ Language}
  807. \label{sec:s0}
  808. The $R_1$ language extends the $R_0$ language
  809. (Figure~\ref{fig:r0-syntax}) with variable definitions. The syntax of
  810. the $R_1$ language is defined by the grammar in
  811. Figure~\ref{fig:r1-syntax}. The non-terminal \Var{} may be any Racket
  812. identifier. As in $R_0$, \key{read} is a nullary operator, \key{-} is
  813. a unary operator, and \key{+} is a binary operator. Similar to $R_0$,
  814. the $R_1$ language includes the \key{program} construct to mark the
  815. top of the program, which is helpful in parts of the compiler. The
  816. $\itm{info}$ field of the \key{program} construct contain an
  817. association list that is used to communicating auxiliary data from one
  818. step of the compiler to the next.
  819. The $R_1$ language is rich enough to exhibit several compilation
  820. techniques but simple enough so that the reader, together with couple
  821. friends, can implement a compiler for it in a week or two of part-time
  822. work. To give the reader a feeling for the scale of this first
  823. compiler, the instructor solution for the $R_1$ compiler is less than
  824. 500 lines of code.
  825. \begin{figure}[btp]
  826. \centering
  827. \fbox{
  828. \begin{minipage}{0.96\textwidth}
  829. \[
  830. \begin{array}{rcl}
  831. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \\
  832. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  833. R_1 &::=& (\key{program} \;\itm{info}\; \Exp)
  834. \end{array}
  835. \]
  836. \end{minipage}
  837. }
  838. \caption{The syntax of $R_1$, a language of integers and variables.}
  839. \label{fig:r1-syntax}
  840. \end{figure}
  841. Let us dive into the description of the $R_1$ language. The \key{let}
  842. construct defines a variable for use within its body and initializes
  843. the variable with the value of an expression. So the following
  844. program initializes \code{x} to \code{32} and then evaluates the body
  845. \code{(+ 10 x)}, producing \code{42}.
  846. \begin{lstlisting}
  847. (program ()
  848. (let ([x (+ 12 20)]) (+ 10 x)))
  849. \end{lstlisting}
  850. When there are multiple \key{let}'s for the same variable, the closest
  851. enclosing \key{let} is used. That is, variable definitions overshadow
  852. prior definitions. Consider the following program with two \key{let}'s
  853. that define variables named \code{x}. Can you figure out the result?
  854. \begin{lstlisting}
  855. (program ()
  856. (let ([x 32]) (+ (let ([x 10]) x) x)))
  857. \end{lstlisting}
  858. For the purposes of showing which variable uses correspond to which
  859. definitions, the following shows the \code{x}'s annotated with subscripts
  860. to distinguish them. Double check that your answer for the above is
  861. the same as your answer for this annotated version of the program.
  862. \begin{lstlisting}
  863. (program ()
  864. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|)))
  865. \end{lstlisting}
  866. The initializing expression is always evaluated before the body of the
  867. \key{let}, so in the following, the \key{read} for \code{x} is
  868. performed before the \key{read} for \code{y}. Given the input
  869. \code{52} then \code{10}, the following produces \code{42} (and not
  870. \code{-42}).
  871. \begin{lstlisting}
  872. (program ()
  873. (let ([x (read)]) (let ([y (read)]) (+ x (- y)))))
  874. \end{lstlisting}
  875. Figure~\ref{fig:interp-R1} shows the interpreter for the $R_1$
  876. language. It extends the interpreter for $R_0$ with two new
  877. \key{match} clauses for variables and for \key{let}. For \key{let},
  878. we will need a way to communicate the initializing value of a variable
  879. to all the uses of a variable. To accomplish this, we maintain a
  880. mapping from variables to values, which is traditionally called an
  881. \emph{environment}. For simplicity, here we use an association list to
  882. represent the environment. The \code{interp-R1} function takes the
  883. current environment, \code{env}, as an extra parameter. When the
  884. interpreter encounters a variable, it finds the corresponding value
  885. using the \code{lookup} function (Appendix~\ref{appendix:utilities}).
  886. When the interpreter encounters a \key{let}, it evaluates the
  887. initializing expression, extends the environment with the result bound
  888. to the variable, then evaluates the body of the \key{let}.
  889. \begin{figure}[tbp]
  890. \begin{lstlisting}
  891. (define (interp-exp env)
  892. (lambda (e)
  893. (match e
  894. [(? fixnum?) e]
  895. [`(read)
  896. (define r (read))
  897. (cond [(fixnum? r) r]
  898. [else (error 'interp-R1 "expected an integer" r)])]
  899. [`(- ,e)
  900. (define v ((interp-exp env) e))
  901. (fx- 0 v)]
  902. [`(+ ,e1 ,e2)
  903. (define v1 ((interp-exp env) e1))
  904. (define v2 ((interp-exp env) e2))
  905. (fx+ v1 v2)]
  906. [(? symbol?) (lookup e env)]
  907. [`(let ([,x ,e]) ,body)
  908. (define new-env (cons (cons x ((interp-exp env) e)) env))
  909. ((interp-exp new-env) body)]
  910. )))
  911. (define (interp-R1 env)
  912. (lambda (p)
  913. (match p
  914. [`(program ,info ,e) ((interp-exp '()) e)])))
  915. \end{lstlisting}
  916. \caption{Interpreter for the $R_1$ language.}
  917. \label{fig:interp-R1}
  918. \end{figure}
  919. The goal for this chapter is to implement a compiler that translates
  920. any program $P_1$ in the $R_1$ language into an x86 assembly
  921. program $P_2$ such that $P_2$ exhibits the same behavior on an x86
  922. computer as the $R_1$ program running in a Racket implementation.
  923. That is, they both output the same integer $n$.
  924. \[
  925. \begin{tikzpicture}[baseline=(current bounding box.center)]
  926. \node (p1) at (0, 0) {$P_1$};
  927. \node (p2) at (4, 0) {$P_2$};
  928. \node (o) at (4, -2) {$n$};
  929. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  930. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  931. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  932. \end{tikzpicture}
  933. \]
  934. In the next section we introduce enough of the x86 assembly
  935. language to compile $R_1$.
  936. \section{The x86 Assembly Language}
  937. \label{sec:x86}
  938. An x86 program is a sequence of instructions. The program is stored in the
  939. computer's memory and the \emph{program counter} points to the address of the
  940. next instruction to be executed. For most instructions, once the instruction is
  941. executed, the program counter is incremented to point to the immediately
  942. following instruction in memory. Each instruction may refer to integer
  943. constants (called \emph{immediate values}), variables called \emph{registers},
  944. and instructions may load and store values into memory. For our purposes, we
  945. can think of the computer's memory as a mapping of 64-bit addresses to 64-bit
  946. values%
  947. \footnote{This simple story suffices for describing how sequential
  948. programs access memory but is not sufficient for multi-threaded
  949. programs. However, multi-threaded execution is beyond the scope of
  950. this book.}.
  951. %
  952. Figure~\ref{fig:x86-a} defines the syntax for the
  953. subset of the x86 assembly language needed for this chapter.
  954. %
  955. We use the AT\&T syntax expected by the GNU assembler, which comes
  956. with the \key{gcc} compiler that we use for compiling assembly code to
  957. machine code.
  958. %
  959. Also, Appendix~\ref{sec:x86-quick-reference} includes a quick-reference of all
  960. the x86 instructions used in this book and a short explanation of what they do.
  961. % to do: finish treatment of imulq
  962. % it's needed for vector's in R6/R7
  963. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  964. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  965. && \key{r8} \mid \key{r9} \mid \key{r10}
  966. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  967. \mid \key{r14} \mid \key{r15}}
  968. \begin{figure}[tp]
  969. \fbox{
  970. \begin{minipage}{0.96\textwidth}
  971. \[
  972. \begin{array}{lcl}
  973. \Reg &::=& \allregisters{} \\
  974. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int(\key{\%}\Reg) \\
  975. \Instr &::=& \key{addq} \; \Arg, \Arg \mid
  976. \key{subq} \; \Arg, \Arg \mid
  977. \key{negq} \; \Arg \mid \key{movq} \; \Arg, \Arg \mid \\
  978. && \key{callq} \; \mathit{label} \mid
  979. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \itm{label}\key{:}\; \Instr \\
  980. \Prog &::= & \key{.globl main}\\
  981. & & \key{main:} \; \Instr^{+}
  982. \end{array}
  983. \]
  984. \end{minipage}
  985. }
  986. \caption{A subset of the x86 assembly language (AT\&T syntax).}
  987. \label{fig:x86-a}
  988. \end{figure}
  989. An immediate value is written using the notation \key{\$}$n$ where $n$
  990. is an integer.
  991. %
  992. A register is written with a \key{\%} followed by the register name,
  993. such as \key{\%rax}.
  994. %
  995. An access to memory is specified using the syntax $n(\key{\%}r)$,
  996. which obtains the address stored in register $r$ and then
  997. offsets the address by $n$ bytes
  998. (8 bits). The address is then used to either load or store to memory
  999. depending on whether it occurs as a source or destination argument of
  1000. an instruction.
  1001. An arithmetic instruction, such as $\key{addq}\,s,\,d$, reads from the
  1002. source $s$ and destination $d$, applies the arithmetic operation, then
  1003. writes the result in $d$.
  1004. %
  1005. The move instruction, $\key{movq}\,s\,d$ reads from $s$ and stores the
  1006. result in $d$.
  1007. %
  1008. The $\key{callq}\,\mathit{label}$ instruction executes the procedure
  1009. specified by the label.
  1010. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  1011. to \code{(+ 10 32)}. The \key{globl} directive says that the
  1012. \key{main} procedure is externally visible, which is necessary so
  1013. that the operating system can call it. The label \key{main:}
  1014. indicates the beginning of the \key{main} procedure which is where
  1015. the operating system starts executing this program. The instruction
  1016. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  1017. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  1018. $10$ in \key{rax} and puts the result, $42$, back into
  1019. \key{rax}.
  1020. The last instruction, \key{retq}, finishes the \key{main} function by
  1021. returning the integer in \key{rax} to the operating system. The
  1022. operating system interprets this integer as the program's exit
  1023. code. By convention, an exit code of 0 indicates the program was
  1024. successful, and all other exit codes indicate various errors.
  1025. Nevertheless, we return the result of the program as the exit code.
  1026. %\begin{wrapfigure}{r}{2.25in}
  1027. \begin{figure}[tbp]
  1028. \begin{lstlisting}
  1029. .globl main
  1030. main:
  1031. movq $10, %rax
  1032. addq $32, %rax
  1033. retq
  1034. \end{lstlisting}
  1035. \caption{An x86 program equivalent to $\BINOP{+}{10}{32}$.}
  1036. \label{fig:p0-x86}
  1037. %\end{wrapfigure}
  1038. \end{figure}
  1039. Unfortunately, x86 varies in a couple ways depending on what operating
  1040. system it is assembled in. The code examples shown here are correct on
  1041. Linux and most Unix-like platforms, but when assembled on Mac OS X,
  1042. labels like \key{main} must be prefixed with an underscore, as in
  1043. \key{\_main}.
  1044. We exhibit the use of memory for storing intermediate results in the
  1045. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1046. equivalent to $\BINOP{+}{52}{ \UNIOP{-}{10} }$. This program uses a
  1047. region of memory called the \emph{procedure call stack} (or
  1048. \emph{stack} for short). The stack consists of a separate \emph{frame}
  1049. for each procedure call. The memory layout for an individual frame is
  1050. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1051. \emph{stack pointer} and points to the item at the top of the
  1052. stack. The stack grows downward in memory, so we increase the size of
  1053. the stack by subtracting from the stack pointer. The frame size is
  1054. required to be a multiple of 16 bytes. In the context of a procedure
  1055. call, the \emph{return address} is the next instruction on the caller
  1056. side that comes after the call instruction. During a function call,
  1057. the return address is pushed onto the stack. The register \key{rbp}
  1058. is the \emph{base pointer} which serves two purposes: 1) it saves the
  1059. location of the stack pointer for the calling procedure and 2) it is
  1060. used to access variables associated with the current procedure. The
  1061. base pointer of the calling procedure is pushed onto the stack after
  1062. the return address. We number the variables from $1$ to $n$. Variable
  1063. $1$ is stored at address $-8\key{(\%rbp)}$, variable $2$ at
  1064. $-16\key{(\%rbp)}$, etc.
  1065. \begin{figure}[tbp]
  1066. \begin{lstlisting}
  1067. start:
  1068. movq $10, -8(%rbp)
  1069. negq -8(%rbp)
  1070. movq -8(%rbp), %rax
  1071. addq $52, %rax
  1072. jmp conclusion
  1073. .globl main
  1074. main:
  1075. pushq %rbp
  1076. movq %rsp, %rbp
  1077. subq $16, %rsp
  1078. jmp start
  1079. conclusion:
  1080. addq $16, %rsp
  1081. popq %rbp
  1082. retq
  1083. \end{lstlisting}
  1084. \caption{An x86 program equivalent to $\BINOP{+}{52}{\UNIOP{-}{10} }$.}
  1085. \label{fig:p1-x86}
  1086. \end{figure}
  1087. \begin{figure}[tbp]
  1088. \centering
  1089. \begin{tabular}{|r|l|} \hline
  1090. Position & Contents \\ \hline
  1091. 8(\key{\%rbp}) & return address \\
  1092. 0(\key{\%rbp}) & old \key{rbp} \\
  1093. -8(\key{\%rbp}) & variable $1$ \\
  1094. -16(\key{\%rbp}) & variable $2$ \\
  1095. \ldots & \ldots \\
  1096. 0(\key{\%rsp}) & variable $n$\\ \hline
  1097. \end{tabular}
  1098. \caption{Memory layout of a frame.}
  1099. \label{fig:frame}
  1100. \end{figure}
  1101. Getting back to the program in Figure~\ref{fig:p1-x86}, the first
  1102. three instructions are the typical \emph{prelude} for a procedure.
  1103. The instruction \key{pushq \%rbp} saves the base pointer for the
  1104. procedure that called the current one onto the stack and subtracts $8$
  1105. from the stack pointer. The second instruction \key{movq \%rsp, \%rbp}
  1106. changes the base pointer to the top of the stack. The instruction
  1107. \key{subq \$16, \%rsp} moves the stack pointer down to make enough
  1108. room for storing variables. This program just needs one variable ($8$
  1109. bytes) but because the frame size is required to be a multiple of 16
  1110. bytes, it rounds to 16 bytes.
  1111. The four instructions under the label \code{start} carry out the work
  1112. of computing $\BINOP{+}{52}{\UNIOP{-}{10} }$. The first instruction
  1113. \key{movq \$10, -8(\%rbp)} stores $10$ in variable $1$. The
  1114. instruction \key{negq -8(\%rbp)} changes variable $1$ to $-10$. The
  1115. \key{movq \$52, \%rax} places $52$ in the register \key{rax} and
  1116. \key{addq -8(\%rbp), \%rax} adds the contents of variable $1$ to
  1117. \key{rax}, at which point \key{rax} contains $42$.
  1118. The three instructions under the label \code{conclusion} are the
  1119. typical finale of a procedure. The first two are necessary to get the
  1120. state of the machine back to where it was at the beginning of the
  1121. procedure. The \key{addq \$16, \%rsp} instruction moves the stack
  1122. pointer back to point at the old base pointer. The amount added here
  1123. needs to match the amount that was subtracted in the prelude of the
  1124. procedure. Then \key{popq \%rbp} returns the old base pointer to
  1125. \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  1126. \key{retq}, jumps back to the procedure that called this one and adds
  1127. 8 to the stack pointer, which returns the stack pointer to where it
  1128. was prior to the procedure call.
  1129. The compiler will need a convenient representation for manipulating
  1130. x86 programs, so we define an abstract syntax for x86 in
  1131. Figure~\ref{fig:x86-ast-a}. We refer to this language as $x86_0$ with
  1132. a subscript $0$ because later we introduce extended versions of this
  1133. assembly language. The main difference compared to the concrete syntax
  1134. of x86 (Figure~\ref{fig:x86-a}) is that it does nto allow labelled
  1135. instructions to appear anywhere, but instead organizes instructions
  1136. into groups called \emph{blocks} and a label is associated with every
  1137. block, which is why the \key{program} form includes an association
  1138. list mapping labels to blocks. The reason for this organization
  1139. becomes apparent in Chapter~\ref{ch:bool-types}.
  1140. \begin{figure}[tp]
  1141. \fbox{
  1142. \begin{minipage}{0.96\textwidth}
  1143. \[
  1144. \begin{array}{lcl}
  1145. \itm{register} &::=& \allregisters{} \\
  1146. \Arg &::=& \INT{\Int} \mid \REG{\itm{register}}
  1147. \mid (\key{deref}\;\itm{register}\;\Int) \\
  1148. \Instr &::=& (\key{addq} \; \Arg\; \Arg) \mid
  1149. (\key{subq} \; \Arg\; \Arg) \mid
  1150. (\key{movq} \; \Arg\; \Arg) \mid
  1151. (\key{retq})\\
  1152. &\mid& (\key{negq} \; \Arg) \mid
  1153. (\key{callq} \; \mathit{label}) \mid
  1154. (\key{pushq}\;\Arg) \mid
  1155. (\key{popq}\;\Arg) \\
  1156. \Block &::= & (\key{block} \;\itm{info}\; \Instr^{+}) \\
  1157. x86_0 &::= & (\key{program} \;\itm{info} \; ((\itm{label} \,\key{.}\, \Block)^{+}))
  1158. \end{array}
  1159. \]
  1160. \end{minipage}
  1161. }
  1162. \caption{Abstract syntax for $x86_0$ assembly.}
  1163. \label{fig:x86-ast-a}
  1164. \end{figure}
  1165. \section{Planning the trip to x86 via the $C_0$ language}
  1166. \label{sec:plan-s0-x86}
  1167. To compile one language to another it helps to focus on the
  1168. differences between the two languages because the compiler will need
  1169. to bridge them. What are the differences between $R_1$ and x86
  1170. assembly? Here we list some of the most important ones.
  1171. \begin{enumerate}
  1172. \item[(a)] x86 arithmetic instructions typically have two arguments
  1173. and update the second argument in place. In contrast, $R_1$
  1174. arithmetic operations take two arguments and produce a new value.
  1175. An x86 instruction may have at most one memory-accessing argument.
  1176. Furthermore, some instructions place special restrictions on their
  1177. arguments.
  1178. \item[(b)] An argument to an $R_1$ operator can be any expression,
  1179. whereas x86 instructions restrict their arguments to be \emph{simple
  1180. expressions} like integers, registers, and memory locations. (All
  1181. the other kinds are called \emph{complex expressions}.)
  1182. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1183. sequence of instructions and jumps to labeled positions, whereas in
  1184. $R_1$ it is a left-to-right depth-first traversal of the abstract
  1185. syntax tree.
  1186. \item[(d)] An $R_1$ program can have any number of variables whereas
  1187. x86 has 16 registers and the procedure calls stack.
  1188. \item[(e)] Variables in $R_1$ can overshadow other variables with the
  1189. same name. The registers and memory locations of x86 all have unique
  1190. names or addresses.
  1191. \end{enumerate}
  1192. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1193. the problem into several steps, dealing with the above differences one
  1194. at a time. Each of these steps is called a \emph{pass} of the
  1195. compiler, because step traverses (passes over) the AST of the program.
  1196. %
  1197. We begin by giving a sketch about how we might implement each pass,
  1198. and give them names. We shall then figure out an ordering of the
  1199. passes and the input/output language for each pass. The very first
  1200. pass has $R_1$ as its input language and the last pass has x86 as its
  1201. output language. In between we can choose whichever language is most
  1202. convenient for expressing the output of each pass, whether that be
  1203. $R_1$, x86, or new \emph{intermediate languages} of our own design.
  1204. Finally, to implement the compiler, we shall write one function,
  1205. typically a structural recursive function, per pass.
  1206. \begin{description}
  1207. \item[Pass \key{select-instructions}] To handle the difference between
  1208. $R_1$ operations and x86 instructions we shall convert each $R_1$
  1209. operation to a short sequence of instructions that accomplishes the
  1210. same task.
  1211. \item[Pass \key{remove-complex-opera*}] To ensure that each
  1212. subexpression (i.e. operator and operand, and hence \key{opera*}) is
  1213. a simple expression, we shall introduce temporary variables to hold
  1214. the results of subexpressions.
  1215. \item[Pass \key{explicate-control}] To make the execution order of the
  1216. program explicit, we shall convert from the abstract syntax tree
  1217. representation into a graph representation in which each node
  1218. contains a sequence of actions and the edges say where to go after
  1219. the sequence is complete.
  1220. \item[Pass \key{assign-homes}] To handle the difference between the
  1221. variables in $R_1$ versus the registers and stack location in x86,
  1222. we shall come up with an assignment of each variable to its
  1223. \emph{home}, that is, to a register or stack location.
  1224. \item[Pass \key{uniquify}] This pass deals with the shadowing of variables
  1225. by renaming every variable to a unique name, so that shadowing no
  1226. longer occurs.
  1227. \end{description}
  1228. The next question is: in what order should we apply these passes? This
  1229. question can be a challenging one to answer because it is difficult to
  1230. know ahead of time which orders will be better (easier to implement,
  1231. produce more efficient code, etc.) so often some trial-and-error is
  1232. involved. Nevertheless, we can try to plan ahead and make educated
  1233. choices regarding the orderings.
  1234. Let us consider the ordering of \key{uniquify} and
  1235. \key{remove-complex-opera*}. The assignment of subexpressions to
  1236. temporary variables involves introducing new variables and moving
  1237. subexpressions, which might change the shadowing of variables and
  1238. inadvertently change the behavior of the program. But if we apply
  1239. \key{uniquify} first, this will not be an issue. Of course, this means
  1240. that in \key{remove-complex-opera*}, we need to ensure that the
  1241. temporary variables that it creates are unique.
  1242. Next we shall consider the ordering of the \key{explicate-control}
  1243. pass and \key{select-instructions}. It is clear that
  1244. \key{explicate-control} must come first because the control-flow graph
  1245. that it generates is needed when determining where to place the x86
  1246. label and jump instructions.
  1247. %
  1248. Regarding the ordering of \key{explicate-control} with respect to
  1249. \key{uniquify}, it is important to apply \key{uniquify} first because
  1250. in \key{explicate-control} we change all the \key{let}-bound variables
  1251. to become local variables whose scope is the entire program.
  1252. %
  1253. With respect to \key{remove-complex-opera*}, it perhaps does not
  1254. matter very much, but it works well to place \key{explicate-control}
  1255. after removing complex subexpressions.
  1256. The \key{assign-homes} pass should come after
  1257. \key{remove-complex-opera*} and \key{explicate-control}. The
  1258. \key{remove-complex-opera*} pass generates temporary variables, which
  1259. also need to be assigned homes. The \key{explicate-control} pass
  1260. deletes branches that will never be executed, which can remove
  1261. variables. Thus it is good to place \key{explicate-control} prior to
  1262. \key{assign-homes} so that there are fewer variables that need to be
  1263. assigned homes. This is important because the \key{assign-homes} pass
  1264. has the highest time complexity.
  1265. Last, we need to decide on the ordering of \key{select-instructions}
  1266. and \key{assign-homes}. These two issues are intertwined, creating a
  1267. bit of a Gordian Knot. To do a good job of assigning homes, it is
  1268. helpful to have already determined which instructions will be used,
  1269. because x86 instructions have restrictions about which of their
  1270. arguments can be registers versus stack locations. For example, one
  1271. can give preferential treatment to variables that occur in
  1272. register-argument positions. On the other hand, it may turn out to be
  1273. impossible to make sure that all such variables are assigned to
  1274. registers, and then one must redo the selection of instructions. Some
  1275. compilers handle this problem by iteratively repeating these two
  1276. passes until a good solution is found. We shall use a simpler
  1277. approach in which \key{select-instructions} comes first, followed by
  1278. the \key{assign-homes}, followed by a third pass, named
  1279. \key{patch-instructions}, that uses a reserved register (\key{rax}) to
  1280. patch-up outstanding problems regarding instructions with too many
  1281. memory accesses.
  1282. \begin{figure}[tbp]
  1283. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1284. \node (R1) at (0,2) {\large $R_1$};
  1285. \node (R1-2) at (3,2) {\large $R_1$};
  1286. \node (R1-3) at (6,2) {\large $R_1$};
  1287. \node (C0-1) at (6,0) {\large $C_0$};
  1288. \node (C0-2) at (3,0) {\large $C_0$};
  1289. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_0$};
  1290. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_0$};
  1291. \node (x86-4) at (9,-2) {\large $\text{x86}_0$};
  1292. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}_0$};
  1293. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1294. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  1295. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  1296. \path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  1297. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1298. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1299. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1300. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1301. \end{tikzpicture}
  1302. \caption{Overview of the passes for compiling $R_1$. }
  1303. \label{fig:R1-passes}
  1304. \end{figure}
  1305. Figure~\ref{fig:R1-passes} presents the ordering of the compiler
  1306. passes in the form of a graph. Each pass is an edge and the
  1307. input/output language of each pass is a node in the graph. The output
  1308. of \key{uniquify} and \key{remove-complex-opera*} are programs that
  1309. are still in the $R_1$ language, but the output of the pass
  1310. \key{explicate-control} is in a different language that is designed to
  1311. make the order of evaluation explicit in its syntax, which we
  1312. introduce in the next section. Also, there are two passes of lesser
  1313. importance in Figure~\ref{fig:R1-passes} that we have not yet talked
  1314. about, \key{uncover-locals} and \key{print-x86}. We shall discuss them
  1315. later in this Chapter.
  1316. \subsection{The $C_0$ Intermediate Language}
  1317. It so happens that the output of \key{explicate-control} is vaguely
  1318. similar to the $C$ language~\citep{Kernighan:1988nx}, so we name it
  1319. $C_0$. The syntax for $C_0$ is defined in Figure~\ref{fig:c0-syntax}.
  1320. %
  1321. The $C_0$ language supports the same operators as $R_1$ but the
  1322. arguments of operators are now restricted to just variables and
  1323. integers, thanks to the \key{remove-complex-opera*} pass. In the
  1324. literature this style of intermediate language is called
  1325. administrative normal form, or ANF for
  1326. short~\citep{Danvy:1991fk,Flanagan:1993cg}. Instead of \key{let}
  1327. expressions, $C_0$ has assignment statements which can be executed in
  1328. sequence using the \key{seq} construct. A sequence of statements
  1329. always ends with \key{return}, a guarantee that is baked into the
  1330. grammar rules for the \itm{tail} non-terminal. The naming of this
  1331. non-terminal comes from the term \emph{tail position}, which refers to
  1332. an expression that is the last one to execute within a function. (A
  1333. expression in tail position may contain subexpressions, and those may
  1334. or may not be in tail position depending on the kind of expression.)
  1335. A $C_0$ program consists of an association list mapping labels to
  1336. tails. This is overkill for the present Chapter, as we do not yet need
  1337. to introduce \key{goto} for jumping to labels, but it saves us from
  1338. having to change the syntax of the program construct in
  1339. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1340. \key{start}, and the whole program will be it's tail.
  1341. %
  1342. The $\itm{info}$ field of the program construt, after the
  1343. \key{uncover-locals} pass, will contain a mapping from the symbol
  1344. \key{locals} to a list of variables, that is, a list of all the
  1345. variables used in the program. At the start of the program, these
  1346. variables are uninitialized (they contain garbage) and each variable
  1347. becomes initialized on its first assignment.
  1348. \begin{figure}[tbp]
  1349. \fbox{
  1350. \begin{minipage}{0.96\textwidth}
  1351. \[
  1352. \begin{array}{lcl}
  1353. \Arg &::=& \Int \mid \Var \\
  1354. \Exp &::=& \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)\\
  1355. \Stmt &::=& \ASSIGN{\Var}{\Exp} \\
  1356. \Tail &::= & \RETURN{\Exp} \mid (\key{seq}\; \Stmt\; \Tail) \\
  1357. C_0 & ::= & (\key{program}\;\itm{info}\;((\itm{label}\,\key{.}\,\Tail)^{+}))
  1358. \end{array}
  1359. \]
  1360. \end{minipage}
  1361. }
  1362. \caption{The $C_0$ intermediate language.}
  1363. \label{fig:c0-syntax}
  1364. \end{figure}
  1365. %% The \key{select-instructions} pass is optimistic in the sense that it
  1366. %% treats variables as if they were all mapped to registers. The
  1367. %% \key{select-instructions} pass generates a program that consists of
  1368. %% x86 instructions but that still uses variables, so it is an
  1369. %% intermediate language that is technically different than x86, which
  1370. %% explains the asterisks in the diagram above.
  1371. %% In this Chapter we shall take the easy road to implementing
  1372. %% \key{assign-homes} and simply map all variables to stack locations.
  1373. %% The topic of Chapter~\ref{ch:register-allocation-r1} is implementing a
  1374. %% smarter approach in which we make a best-effort to map variables to
  1375. %% registers, resorting to the stack only when necessary.
  1376. %% Once variables have been assigned to their homes, we can finalize the
  1377. %% instruction selection by dealing with an idiosyncrasy of x86
  1378. %% assembly. Many x86 instructions have two arguments but only one of the
  1379. %% arguments may be a memory reference (and the stack is a part of
  1380. %% memory). Because some variables may get mapped to stack locations,
  1381. %% some of our generated instructions may violate this restriction. The
  1382. %% purpose of the \key{patch-instructions} pass is to fix this problem by
  1383. %% replacing every violating instruction with a short sequence of
  1384. %% instructions that use the \key{rax} register. Once we have implemented
  1385. %% a good register allocator (Chapter~\ref{ch:register-allocation-r1}), the
  1386. %% need to patch instructions will be relatively rare.
  1387. \subsection{The dialects of x86}
  1388. The x86$^{*}_0$ language, pronounced ``pseudo-x86'', is the output of
  1389. the pass \key{select-instructions}. It extends $x86_0$ with variables
  1390. and looser rules regarding instruction arguments. The x86$^{\dagger}$
  1391. language, the output of \key{print-x86}, is the concrete syntax for
  1392. x86.
  1393. \section{Uniquify Variables}
  1394. \label{sec:uniquify-s0}
  1395. The purpose of this pass is to make sure that each \key{let} uses a
  1396. unique variable name. For example, the \code{uniquify} pass should
  1397. translate the program on the left into the program on the right. \\
  1398. \begin{tabular}{lll}
  1399. \begin{minipage}{0.4\textwidth}
  1400. \begin{lstlisting}
  1401. (program ()
  1402. (let ([x 32])
  1403. (+ (let ([x 10]) x) x)))
  1404. \end{lstlisting}
  1405. \end{minipage}
  1406. &
  1407. $\Rightarrow$
  1408. &
  1409. \begin{minipage}{0.4\textwidth}
  1410. \begin{lstlisting}
  1411. (program ()
  1412. (let ([x.1 32])
  1413. (+ (let ([x.2 10]) x.2) x.1)))
  1414. \end{lstlisting}
  1415. \end{minipage}
  1416. \end{tabular} \\
  1417. %
  1418. The following is another example translation, this time of a program
  1419. with a \key{let} nested inside the initializing expression of another
  1420. \key{let}.\\
  1421. \begin{tabular}{lll}
  1422. \begin{minipage}{0.4\textwidth}
  1423. \begin{lstlisting}
  1424. (program ()
  1425. (let ([x (let ([x 4])
  1426. (+ x 1))])
  1427. (+ x 2)))
  1428. \end{lstlisting}
  1429. \end{minipage}
  1430. &
  1431. $\Rightarrow$
  1432. &
  1433. \begin{minipage}{0.4\textwidth}
  1434. \begin{lstlisting}
  1435. (program ()
  1436. (let ([x.2 (let ([x.1 4])
  1437. (+ x.1 1))])
  1438. (+ x.2 2)))
  1439. \end{lstlisting}
  1440. \end{minipage}
  1441. \end{tabular}
  1442. We recommend implementing \code{uniquify} as a structurally recursive
  1443. function that mostly copies the input program. However, when
  1444. encountering a \key{let}, it should generate a unique name for the
  1445. variable (the Racket function \code{gensym} is handy for this) and
  1446. associate the old name with the new unique name in an association
  1447. list. The \code{uniquify} function will need to access this
  1448. association list when it gets to a variable reference, so we add
  1449. another parameter to \code{uniquify} for the association list. It is
  1450. quite common for a compiler pass to need a map to store extra
  1451. information about variables. Such maps are often called \emph{symbol
  1452. tables}.
  1453. The skeleton of the \code{uniquify} function is shown in
  1454. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1455. convenient to partially apply it to an association list and then apply
  1456. it to different expressions, as in the last clause for primitive
  1457. operations in Figure~\ref{fig:uniquify-s0}. In the last \key{match}
  1458. clause for the primitive operators, note the use of the comma-@
  1459. operator to splice a list of S-expressions into an enclosing
  1460. S-expression.
  1461. \begin{exercise}
  1462. \normalfont % I don't like the italics for exercises. -Jeremy
  1463. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1464. implement the clauses for variables and for the \key{let} construct.
  1465. \end{exercise}
  1466. \begin{figure}[tbp]
  1467. \begin{lstlisting}
  1468. (define (uniquify-exp alist)
  1469. (lambda (e)
  1470. (match e
  1471. [(? symbol?) ___]
  1472. [(? integer?) e]
  1473. [`(let ([,x ,e]) ,body) ___]
  1474. [`(,op ,es ...)
  1475. `(,op ,@(for/list ([e es]) ((uniquify-exp alist) e)))]
  1476. )))
  1477. (define (uniquify alist)
  1478. (lambda (e)
  1479. (match e
  1480. [`(program ,info ,e)
  1481. `(program ,info ,((uniquify-exp alist) e))]
  1482. )))
  1483. \end{lstlisting}
  1484. \caption{Skeleton for the \key{uniquify} pass.}
  1485. \label{fig:uniquify-s0}
  1486. \end{figure}
  1487. \begin{exercise}
  1488. \normalfont % I don't like the italics for exercises. -Jeremy
  1489. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1490. and checking whether the output programs produce the same result as
  1491. the input programs. The $R_1$ programs should be designed to test the
  1492. most interesting parts of the \key{uniquify} pass, that is, the
  1493. programs should include \key{let} constructs, variables, and variables
  1494. that overshadow each other. The five programs should be in a
  1495. subdirectory named \key{tests} and they should have the same file name
  1496. except for a different integer at the end of the name, followed by the
  1497. ending \key{.rkt}. Use the \key{interp-tests} function
  1498. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1499. your \key{uniquify} pass on the example programs.
  1500. \end{exercise}
  1501. \section{Remove Complex Operators and Operands}
  1502. \label{sec:remove-complex-opera-r1}
  1503. The \code{remove-complex-opera*} pass will transform $R_1$ programs so
  1504. that the arguments of operations are simple expressions. Put another
  1505. way, this pass removes complex subexpressions, such as the expression
  1506. \code{(- 10)} in the program below. This is accomplished by
  1507. introducing a new \key{let}-bound variable, binding the complex
  1508. subexpression to the new variable, and then using the new variable in
  1509. place of the complex expression, as shown in the output of
  1510. \code{remove-complex-opera*} on the right.\\
  1511. \begin{tabular}{lll}
  1512. \begin{minipage}{0.4\textwidth}
  1513. % s0_19.rkt
  1514. \begin{lstlisting}
  1515. (program ()
  1516. (+ 52 (- 10)))
  1517. \end{lstlisting}
  1518. \end{minipage}
  1519. &
  1520. $\Rightarrow$
  1521. &
  1522. \begin{minipage}{0.4\textwidth}
  1523. \begin{lstlisting}
  1524. (program ()
  1525. (let ([tmp.1 (- 10)])
  1526. (+ 52 tmp.1)))
  1527. \end{lstlisting}
  1528. \end{minipage}
  1529. \end{tabular}
  1530. We recommend implementing this pass with two mutually recursive
  1531. functions, \code{rco-arg} and \code{rco-exp}. The idea is to apply
  1532. \code{rco-arg} to subexpressions that need to become simple and to
  1533. apply \code{rco-exp} to subexpressions can stay complex.
  1534. Both functions take an expression in $R_1$ as input.
  1535. The \code{rco-exp} function returns an expression.
  1536. The \code{rco-arg} function returns two things:
  1537. a simple expression and association list mapping temporary variables
  1538. to complex subexpressions. You can return multiple things from a
  1539. function using Racket's \key{values} form and you can receive multiple
  1540. things from a function call using the \key{define-values} form. If you
  1541. are not familiar with these constructs, the Racket documentation will
  1542. be of help. Also, the \key{for/lists} construct is useful for
  1543. applying a function to each element of a list, in the case where the
  1544. function returns multiple values.
  1545. \begin{tabular}{lll}
  1546. \begin{minipage}{0.4\textwidth}
  1547. \begin{lstlisting}
  1548. (rco-arg `(- 10))
  1549. \end{lstlisting}
  1550. \end{minipage}
  1551. &
  1552. $\Rightarrow$
  1553. &
  1554. \begin{minipage}{0.4\textwidth}
  1555. \begin{lstlisting}
  1556. (values `tmp.1
  1557. `((tmp.1 . (- 10))))
  1558. \end{lstlisting}
  1559. \end{minipage}
  1560. \end{tabular}
  1561. Take special care of programs such as the following that
  1562. \key{let}-bind variables with integers or other variables. It should
  1563. leave them unchanged, as shown in to the program on the right \\
  1564. \begin{tabular}{lll}
  1565. \begin{minipage}{0.4\textwidth}
  1566. \begin{lstlisting}
  1567. (program ()
  1568. (let ([a 42])
  1569. (let ([b a])
  1570. b)))
  1571. \end{lstlisting}
  1572. \end{minipage}
  1573. &
  1574. $\Rightarrow$
  1575. &
  1576. \begin{minipage}{0.4\textwidth}
  1577. \begin{lstlisting}
  1578. (program ()
  1579. (let ([a 42])
  1580. (let ([b a])
  1581. b)))
  1582. \end{lstlisting}
  1583. \end{minipage}
  1584. \end{tabular} \\
  1585. and not translate them to the following, which might result from a
  1586. careless implementation of \key{rco-exp} and \key{rco-arg}.
  1587. \begin{minipage}{0.4\textwidth}
  1588. \begin{lstlisting}
  1589. (program ()
  1590. (let ([tmp.1 42])
  1591. (let ([a tmp.1])
  1592. (let ([tmp.2 a])
  1593. (let ([b tmp.2])
  1594. b)))))
  1595. \end{lstlisting}
  1596. \end{minipage}
  1597. \begin{exercise}
  1598. \normalfont Implement the \code{remove-complex-opera*} pass and test
  1599. it on all of the example programs that you created to test the
  1600. \key{uniquify} pass and create three new example programs that are
  1601. designed to exercise all of the interesting code in the
  1602. \code{remove-complex-opera*} pass. Use the \key{interp-tests} function
  1603. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1604. your passes on the example programs.
  1605. \end{exercise}
  1606. \section{Explicate Control}
  1607. \label{sec:explicate-control-r1}
  1608. The \code{explicate-control} pass makes the order of execution
  1609. explicit in the syntax of the program. For $R_1$, this amounts to
  1610. flattening \key{let} constructs into a sequence of assignment
  1611. statements. For example, consider the following $R_1$ program.
  1612. % s0_11.rkt
  1613. \begin{lstlisting}
  1614. (program ()
  1615. (let ([y (let ([x 20])
  1616. (+ x (let ([x 22]) x)))])
  1617. y))
  1618. \end{lstlisting}
  1619. %
  1620. The output of \code{remove-complex-opera*} is shown below, on the
  1621. left. The right-hand-side of a \key{let} executes before its body, so
  1622. the order of evaluation for this program is to assign \code{20} to
  1623. \code{x.1}, assign \code{22} to \code{x.2}, assign \code{(+ x.1 x.2)}
  1624. to \code{y}, then return \code{y}. Indeed, the result of
  1625. \code{explicate-control} produces code in the $C_0$ language that
  1626. makes this explicit.\\
  1627. \begin{tabular}{lll}
  1628. \begin{minipage}{0.4\textwidth}
  1629. \begin{lstlisting}
  1630. (program ()
  1631. (let ([y (let ([x.1 20])
  1632. (let ([x.2 22])
  1633. (+ x.1 x.2)))])
  1634. y))
  1635. \end{lstlisting}
  1636. \end{minipage}
  1637. &
  1638. $\Rightarrow$
  1639. &
  1640. \begin{minipage}{0.4\textwidth}
  1641. \begin{lstlisting}
  1642. (program ()
  1643. ((start .
  1644. (seq (assign x.1 20)
  1645. (seq (assign x.2 22)
  1646. (seq (assign y (+ x.1 x.2))
  1647. (return y)))))))
  1648. \end{lstlisting}
  1649. \end{minipage}
  1650. \end{tabular}
  1651. We recommend implementing \code{explicate-control} using two mutually
  1652. recursive functions: \code{explicate-control-tail} and
  1653. \code{explicate-control-assign}. The \code{explicate-control-tail}
  1654. function should be applied to expressions in tail position, whereas
  1655. \code{explicate-control-assign} should be applied to expressions that
  1656. occur on the right-hand-side of a \code{let}. The function
  1657. \code{explicate-control-tail} takes an $R_1$ expression as input and
  1658. produces a $C_0$ $\Tail$ (see the grammar in
  1659. Figure~\ref{fig:c0-syntax}). The \code{explicate-control-assign}
  1660. function takes an $R_1$ expression, the variable that it is to be
  1661. assigned to, and $C_0$ code (a $\Tail$) that should come after the
  1662. assignment (e.g., the code generated for the body of the \key{let}).
  1663. \section{Uncover Locals}
  1664. \label{sec:uncover-locals-r1}
  1665. The pass \code{uncover-locals} simply collects all of the variables in
  1666. the program and places then in the $\itm{info}$ of the program
  1667. construct. Here is the output for the example program of the last
  1668. section.
  1669. \begin{minipage}{0.4\textwidth}
  1670. \begin{lstlisting}
  1671. (program ((locals . (x.1 x.2 y)))
  1672. ((start .
  1673. (seq (assign x.1 20)
  1674. (seq (assign x.2 22)
  1675. (seq (assign y (+ x.1 x.2))
  1676. (return y)))))))
  1677. \end{lstlisting}
  1678. \end{minipage}
  1679. \section{Select Instructions}
  1680. \label{sec:select-r1}
  1681. In the \code{select-instructions} pass we begin the work of
  1682. translating from $C_0$ to x86. The target language of this pass is a
  1683. pseudo-x86 language that still uses variables, so we add an AST node
  1684. of the form $\VAR{\itm{var}}$ to the x86 abstract syntax. We
  1685. recommend implementing the \code{select-instructions} in terms of
  1686. three auxilliary functions, one for each of the non-terminals of
  1687. $C_0$: $\Arg$, $\Stmt$, and $\Tail$.
  1688. The cases for $\itm{arg}$ are straightforward, simply putting
  1689. variables and integer literals into the s-expression format expected
  1690. of pseudo-x86, \code{(var $x$)} and \code{(int $n$)}, respectively.
  1691. Next we discuss some of the cases for $\itm{stmt}$, starting with
  1692. arithmetic operations. For example, in $C_0$ an addition operation can
  1693. take the form below. To translate to x86, we need to use the
  1694. \key{addq} instruction which does an in-place update. So we must first
  1695. move \code{10} to \code{x}. \\
  1696. \begin{tabular}{lll}
  1697. \begin{minipage}{0.4\textwidth}
  1698. \begin{lstlisting}
  1699. (assign x (+ 10 32))
  1700. \end{lstlisting}
  1701. \end{minipage}
  1702. &
  1703. $\Rightarrow$
  1704. &
  1705. \begin{minipage}{0.4\textwidth}
  1706. \begin{lstlisting}
  1707. (movq (int 10) (var x))
  1708. (addq (int 32) (var x))
  1709. \end{lstlisting}
  1710. \end{minipage}
  1711. \end{tabular} \\
  1712. %
  1713. There are some cases that require special care to avoid generating
  1714. needlessly complicated code. If one of the arguments is the same as
  1715. the left-hand side of the assignment, then there is no need for the
  1716. extra move instruction. For example, the following assignment
  1717. statement can be translated into a single \key{addq} instruction.\\
  1718. \begin{tabular}{lll}
  1719. \begin{minipage}{0.4\textwidth}
  1720. \begin{lstlisting}
  1721. (assign x (+ 10 x))
  1722. \end{lstlisting}
  1723. \end{minipage}
  1724. &
  1725. $\Rightarrow$
  1726. &
  1727. \begin{minipage}{0.4\textwidth}
  1728. \begin{lstlisting}
  1729. (addq (int 10) (var x))
  1730. \end{lstlisting}
  1731. \end{minipage}
  1732. \end{tabular} \\
  1733. The \key{read} operation does not have a direct counterpart in x86
  1734. assembly, so we have instead implemented this functionality in the C
  1735. language, with the function \code{read\_int} in the file
  1736. \code{runtime.c}. In general, we refer to all of the functionality in
  1737. this file as the \emph{runtime system}, or simply the \emph{runtime}
  1738. for short. When compiling your generated x86 assembly code, you
  1739. will need to compile \code{runtime.c} to \code{runtime.o} (an ``object
  1740. file'', using \code{gcc} option \code{-c}) and link it into the final
  1741. executable. For our purposes of code generation, all you need to do is
  1742. translate an assignment of \key{read} to some variable $\itm{lhs}$
  1743. (for left-hand side) into a call to the \code{read\_int} function
  1744. followed by a move from \code{rax} to the left-hand side. The move
  1745. from \code{rax} is needed because the return value from
  1746. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  1747. \begin{tabular}{lll}
  1748. \begin{minipage}{0.4\textwidth}
  1749. \begin{lstlisting}
  1750. (assign |$\itm{lhs}$| (read))
  1751. \end{lstlisting}
  1752. \end{minipage}
  1753. &
  1754. $\Rightarrow$
  1755. &
  1756. \begin{minipage}{0.4\textwidth}
  1757. \begin{lstlisting}
  1758. (callq read_int)
  1759. (movq (reg rax) (var |$\itm{lhs}$|))
  1760. \end{lstlisting}
  1761. \end{minipage}
  1762. \end{tabular} \\
  1763. There are two cases for the $\Tail$ non-terminal: \key{return} and
  1764. \key{seq}. Regarding \RETURN{e}, we recommend treating it as an
  1765. assignment to the \key{rax} register followed by a jump to the
  1766. conclusion of the program (so the conclusion needs to be labeled).
  1767. For $(\key{seq}\,s\,t)$, we simply process the statement $s$ and tail
  1768. $t$ recursively and append the resulting instructions.
  1769. \begin{exercise}
  1770. \normalfont
  1771. Implement the \key{select-instructions} pass and test it on all of the
  1772. example programs that you created for the previous passes and create
  1773. three new example programs that are designed to exercise all of the
  1774. interesting code in this pass. Use the \key{interp-tests} function
  1775. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1776. your passes on the example programs.
  1777. \end{exercise}
  1778. \section{Assign Homes}
  1779. \label{sec:assign-r1}
  1780. As discussed in Section~\ref{sec:plan-s0-x86}, the
  1781. \key{assign-homes} pass places all of the variables on the stack.
  1782. Consider again the example $R_1$ program \code{(+ 52 (- 10))},
  1783. which after \key{select-instructions} looks like the following.
  1784. \begin{lstlisting}
  1785. (movq (int 10) (var tmp.1))
  1786. (negq (var tmp.1))
  1787. (movq (var tmp.1) (var tmp.2))
  1788. (addq (int 52) (var tmp.2))
  1789. (movq (var tmp.2) (reg rax)))
  1790. \end{lstlisting}
  1791. The variable \code{tmp.1} is assigned to stack location
  1792. \code{-8(\%rbp)}, and \code{tmp.2} is assign to \code{-16(\%rbp)}, so
  1793. the \code{assign-homes} pass translates the above to
  1794. \begin{lstlisting}
  1795. (movq (int 10) (deref rbp -8))
  1796. (negq (deref rbp -8))
  1797. (movq (deref rbp -8) (deref rbp -16))
  1798. (addq (int 52) (deref rbp -16))
  1799. (movq (deref rbp -16) (reg rax)))
  1800. \end{lstlisting}
  1801. In the process of assigning stack locations to variables, it is
  1802. convenient to compute and store the size of the frame (in bytes) in
  1803. the $\itm{info}$ field of the \key{program} node, with the key
  1804. \code{stack-space}, which will be needed later to generate the
  1805. procedure conclusion. Some operating systems place restrictions on
  1806. the frame size. For example, Mac OS X requires the frame size to be a
  1807. multiple of 16 bytes.
  1808. \begin{exercise}
  1809. \normalfont Implement the \key{assign-homes} pass and test it on all
  1810. of the example programs that you created for the previous passes pass.
  1811. We recommend that \key{assign-homes} take an extra parameter that is a
  1812. mapping of variable names to homes (stack locations for now). Use the
  1813. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  1814. \key{utilities.rkt} to test your passes on the example programs.
  1815. \end{exercise}
  1816. \section{Patch Instructions}
  1817. \label{sec:patch-s0}
  1818. The purpose of this pass is to make sure that each instruction adheres
  1819. to the restrictions regarding which arguments can be memory
  1820. references. For most instructions, the rule is that at most one
  1821. argument may be a memory reference.
  1822. Consider again the following example.
  1823. \begin{lstlisting}
  1824. (let ([a 42])
  1825. (let ([b a])
  1826. b))
  1827. \end{lstlisting}
  1828. After \key{assign-homes} pass, the above has been translated to
  1829. \begin{lstlisting}
  1830. (movq (int 42) (deref rbp -8))
  1831. (movq (deref rbp -8) (deref rbp -16))
  1832. (movq (deref rbp -16) (reg rax))
  1833. (jmp conclusion)
  1834. \end{lstlisting}
  1835. The second \key{movq} instruction is problematic because both
  1836. arguments are stack locations. We suggest fixing this problem by
  1837. moving from the source to the register \key{rax} and then from
  1838. \key{rax} to the destination, as follows.
  1839. \begin{lstlisting}
  1840. (movq (int 42) (deref rbp -8))
  1841. (movq (deref rbp -8) (reg rax))
  1842. (movq (reg rax) (deref rbp -16))
  1843. (movq (deref rbp -16) (reg rax))
  1844. \end{lstlisting}
  1845. \begin{exercise}
  1846. \normalfont
  1847. Implement the \key{patch-instructions} pass and test it on all of the
  1848. example programs that you created for the previous passes and create
  1849. three new example programs that are designed to exercise all of the
  1850. interesting code in this pass. Use the \key{interp-tests} function
  1851. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1852. your passes on the example programs.
  1853. \end{exercise}
  1854. \section{Print x86}
  1855. \label{sec:print-x86}
  1856. The last step of the compiler from $R_1$ to x86 is to convert the x86
  1857. AST (defined in Figure~\ref{fig:x86-ast-a}) to the string
  1858. representation (defined in Figure~\ref{fig:x86-a}). The Racket
  1859. \key{format} and \key{string-append} functions are useful in this
  1860. regard. The main work that this step needs to perform is to create the
  1861. \key{main} function and the standard instructions for its prelude and
  1862. conclusion, as shown in Figure~\ref{fig:p1-x86} of
  1863. Section~\ref{sec:x86}. You need to know the number of stack-allocated
  1864. variables, so we suggest computing it in the \key{assign-homes} pass
  1865. (Section~\ref{sec:assign-r1}) and storing it in the $\itm{info}$ field
  1866. of the \key{program} node.
  1867. %% Your compiled code should print the result of the program's execution
  1868. %% by using the \code{print\_int} function provided in
  1869. %% \code{runtime.c}. If your compiler has been implemented correctly so
  1870. %% far, this final result should be stored in the \key{rax} register.
  1871. %% We'll talk more about how to perform function calls with arguments in
  1872. %% general later on, but for now, place the following after the compiled
  1873. %% code for the $R_1$ program but before the conclusion:
  1874. %% \begin{lstlisting}
  1875. %% movq %rax, %rdi
  1876. %% callq print_int
  1877. %% \end{lstlisting}
  1878. %% These lines move the value in \key{rax} into the \key{rdi} register, which
  1879. %% stores the first argument to be passed into \key{print\_int}.
  1880. If you want your program to run on Mac OS X, your code needs to
  1881. determine whether or not it is running on a Mac, and prefix
  1882. underscores to labels like \key{main}. You can determine the platform
  1883. with the Racket call \code{(system-type 'os)}, which returns
  1884. \code{'macosx}, \code{'unix}, or \code{'windows}.
  1885. %% In addition to
  1886. %% placing underscores on \key{main}, you need to put them in front of
  1887. %% \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  1888. %% \_print\_int}).
  1889. \begin{exercise}
  1890. \normalfont Implement the \key{print-x86} pass and test it on all of
  1891. the example programs that you created for the previous passes. Use the
  1892. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  1893. \key{utilities.rkt} to test your complete compiler on the example
  1894. programs.
  1895. % The following is specific to P423/P523. -Jeremy
  1896. %Mac support is optional, but your compiler has to output
  1897. %valid code for Unix machines.
  1898. \end{exercise}
  1899. \margincomment{\footnotesize To do: add a challenge section. Perhaps
  1900. extending the partial evaluation to $R_0$? \\ --Jeremy}
  1901. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1902. \chapter{Register Allocation}
  1903. \label{ch:register-allocation-r1}
  1904. In Chapter~\ref{ch:int-exp} we simplified the generation of x86
  1905. assembly by placing all variables on the stack. We can improve the
  1906. performance of the generated code considerably if we instead place as
  1907. many variables as possible into registers. The CPU can access a
  1908. register in a single cycle, whereas accessing the stack takes many
  1909. cycles to go to cache or many more to access main memory.
  1910. Figure~\ref{fig:reg-eg} shows a program with four variables that
  1911. serves as a running example. We show the source program and also the
  1912. output of instruction selection. At that point the program is almost
  1913. x86 assembly but not quite; it still contains variables instead of
  1914. stack locations or registers.
  1915. \begin{figure}
  1916. \begin{minipage}{0.45\textwidth}
  1917. $R_1$ program:
  1918. % s0_22.rkt
  1919. \begin{lstlisting}
  1920. (program ()
  1921. (let ([v 1])
  1922. (let ([w 46])
  1923. (let ([x (+ v 7)])
  1924. (let ([y (+ 4 x)])
  1925. (let ([z (+ x w)])
  1926. (+ z (- y))))))))
  1927. \end{lstlisting}
  1928. \end{minipage}
  1929. \begin{minipage}{0.45\textwidth}
  1930. After instruction selection:
  1931. \begin{lstlisting}
  1932. (program
  1933. ((locals . (v w x y z t.1)))
  1934. ((start .
  1935. (block ()
  1936. (movq (int 1) (var v))
  1937. (movq (int 46) (var w))
  1938. (movq (var v) (var x))
  1939. (addq (int 7) (var x))
  1940. (movq (var x) (var y))
  1941. (addq (int 4) (var y))
  1942. (movq (var x) (var z))
  1943. (addq (var w) (var z))
  1944. (movq (var y) (var t.1))
  1945. (negq (var t.1))
  1946. (movq (var z) (reg rax))
  1947. (addq (var t.1) (reg rax))
  1948. (jmp conclusion)))))
  1949. \end{lstlisting}
  1950. \end{minipage}
  1951. \caption{An example program for register allocation.}
  1952. \label{fig:reg-eg}
  1953. \end{figure}
  1954. The goal of register allocation is to fit as many variables into
  1955. registers as possible. It is often the case that we have more
  1956. variables than registers, so we cannot map each variable to a
  1957. different register. Fortunately, it is common for different variables
  1958. to be needed during different periods of time, and in such cases
  1959. several variables can be mapped to the same register. Consider
  1960. variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}. After the
  1961. variable \code{x} is moved to \code{z} it is no longer needed.
  1962. Variable \code{y}, on the other hand, is used only after this point,
  1963. so \code{x} and \code{y} could share the same register. The topic of
  1964. Section~\ref{sec:liveness-analysis-r1} is how we compute where a variable
  1965. is needed. Once we have that information, we compute which variables
  1966. are needed at the same time, i.e., which ones \emph{interfere}, and
  1967. represent this relation as graph whose vertices are variables and
  1968. edges indicate when two variables interfere with eachother
  1969. (Section~\ref{sec:build-interference}). We then model register
  1970. allocation as a graph coloring problem, which we discuss in
  1971. Section~\ref{sec:graph-coloring}.
  1972. In the event that we run out of registers despite these efforts, we
  1973. place the remaining variables on the stack, similar to what we did in
  1974. Chapter~\ref{ch:int-exp}. It is common to say that when a variable
  1975. that is assigned to a stack location, it has been \emph{spilled}. The
  1976. process of spilling variables is handled as part of the graph coloring
  1977. process described in \ref{sec:graph-coloring}.
  1978. \section{Registers and Calling Conventions}
  1979. \label{sec:calling-conventions}
  1980. As we perform register allocation, we will need to be aware of the
  1981. conventions that govern the way in which registers interact with
  1982. function calls. The convention for x86 is that the caller is
  1983. responsible for freeing up some registers, the \emph{caller-saved
  1984. registers}, prior to the function call, and the callee is
  1985. responsible for saving and restoring some other registers, the
  1986. \emph{callee-saved registers}, before and after using them. The
  1987. caller-saved registers are
  1988. \begin{lstlisting}
  1989. rax rdx rcx rsi rdi r8 r9 r10 r11
  1990. \end{lstlisting}
  1991. while the callee-saved registers are
  1992. \begin{lstlisting}
  1993. rsp rbp rbx r12 r13 r14 r15
  1994. \end{lstlisting}
  1995. Another way to think about this caller/callee convention is the
  1996. following. The caller should assume that all the caller-saved registers
  1997. get overwritten with arbitrary values by the callee. On the other
  1998. hand, the caller can safely assume that all the callee-saved registers
  1999. contain the same values after the call that they did before the call.
  2000. The callee can freely use any of the caller-saved registers. However,
  2001. if the callee wants to use a callee-saved register, the callee must
  2002. arrange to put the original value back in the register prior to
  2003. returning to the caller, which is usually accomplished by saving and
  2004. restoring the value from the stack.
  2005. \section{Liveness Analysis}
  2006. \label{sec:liveness-analysis-r1}
  2007. A variable is \emph{live} if the variable is used at some later point
  2008. in the program and there is not an intervening assignment to the
  2009. variable.
  2010. %
  2011. To understand the latter condition, consider the following code
  2012. fragment in which there are two writes to \code{b}. Are \code{a} and
  2013. \code{b} both live at the same time?
  2014. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2015. (movq (int 5) (var a))
  2016. (movq (int 30) (var b))
  2017. (movq (var a) (var c))
  2018. (movq (int 10) (var b))
  2019. (addq (var b) (var c))
  2020. \end{lstlisting}
  2021. The answer is no because the value \code{30} written to \code{b} on
  2022. line 2 is never used. The variable \code{b} is read on line 5 and
  2023. there is an intervening write to \code{b} on line 4, so the read on
  2024. line 5 receives the value written on line 4, not line 2.
  2025. The live variables can be computed by traversing the instruction
  2026. sequence back to front (i.e., backwards in execution order). Let
  2027. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2028. $L_{\mathsf{after}}(k)$ for the set of live variables after
  2029. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2030. variables before instruction $I_k$. The live variables after an
  2031. instruction are always the same as the live variables before the next
  2032. instruction.
  2033. \begin{equation*}
  2034. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2035. \end{equation*}
  2036. To start things off, there are no live variables after the last
  2037. instruction, so
  2038. \begin{equation*}
  2039. L_{\mathsf{after}}(n) = \emptyset
  2040. \end{equation*}
  2041. We then apply the following rule repeatedly, traversing the
  2042. instruction sequence back to front.
  2043. \begin{equation*}
  2044. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2045. \end{equation*}
  2046. where $W(k)$ are the variables written to by instruction $I_k$ and
  2047. $R(k)$ are the variables read by instruction $I_k$.
  2048. Figure~\ref{fig:live-eg} shows the results of live variables analysis
  2049. for the running example, with each instruction aligned with its
  2050. $L_{\mathtt{after}}$ set to make the figure easy to read.
  2051. \margincomment{JM: I think you should walk through the explanation of this formula,
  2052. connecting it back to the example from before. \\
  2053. JS: Agreed.}
  2054. \begin{figure}[tbp]
  2055. \hspace{20pt}
  2056. \begin{minipage}{0.45\textwidth}
  2057. \begin{lstlisting}[numbers=left]
  2058. (block ()
  2059. (movq (int 1) (var v))
  2060. (movq (int 46) (var w))
  2061. (movq (var v) (var x))
  2062. (addq (int 7) (var x))
  2063. (movq (var x) (var y))
  2064. (addq (int 4) (var y))
  2065. (movq (var x) (var z))
  2066. (addq (var w) (var z))
  2067. (movq (var y) (var t.1))
  2068. (negq (var t.1))
  2069. (movq (var z) (reg rax))
  2070. (addq (var t.1) (reg rax))
  2071. (jmp conclusion))
  2072. \end{lstlisting}
  2073. \end{minipage}
  2074. \vrule\hspace{10pt}
  2075. \begin{minipage}{0.45\textwidth}
  2076. \begin{lstlisting}
  2077. |$\{\}$|
  2078. |$\{v \}$|
  2079. |$\{v,w\}$|
  2080. |$\{w,x\}$|
  2081. |$\{w,x\}$|
  2082. |$\{w,x,y\}$|
  2083. |$\{w,x,y\}$|
  2084. |$\{w,y,z\}$|
  2085. |$\{y,z\}$|
  2086. |$\{z,t.1\}$|
  2087. |$\{z,t.1\}$|
  2088. |$\{t.1\}$|
  2089. |$\{\}$|
  2090. |$\{\}$|
  2091. \end{lstlisting}
  2092. \end{minipage}
  2093. \caption{An example block annotated with live-after sets.}
  2094. \label{fig:live-eg}
  2095. \end{figure}
  2096. \begin{exercise}\normalfont
  2097. Implement the compiler pass named \code{uncover-live} that computes
  2098. the live-after sets. We recommend storing the live-after sets (a list
  2099. of lists of variables) in the $\itm{info}$ field of the \key{block}
  2100. construct.
  2101. %
  2102. We recommend organizing your code to use a helper function that takes
  2103. a list of instructions and an initial live-after set (typically empty)
  2104. and returns the list of live-after sets.
  2105. %
  2106. We recommend creating helper functions to 1) compute the set of
  2107. variables that appear in an argument (of an instruction), 2) compute
  2108. the variables read by an instruction which corresponds to the $R$
  2109. function discussed above, and 3) the variables written by an
  2110. instruction which corresponds to $W$.
  2111. \end{exercise}
  2112. \section{Building the Interference Graph}
  2113. \label{sec:build-interference}
  2114. Based on the liveness analysis, we know where each variable is needed.
  2115. However, during register allocation, we need to answer questions of
  2116. the specific form: are variables $u$ and $v$ live at the same time?
  2117. (And therefore cannot be assigned to the same register.) To make this
  2118. question easier to answer, we create an explicit data structure, an
  2119. \emph{interference graph}. An interference graph is an undirected
  2120. graph that has an edge between two variables if they are live at the
  2121. same time, that is, if they interfere with each other.
  2122. The most obvious way to compute the interference graph is to look at
  2123. the set of live variables between each statement in the program, and
  2124. add an edge to the graph for every pair of variables in the same set.
  2125. This approach is less than ideal for two reasons. First, it can be
  2126. rather expensive because it takes $O(n^2)$ time to look at every pair
  2127. in a set of $n$ live variables. Second, there is a special case in
  2128. which two variables that are live at the same time do not actually
  2129. interfere with each other: when they both contain the same value
  2130. because we have assigned one to the other.
  2131. A better way to compute the interference graph is to focus on the
  2132. writes. That is, for each instruction, create an edge between the
  2133. variable being written to and all the \emph{other} live variables.
  2134. (One should not create self edges.) For a \key{callq} instruction,
  2135. think of all caller-saved registers as being written to, so and edge
  2136. must be added between every live variable and every caller-saved
  2137. register. For \key{movq}, we deal with the above-mentioned special
  2138. case by not adding an edge between a live variable $v$ and destination
  2139. $d$ if $v$ matches the source of the move. So we have the following
  2140. three rules.
  2141. \begin{enumerate}
  2142. \item If instruction $I_k$ is an arithmetic instruction such as
  2143. (\key{addq} $s$\, $d$), then add the edge $(d,v)$ for every $v \in
  2144. L_{\mathsf{after}}(k)$ unless $v = d$.
  2145. \item If instruction $I_k$ is of the form (\key{callq}
  2146. $\mathit{label}$), then add an edge $(r,v)$ for every caller-saved
  2147. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2148. \item If instruction $I_k$ is a move: (\key{movq} $s$\, $d$), then add
  2149. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  2150. d$ or $v = s$.
  2151. \end{enumerate}
  2152. \margincomment{JM: I think you could give examples of each one of these
  2153. using the example program and use those to help explain why these
  2154. rules are correct.\\
  2155. JS: Agreed.}
  2156. Working from the top to bottom of Figure~\ref{fig:live-eg}, we obtain
  2157. the following interference for the instruction at the specified line
  2158. number.
  2159. \begin{quote}
  2160. Line 2: no interference,\\
  2161. Line 3: $w$ interferes with $v$,\\
  2162. Line 4: $x$ interferes with $w$,\\
  2163. Line 5: $x$ interferes with $w$,\\
  2164. Line 6: $y$ interferes with $w$,\\
  2165. Line 7: $y$ interferes with $w$ and $x$,\\
  2166. Line 8: $z$ interferes with $w$ and $y$,\\
  2167. Line 9: $z$ interferes with $y$, \\
  2168. Line 10: $t.1$ interferes with $z$, \\
  2169. Line 11: $t.1$ interferes with $z$, \\
  2170. Line 12: no interference, \\
  2171. Line 13: no interference. \\
  2172. Line 14: no interference.
  2173. \end{quote}
  2174. The resulting interference graph is shown in
  2175. Figure~\ref{fig:interfere}.
  2176. \begin{figure}[tbp]
  2177. \large
  2178. \[
  2179. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2180. \node (v) at (0,0) {$v$};
  2181. \node (w) at (2,0) {$w$};
  2182. \node (x) at (4,0) {$x$};
  2183. \node (t1) at (6,-2) {$t.1$};
  2184. \node (y) at (2,-2) {$y$};
  2185. \node (z) at (4,-2) {$z$};
  2186. \draw (v) to (w);
  2187. \foreach \i in {w,x,y}
  2188. {
  2189. \foreach \j in {w,x,y}
  2190. {
  2191. \draw (\i) to (\j);
  2192. }
  2193. }
  2194. \draw (z) to (w);
  2195. \draw (z) to (y);
  2196. \draw (t1) to (z);
  2197. \end{tikzpicture}
  2198. \]
  2199. \caption{The interference graph of the example program.}
  2200. \label{fig:interfere}
  2201. \end{figure}
  2202. %% Our next concern is to choose a data structure for representing the
  2203. %% interference graph. There are many choices for how to represent a
  2204. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2205. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2206. %% data structure is to study the algorithm that uses the data structure,
  2207. %% determine what operations need to be performed, and then choose the
  2208. %% data structure that provide the most efficient implementations of
  2209. %% those operations. Often times the choice of data structure can have an
  2210. %% effect on the time complexity of the algorithm, as it does here. If
  2211. %% you skim the next section, you will see that the register allocation
  2212. %% algorithm needs to ask the graph for all of its vertices and, given a
  2213. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2214. %% correct choice of graph representation is that of an adjacency
  2215. %% list. There are helper functions in \code{utilities.rkt} for
  2216. %% representing graphs using the adjacency list representation:
  2217. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2218. %% (Appendix~\ref{appendix:utilities}).
  2219. %% %
  2220. %% \margincomment{\footnotesize To do: change to use the
  2221. %% Racket graph library. \\ --Jeremy}
  2222. %% %
  2223. %% In particular, those functions use a hash table to map each vertex to
  2224. %% the set of adjacent vertices, and the sets are represented using
  2225. %% Racket's \key{set}, which is also a hash table.
  2226. \begin{exercise}\normalfont
  2227. Implement the compiler pass named \code{build-interference} according
  2228. to the algorithm suggested above. We recommend using the Racket
  2229. \code{graph} package to create and inspect the interference graph.
  2230. The output graph of this pass should be stored in the $\itm{info}$
  2231. field of the program, under the key \code{conflicts}.
  2232. \end{exercise}
  2233. \section{Graph Coloring via Sudoku}
  2234. \label{sec:graph-coloring}
  2235. We now come to the main event, mapping variables to registers (or to
  2236. stack locations in the event that we run out of registers). We need
  2237. to make sure not to map two variables to the same register if the two
  2238. variables interfere with each other. In terms of the interference
  2239. graph, this means that adjacent vertices must be mapped to different
  2240. registers. If we think of registers as colors, the register
  2241. allocation problem becomes the widely-studied graph coloring
  2242. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2243. The reader may be more familiar with the graph coloring problem than he
  2244. or she realizes; the popular game of Sudoku is an instance of the
  2245. graph coloring problem. The following describes how to build a graph
  2246. out of an initial Sudoku board.
  2247. \begin{itemize}
  2248. \item There is one vertex in the graph for each Sudoku square.
  2249. \item There is an edge between two vertices if the corresponding squares
  2250. are in the same row, in the same column, or if the squares are in
  2251. the same $3\times 3$ region.
  2252. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2253. \item Based on the initial assignment of numbers to squares in the
  2254. Sudoku board, assign the corresponding colors to the corresponding
  2255. vertices in the graph.
  2256. \end{itemize}
  2257. If you can color the remaining vertices in the graph with the nine
  2258. colors, then you have also solved the corresponding game of Sudoku.
  2259. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2260. the corresponding graph with colored vertices. We map the Sudoku
  2261. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2262. sampling of the vertices (those that are colored) because showing
  2263. edges for all of the vertices would make the graph unreadable.
  2264. \begin{figure}[tbp]
  2265. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2266. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2267. \caption{A Sudoku game board and the corresponding colored graph.}
  2268. \label{fig:sudoku-graph}
  2269. \end{figure}
  2270. Given that Sudoku is an instance of graph coloring, one can use Sudoku
  2271. strategies to come up with an algorithm for allocating registers. For
  2272. example, one of the basic techniques for Sudoku is called Pencil
  2273. Marks. The idea is that you use a process of elimination to determine
  2274. what numbers no longer make sense for a square, and write down those
  2275. numbers in the square (writing very small). For example, if the number
  2276. $1$ is assigned to a square, then by process of elimination, you can
  2277. write the pencil mark $1$ in all the squares in the same row, column,
  2278. and region. Many Sudoku computer games provide automatic support for
  2279. Pencil Marks.
  2280. %
  2281. The Pencil Marks technique corresponds to the notion of color
  2282. \emph{saturation} due to \cite{Brelaz:1979eu}. The saturation of a
  2283. vertex, in Sudoku terms, is the set of colors that are no longer
  2284. available. In graph terminology, we have the following definition:
  2285. \begin{equation*}
  2286. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  2287. \text{ and } \mathrm{color}(v) = c \}
  2288. \end{equation*}
  2289. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  2290. edge with $u$.
  2291. Using the Pencil Marks technique leads to a simple strategy for
  2292. filling in numbers: if there is a square with only one possible number
  2293. left, then write down that number! But what if there are no squares
  2294. with only one possibility left? One brute-force approach is to just
  2295. make a guess. If that guess ultimately leads to a solution, great. If
  2296. not, backtrack to the guess and make a different guess. One good
  2297. thing about Pencil Marks is that it reduces the degree of branching in
  2298. the search tree. Nevertheless, backtracking can be horribly time
  2299. consuming. One way to reduce the amount of backtracking is to use the
  2300. most-constrained-first heuristic. That is, when making a guess, always
  2301. choose a square with the fewest possibilities left (the vertex with
  2302. the highest saturation). The idea is that choosing highly constrained
  2303. squares earlier rather than later is better because later there may
  2304. not be any possibilities.
  2305. In some sense, register allocation is easier than Sudoku because we
  2306. can always cheat and add more numbers by mapping variables to the
  2307. stack. We say that a variable is \emph{spilled} when we decide to map
  2308. it to a stack location. We would like to minimize the time needed to
  2309. color the graph, and backtracking is expensive. Thus, it makes sense
  2310. to keep the most-constrained-first heuristic but drop the backtracking
  2311. in favor of greedy search (guess and just keep going).
  2312. Figure~\ref{fig:satur-algo} gives the pseudo-code for this simple
  2313. greedy algorithm for register allocation based on saturation and the
  2314. most-constrained-first heuristic, which is roughly equivalent to the
  2315. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2316. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just
  2317. as in Sudoku, the algorithm represents colors with integers, with the
  2318. first $k$ colors corresponding to the $k$ registers in a given machine
  2319. and the rest of the integers corresponding to stack locations.
  2320. \begin{figure}[btp]
  2321. \centering
  2322. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2323. Algorithm: DSATUR
  2324. Input: a graph |$G$|
  2325. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  2326. |$W \gets \mathit{vertices}(G)$|
  2327. while |$W \neq \emptyset$| do
  2328. pick a vertex |$u$| from |$W$| with the highest saturation,
  2329. breaking ties randomly
  2330. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  2331. |$\mathrm{color}[u] \gets c$|
  2332. |$W \gets W - \{u\}$|
  2333. \end{lstlisting}
  2334. \caption{The saturation-based greedy graph coloring algorithm.}
  2335. \label{fig:satur-algo}
  2336. \end{figure}
  2337. With this algorithm in hand, let us return to the running example and
  2338. consider how to color the interference graph in
  2339. Figure~\ref{fig:interfere}. We shall not use register \key{rax} for
  2340. register allocation because we use it to patch instructions, so we
  2341. remove that vertex from the graph. Initially, all of the vertices are
  2342. not yet colored and they are unsaturated, so we annotate each of them
  2343. with a dash for their color and an empty set for the saturation.
  2344. \[
  2345. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2346. \node (v) at (0,0) {$v:-,\{\}$};
  2347. \node (w) at (3,0) {$w:-,\{\}$};
  2348. \node (x) at (6,0) {$x:-,\{\}$};
  2349. \node (y) at (3,-1.5) {$y:-,\{\}$};
  2350. \node (z) at (6,-1.5) {$z:-,\{\}$};
  2351. \node (t1) at (9,-1.5) {$t.1:-,\{\}$};
  2352. \draw (v) to (w);
  2353. \foreach \i in {w,x,y}
  2354. {
  2355. \foreach \j in {w,x,y}
  2356. {
  2357. \draw (\i) to (\j);
  2358. }
  2359. }
  2360. \draw (z) to (w);
  2361. \draw (z) to (y);
  2362. \draw (t1) to (z);
  2363. \end{tikzpicture}
  2364. \]
  2365. We select a maximally saturated vertex and color it $0$. In this case we
  2366. have a 7-way tie, so we arbitrarily pick $t.1$. The then mark color $0$
  2367. as no longer available for $z$ because it interferes
  2368. with $t.1$.
  2369. \[
  2370. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2371. \node (v) at (0,0) {$v:-,\{\}$};
  2372. \node (w) at (3,0) {$w:-,\{\}$};
  2373. \node (x) at (6,0) {$x:-,\{\}$};
  2374. \node (y) at (3,-1.5) {$y:-,\{\}$};
  2375. \node (z) at (6,-1.5) {$z:-,\{\mathbf{0}\}$};
  2376. \node (t1) at (9,-1.5) {$t.1:\mathbf{0},\{\}$};
  2377. \draw (v) to (w);
  2378. \foreach \i in {w,x,y}
  2379. {
  2380. \foreach \j in {w,x,y}
  2381. {
  2382. \draw (\i) to (\j);
  2383. }
  2384. }
  2385. \draw (z) to (w);
  2386. \draw (z) to (y);
  2387. \draw (t1) to (z);
  2388. \end{tikzpicture}
  2389. \]
  2390. Now we repeat the process, selecting another maximally saturated
  2391. vertex, which in this case is $z$. We color $z$ with $1$.
  2392. \[
  2393. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2394. \node (v) at (0,0) {$v:-,\{\}$};
  2395. \node (w) at (3,0) {$w:-,\{\mathbf{1}\}$};
  2396. \node (x) at (6,0) {$x:-,\{\}$};
  2397. \node (y) at (3,-1.5) {$y:-,\{\mathbf{1}\}$};
  2398. \node (z) at (6,-1.5) {$z:\mathbf{1},\{0\}$};
  2399. \node (t1) at (9,-1.5) {$t.1:0,\{\mathbf{1}\}$};
  2400. \draw (t1) to (z);
  2401. \draw (v) to (w);
  2402. \foreach \i in {w,x,y}
  2403. {
  2404. \foreach \j in {w,x,y}
  2405. {
  2406. \draw (\i) to (\j);
  2407. }
  2408. }
  2409. \draw (z) to (w);
  2410. \draw (z) to (y);
  2411. \end{tikzpicture}
  2412. \]
  2413. The most saturated vertices are now $w$ and $y$. We color $y$ with the
  2414. first available color, which is $0$.
  2415. \[
  2416. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2417. \node (v) at (0,0) {$v:-,\{\}$};
  2418. \node (w) at (3,0) {$w:-,\{\mathbf{0},1\}$};
  2419. \node (x) at (6,0) {$x:-,\{\mathbf{0},\}$};
  2420. \node (y) at (3,-1.5) {$y:\mathbf{0},\{1\}$};
  2421. \node (z) at (6,-1.5) {$z:1,\{\mathbf{0}\}$};
  2422. \node (t1) at (9,-1.5) {$t.1:0,\{1\}$};
  2423. \draw (t1) to (z);
  2424. \draw (v) to (w);
  2425. \foreach \i in {w,x,y}
  2426. {
  2427. \foreach \j in {w,x,y}
  2428. {
  2429. \draw (\i) to (\j);
  2430. }
  2431. }
  2432. \draw (z) to (w);
  2433. \draw (z) to (y);
  2434. \end{tikzpicture}
  2435. \]
  2436. Vertex $w$ is now the most highly saturated, so we color $w$ with $2$.
  2437. \[
  2438. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2439. \node (v) at (0,0) {$v:-,\{2\}$};
  2440. \node (w) at (3,0) {$w:\mathbf{2},\{0,1\}$};
  2441. \node (x) at (6,0) {$x:-,\{0,\mathbf{2}\}$};
  2442. \node (y) at (3,-1.5) {$y:0,\{1,\mathbf{2}\}$};
  2443. \node (z) at (6,-1.5) {$z:1,\{0,\mathbf{2}\}$};
  2444. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2445. \draw (t1) to (z);
  2446. \draw (v) to (w);
  2447. \foreach \i in {w,x,y}
  2448. {
  2449. \foreach \j in {w,x,y}
  2450. {
  2451. \draw (\i) to (\j);
  2452. }
  2453. }
  2454. \draw (z) to (w);
  2455. \draw (z) to (y);
  2456. \end{tikzpicture}
  2457. \]
  2458. Now $x$ has the highest saturation, so we color it $1$.
  2459. \[
  2460. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2461. \node (v) at (0,0) {$v:-,\{2\}$};
  2462. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  2463. \node (x) at (6,0) {$x:\mathbf{1},\{0,2\}$};
  2464. \node (y) at (3,-1.5) {$y:0,\{\mathbf{1},2\}$};
  2465. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2466. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2467. \draw (t1) to (z);
  2468. \draw (v) to (w);
  2469. \foreach \i in {w,x,y}
  2470. {
  2471. \foreach \j in {w,x,y}
  2472. {
  2473. \draw (\i) to (\j);
  2474. }
  2475. }
  2476. \draw (z) to (w);
  2477. \draw (z) to (y);
  2478. \end{tikzpicture}
  2479. \]
  2480. In the last step of the algorithm, we color $v$ with $0$.
  2481. \[
  2482. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2483. \node (v) at (0,0) {$v:\mathbf{0},\{2\}$};
  2484. \node (w) at (3,0) {$w:2,\{\mathbf{0},1\}$};
  2485. \node (x) at (6,0) {$x:1,\{0,2\}$};
  2486. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2487. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2488. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2489. \draw (t1) to (z);
  2490. \draw (v) to (w);
  2491. \foreach \i in {w,x,y}
  2492. {
  2493. \foreach \j in {w,x,y}
  2494. {
  2495. \draw (\i) to (\j);
  2496. }
  2497. }
  2498. \draw (z) to (w);
  2499. \draw (z) to (y);
  2500. \end{tikzpicture}
  2501. \]
  2502. With the coloring complete, we can finalize the assignment of
  2503. variables to registers and stack locations. Recall that if we have $k$
  2504. registers, we map the first $k$ colors to registers and the rest to
  2505. stack locations. Suppose for the moment that we have just one
  2506. register to use for register allocation, \key{rcx}. Then the following
  2507. is the mapping of colors to registers and stack allocations.
  2508. \[
  2509. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)}, \ldots \}
  2510. \]
  2511. Putting this mapping together with the above coloring of the variables, we
  2512. arrive at the assignment:
  2513. \begin{gather*}
  2514. \{ v \mapsto \key{\%rcx}, \,
  2515. w \mapsto \key{-16(\%rbp)}, \,
  2516. x \mapsto \key{-8(\%rbp)}, \\
  2517. y \mapsto \key{\%rcx}, \,
  2518. z\mapsto \key{-8(\%rbp)},
  2519. t.1\mapsto \key{\%rcx} \}
  2520. \end{gather*}
  2521. Applying this assignment to our running example, on the left, yields
  2522. the program on the right.\\
  2523. % why frame size of 32? -JGS
  2524. \begin{minipage}{0.4\textwidth}
  2525. \begin{lstlisting}
  2526. (block ()
  2527. (movq (int 1) (var v))
  2528. (movq (int 46) (var w))
  2529. (movq (var v) (var x))
  2530. (addq (int 7) (var x))
  2531. (movq (var x) (var y))
  2532. (addq (int 4) (var y))
  2533. (movq (var x) (var z))
  2534. (addq (var w) (var z))
  2535. (movq (var y) (var t.1))
  2536. (negq (var t.1))
  2537. (movq (var z) (reg rax))
  2538. (addq (var t.1) (reg rax))
  2539. (jmp conclusion))
  2540. \end{lstlisting}
  2541. \end{minipage}
  2542. $\Rightarrow$
  2543. \begin{minipage}{0.45\textwidth}
  2544. \begin{lstlisting}
  2545. (block ()
  2546. (movq (int 1) (reg rcx))
  2547. (movq (int 46) (deref rbp -16))
  2548. (movq (reg rcx) (deref rbp -8))
  2549. (addq (int 7) (deref rbp -8))
  2550. (movq (deref rbp -8) (reg rcx))
  2551. (addq (int 4) (reg rcx))
  2552. (movq (deref rbp -8) (deref rbp -8))
  2553. (addq (deref rbp -16) (deref rbp -8))
  2554. (movq (reg rcx) (reg rcx))
  2555. (negq (reg rcx))
  2556. (movq (deref rbp -8) (reg rax))
  2557. (addq (reg rcx) (reg rax))
  2558. (jmp conclusion))
  2559. \end{lstlisting}
  2560. \end{minipage}
  2561. The resulting program is almost an x86 program. The remaining step
  2562. is to apply the patch instructions pass. In this example, the trivial
  2563. move of \code{-8(\%rbp)} to itself is deleted and the addition of
  2564. \code{-16(\%rbp)} to \key{-8(\%rbp)} is fixed by going through
  2565. \code{rax} as follows.
  2566. \begin{lstlisting}
  2567. (movq (deref rbp -16) (reg rax)
  2568. (addq (reg rax) (deref rbp -8))
  2569. \end{lstlisting}
  2570. An overview of all of the passes involved in register allocation is
  2571. shown in Figure~\ref{fig:reg-alloc-passes}.
  2572. \begin{figure}[tbp]
  2573. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2574. \node (R1) at (0,2) {\large $R_1$};
  2575. \node (R1-2) at (3,2) {\large $R_1$};
  2576. \node (R1-3) at (6,2) {\large $R_1$};
  2577. \node (C0-1) at (6,0) {\large $C_0$};
  2578. \node (C0-2) at (3,0) {\large $C_0$};
  2579. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  2580. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  2581. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  2582. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  2583. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  2584. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  2585. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  2586. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  2587. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  2588. \path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  2589. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  2590. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  2591. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  2592. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  2593. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  2594. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  2595. \end{tikzpicture}
  2596. \caption{Diagram of the passes for $R_1$ with register allocation.}
  2597. \label{fig:reg-alloc-passes}
  2598. \end{figure}
  2599. \begin{exercise}\normalfont
  2600. Implement the pass \code{allocate-registers}, which should come
  2601. after the \code{build-interference} pass. The three new passes,
  2602. \code{uncover-live}, \code{build-interference}, and
  2603. \code{allocate-registers} replace the \code{assign-homes} pass of
  2604. Section~\ref{sec:assign-r1}.
  2605. We recommend that you create a helper function named
  2606. \code{color-graph} that takes an interference graph and a list of
  2607. all the variables in the program. This function should return a
  2608. mapping of variables to their colors (represented as natural
  2609. numbers). By creating this helper function, you will be able to
  2610. reuse it in Chapter~\ref{ch:functions} when you add support for
  2611. functions.
  2612. Once you have obtained the coloring from \code{color-graph}, you can
  2613. assign the variables to registers or stack locations and then reuse
  2614. code from the \code{assign-homes} pass from
  2615. Section~\ref{sec:assign-r1} to replace the variables with their
  2616. assigned location.
  2617. Test your updated compiler by creating new example programs that
  2618. exercise all of the register allocation algorithm, such as forcing
  2619. variables to be spilled to the stack.
  2620. \end{exercise}
  2621. \section{Print x86 and Conventions for Registers}
  2622. \label{sec:print-x86-reg-alloc}
  2623. Recall the \code{print-x86} pass generates the prelude and
  2624. conclusion instructions for the \code{main} function.
  2625. %
  2626. The prelude saved the values in \code{rbp} and \code{rsp} and the
  2627. conclusion returned those values to \code{rbp} and \code{rsp}. The
  2628. reason for this is that our \code{main} function must adhere to the
  2629. x86 calling conventions that we described in
  2630. Section~\ref{sec:calling-conventions}. In addition, the \code{main}
  2631. function needs to restore (in the conclusion) any callee-saved
  2632. registers that get used during register allocation. The simplest
  2633. approach is to save and restore all of the callee-saved registers. The
  2634. more efficient approach is to keep track of which callee-saved
  2635. registers were used and only save and restore them. Either way, make
  2636. sure to take this use of stack space into account when you are
  2637. calculating the size of the frame. Also, don't forget that the size of
  2638. the frame needs to be a multiple of 16 bytes.
  2639. \section{Challenge: Move Biasing$^{*}$}
  2640. \label{sec:move-biasing}
  2641. This section describes an optional enhancement to register allocation
  2642. for those students who are looking for an extra challenge or who have
  2643. a deeper interest in register allocation.
  2644. We return to the running example, but we remove the supposition that
  2645. we only have one register to use. So we have the following mapping of
  2646. color numbers to registers.
  2647. \[
  2648. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx}, \ldots \}
  2649. \]
  2650. Using the same assignment that was produced by register allocator
  2651. described in the last section, we get the following program.
  2652. \begin{minipage}{0.45\textwidth}
  2653. \begin{lstlisting}
  2654. (block ()
  2655. (movq (int 1) (var v))
  2656. (movq (int 46) (var w))
  2657. (movq (var v) (var x))
  2658. (addq (int 7) (var x))
  2659. (movq (var x) (var y))
  2660. (addq (int 4) (var y))
  2661. (movq (var x) (var z))
  2662. (addq (var w) (var z))
  2663. (movq (var y) (var t.1))
  2664. (negq (var t.1))
  2665. (movq (var z) (reg rax))
  2666. (addq (var t.1) (reg rax))
  2667. (jmp conclusion))
  2668. \end{lstlisting}
  2669. \end{minipage}
  2670. $\Rightarrow$
  2671. \begin{minipage}{0.45\textwidth}
  2672. \begin{lstlisting}
  2673. (block ()
  2674. (movq (int 1) (reg rbx))
  2675. (movq (int 46) (reg rdx))
  2676. (movq (reg rbx) (reg rcx))
  2677. (addq (int 7) (reg rcx))
  2678. (movq (reg rcx) (reg rbx))
  2679. (addq (int 4) (reg rbx))
  2680. (movq (reg rcx) (reg rcx))
  2681. (addq (reg rdx) (reg rcx))
  2682. (movq (reg rbx) (reg rbx))
  2683. (negq (reg rbx))
  2684. (movq (reg rcx) (reg rax))
  2685. (addq (reg rbx) (reg rax))
  2686. (jmp conclusion))
  2687. \end{lstlisting}
  2688. \end{minipage}
  2689. While this allocation is quite good, we could do better. For example,
  2690. the variables \key{v} and \key{x} ended up in different registers, but
  2691. if they had been placed in the same register, then the move from
  2692. \key{v} to \key{x} could be removed.
  2693. We say that two variables $p$ and $q$ are \emph{move related} if they
  2694. participate together in a \key{movq} instruction, that is, \key{movq}
  2695. $p$, $q$ or \key{movq} $q$, $p$. When the register allocator chooses a
  2696. color for a variable, it should prefer a color that has already been
  2697. used for a move-related variable (assuming that they do not
  2698. interfere). Of course, this preference should not override the
  2699. preference for registers over stack locations, but should only be used
  2700. as a tie breaker when choosing between registers or when choosing
  2701. between stack locations.
  2702. We recommend that you represent the move relationships in a graph,
  2703. similar to how we represented interference. The following is the
  2704. \emph{move graph} for our running example.
  2705. \[
  2706. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2707. \node (v) at (0,0) {$v$};
  2708. \node (w) at (3,0) {$w$};
  2709. \node (x) at (6,0) {$x$};
  2710. \node (y) at (3,-1.5) {$y$};
  2711. \node (z) at (6,-1.5) {$z$};
  2712. \node (t1) at (9,-1.5) {$t.1$};
  2713. \draw[bend left=15] (t1) to (y);
  2714. \draw[bend left=15] (v) to (x);
  2715. \draw (x) to (y);
  2716. \draw (x) to (z);
  2717. \end{tikzpicture}
  2718. \]
  2719. Now we replay the graph coloring, pausing to see the coloring of $x$
  2720. and $v$. So we have the following coloring and the most saturated
  2721. vertex is $x$.
  2722. \[
  2723. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2724. \node (v) at (0,0) {$v:-,\{2\}$};
  2725. \node (w) at (3,0) {$w:2,\{0,1\}$};
  2726. \node (x) at (6,0) {$x:-,\{0,2\}$};
  2727. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2728. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2729. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2730. \draw (t1) to (z);
  2731. \draw (v) to (w);
  2732. \foreach \i in {w,x,y}
  2733. {
  2734. \foreach \j in {w,x,y}
  2735. {
  2736. \draw (\i) to (\j);
  2737. }
  2738. }
  2739. \draw (z) to (w);
  2740. \draw (z) to (y);
  2741. \end{tikzpicture}
  2742. \]
  2743. Last time we chose to color $x$ with $1$,
  2744. %
  2745. which so happens to be the color of $z$, and $x$ is move related to
  2746. $z$. This was rather lucky, and if the program had been a little
  2747. different, and say $z$ had been already assigned to $2$, then $x$
  2748. would still get $1$ and our luck would have run out. With move
  2749. biasing, we use the fact that $x$ and $z$ are move related to
  2750. influence the choice of color for $x$, in this case choosing $1$
  2751. because that's the color of $z$.
  2752. \[
  2753. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2754. \node (v) at (0,0) {$v:-,\{2\}$};
  2755. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  2756. \node (x) at (6,0) {$x:\mathbf{1},\{0,2\}$};
  2757. \node (y) at (3,-1.5) {$y:0,\{\mathbf{1},2\}$};
  2758. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2759. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2760. \draw (t1) to (z);
  2761. \draw (v) to (w);
  2762. \foreach \i in {w,x,y}
  2763. {
  2764. \foreach \j in {w,x,y}
  2765. {
  2766. \draw (\i) to (\j);
  2767. }
  2768. }
  2769. \draw (z) to (w);
  2770. \draw (z) to (y);
  2771. \end{tikzpicture}
  2772. \]
  2773. Next we consider coloring the variable $v$, and we just need to avoid
  2774. choosing $2$ because of the interference with $w$. Last time we choose
  2775. the color $0$, simply because it was the lowest, but this time we know
  2776. that $v$ is move related to $x$, so we choose the color $1$.
  2777. \[
  2778. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2779. \node (v) at (0,0) {$v:\mathbf{1},\{2\}$};
  2780. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  2781. \node (x) at (6,0) {$x:1,\{0,2\}$};
  2782. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2783. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2784. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2785. \draw (t1) to (z);
  2786. \draw (v) to (w);
  2787. \foreach \i in {w,x,y}
  2788. {
  2789. \foreach \j in {w,x,y}
  2790. {
  2791. \draw (\i) to (\j);
  2792. }
  2793. }
  2794. \draw (z) to (w);
  2795. \draw (z) to (y);
  2796. \end{tikzpicture}
  2797. \]
  2798. We apply this register assignment to the running example, on the left,
  2799. to obtain the code on right.
  2800. \begin{minipage}{0.45\textwidth}
  2801. \begin{lstlisting}
  2802. (block ()
  2803. (movq (int 1) (var v))
  2804. (movq (int 46) (var w))
  2805. (movq (var v) (var x))
  2806. (addq (int 7) (var x))
  2807. (movq (var x) (var y))
  2808. (addq (int 4) (var y))
  2809. (movq (var x) (var z))
  2810. (addq (var w) (var z))
  2811. (movq (var y) (var t.1))
  2812. (negq (var t.1))
  2813. (movq (var z) (reg rax))
  2814. (addq (var t.1) (reg rax))
  2815. (jmp conclusion))
  2816. \end{lstlisting}
  2817. \end{minipage}
  2818. $\Rightarrow$
  2819. \begin{minipage}{0.45\textwidth}
  2820. \begin{lstlisting}
  2821. (block ()
  2822. (movq (int 1) (reg rcx))
  2823. (movq (int 46) (reg rbx))
  2824. (movq (reg rcx) (reg rcx))
  2825. (addq (int 7) (reg rcx))
  2826. (movq (reg rcx) (reg rdx))
  2827. (addq (int 4) (reg rdx))
  2828. (movq (reg rcx) (reg rcx))
  2829. (addq (reg rbx) (reg rcx))
  2830. (movq (reg rdx) (reg rbx))
  2831. (negq (reg rbx))
  2832. (movq (reg rcx) (reg rax))
  2833. (addq (reg rbx) (reg rax))
  2834. (jmp conclusion))
  2835. \end{lstlisting}
  2836. \end{minipage}
  2837. The \code{patch-instructions} then removes the trivial moves from
  2838. \key{v} to \key{x} and from \key{x} to \key{z} to obtain the following
  2839. result.
  2840. \begin{minipage}{0.45\textwidth}
  2841. \begin{lstlisting}
  2842. (block ()
  2843. (movq (int 1) (reg rcx))
  2844. (movq (int 46) (reg rbx))
  2845. (addq (int 7) (reg rcx))
  2846. (movq (reg rcx) (reg rdx))
  2847. (addq (int 4) (reg rdx))
  2848. (addq (reg rbx) (reg rcx))
  2849. (movq (reg rdx) (reg rbx))
  2850. (negq (reg rbx))
  2851. (movq (reg rcx) (reg rax))
  2852. (addq (reg rbx) (reg rax))
  2853. (jmp conclusion))
  2854. \end{lstlisting}
  2855. \end{minipage}
  2856. \begin{exercise}\normalfont
  2857. Change your implementation of \code{allocate-registers} to take move
  2858. biasing into account. Make sure that your compiler still passes all of
  2859. the previous tests. Create two new tests that include at least one
  2860. opportunity for move biasing and visually inspect the output x86
  2861. programs to make sure that your move biasing is working properly.
  2862. \end{exercise}
  2863. \margincomment{\footnotesize To do: another neat challenge would be to do
  2864. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  2865. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2866. \chapter{Booleans and Control Flow}
  2867. \label{ch:bool-types}
  2868. The $R_0$ and $R_1$ languages only had a single kind of value, the
  2869. integers. In this Chapter we add a second kind of value, the Booleans,
  2870. to create the $R_2$ language. The Boolean values \emph{true} and
  2871. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  2872. Racket. We also introduce several operations that involve Booleans
  2873. (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the conditional
  2874. \key{if} expression. With the addition of \key{if} expressions,
  2875. programs can have non-trivial control flow which has an impact on
  2876. several parts of the compiler. Also, because we now have two kinds of
  2877. values, we need to worry about programs that apply an operation to the
  2878. wrong kind of value, such as \code{(not 1)}.
  2879. There are two language design options for such situations. One option
  2880. is to signal an error and the other is to provide a wider
  2881. interpretation of the operation. The Racket language uses a mixture of
  2882. these two options, depending on the operation and the kind of
  2883. value. For example, the result of \code{(not 1)} in Racket is
  2884. \code{\#f} because Racket treats non-zero integers like \code{\#t}. On
  2885. the other hand, \code{(car 1)} results in a run-time error in Racket
  2886. stating that \code{car} expects a pair.
  2887. The Typed Racket language makes similar design choices as Racket,
  2888. except much of the error detection happens at compile time instead of
  2889. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  2890. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  2891. reports a compile-time error because Typed Racket expects the type of
  2892. the argument to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  2893. For the $R_2$ language we choose to be more like Typed Racket in that
  2894. we shall perform type checking during compilation. In
  2895. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  2896. is, how to compile a dynamically typed language like Racket. The
  2897. $R_2$ language is a subset of Typed Racket but by no means includes
  2898. all of Typed Racket. Furthermore, for many of the operations we shall
  2899. take a narrower interpretation than Typed Racket, for example,
  2900. rejecting \code{(not 1)}.
  2901. This chapter is organized as follows. We begin by defining the syntax
  2902. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  2903. then introduce the idea of type checking and build a type checker for
  2904. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  2905. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  2906. Section~\ref{sec:c1}. The remaining sections of this Chapter discuss
  2907. how our compiler passes need to change to accommodate Booleans and
  2908. conditional control flow.
  2909. \section{The $R_2$ Language}
  2910. \label{sec:r2-lang}
  2911. The syntax of the $R_2$ language is defined in
  2912. Figure~\ref{fig:r2-syntax}. It includes all of $R_1$ (shown in gray),
  2913. the Boolean literals \code{\#t} and \code{\#f}, and the conditional
  2914. \code{if} expression. Also, we expand the operators to include
  2915. subtraction, \key{and}, \key{or} and \key{not}, the \key{eq?}
  2916. operations for comparing two integers or two Booleans, and the
  2917. \key{<}, \key{<=}, \key{>}, and \key{>=} operations for comparing
  2918. integers.
  2919. \begin{figure}[tp]
  2920. \centering
  2921. \fbox{
  2922. \begin{minipage}{0.96\textwidth}
  2923. \[
  2924. \begin{array}{lcl}
  2925. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  2926. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \mid (\key{-}\;\Exp\;\Exp) \\
  2927. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  2928. &\mid& \key{\#t} \mid \key{\#f}
  2929. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  2930. \mid (\key{not}\;\Exp) \\
  2931. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  2932. R_2 &::=& (\key{program} \; \itm{info}\; \Exp)
  2933. \end{array}
  2934. \]
  2935. \end{minipage}
  2936. }
  2937. \caption{The syntax of $R_2$, extending $R_1$
  2938. (Figure~\ref{fig:r1-syntax}) with Booleans and conditionals.}
  2939. \label{fig:r2-syntax}
  2940. \end{figure}
  2941. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  2942. the parts that are the same as the interpreter for $R_1$
  2943. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  2944. simply evaluate to themselves. The conditional expression $(\key{if}\,
  2945. \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates the Boolean expression
  2946. \itm{cnd} and then either evaluates \itm{thn} or \itm{els} depending
  2947. on whether \itm{cnd} produced \code{\#t} or \code{\#f}. The logical
  2948. operations \code{not} and \code{and} behave as you might expect, but
  2949. note that the \code{and} operation is short-circuiting. That is, given
  2950. the expression $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not
  2951. evaluated if $e_1$ evaluates to \code{\#f}.
  2952. With the addition of the comparison operations, there are quite a few
  2953. primitive operations and the interpreter code for them is somewhat
  2954. repetitive. In Figure~\ref{fig:interp-R2} we factor out the different
  2955. parts into the \code{interp-op} function and the similar parts into
  2956. the one match clause shown in Figure~\ref{fig:interp-R2}. We do not
  2957. use \code{interp-op} for the \code{and} operation because of the
  2958. short-circuiting behavior in the order of evaluation of its arguments.
  2959. \begin{figure}[tbp]
  2960. \begin{lstlisting}
  2961. (define primitives (set '+ '- 'eq? '< '<= '> '>= 'not 'read))
  2962. (define (interp-op op)
  2963. (match op
  2964. ...
  2965. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  2966. ['eq? (lambda (v1 v2)
  2967. (cond [(or (and (fixnum? v1) (fixnum? v2))
  2968. (and (boolean? v1) (boolean? v2)))
  2969. (eq? v1 v2)]))]
  2970. ['< (lambda (v1 v2)
  2971. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  2972. ['<= (lambda (v1 v2)
  2973. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  2974. ['> (lambda (v1 v2)
  2975. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  2976. ['>= (lambda (v1 v2)
  2977. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  2978. [else (error 'interp-op "unknown operator")]))
  2979. (define (interp-exp env)
  2980. (lambda (e)
  2981. (define recur (interp-exp env))
  2982. (match e
  2983. ...
  2984. [(? boolean?) e]
  2985. [`(if ,cnd ,thn ,els)
  2986. (define b (recur cnd))
  2987. (match b
  2988. [#t (recur thn)]
  2989. [#f (recur els)])]
  2990. [`(and ,e1 ,e2)
  2991. (define v1 (recur e1))
  2992. (match v1
  2993. [#t (match (recur e2) [#t #t] [#f #f])]
  2994. [#f #f])]
  2995. [`(,op ,args ...)
  2996. #:when (set-member? primitives op)
  2997. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  2998. )))
  2999. (define (interp-R2 env)
  3000. (lambda (p)
  3001. (match p
  3002. [`(program ,info ,e)
  3003. ((interp-exp '()) e)])))
  3004. \end{lstlisting}
  3005. \caption{Interpreter for the $R_2$ language.}
  3006. \label{fig:interp-R2}
  3007. \end{figure}
  3008. \section{Type Checking $R_2$ Programs}
  3009. \label{sec:type-check-r2}
  3010. It is helpful to think about type checking in two complementary
  3011. ways. A type checker predicts the \emph{type} of value that will be
  3012. produced by each expression in the program. For $R_2$, we have just
  3013. two types, \key{Integer} and \key{Boolean}. So a type checker should
  3014. predict that
  3015. \begin{lstlisting}
  3016. (+ 10 (- (+ 12 20)))
  3017. \end{lstlisting}
  3018. produces an \key{Integer} while
  3019. \begin{lstlisting}
  3020. (and (not #f) #t)
  3021. \end{lstlisting}
  3022. produces a \key{Boolean}.
  3023. As mentioned at the beginning of this chapter, a type checker also
  3024. rejects programs that apply operators to the wrong type of value. Our
  3025. type checker for $R_2$ will signal an error for the following
  3026. expression because, as we have seen above, the expression \code{(+ 10
  3027. ...)} has type \key{Integer}, and we require the argument of a
  3028. \code{not} to have type \key{Boolean}.
  3029. \begin{lstlisting}
  3030. (not (+ 10 (- (+ 12 20))))
  3031. \end{lstlisting}
  3032. The type checker for $R_2$ is best implemented as a structurally
  3033. recursive function over the AST. Figure~\ref{fig:type-check-R2} shows
  3034. many of the clauses for the \code{type-check-exp} function. Given an
  3035. input expression \code{e}, the type checker either returns the type
  3036. (\key{Integer} or \key{Boolean}) or it signals an error. Of course,
  3037. the type of an integer literal is \code{Integer} and the type of a
  3038. Boolean literal is \code{Boolean}. To handle variables, the type
  3039. checker, like the interpreter, uses an association list. However, in
  3040. this case the association list maps variables to types instead of
  3041. values. Consider the clause for \key{let}. We type check the
  3042. initializing expression to obtain its type \key{T} and then associate
  3043. type \code{T} with the variable \code{x}. When the type checker
  3044. encounters the use of a variable, it can find its type in the
  3045. association list.
  3046. \begin{figure}[tbp]
  3047. \begin{lstlisting}
  3048. (define (type-check-exp env)
  3049. (lambda (e)
  3050. (define recur (type-check-exp env))
  3051. (match e
  3052. [(? fixnum?) 'Integer]
  3053. [(? boolean?) 'Boolean]
  3054. [(? symbol? x) (dict-ref env x)]
  3055. [`(read) 'Integer]
  3056. [`(let ([,x ,e]) ,body)
  3057. (define T (recur e))
  3058. (define new-env (cons (cons x T) env))
  3059. (type-check-exp new-env body)]
  3060. ...
  3061. [`(not ,e)
  3062. (match (recur e)
  3063. ['Boolean 'Boolean]
  3064. [else (error 'type-check-exp "'not' expects a Boolean" e)])]
  3065. ...
  3066. )))
  3067. (define (type-check-R2 env)
  3068. (lambda (e)
  3069. (match e
  3070. [`(program ,info ,body)
  3071. (define ty ((type-check-exp '()) body))
  3072. `(program ,info ,body)]
  3073. )))
  3074. \end{lstlisting}
  3075. \caption{Skeleton of a type checker for the $R_2$ language.}
  3076. \label{fig:type-check-R2}
  3077. \end{figure}
  3078. %% To print the resulting value correctly, the overall type of the
  3079. %% program must be threaded through the remainder of the passes. We can
  3080. %% store the type within the \key{program} form as shown in Figure
  3081. %% \ref{fig:type-check-R2}. Let $R^\dagger_2$ be the name for the
  3082. %% intermediate language produced by the type checker, which we define as
  3083. %% follows: \\[1ex]
  3084. %% \fbox{
  3085. %% \begin{minipage}{0.87\textwidth}
  3086. %% \[
  3087. %% \begin{array}{lcl}
  3088. %% R^\dagger_2 &::=& (\key{program}\;(\key{type}\;\itm{type})\; \Exp)
  3089. %% \end{array}
  3090. %% \]
  3091. %% \end{minipage}
  3092. %% }
  3093. \begin{exercise}\normalfont
  3094. Complete the implementation of \code{type-check-R2} and test it on 10
  3095. new example programs in $R_2$ that you choose based on how thoroughly
  3096. they test the type checking algorithm. Half of the example programs
  3097. should have a type error, to make sure that your type checker properly
  3098. rejects them. The other half of the example programs should not have
  3099. type errors. Your testing should check that the result of the type
  3100. checker agrees with the value returned by the interpreter, that is, if
  3101. the type checker returns \key{Integer}, then the interpreter should
  3102. return an integer. Likewise, if the type checker returns
  3103. \key{Boolean}, then the interpreter should return \code{\#t} or
  3104. \code{\#f}. Note that if your type checker does not signal an error
  3105. for a program, then interpreting that program should not encounter an
  3106. error. If it does, there is something wrong with your type checker.
  3107. \end{exercise}
  3108. \section{Shrink the $R_2$ Language}
  3109. \label{sec:shrink-r2}
  3110. The $R_2$ language includes several operators that are easily
  3111. expressible in terms of other operators. For example, subtraction is
  3112. expressible in terms of addition and negation.
  3113. \[
  3114. (\key{-}\; e_1 \; e_2) \quad \Rightarrow \quad (\key{+} \; e_1 \; (\key{-} \; e_2))
  3115. \]
  3116. Several of the comparison operations are expressible in terms of
  3117. less-than and logical negation.
  3118. \[
  3119. (\key{<=}\; e_1 \; e_2) \quad \Rightarrow \quad (\key{not}\;(\key{<}\;e_2\;e_1))
  3120. \]
  3121. By performing these translations near the front-end of the compiler,
  3122. the later passes of the compiler will not need to deal with these
  3123. constructs, making those passes shorter. On the other hand, sometimes
  3124. these translations make it more difficult to generate the most
  3125. efficient code with respect to the number of instructions. However,
  3126. these differences typically do not affect the number of accesses to
  3127. memory, which is the primary factor that determines execution time on
  3128. modern computer architectures.
  3129. \begin{exercise}\normalfont
  3130. Implement the pass \code{shrink} that removes subtraction,
  3131. \key{and}, \key{or}, \key{<=}, \key{>}, and \key{>=} from the language
  3132. by translating them to other constructs in $R_2$. Create tests to
  3133. make sure that the behavior of all of these constructs stays the
  3134. same after translation.
  3135. \end{exercise}
  3136. \section{XOR, Comparisons, and Control Flow in x86}
  3137. \label{sec:x86-1}
  3138. To implement the new logical operations, the comparison operations,
  3139. and the \key{if} expression, we need to delve further into the x86
  3140. language. Figure~\ref{fig:x86-1} defines the abstract syntax for a
  3141. larger subset of x86 that includes instructions for logical
  3142. operations, comparisons, and jumps.
  3143. One small challenge is that x86 does not provide an instruction that
  3144. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  3145. However, the \code{xorq} instruction can be used to encode \code{not}.
  3146. The \key{xorq} instruction takes two arguments, performs a pairwise
  3147. exclusive-or operation on each bit of its arguments, and writes the
  3148. results into its second argument. Recall the truth table for
  3149. exclusive-or:
  3150. \begin{center}
  3151. \begin{tabular}{l|cc}
  3152. & 0 & 1 \\ \hline
  3153. 0 & 0 & 1 \\
  3154. 1 & 1 & 0
  3155. \end{tabular}
  3156. \end{center}
  3157. For example, $0011 \mathrel{\mathrm{XOR}} 0101 = 0110$. Notice that
  3158. in row of the table for the bit $1$, the result is the opposite of the
  3159. second bit. Thus, the \code{not} operation can be implemented by
  3160. \code{xorq} with $1$ as the first argument: $0001
  3161. \mathrel{\mathrm{XOR}} 0000 = 0001$ and $0001 \mathrel{\mathrm{XOR}}
  3162. 0001 = 0000$.
  3163. \begin{figure}[tp]
  3164. \fbox{
  3165. \begin{minipage}{0.96\textwidth}
  3166. \[
  3167. \begin{array}{lcl}
  3168. \Arg &::=& \gray{\INT{\Int} \mid \REG{\itm{register}}
  3169. \mid (\key{deref}\,\itm{register}\,\Int)} \\
  3170. &\mid& (\key{byte-reg}\; \itm{register}) \\
  3171. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3172. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  3173. (\key{subq} \; \Arg\; \Arg) \mid
  3174. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  3175. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  3176. (\key{pushq}\;\Arg) \mid
  3177. (\key{popq}\;\Arg) \mid
  3178. (\key{retq})} \\
  3179. &\mid& (\key{xorq} \; \Arg\;\Arg)
  3180. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\;\itm{cc} \; \Arg) \\
  3181. &\mid& (\key{movzbq}\;\Arg\;\Arg)
  3182. \mid (\key{jmp} \; \itm{label})
  3183. \mid (\key{jmp-if}\; \itm{cc} \; \itm{label}) \\
  3184. &\mid& (\key{label} \; \itm{label}) \\
  3185. x86_1 &::= & (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+})
  3186. \end{array}
  3187. \]
  3188. \end{minipage}
  3189. }
  3190. \caption{The x86$_1$ language (extends x86$_0$ of Figure~\ref{fig:x86-ast-a}).}
  3191. \label{fig:x86-1}
  3192. \end{figure}
  3193. Next we consider the x86 instructions that are relevant for
  3194. compiling the comparison operations. The \key{cmpq} instruction
  3195. compares its two arguments to determine whether one argument is less
  3196. than, equal, or greater than the other argument. The \key{cmpq}
  3197. instruction is unusual regarding the order of its arguments and where
  3198. the result is placed. The argument order is backwards: if you want to
  3199. test whether $x < y$, then write \code{cmpq y, x}. The result of
  3200. \key{cmpq} is placed in the special EFLAGS register. This register
  3201. cannot be accessed directly but it can be queried by a number of
  3202. instructions, including the \key{set} instruction. The \key{set}
  3203. instruction puts a \key{1} or \key{0} into its destination depending
  3204. on whether the comparison came out according to the condition code
  3205. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  3206. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  3207. The set instruction has an annoying quirk in that its destination
  3208. argument must be single byte register, such as \code{al}, which is
  3209. part of the \code{rax} register. Thankfully, the \key{movzbq}
  3210. instruction can then be used to move from a single byte register to a
  3211. normal 64-bit register.
  3212. For compiling the \key{if} expression, the x86 instructions for
  3213. jumping are relevant. The \key{jmp} instruction updates the program
  3214. counter to point to the instruction after the indicated label. The
  3215. \key{jmp-if} instruction updates the program counter to point to the
  3216. instruction after the indicated label depending on whether the result
  3217. in the EFLAGS register matches the condition code \itm{cc}, otherwise
  3218. the \key{jmp-if} instruction falls through to the next
  3219. instruction. Because the \key{jmp-if} instruction relies on the EFLAGS
  3220. register, it is quite common for the \key{jmp-if} to be immediately
  3221. preceeded by a \key{cmpq} instruction, to set the EFLAGS regsiter.
  3222. Our abstract syntax for \key{jmp-if} differs from the concrete syntax
  3223. for x86 to separate the instruction name from the condition code. For
  3224. example, \code{(jmp-if le foo)} corresponds to \code{jle foo}.
  3225. \section{The $C_1$ Intermediate Language}
  3226. \label{sec:c1}
  3227. As with $R_1$, we shall compile $R_2$ to a C-like intermediate
  3228. language, but we need to grow that intermediate language to handle the
  3229. new features in $R_2$: Booleans and conditional expressions.
  3230. Figure~\ref{fig:c1-syntax} shows the new features of $C_1$; we add
  3231. logic and comparison operators to the $\Exp$ non-terminal, the
  3232. literals \key{\#t} and \key{\#f} to the $\Arg$ non-terminal.
  3233. Regarding control flow, $C_1$ differs considerably from $R_2$.
  3234. Instead of \key{if} expressions, $C_1$ has goto's and conditional
  3235. goto's in the grammar for $\Tail$. This means that a sequence of
  3236. statements may now end with a \code{goto} or a conditional
  3237. \code{goto}, which jumps to one of two labeled pieces of code
  3238. depending on the outcome of the comparison. In
  3239. Section~\ref{sec:explicate-control-r2} we discuss how to translate
  3240. from $R_2$ to $C_1$, bridging this gap between \key{if} expressions
  3241. and \key{goto}'s.
  3242. \begin{figure}[tp]
  3243. \fbox{
  3244. \begin{minipage}{0.96\textwidth}
  3245. \[
  3246. \begin{array}{lcl}
  3247. \Arg &::=& \gray{\Int \mid \Var} \mid \key{\#t} \mid \key{\#f} \\
  3248. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3249. \Exp &::= & \gray{\Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)}
  3250. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) \\
  3251. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} } \\
  3252. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  3253. &\mid& (\key{goto}\,\itm{label}) \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})} \\
  3254. C_1 & ::= & (\key{program}\;\itm{info}\; ((\itm{label}\,\key{.}\,\Tail)^{+}))
  3255. \end{array}
  3256. \]
  3257. \end{minipage}
  3258. }
  3259. \caption{The $C_1$ language, extending $C_0$ with Booleans and conditionals.}
  3260. \label{fig:c1-syntax}
  3261. \end{figure}
  3262. \section{Explicate Control}
  3263. \label{sec:explicate-control-r2}
  3264. Recall that the purpose of \code{explicate-control} is to make the
  3265. order of evaluation explicit in the syntax of the program. With the
  3266. addition of \key{if} in $R_2$, things get more interesting.
  3267. As a motivating example, consider the following program that has an
  3268. \key{if} expression nested in the predicate of another \key{if}.
  3269. % s1_38.rkt
  3270. \begin{lstlisting}
  3271. (program ()
  3272. (if (if (eq? (read) 1)
  3273. (eq? (read) 0)
  3274. (eq? (read) 2))
  3275. (+ 10 32)
  3276. (+ 700 77)))
  3277. \end{lstlisting}
  3278. %
  3279. The naive way to compile \key{if} and \key{eq?} would be to handle
  3280. each of them in isolation, regardless of their context. Each
  3281. \key{eq?} would be translated into a \key{cmpq} instruction followed
  3282. by a couple instructions to move the result from the EFLAGS register
  3283. into a general purpose register or stack location. Each \key{if} would
  3284. be translated into the combination of a \key{cmpq} and \key{jmp-if}.
  3285. However, if we take context into account we can do better and reduce
  3286. the use of \key{cmpq} and EFLAG-accessing instructions.
  3287. One idea is to try and reorganize the code at the level of $R_2$,
  3288. pushing the outer \key{if} inside the inner one. This would yield the
  3289. following code.
  3290. \begin{lstlisting}
  3291. (if (eq? (read) 1)
  3292. (if (eq? (read) 0)
  3293. (+ 10 32)
  3294. (+ 700 77))
  3295. (if (eq? (read) 2))
  3296. (+ 10 32)
  3297. (+ 700 77))
  3298. \end{lstlisting}
  3299. Unfortunately, this approach duplicates the two branches, and a
  3300. compiler must never duplicate code!
  3301. We need a way to perform the above transformation, but without
  3302. duplicating code. The solution is straightforward if we think at the
  3303. level of x86 assembly: we can label the code for each of the branches
  3304. and insert \key{goto}'s in all the places that need to execute the
  3305. branches. Put another way, we need to move away from abstract syntax
  3306. \emph{trees} and instead use \emph{graphs}. In particular, we shall
  3307. use a standard program representation called a \emph{control flow
  3308. graph} (CFG), due to Frances Elizabeth \citet{Allen:1970uq}. Each
  3309. vertex is a labeled sequence of code, called a \emph{basic block}, and
  3310. each edge represents a jump to another block. The \key{program}
  3311. construct of $C_0$ and $C_1$ represents a control flow graph as an
  3312. association list mapping labels to basic blocks. Each block is
  3313. represented by the $\Tail$ non-terminal.
  3314. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  3315. \code{remove-complex-opera*} pass and then the
  3316. \code{explicate-control} pass on the example program. We shall walk
  3317. through the output program and then discuss the algorithm.
  3318. %
  3319. Following the order of evaluation in the output of
  3320. \code{remove-complex-opera*}, we first have the \code{(read)} and
  3321. comparison to \code{1} from the predicate of the inner \key{if}. In
  3322. the output of \code{explicate-control}, in the \code{start} block,
  3323. this becomes a \code{(read)} followed by a conditional goto to either
  3324. \code{block61} or \code{block62}. Each of these contains the
  3325. translations of the code \code{(eq? (read) 0)} and \code{(eq? (read)
  3326. 1)}, respectively. Regarding \code{block61}, we start with the
  3327. \code{(read)} and comparison to \code{0} and then have a conditional
  3328. goto, either to \code{block59} or \code{block60}, which indirectly
  3329. take us to \code{block55} and \code{block56}, the two branches of the
  3330. outer \key{if}, i.e., \code{(+ 10 32)} and \code{(+ 700 77)}. The
  3331. story for \code{block62} is similar.
  3332. \begin{figure}[tbp]
  3333. \begin{tabular}{lll}
  3334. \begin{minipage}{0.4\textwidth}
  3335. \begin{lstlisting}
  3336. (program ()
  3337. (if (if (eq? (read) 1)
  3338. (eq? (read) 0)
  3339. (eq? (read) 2))
  3340. (+ 10 32)
  3341. (+ 700 77)))
  3342. \end{lstlisting}
  3343. \hspace{40pt}$\Downarrow$
  3344. \begin{lstlisting}
  3345. (program ()
  3346. (if (if (let ([tmp52 (read)])
  3347. (eq? tmp52 1))
  3348. (let ([tmp53 (read)])
  3349. (eq? tmp53 0))
  3350. (let ([tmp54 (read)])
  3351. (eq? tmp54 2)))
  3352. (+ 10 32)
  3353. (+ 700 77)))
  3354. \end{lstlisting}
  3355. \end{minipage}
  3356. &
  3357. $\Rightarrow$
  3358. &
  3359. \begin{minipage}{0.55\textwidth}
  3360. \begin{lstlisting}
  3361. (program ()
  3362. ((block62 .
  3363. (seq (assign tmp54 (read))
  3364. (if (eq? tmp54 2)
  3365. (goto block59)
  3366. (goto block60))))
  3367. (block61 .
  3368. (seq (assign tmp53 (read))
  3369. (if (eq? tmp53 0)
  3370. (goto block57)
  3371. (goto block58))))
  3372. (block60 . (goto block56))
  3373. (block59 . (goto block55))
  3374. (block58 . (goto block56))
  3375. (block57 . (goto block55))
  3376. (block56 . (return (+ 700 77)))
  3377. (block55 . (return (+ 10 32)))
  3378. (start .
  3379. (seq (assign tmp52 (read))
  3380. (if (eq? tmp52 1)
  3381. (goto block61)
  3382. (goto block62))))))
  3383. \end{lstlisting}
  3384. \end{minipage}
  3385. \end{tabular}
  3386. \caption{Example translation from $R_2$ to $C_1$
  3387. via the \code{explicate-control}.}
  3388. \label{fig:explicate-control-s1-38}
  3389. \end{figure}
  3390. The nice thing about the output of \code{explicate-control} is that
  3391. there are no unnecessary uses of \code{eq?} and every use of
  3392. \code{eq?} is part of a conditional jump. The down-side of this output
  3393. is that it includes trivial blocks, such as \code{block57} through
  3394. \code{block60}, that only jump to another block. We discuss a solution
  3395. to this problem in Section~\ref{sec:opt-jumps}.
  3396. Recall that in Section~\ref{sec:explicate-control-r1} we implement the
  3397. \code{explicate-control} pass for $R_1$ using two mutually recursive
  3398. functions, \code{explicate-control-tail} and
  3399. \code{explicate-control-assign}. The former function translated
  3400. expressions in tail position whereas the later function translated
  3401. expressions on the right-hand-side of a \key{let}. With the addition
  3402. of \key{if} expression in $R_2$ we have a new kind of context to deal
  3403. with: the predicate position of the \key{if}. So we shall need another
  3404. function, \code{explicate-control-pred}, that takes an $R_2$
  3405. expression and two pieces of $C_1$ code (two $\Tail$'s) for the
  3406. then-branch and else-branch. The output of
  3407. \code{explicate-control-pred} is a $C_1$ $\Tail$. However, these
  3408. three functions also need to contruct the control-flow graph, which we
  3409. recommend they do via updates to a global variable. Next we consider
  3410. the specific additions to the tail and assign functions, and some of
  3411. cases for the pred function.
  3412. The \code{explicate-control-tail} function needs an additional case
  3413. for \key{if}. The branches of the \key{if} inherit the current
  3414. context, so they are in tail position. Let $B_1$ be the result of
  3415. \code{explicate-control-tail} on the $\itm{thn}$ branch and $B_2$ be
  3416. the result of apply \code{explicate-control-tail} to the $\itm{else}$
  3417. branch. Then the \key{if} translates to the block $B_3$ which is the
  3418. result of applying \code{explicate-control-pred} to the predicate
  3419. $\itm{cnd}$ and the blocks $B_1$ and $B_2$.
  3420. \[
  3421. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  3422. \]
  3423. Next we consider the case for \key{if} in the
  3424. \code{explicate-control-assign} function. So the context of the
  3425. \key{if} is an assignment to some variable $x$ and then the control
  3426. continues to some block $B_1$. The code that we generate for both the
  3427. $\itm{thn}$ and $\itm{els}$ branches shall both need to continue to
  3428. $B_1$, so we add $B_1$ to the control flow graph with a fresh label
  3429. $\ell_1$. Again, the branches of the \key{if} inherit the current
  3430. context, so that are in assignment positions. Let $B_2$ be the result
  3431. of applying \code{explicate-control-assign} to the $\itm{thn}$ branch,
  3432. variable $x$, and the block \code{(goto $\ell_1$)}. Let $B_3$ be the
  3433. result of applying \code{explicate-control-assign} to the $\itm{else}$
  3434. branch, variable $x$, and the block \code{(goto $\ell_1$)}. The
  3435. \key{if} translates to the block $B_4$ which is the result of applying
  3436. \code{explicate-control-pred} to the predicate $\itm{cnd}$ and the
  3437. blocks $B_2$ and $B_3$.
  3438. \[
  3439. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  3440. \]
  3441. The function \code{explicate-control-pred} will need a case for every
  3442. expression that can have type \code{Boolean}. We detail a few cases
  3443. here and leave the rest for the reader. The input to this function is
  3444. an expression and two blocks, $B_1$ and $B_2$, for the branches of the
  3445. enclosing \key{if}. One of the base cases of this function is when the
  3446. expression is a less-than comparision. We translate it to a
  3447. conditional \code{goto}. We need labels for the two branches $B_1$ and
  3448. $B_2$, so we add them to the control flow graph and obtain some labels
  3449. $\ell_1$ and $\ell_2$. The translation of the less-than comparison is
  3450. as follows.
  3451. \[
  3452. (\key{<}\;e_1\;e_2) \quad\Rightarrow\quad
  3453. (\key{if}\;(\key{<}\;e_1\;e_2)\;(\key{goto}\;\ell_1)\;(\key{goto}\;\ell_2))
  3454. \]
  3455. The case for \key{if} in \code{explicate-control-pred} is particularly
  3456. illuminating, as it deals with the challenges that we discussed above
  3457. regarding the example of the nested \key{if} expressions. Again, we
  3458. add the two input branches $B_1$ and $B_2$ to the control flow graph
  3459. and obtain the labels $\ell_1$ and $\ell_2$. The branches $\itm{thn}$
  3460. and $\itm{els}$ of the current \key{if} inherit their context from the
  3461. current one, i.e., predicate context. So we apply
  3462. \code{explicate-control-pred} to $\itm{thn}$ with the two blocks
  3463. \code{(goto $\ell_1$)} and \code{(goto $\ell_2$)}, to obtain $B_3$.
  3464. Similarly for the $\itm{els}$ branch, to obtain $B_4$.
  3465. Finally, we apply \code{explicate-control-pred} to
  3466. the predicate $\itm{cnd}$ and the blocks $B_3$ and $B_4$
  3467. to obtain the result $B_5$.
  3468. \[
  3469. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  3470. \quad\Rightarrow\quad
  3471. B_5
  3472. \]
  3473. \begin{exercise}\normalfont
  3474. Implement the pass \code{explicate-code} by adding the cases for
  3475. \key{if} to the functions for tail and assignment contexts, and
  3476. implement the function for predicate contexts. Create test cases
  3477. that exercise all of the new cases in the code for this pass.
  3478. \end{exercise}
  3479. \section{Select Instructions}
  3480. \label{sec:select-r2}
  3481. Recall that the \code{select-instructions} pass lowers from our
  3482. $C$-like intermediate representation to the pseudo-x86 language, which
  3483. is suitable for conducting register allocation. The pass is
  3484. implemented using three auxilliary functions, one for each of the
  3485. non-terminals $\Arg$, $\Stmt$, and $\Tail$.
  3486. For $\Arg$, we have new cases for the Booleans. We take the usual
  3487. approach of encoding them as integers, with true as 1 and false as 0.
  3488. \[
  3489. \key{\#t} \Rightarrow \key{1}
  3490. \qquad
  3491. \key{\#f} \Rightarrow \key{0}
  3492. \]
  3493. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  3494. be implemented in terms of \code{xorq} as we discussed at the
  3495. beginning of this section. Given an assignment \code{(assign
  3496. $\itm{lhs}$ (not $\Arg$))}, if the left-hand side $\itm{lhs}$ is
  3497. the same as $\Arg$, then just the \code{xorq} suffices:
  3498. \[
  3499. (\key{assign}\; x\; (\key{not}\; x))
  3500. \quad\Rightarrow\quad
  3501. ((\key{xorq}\;(\key{int}\;1)\;x'))
  3502. \]
  3503. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  3504. semantics of x86. Let $\Arg'$ be the result of recursively processing
  3505. $\Arg$. Then we have
  3506. \[
  3507. (\key{assign}\; \itm{lhs}\; (\key{not}\; \Arg))
  3508. \quad\Rightarrow\quad
  3509. ((\key{movq}\; \Arg'\; \itm{lhs}') \; (\key{xorq}\;(\key{int}\;1)\;\itm{lhs}'))
  3510. \]
  3511. Next consider the cases for \code{eq?} and less-than comparison.
  3512. Translating these operations to x86 is slightly involved due to the
  3513. unusual nature of the \key{cmpq} instruction discussed above. We
  3514. recommend translating an assignment from \code{eq?} into the following
  3515. sequence of three instructions. \\
  3516. \begin{tabular}{lll}
  3517. \begin{minipage}{0.4\textwidth}
  3518. \begin{lstlisting}
  3519. (assign |$\itm{lhs}$| (eq? |$\Arg_1$| |$\Arg_2$|))
  3520. \end{lstlisting}
  3521. \end{minipage}
  3522. &
  3523. $\Rightarrow$
  3524. &
  3525. \begin{minipage}{0.4\textwidth}
  3526. \begin{lstlisting}
  3527. (cmpq |$\Arg'_2$| |$\Arg'_1$|)
  3528. (set e (byte-reg al))
  3529. (movzbq (byte-reg al) |$\itm{lhs}'$|)
  3530. \end{lstlisting}
  3531. \end{minipage}
  3532. \end{tabular} \\
  3533. Regarding the $\Tail$ non-terminal, we have two new cases, for
  3534. \key{goto} and conditional \key{goto}. Both are straightforward
  3535. to handle. A \key{goto} becomes a jump instruction.
  3536. \[
  3537. (\key{goto}\; \ell) \quad \Rightarrow \quad ((\key{jmp} \;\ell))
  3538. \]
  3539. A conditional \key{goto} becomes a compare instruction followed
  3540. by a conditional jump (for ``then'') and the fall-through is
  3541. to a regular jump (for ``else'').\\
  3542. \begin{tabular}{lll}
  3543. \begin{minipage}{0.4\textwidth}
  3544. \begin{lstlisting}
  3545. (if (eq? |$\Arg_1$| |$\Arg_2$|)
  3546. (goto |$\ell_1$|)
  3547. (goto |$\ell_2$|))
  3548. \end{lstlisting}
  3549. \end{minipage}
  3550. &
  3551. $\Rightarrow$
  3552. &
  3553. \begin{minipage}{0.4\textwidth}
  3554. \begin{lstlisting}
  3555. ((cmpq |$\Arg'_2$| |$\Arg'_1$|)
  3556. (jmp-if e |$\ell_1$|)
  3557. (jmp |$\ell_2$|))
  3558. \end{lstlisting}
  3559. \end{minipage}
  3560. \end{tabular} \\
  3561. \begin{exercise}\normalfont
  3562. Expand your \code{select-instructions} pass to handle the new features
  3563. of the $R_2$ language. Test the pass on all the examples you have
  3564. created and make sure that you have some test programs that use the
  3565. \code{eq?} and \code{<} operators, creating some if necessary. Test
  3566. the output using the \code{interp-x86} interpreter
  3567. (Appendix~\ref{appendix:interp}).
  3568. \end{exercise}
  3569. \section{Register Allocation}
  3570. \label{sec:register-allocation-r2}
  3571. The changes required for $R_2$ affect the liveness analysis, building
  3572. the interference graph, and assigning homes, but the graph coloring
  3573. algorithm itself does not need to change.
  3574. \subsection{Liveness Analysis}
  3575. \label{sec:liveness-analysis-r2}
  3576. Recall that for $R_1$ we implemented liveness analysis for a single
  3577. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  3578. addition of \key{if} expressions to $R_2$, \code{explicate-control}
  3579. now produces many basic blocks arranged in a control-flow graph. The
  3580. first question we need to consider is in what order should we process
  3581. the basic blocks? Recall that to perform liveness analysis, we need to
  3582. know the live-after set. If a basic block has no successor blocks,
  3583. then it has an empty live-after set and we can immediately apply
  3584. liveness analysis to it. If a basic block has some successors, then we
  3585. need to complete liveness analysis on those blocks first.
  3586. Furthermore, we know that the control flow graph does not contain any
  3587. cycles (it is a DAG, that is, a directed acyclic graph)\footnote{If we
  3588. were to add loops to the language, then the CFG could contain cycles
  3589. and we would instead need to use the classic worklist algorithm for
  3590. computing the fixed point of the liveness
  3591. analysis~\citep{Aho:1986qf}.}. What all this amounts to is that we
  3592. need to process the basic blocks in reverse topological order. We
  3593. recommend using the \code{tsort} and \code{transpose} functions of the
  3594. Racket \code{graph} package to obtain this ordering.
  3595. The next question is how to compute the live-after set of a block
  3596. given the live-before sets of all its successor blocks. During
  3597. compilation we do not know which way the branch will go, so we do not
  3598. know which of the successor's live-before set to use. The solution
  3599. comes from the observation that there is no harm in identifying more
  3600. variables as live than absolutely necessary. Thus, we can take the
  3601. union of the live-before sets from all the successors to be the
  3602. live-after set for the block. Once we have computed the live-after
  3603. set, we can proceed to perform liveness analysis on the block just as
  3604. we did in Section~\ref{sec:liveness-analysis-r1}.
  3605. The helper functions for computing the variables in an instruction's
  3606. argument and for computing the variables read-from ($R$) or written-to
  3607. ($W$) by an instruction need to be updated to handle the new kinds of
  3608. arguments and instructions in x86$_1$.
  3609. \subsection{Build Interference}
  3610. \label{sec:build-interference-r2}
  3611. Many of the new instructions in x86$_1$ can be handled in the same way
  3612. as the instructions in x86$_0$. Thus, if your code was already quite
  3613. general, it will not need to be changed to handle the new
  3614. instructions. If not, I recommend that you change your code to be more
  3615. general. The \key{movzbq} instruction should be handled like the
  3616. \key{movq} instruction.
  3617. %% \subsection{Assign Homes}
  3618. %% \label{sec:assign-homes-r2}
  3619. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  3620. %% to be updated to handle the \key{if} statement, simply by recursively
  3621. %% processing the child nodes. Hopefully your code already handles the
  3622. %% other new instructions, but if not, you can generalize your code.
  3623. \begin{exercise}\normalfont
  3624. Update the \code{register-allocation} pass so that it works for $R_2$
  3625. and test your compiler using your previously created programs on the
  3626. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  3627. \end{exercise}
  3628. %% \section{Lower Conditionals (New Pass)}
  3629. %% \label{sec:lower-conditionals}
  3630. %% In the \code{select-instructions} pass we decided to procrastinate in
  3631. %% the lowering of the \key{if} statement, thereby making liveness
  3632. %% analysis easier. Now we need to make up for that and turn the \key{if}
  3633. %% statement into the appropriate instruction sequence. The following
  3634. %% translation gives the general idea. If the condition is true, we need
  3635. %% to execute the $\itm{thns}$ branch and otherwise we need to execute
  3636. %% the $\itm{elss}$ branch. So we use \key{cmpq} and do a conditional
  3637. %% jump to the $\itm{thenlabel}$, choosing the condition code $cc$ that
  3638. %% is appropriate for the comparison operator \itm{cmp}. If the
  3639. %% condition is false, we fall through to the $\itm{elss}$ branch. At the
  3640. %% end of the $\itm{elss}$ branch we need to take care to not fall
  3641. %% through to the $\itm{thns}$ branch. So we jump to the
  3642. %% $\itm{endlabel}$. All of the labels in the generated code should be
  3643. %% created with \code{gensym}.
  3644. %% \begin{tabular}{lll}
  3645. %% \begin{minipage}{0.4\textwidth}
  3646. %% \begin{lstlisting}
  3647. %% (if (|\itm{cmp}| |$\Arg_1$| |$\Arg_2$|) |$\itm{thns}$| |$\itm{elss}$|)
  3648. %% \end{lstlisting}
  3649. %% \end{minipage}
  3650. %% &
  3651. %% $\Rightarrow$
  3652. %% &
  3653. %% \begin{minipage}{0.4\textwidth}
  3654. %% \begin{lstlisting}
  3655. %% (cmpq |$\Arg_2$| |$\Arg_1$|)
  3656. %% (jmp-if |$cc$| |$\itm{thenlabel}$|)
  3657. %% |$\itm{elss}$|
  3658. %% (jmp |$\itm{endlabel}$|)
  3659. %% (label |$\itm{thenlabel}$|)
  3660. %% |$\itm{thns}$|
  3661. %% (label |$\itm{endlabel}$|)
  3662. %% \end{lstlisting}
  3663. %% \end{minipage}
  3664. %% \end{tabular}
  3665. %% \begin{exercise}\normalfont
  3666. %% Implement the \code{lower-conditionals} pass. Test your compiler using
  3667. %% your previously created programs on the \code{interp-x86} interpreter
  3668. %% (Appendix~\ref{appendix:interp}).
  3669. %% \end{exercise}
  3670. \section{Patch Instructions}
  3671. The second argument of the \key{cmpq} instruction must not be an
  3672. immediate value (such as a literal integer). So if you are comparing
  3673. two immediates, we recommend inserting a \key{movq} instruction to put
  3674. the second argument in \key{rax}.
  3675. %
  3676. The second argument of the \key{movzbq} must be a register.
  3677. %
  3678. There are no special restrictions on the x86 instructions
  3679. \key{jmp-if}, \key{jmp}, and \key{label}.
  3680. \begin{exercise}\normalfont
  3681. Update \code{patch-instructions} to handle the new x86 instructions.
  3682. Test your compiler using your previously created programs on the
  3683. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  3684. \end{exercise}
  3685. \section{An Example Translation}
  3686. Figure~\ref{fig:if-example-x86} shows a simple example program in
  3687. $R_2$ translated to x86, showing the results of
  3688. \code{explicate-control}, \code{select-instructions}, and the final
  3689. x86 assembly code.
  3690. \begin{figure}[tbp]
  3691. \begin{tabular}{lll}
  3692. \begin{minipage}{0.5\textwidth}
  3693. % s1_20.rkt
  3694. \begin{lstlisting}
  3695. (program ()
  3696. (if (eq? (read) 1) 42 0))
  3697. \end{lstlisting}
  3698. $\Downarrow$
  3699. \begin{lstlisting}
  3700. (program ()
  3701. ((block32 . (return 0))
  3702. (block31 . (return 42))
  3703. (start .
  3704. (seq (assign tmp30 (read))
  3705. (if (eq? tmp30 1)
  3706. (goto block31)
  3707. (goto block32))))))
  3708. \end{lstlisting}
  3709. $\Downarrow$
  3710. \begin{lstlisting}
  3711. (program ((locals . (tmp30)))
  3712. ((block32 .
  3713. (block ()
  3714. (movq (int 0) (reg rax))
  3715. (jmp conclusion)))
  3716. (block31 .
  3717. (block ()
  3718. (movq (int 42) (reg rax))
  3719. (jmp conclusion)))
  3720. (start .
  3721. (block ()
  3722. (callq read_int)
  3723. (movq (reg rax) (var tmp30))
  3724. (cmpq (int 1) (var tmp30))
  3725. (jmp-if e block31)
  3726. (jmp block32)))))
  3727. \end{lstlisting}
  3728. \end{minipage}
  3729. &
  3730. $\Rightarrow$
  3731. \begin{minipage}{0.4\textwidth}
  3732. \begin{lstlisting}
  3733. _block31:
  3734. movq $42, %rax
  3735. jmp _conclusion
  3736. _block32:
  3737. movq $0, %rax
  3738. jmp _conclusion
  3739. _start:
  3740. callq _read_int
  3741. movq %rax, %rcx
  3742. cmpq $1, %rcx
  3743. je _block31
  3744. jmp _block32
  3745. .globl _main
  3746. _main:
  3747. pushq %rbp
  3748. movq %rsp, %rbp
  3749. pushq %r12
  3750. pushq %rbx
  3751. pushq %r13
  3752. pushq %r14
  3753. subq $0, %rsp
  3754. jmp _start
  3755. _conclusion:
  3756. addq $0, %rsp
  3757. popq %r14
  3758. popq %r13
  3759. popq %rbx
  3760. popq %r12
  3761. popq %rbp
  3762. retq
  3763. \end{lstlisting}
  3764. \end{minipage}
  3765. \end{tabular}
  3766. \caption{Example compilation of an \key{if} expression to x86.}
  3767. \label{fig:if-example-x86}
  3768. \end{figure}
  3769. \begin{figure}[p]
  3770. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3771. \node (R2) at (0,2) {\large $R_2$};
  3772. \node (R2-2) at (3,2) {\large $R_2$};
  3773. \node (R2-3) at (6,2) {\large $R_2$};
  3774. \node (R2-4) at (9,2) {\large $R_2$};
  3775. \node (R2-5) at (12,2) {\large $R_2$};
  3776. \node (C1-1) at (6,0) {\large $C_1$};
  3777. \node (C1-2) at (3,0) {\large $C_1$};
  3778. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  3779. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  3780. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}$};
  3781. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  3782. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  3783. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  3784. \path[->,bend left=15] (R2) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R2-2);
  3785. \path[->,bend left=15] (R2-2) edge [above] node {\ttfamily\footnotesize\color{red} shrink} (R2-3);
  3786. \path[->,bend left=15] (R2-3) edge [above] node {\ttfamily\footnotesize uniquify} (R2-4);
  3787. \path[->,bend left=15] (R2-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R2-5);
  3788. \path[->,bend left=15] (R2-5) edge [right] node {\ttfamily\footnotesize\color{red} explicate-control} (C1-1);
  3789. \path[->,bend right=15] (C1-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C1-2);
  3790. \path[->,bend right=15] (C1-2) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  3791. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  3792. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  3793. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  3794. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  3795. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize\color{red} print-x86 } (x86-5);
  3796. \end{tikzpicture}
  3797. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  3798. \label{fig:R2-passes}
  3799. \end{figure}
  3800. Figure~\ref{fig:R2-passes} lists all the passes needed for the
  3801. compilation of $R_2$.
  3802. \section{Challenge: Optimize Jumps$^{*}$}
  3803. \label{sec:opt-jumps}
  3804. UNDER CONSTRUCTION
  3805. %% \section{Challenge: Optimizing Conditions$^{*}$}
  3806. %% \label{sec:opt-if}
  3807. %% A close inspection of the x86 code generated in
  3808. %% Figure~\ref{fig:if-example-x86} reveals some redundant computation
  3809. %% regarding the condition of the \key{if}. We compare \key{rcx} to $1$
  3810. %% twice using \key{cmpq} as follows.
  3811. %% % Wierd LaTeX bug if I remove the following. -Jeremy
  3812. %% % Does it have to do with page breaks?
  3813. %% \begin{lstlisting}
  3814. %% \end{lstlisting}
  3815. %% \begin{lstlisting}
  3816. %% cmpq $1, %rcx
  3817. %% sete %al
  3818. %% movzbq %al, %rcx
  3819. %% cmpq $1, %rcx
  3820. %% je then21288
  3821. %% \end{lstlisting}
  3822. %% The reason for this non-optimal code has to do with the \code{flatten}
  3823. %% pass earlier in this Chapter. We recommended flattening the condition
  3824. %% to an $\Arg$ and then comparing with \code{\#t}. But if the condition
  3825. %% is already an \code{eq?} test, then we would like to use that
  3826. %% directly. In fact, for many of the expressions of Boolean type, we can
  3827. %% generate more optimized code. For example, if the condition is
  3828. %% \code{\#t} or \code{\#f}, we do not need to generate an \code{if} at
  3829. %% all. If the condition is a \code{let}, we can optimize based on the
  3830. %% form of its body. If the condition is a \code{not}, then we can flip
  3831. %% the two branches.
  3832. %% %
  3833. %% \margincomment{\tiny We could do even better by converting to basic
  3834. %% blocks.\\ --Jeremy}
  3835. %% %
  3836. %% On the other hand, if the condition is a \code{and}
  3837. %% or another \code{if}, we should flatten them into an $\Arg$ to avoid
  3838. %% code duplication.
  3839. %% Figure~\ref{fig:opt-if} shows an example program and the result of
  3840. %% applying the above suggested optimizations.
  3841. %% \begin{exercise}\normalfont
  3842. %% Change the \code{flatten} pass to improve the code that gets
  3843. %% generated for \code{if} expressions. We recommend writing a helper
  3844. %% function that recursively traverses the condition of the \code{if}.
  3845. %% \end{exercise}
  3846. %% \begin{figure}[tbp]
  3847. %% \begin{tabular}{lll}
  3848. %% \begin{minipage}{0.5\textwidth}
  3849. %% \begin{lstlisting}
  3850. %% (program
  3851. %% (if (let ([x 1])
  3852. %% (not (eq? x (read))))
  3853. %% 777
  3854. %% 42))
  3855. %% \end{lstlisting}
  3856. %% $\Downarrow$
  3857. %% \begin{lstlisting}
  3858. %% (program (x.1 if.2 tmp.3)
  3859. %% (type Integer)
  3860. %% (assign x.1 1)
  3861. %% (assign tmp.3 (read))
  3862. %% (if (eq? x.1 tmp.3)
  3863. %% ((assign if.2 42))
  3864. %% ((assign if.2 777)))
  3865. %% (return if.2))
  3866. %% \end{lstlisting}
  3867. %% $\Downarrow$
  3868. %% \begin{lstlisting}
  3869. %% (program (x.1 if.2 tmp.3)
  3870. %% (type Integer)
  3871. %% (movq (int 1) (var x.1))
  3872. %% (callq read_int)
  3873. %% (movq (reg rax) (var tmp.3))
  3874. %% (if (eq? (var x.1) (var tmp.3))
  3875. %% ((movq (int 42) (var if.2)))
  3876. %% ((movq (int 777) (var if.2))))
  3877. %% (movq (var if.2) (reg rax)))
  3878. %% \end{lstlisting}
  3879. %% \end{minipage}
  3880. %% &
  3881. %% $\Rightarrow$
  3882. %% \begin{minipage}{0.4\textwidth}
  3883. %% \begin{lstlisting}
  3884. %% .globl _main
  3885. %% _main:
  3886. %% pushq %rbp
  3887. %% movq %rsp, %rbp
  3888. %% pushq %r13
  3889. %% pushq %r14
  3890. %% pushq %r12
  3891. %% pushq %rbx
  3892. %% subq $0, %rsp
  3893. %% movq $1, %rbx
  3894. %% callq _read_int
  3895. %% movq %rax, %rcx
  3896. %% cmpq %rcx, %rbx
  3897. %% je then35989
  3898. %% movq $777, %rbx
  3899. %% jmp if_end35990
  3900. %% then35989:
  3901. %% movq $42, %rbx
  3902. %% if_end35990:
  3903. %% movq %rbx, %rax
  3904. %% movq %rax, %rdi
  3905. %% callq _print_int
  3906. %% movq $0, %rax
  3907. %% addq $0, %rsp
  3908. %% popq %rbx
  3909. %% popq %r12
  3910. %% popq %r14
  3911. %% popq %r13
  3912. %% popq %rbp
  3913. %% retq
  3914. %% \end{lstlisting}
  3915. %% \end{minipage}
  3916. %% \end{tabular}
  3917. %% \caption{Example program with optimized conditionals.}
  3918. %% \label{fig:opt-if}
  3919. %% \end{figure}
  3920. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3921. \chapter{Tuples and Garbage Collection}
  3922. \label{ch:tuples}
  3923. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  3924. things to discuss in this chapter. \\ --Jeremy}
  3925. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  3926. all the IR grammars are spelled out! \\ --Jeremy}
  3927. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  3928. but keep type annotations on vector creation and local variables, function
  3929. parameters, etc. \\ --Jeremy}
  3930. \margincomment{\scriptsize Be more explicit about how to deal with
  3931. the root stack. \\ --Jeremy}
  3932. In this chapter we study the implementation of mutable tuples (called
  3933. ``vectors'' in Racket). This language feature is the first to use the
  3934. computer's \emph{heap} because the lifetime of a Racket tuple is
  3935. indefinite, that is, a tuple lives forever from the programmer's
  3936. viewpoint. Of course, from an implementor's viewpoint, it is important
  3937. to reclaim the space associated with a tuple when it is no longer
  3938. needed, which is why we also study \emph{garbage collection}
  3939. techniques in this chapter.
  3940. Section~\ref{sec:r3} introduces the $R_3$ language including its
  3941. interpreter and type checker. The $R_3$ language extends the $R_2$
  3942. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  3943. ``void'' value. The reason for including the later is that the
  3944. \code{vector-set!} operation returns a value of type
  3945. \code{Void}\footnote{This may sound contradictory, but Racket's
  3946. \code{Void} type corresponds to what is more commonly called the
  3947. \code{Unit} type. This type is inhabited by a single value that is
  3948. usually written \code{unit} or \code{()}\citep{Pierce:2002hj}.}.
  3949. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  3950. copying live objects back and forth between two halves of the
  3951. heap. The garbage collector requires coordination with the compiler so
  3952. that it can see all of the \emph{root} pointers, that is, pointers in
  3953. registers or on the procedure call stack.
  3954. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  3955. discuss all the necessary changes and additions to the compiler
  3956. passes, including a new compiler pass named \code{expose-allocation}.
  3957. \section{The $R_3$ Language}
  3958. \label{sec:r3}
  3959. Figure~\ref{fig:r3-syntax} defines the syntax for $R_3$, which
  3960. includes three new forms for creating a tuple, reading an element of a
  3961. tuple, and writing to an element of a tuple. The program in
  3962. Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  3963. create a 3-tuple \code{t} and a 1-tuple. The 1-tuple is stored at
  3964. index $2$ of the 3-tuple, demonstrating that tuples are first-class
  3965. values. The element at index $1$ of \code{t} is \code{\#t}, so the
  3966. ``then'' branch is taken. The element at index $0$ of \code{t} is
  3967. $40$, to which we add the $2$, the element at index $0$ of the
  3968. 1-tuple.
  3969. \begin{figure}[tbp]
  3970. \begin{lstlisting}
  3971. (let ([t (vector 40 #t (vector 2))])
  3972. (if (vector-ref t 1)
  3973. (+ (vector-ref t 0)
  3974. (vector-ref (vector-ref t 2) 0))
  3975. 44))
  3976. \end{lstlisting}
  3977. \caption{Example program that creates tuples and reads from them.}
  3978. \label{fig:vector-eg}
  3979. \end{figure}
  3980. \begin{figure}[tbp]
  3981. \centering
  3982. \fbox{
  3983. \begin{minipage}{0.96\textwidth}
  3984. \[
  3985. \begin{array}{lcl}
  3986. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  3987. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}\\
  3988. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  3989. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  3990. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  3991. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  3992. \mid (\key{and}\;\Exp\;\Exp)
  3993. \mid (\key{or}\;\Exp\;\Exp)
  3994. \mid (\key{not}\;\Exp) } \\
  3995. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  3996. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  3997. &\mid& (\key{vector}\;\Exp^{+})
  3998. \mid (\key{vector-ref}\;\Exp\;\Int) \\
  3999. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)\\
  4000. &\mid& (\key{void}) \\
  4001. R_3 &::=& (\key{program} \; \Exp)
  4002. \end{array}
  4003. \]
  4004. \end{minipage}
  4005. }
  4006. \caption{The syntax of $R_3$, extending $R_2$
  4007. (Figure~\ref{fig:r2-syntax}) with tuples.}
  4008. \label{fig:r3-syntax}
  4009. \end{figure}
  4010. Tuples are our first encounter with heap-allocated data, which raises
  4011. several interesting issues. First, variable binding performs a
  4012. shallow-copy when dealing with tuples, which means that different
  4013. variables can refer to the same tuple, i.e., different variables can
  4014. be \emph{aliases} for the same thing. Consider the following example
  4015. in which both \code{t1} and \code{t2} refer to the same tuple. Thus,
  4016. the mutation through \code{t2} is visible when referencing the tuple
  4017. from \code{t1}, so the result of this program is \code{42}.
  4018. \begin{lstlisting}
  4019. (let ([t1 (vector 3 7)])
  4020. (let ([t2 t1])
  4021. (let ([_ (vector-set! t2 0 42)])
  4022. (vector-ref t1 0))))
  4023. \end{lstlisting}
  4024. The next issue concerns the lifetime of tuples. Of course, they are
  4025. created by the \code{vector} form, but when does their lifetime end?
  4026. Notice that the grammar in Figure~\ref{fig:r3-syntax} does not include
  4027. an operation for deleting tuples. Furthermore, the lifetime of a tuple
  4028. is not tied to any notion of static scoping. For example, the
  4029. following program returns \code{3} even though the variable \code{t}
  4030. goes out of scope prior to accessing the vector.
  4031. \begin{lstlisting}
  4032. (vector-ref
  4033. (let ([t (vector 3 7)])
  4034. t)
  4035. 0)
  4036. \end{lstlisting}
  4037. From the perspective of programmer-observable behavior, tuples live
  4038. forever. Of course, if they really lived forever, then many programs
  4039. would run out of memory.\footnote{The $R_3$ language does not have
  4040. looping or recursive function, so it is nigh impossible to write a
  4041. program in $R_3$ that will run out of memory. However, we add
  4042. recursive functions in the next Chapter!} A Racket implementation
  4043. must therefore perform automatic garbage collection.
  4044. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  4045. $R_3$ language and Figure~\ref{fig:typecheck-R3} shows the type
  4046. checker. The additions to the interpreter are straightforward but the
  4047. updates to the type checker deserve some explanation. As we shall see
  4048. in Section~\ref{sec:GC}, we need to know which variables are pointers
  4049. into the heap, that is, which variables are vectors. Also, when
  4050. allocating a vector, we shall need to know which elements of the
  4051. vector are pointers. We can obtain this information during type
  4052. checking and when we uncover local variables. The type checker in
  4053. Figure~\ref{fig:typecheck-R3} not only computes the type of an
  4054. expression, it also wraps every sub-expression $e$ with the form
  4055. $(\key{has-type}\; e\; T)$, where $T$ is $e$'s type. Subsequently, in
  4056. the \code{uncover-locals} pass (Section~\ref{sec:uncover-locals-r3})
  4057. this type information is propagated to all variables (including the
  4058. temporaries generated by \code{remove-complex-opera*}).
  4059. \begin{figure}[tbp]
  4060. \begin{lstlisting}
  4061. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  4062. (define (interp-op op)
  4063. (match op
  4064. ...
  4065. ['vector vector]
  4066. ['vector-ref vector-ref]
  4067. ['vector-set! vector-set!]
  4068. [else (error 'interp-op "unknown operator")]))
  4069. (define (interp-R3 env)
  4070. (lambda (e)
  4071. (match e
  4072. ...
  4073. [else (error 'interp-R3 "unrecognized expression")]
  4074. )))
  4075. \end{lstlisting}
  4076. \caption{Interpreter for the $R_3$ language.}
  4077. \label{fig:interp-R3}
  4078. \end{figure}
  4079. \begin{figure}[tbp]
  4080. \begin{lstlisting}
  4081. (define (type-check-exp env)
  4082. (lambda (e)
  4083. (define recur (type-check-exp env))
  4084. (match e
  4085. ...
  4086. ['(void) (values '(has-type (void) Void) 'Void)]
  4087. [`(vector ,es ...)
  4088. (define-values (e* t*) (for/lists (e* t*) ([e es])
  4089. (recur e)))
  4090. (let ([t `(Vector ,@t*)])
  4091. (debug "vector/type-check-exp finished vector" t)
  4092. (values `(has-type (vector ,@e*) ,t) t))]
  4093. [`(vector-ref ,e ,i)
  4094. (define-values (e^ t) (recur e))
  4095. (match t
  4096. [`(Vector ,ts ...)
  4097. (unless (and (exact-nonnegative-integer? i) (< i (length ts)))
  4098. (error 'type-check-exp "invalid index ~a" i))
  4099. (let ([t (list-ref ts i)])
  4100. (values `(has-type (vector-ref ,e^ (has-type ,i Integer)) ,t)
  4101. t))]
  4102. [else (error "expected a vector in vector-ref, not" t)])]
  4103. [`(eq? ,arg1 ,arg2)
  4104. (define-values (e1 t1) (recur arg1))
  4105. (define-values (e2 t2) (recur arg2))
  4106. (match* (t1 t2)
  4107. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  4108. (values `(has-type (eq? ,e1 ,e2) Boolean) 'Boolean)]
  4109. [(other wise) ((super type-check-exp env) e)])]
  4110. ...
  4111. )))
  4112. \end{lstlisting}
  4113. \caption{Type checker for the $R_3$ language.}
  4114. \label{fig:typecheck-R3}
  4115. \end{figure}
  4116. \section{Garbage Collection}
  4117. \label{sec:GC}
  4118. Here we study a relatively simple algorithm for garbage collection
  4119. that is the basis of state-of-the-art garbage
  4120. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  4121. particular, we describe a two-space copying
  4122. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  4123. perform the
  4124. copy~\citep{Cheney:1970aa}. Figure~\ref{fig:copying-collector} gives a
  4125. coarse-grained depiction of what happens in a two-space collector,
  4126. showing two time steps, prior to garbage collection on the top and
  4127. after garbage collection on the bottom. In a two-space collector, the
  4128. heap is divided into two parts, the FromSpace and the
  4129. ToSpace. Initially, all allocations go to the FromSpace until there is
  4130. not enough room for the next allocation request. At that point, the
  4131. garbage collector goes to work to make more room.
  4132. The garbage collector must be careful not to reclaim tuples that will
  4133. be used by the program in the future. Of course, it is impossible in
  4134. general to predict what a program will do, but we can overapproximate
  4135. the will-be-used tuples by preserving all tuples that could be
  4136. accessed by \emph{any} program given the current computer state. A
  4137. program could access any tuple whose address is in a register or on
  4138. the procedure call stack. These addresses are called the \emph{root
  4139. set}. In addition, a program could access any tuple that is
  4140. transitively reachable from the root set. Thus, it is safe for the
  4141. garbage collector to reclaim the tuples that are not reachable in this
  4142. way.
  4143. So the goal of the garbage collector is twofold:
  4144. \begin{enumerate}
  4145. \item preserve all tuple that are reachable from the root set via a
  4146. path of pointers, that is, the \emph{live} tuples, and
  4147. \item reclaim the memory of everything else, that is, the
  4148. \emph{garbage}.
  4149. \end{enumerate}
  4150. A copying collector accomplishes this by copying all of the live
  4151. objects from the FromSpace into the ToSpace and then performs a slight
  4152. of hand, treating the ToSpace as the new FromSpace and the old
  4153. FromSpace as the new ToSpace. In the example of
  4154. Figure~\ref{fig:copying-collector}, there are three pointers in the
  4155. root set, one in a register and two on the stack. All of the live
  4156. objects have been copied to the ToSpace (the right-hand side of
  4157. Figure~\ref{fig:copying-collector}) in a way that preserves the
  4158. pointer relationships. For example, the pointer in the register still
  4159. points to a 2-tuple whose first element is a 3-tuple and second
  4160. element is a 2-tuple. There are four tuples that are not reachable
  4161. from the root set and therefore do not get copied into the ToSpace.
  4162. (The sitation in Figure~\ref{fig:copying-collector}, with a
  4163. cycle, cannot be created by a well-typed program in $R_3$. However,
  4164. creating cycles will be possible once we get to $R_6$. We design
  4165. the garbage collector to deal with cycles to begin with, so we will
  4166. not need to revisit this issue.)
  4167. \begin{figure}[tbp]
  4168. \centering
  4169. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  4170. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  4171. \caption{A copying collector in action.}
  4172. \label{fig:copying-collector}
  4173. \end{figure}
  4174. There are many alternatives to copying collectors (and their older
  4175. siblings, the generational collectors) when its comes to garbage
  4176. collection, such as mark-and-sweep and reference counting. The
  4177. strengths of copying collectors are that allocation is fast (just a
  4178. test and pointer increment), there is no fragmentation, cyclic garbage
  4179. is collected, and the time complexity of collection only depends on
  4180. the amount of live data, and not on the amount of
  4181. garbage~\citep{Wilson:1992fk}. The main disadvantage of two-space
  4182. copying collectors is that they use a lot of space, though that
  4183. problem is ameliorated in generational collectors. Racket and Scheme
  4184. programs tend to allocate many small objects and generate a lot of
  4185. garbage, so copying and generational collectors are a good fit. Of
  4186. course, garbage collection is an active research topic, especially
  4187. concurrent garbage collection~\citep{Tene:2011kx}. Researchers are
  4188. continuously developing new techniques and revisiting old
  4189. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa}.
  4190. \subsection{Graph Copying via Cheney's Algorithm}
  4191. \label{sec:cheney}
  4192. Let us take a closer look at how the copy works. The allocated objects
  4193. and pointers can be viewed as a graph and we need to copy the part of
  4194. the graph that is reachable from the root set. To make sure we copy
  4195. all of the reachable vertices in the graph, we need an exhaustive
  4196. graph traversal algorithm, such as depth-first search or breadth-first
  4197. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  4198. take into account the possibility of cycles by marking which vertices
  4199. have already been visited, so as to ensure termination of the
  4200. algorithm. These search algorithms also use a data structure such as a
  4201. stack or queue as a to-do list to keep track of the vertices that need
  4202. to be visited. We shall use breadth-first search and a trick due to
  4203. \citet{Cheney:1970aa} for simultaneously representing the queue and
  4204. copying tuples into the ToSpace.
  4205. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  4206. copy progresses. The queue is represented by a chunk of contiguous
  4207. memory at the beginning of the ToSpace, using two pointers to track
  4208. the front and the back of the queue. The algorithm starts by copying
  4209. all tuples that are immediately reachable from the root set into the
  4210. ToSpace to form the initial queue. When we copy a tuple, we mark the
  4211. old tuple to indicate that it has been visited. (We discuss the
  4212. marking in Section~\ref{sec:data-rep-gc}.) Note that any pointers
  4213. inside the copied tuples in the queue still point back to the
  4214. FromSpace. Once the initial queue has been created, the algorithm
  4215. enters a loop in which it repeatedly processes the tuple at the front
  4216. of the queue and pops it off the queue. To process a tuple, the
  4217. algorithm copies all the tuple that are directly reachable from it to
  4218. the ToSpace, placing them at the back of the queue. The algorithm then
  4219. updates the pointers in the popped tuple so they point to the newly
  4220. copied tuples. Getting back to Figure~\ref{fig:cheney}, in the first
  4221. step we copy the tuple whose second element is $42$ to the back of the
  4222. queue. The other pointer goes to a tuple that has already been copied,
  4223. so we do not need to copy it again, but we do need to update the
  4224. pointer to the new location. This can be accomplished by storing a
  4225. \emph{forwarding} pointer to the new location in the old tuple, back
  4226. when we initially copied the tuple into the ToSpace. This completes
  4227. one step of the algorithm. The algorithm continues in this way until
  4228. the front of the queue is empty, that is, until the front catches up
  4229. with the back.
  4230. \begin{figure}[tbp]
  4231. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  4232. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  4233. \label{fig:cheney}
  4234. \end{figure}
  4235. \subsection{Data Representation}
  4236. \label{sec:data-rep-gc}
  4237. The garbage collector places some requirements on the data
  4238. representations used by our compiler. First, the garbage collector
  4239. needs to distinguish between pointers and other kinds of data. There
  4240. are several ways to accomplish this.
  4241. \begin{enumerate}
  4242. \item Attached a tag to each object that identifies what type of
  4243. object it is~\citep{McCarthy:1960dz}.
  4244. \item Store different types of objects in different
  4245. regions~\citep{Steele:1977ab}.
  4246. \item Use type information from the program to either generate
  4247. type-specific code for collecting or to generate tables that can
  4248. guide the
  4249. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  4250. \end{enumerate}
  4251. Dynamically typed languages, such as Lisp, need to tag objects
  4252. anyways, so option 1 is a natural choice for those languages.
  4253. However, $R_3$ is a statically typed language, so it would be
  4254. unfortunate to require tags on every object, especially small and
  4255. pervasive objects like integers and Booleans. Option 3 is the
  4256. best-performing choice for statically typed languages, but comes with
  4257. a relatively high implementation complexity. To keep this chapter to a
  4258. 2-week time budget, we recommend a combination of options 1 and 2,
  4259. with separate strategies used for the stack and the heap.
  4260. Regarding the stack, we recommend using a separate stack for
  4261. pointers~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}, which
  4262. we call a \emph{root stack} (a.k.a. ``shadow stack''). That is, when a
  4263. local variable needs to be spilled and is of type \code{(Vector
  4264. $\Type_1 \ldots \Type_n$)}, then we put it on the root stack instead
  4265. of the normal procedure call stack. Furthermore, we always spill
  4266. vector-typed variables if they are live during a call to the
  4267. collector, thereby ensuring that no pointers are in registers during a
  4268. collection. Figure~\ref{fig:shadow-stack} reproduces the example from
  4269. Figure~\ref{fig:copying-collector} and contrasts it with the data
  4270. layout using a root stack. The root stack contains the two pointers
  4271. from the regular stack and also the pointer in the second
  4272. register.
  4273. \begin{figure}[tbp]
  4274. \centering \includegraphics[width=0.7\textwidth]{figs/root-stack}
  4275. \caption{Maintaining a root stack to facilitate garbage collection.}
  4276. \label{fig:shadow-stack}
  4277. \end{figure}
  4278. The problem of distinguishing between pointers and other kinds of data
  4279. also arises inside of each tuple. We solve this problem by attaching a
  4280. tag, an extra 64-bits, to each tuple. Figure~\ref{fig:tuple-rep} zooms
  4281. in on the tags for two of the tuples in the example from
  4282. Figure~\ref{fig:copying-collector}. Note that we have drawn the bits
  4283. in a big-endian way, from right-to-left, with bit location 0 (the
  4284. least significant bit) on the far right, which corresponds to the
  4285. directionality of the x86 shifting instructions \key{salq} (shift
  4286. left) and \key{sarq} (shift right). Part of each tag is dedicated to
  4287. specifying which elements of the tuple are pointers, the part labeled
  4288. ``pointer mask''. Within the pointer mask, a 1 bit indicates there is
  4289. a pointer and a 0 bit indicates some other kind of data. The pointer
  4290. mask starts at bit location 7. We have limited tuples to a maximum
  4291. size of 50 elements, so we just need 50 bits for the pointer mask. The
  4292. tag also contains two other pieces of information. The length of the
  4293. tuple (number of elements) is stored in bits location 1 through
  4294. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  4295. to be copied to the ToSpace. If the bit has value 1, then this tuple
  4296. has not yet been copied. If the bit has value 0 then the entire tag
  4297. is in fact a forwarding pointer. (The lower 3 bits of an pointer are
  4298. always zero anyways because our tuples are 8-byte aligned.)
  4299. \begin{figure}[tbp]
  4300. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  4301. \caption{Representation for tuples in the heap.}
  4302. \label{fig:tuple-rep}
  4303. \end{figure}
  4304. \subsection{Implementation of the Garbage Collector}
  4305. \label{sec:organize-gz}
  4306. The implementation of the garbage collector needs to do a lot of
  4307. bit-level data manipulation and we need to link it with our
  4308. compiler-generated x86 code. Thus, we recommend implementing the
  4309. garbage collector in C~\citep{Kernighan:1988nx} and putting the code
  4310. in the \code{runtime.c} file. Figure~\ref{fig:gc-header} shows the
  4311. interface to the garbage collector. The \code{initialize} function
  4312. creates the FromSpace, ToSpace, and root stack. The \code{initialize}
  4313. function is meant to be called near the beginning of \code{main},
  4314. before the rest of the program executes. The \code{initialize}
  4315. function puts the address of the beginning of the FromSpace into the
  4316. global variable \code{free\_ptr}. The global \code{fromspace\_end}
  4317. points to the address that is 1-past the last element of the
  4318. FromSpace. (We use half-open intervals to represent chunks of
  4319. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} global
  4320. points to the first element of the root stack.
  4321. As long as there is room left in the FromSpace, your generated code
  4322. can allocate tuples simply by moving the \code{free\_ptr} forward.
  4323. %
  4324. \margincomment{\tiny Should we dedicate a register to the free pointer? \\
  4325. --Jeremy}
  4326. %
  4327. The amount of room left in FromSpace is the difference between the
  4328. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  4329. function should be called when there is not enough room left in the
  4330. FromSpace for the next allocation. The \code{collect} function takes
  4331. a pointer to the current top of the root stack (one past the last item
  4332. that was pushed) and the number of bytes that need to be
  4333. allocated. The \code{collect} function performs the copying collection
  4334. and leaves the heap in a state such that the next allocation will
  4335. succeed.
  4336. \begin{figure}[tbp]
  4337. \begin{lstlisting}
  4338. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  4339. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  4340. int64_t* free_ptr;
  4341. int64_t* fromspace_begin;
  4342. int64_t* fromspace_end;
  4343. int64_t** rootstack_begin;
  4344. \end{lstlisting}
  4345. \caption{The compiler's interface to the garbage collector.}
  4346. \label{fig:gc-header}
  4347. \end{figure}
  4348. \begin{exercise}
  4349. In the file \code{runtime.c} you will find the implementation of
  4350. \code{initialize} and a partial implementation of \code{collect}.
  4351. The \code{collect} function calls another function, \code{cheney},
  4352. to perform the actual copy, and that function is left to the reader
  4353. to implement. The following is the prototype for \code{cheney}.
  4354. \begin{lstlisting}
  4355. static void cheney(int64_t** rootstack_ptr);
  4356. \end{lstlisting}
  4357. The parameter \code{rootstack\_ptr} is a pointer to the top of the
  4358. rootstack (which is an array of pointers). The \code{cheney} function
  4359. also communicates with \code{collect} through the global
  4360. variables \code{fromspace\_begin} and \code{fromspace\_end}
  4361. mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  4362. the ToSpace:
  4363. \begin{lstlisting}
  4364. static int64_t* tospace_begin;
  4365. static int64_t* tospace_end;
  4366. \end{lstlisting}
  4367. The job of the \code{cheney} function is to copy all the live
  4368. objects (reachable from the root stack) into the ToSpace, update
  4369. \code{free\_ptr} to point to the next unused spot in the ToSpace,
  4370. update the root stack so that it points to the objects in the
  4371. ToSpace, and finally to swap the global pointers for the FromSpace
  4372. and ToSpace.
  4373. \end{exercise}
  4374. %% \section{Compiler Passes}
  4375. %% \label{sec:code-generation-gc}
  4376. The introduction of garbage collection has a non-trivial impact on our
  4377. compiler passes. We introduce one new compiler pass called
  4378. \code{expose-allocation} and make non-trivial changes to
  4379. \code{type-check}, \code{flatten}, \code{select-instructions},
  4380. \code{allocate-registers}, and \code{print-x86}. The following
  4381. program will serve as our running example. It creates two tuples, one
  4382. nested inside the other. Both tuples have length one. The example then
  4383. accesses the element in the inner tuple tuple via two vector
  4384. references.
  4385. % tests/s2_17.rkt
  4386. \begin{lstlisting}
  4387. (vector-ref (vector-ref (vector (vector 42)) 0) 0))
  4388. \end{lstlisting}
  4389. Next we proceed to discuss the new \code{expose-allocation} pass.
  4390. \section{Expose Allocation}
  4391. \label{sec:expose-allocation}
  4392. The pass \code{expose-allocation} lowers the \code{vector} creation
  4393. form into a conditional call to the collector followed by the
  4394. allocation. We choose to place the \code{expose-allocation} pass
  4395. before \code{flatten} because \code{expose-allocation} introduces new
  4396. variables, which can be done locally with \code{let}, but \code{let}
  4397. is gone after \code{flatten}. In the following, we show the
  4398. transformation for the \code{vector} form into let-bindings for the
  4399. intializing expressions, by a conditional \code{collect}, an
  4400. \code{allocate}, and the initialization of the vector.
  4401. (The \itm{len} is the length of the vector and \itm{bytes} is how many
  4402. total bytes need to be allocated for the vector, which is 8 for the
  4403. tag plus \itm{len} times 8.)
  4404. \begin{lstlisting}
  4405. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  4406. |$\Longrightarrow$|
  4407. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  4408. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  4409. (global-value fromspace_end))
  4410. (void)
  4411. (collect |\itm{bytes}|))])
  4412. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  4413. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  4414. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  4415. |$v$|) ... )))) ...)
  4416. \end{lstlisting}
  4417. (In the above, we suppressed all of the \code{has-type} forms in the
  4418. output for the sake of readability.) The placement of the initializing
  4419. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and
  4420. the sequence of \code{vector-set!}'s is important, as those expressions
  4421. may trigger garbage collection and we do not want an allocated but
  4422. uninitialized tuple to be present during a garbage collection.
  4423. The output of \code{expose-allocation} is a language that extends
  4424. $R_3$ with the three new forms that we use above in the translation of
  4425. \code{vector}.
  4426. \[
  4427. \begin{array}{lcl}
  4428. \Exp &::=& \cdots
  4429. \mid (\key{collect} \,\itm{int})
  4430. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  4431. \mid (\key{global-value} \,\itm{name})
  4432. \end{array}
  4433. \]
  4434. %% The \code{expose-allocation} inserts an \code{initialize} statement at
  4435. %% the beginning of the program which will instruct the garbage collector
  4436. %% to set up the FromSpace, ToSpace, and all the global variables. The
  4437. %% two arguments of \code{initialize} specify the initial allocated space
  4438. %% for the root stack and for the heap.
  4439. %
  4440. %% The \code{expose-allocation} pass annotates all of the local variables
  4441. %% in the \code{program} form with their type.
  4442. Figure~\ref{fig:expose-alloc-output} shows the output of the
  4443. \code{expose-allocation} pass on our running example.
  4444. \begin{figure}[tbp]
  4445. \begin{lstlisting}
  4446. (program ()
  4447. (vector-ref
  4448. (vector-ref
  4449. (let ((vecinit48
  4450. (let ((vecinit44 42))
  4451. (let ((collectret46
  4452. (if (<
  4453. (+ (global-value free_ptr) 16)
  4454. (global-value fromspace_end))
  4455. (void)
  4456. (collect 16))))
  4457. (let ((alloc43 (allocate 1 (Vector Integer))))
  4458. (let ((initret45 (vector-set! alloc43 0 vecinit44)))
  4459. alloc43))))))
  4460. (let ((collectret50
  4461. (if (< (+ (global-value free_ptr) 16)
  4462. (global-value fromspace_end))
  4463. (void)
  4464. (collect 16))))
  4465. (let ((alloc47 (allocate 1 (Vector (Vector Integer)))))
  4466. (let ((initret49 (vector-set! alloc47 0 vecinit48)))
  4467. alloc47))))
  4468. 0)
  4469. 0))
  4470. \end{lstlisting}
  4471. \caption{Output of the \code{expose-allocation} pass, minus
  4472. all of the \code{has-type} forms.}
  4473. \label{fig:expose-alloc-output}
  4474. \end{figure}
  4475. %\clearpage
  4476. \section{Explicate Control and the $C_2$ language}
  4477. \label{sec:explicate-control-r3}
  4478. \begin{figure}[tp]
  4479. \fbox{
  4480. \begin{minipage}{0.96\textwidth}
  4481. \[
  4482. \begin{array}{lcl}
  4483. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }\\
  4484. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  4485. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  4486. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  4487. &\mid& (\key{allocate} \,\itm{int}\,\itm{type})
  4488. \mid (\key{vector-ref}\, \Arg\, \Int) \\
  4489. &\mid& (\key{vector-set!}\,\Arg\,\Int\,\Arg)
  4490. \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) \\
  4491. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp} }
  4492. \mid (\key{collect} \,\itm{int}) \\
  4493. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  4494. &\mid& \gray{(\key{goto}\,\itm{label})
  4495. \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  4496. C_2 & ::= & (\key{program}\;\itm{info}\; ((\itm{label}\,\key{.}\,\Tail)^{+}))
  4497. \end{array}
  4498. \]
  4499. \end{minipage}
  4500. }
  4501. \caption{The $C_2$ language, extending $C_1$
  4502. (Figure~\ref{fig:c1-syntax}) with vectors.}
  4503. \label{fig:c2-syntax}
  4504. \end{figure}
  4505. The output of \code{explicate-control} is a program in the
  4506. intermediate language $C_2$, whose syntax is defined in
  4507. Figure~\ref{fig:c2-syntax}. The new forms of $C_2$ include the
  4508. \key{allocate}, \key{vector-ref}, and \key{vector-set!}, and
  4509. \key{global-value} expressions and the \code{collect} statement. The
  4510. \code{explicate-control} pass can treat these new forms much like the
  4511. other forms.
  4512. \section{Uncover Locals}
  4513. \label{sec:uncover-locals-r3}
  4514. Recall that the \code{uncover-locals} function collects all of the
  4515. local variables so that it can store them in the $\itm{info}$ field of
  4516. the \code{program} form. Also recall that we need to know the types of
  4517. all the local variables for purposes of identifying the root set for
  4518. the garbage collector. Thus, we change \code{uncover-locals} to
  4519. collect not just the variables, but the variables and their types in
  4520. the form of an association list. Thanks to the \code{has-type} forms,
  4521. the types are readily available. Figure~\ref{fig:uncover-locals-r3}
  4522. lists the output of the \code{uncover-locals} pass on the running
  4523. example.
  4524. \begin{figure}[tbp]
  4525. \begin{lstlisting}
  4526. (program
  4527. ((locals . ((tmp54 . Integer) (tmp51 . Integer) (tmp53 . Integer)
  4528. (alloc43 . (Vector Integer)) (tmp55 . Integer)
  4529. (initret45 . Void) (alloc47 . (Vector (Vector Integer)))
  4530. (collectret46 . Void) (vecinit48 . (Vector Integer))
  4531. (tmp52 . Integer) (tmp57 . (Vector Integer))
  4532. (vecinit44 . Integer) (tmp56 . Integer) (initret49 . Void)
  4533. (collectret50 . Void))))
  4534. ((block63 . (seq (collect 16) (goto block61)))
  4535. (block62 . (seq (assign collectret46 (void)) (goto block61)))
  4536. (block61 . (seq (assign alloc43 (allocate 1 (Vector Integer)))
  4537. (seq (assign initret45 (vector-set! alloc43 0 vecinit44))
  4538. (seq (assign vecinit48 alloc43)
  4539. (seq (assign tmp54 (global-value free_ptr))
  4540. (seq (assign tmp55 (+ tmp54 16))
  4541. (seq (assign tmp56 (global-value fromspace_end))
  4542. (if (< tmp55 tmp56) (goto block59) (goto block60)))))))))
  4543. (block60 . (seq (collect 16) (goto block58)))
  4544. (block59 . (seq (assign collectret50 (void)) (goto block58)))
  4545. (block58 . (seq (assign alloc47 (allocate 1 (Vector (Vector Integer))))
  4546. (seq (assign initret49 (vector-set! alloc47 0 vecinit48))
  4547. (seq (assign tmp57 (vector-ref alloc47 0))
  4548. (return (vector-ref tmp57 0))))))
  4549. (start . (seq (assign vecinit44 42)
  4550. (seq (assign tmp51 (global-value free_ptr))
  4551. (seq (assign tmp52 (+ tmp51 16))
  4552. (seq (assign tmp53 (global-value fromspace_end))
  4553. (if (< tmp52 tmp53) (goto block62) (goto block63)))))))))
  4554. \end{lstlisting}
  4555. \caption{Output of \code{uncover-locals} for the running example.}
  4556. \label{fig:uncover-locals-r3}
  4557. \end{figure}
  4558. \clearpage
  4559. \section{Select Instructions}
  4560. \label{sec:select-instructions-gc}
  4561. %% void (rep as zero)
  4562. %% allocate
  4563. %% collect (callq collect)
  4564. %% vector-ref
  4565. %% vector-set!
  4566. %% global-value (postpone)
  4567. In this pass we generate x86 code for most of the new operations that
  4568. were needed to compile tuples, including \code{allocate},
  4569. \code{collect}, \code{vector-ref}, \code{vector-set!}, and
  4570. \code{(void)}. We postpone \code{global-value} to \code{print-x86}.
  4571. The \code{vector-ref} and \code{vector-set!} forms translate into
  4572. \code{movq} instructions with the appropriate \key{deref}. (The
  4573. plus one is to get past the tag at the beginning of the tuple
  4574. representation.)
  4575. \begin{lstlisting}
  4576. (assign |$\itm{lhs}$| (vector-ref |$\itm{vec}$| |$n$|))
  4577. |$\Longrightarrow$|
  4578. (movq |$\itm{vec}'$| (reg r11))
  4579. (movq (deref r11 |$8(n+1)$|) |$\itm{lhs}$|)
  4580. (assign |$\itm{lhs}$| (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|))
  4581. |$\Longrightarrow$|
  4582. (movq |$\itm{vec}'$| (reg r11))
  4583. (movq |$\itm{arg}'$| (deref r11 |$8(n+1)$|))
  4584. (movq (int 0) |$\itm{lhs}$|)
  4585. \end{lstlisting}
  4586. The $\itm{vec}'$ and $\itm{arg}'$ are obtained by recursively
  4587. processing $\itm{vec}$ and $\itm{arg}$. The move of $\itm{vec}'$ to
  4588. register \code{r11} ensures that offsets are only performed with
  4589. register operands. This requires removing \code{r11} from
  4590. consideration by the register allocating.
  4591. We compile the \code{allocate} form to operations on the
  4592. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  4593. is the next free address in the FromSpace, so we move it into the
  4594. \itm{lhs} and then move it forward by enough space for the tuple being
  4595. allocated, which is $8(\itm{len}+1)$ bytes because each element is 8
  4596. bytes (64 bits) and we use 8 bytes for the tag. Last but not least, we
  4597. initialize the \itm{tag}. Refer to Figure~\ref{fig:tuple-rep} to see
  4598. how the tag is organized. We recommend using the Racket operations
  4599. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag.
  4600. The type annoation in the \code{vector} form is used to determine the
  4601. pointer mask region of the tag.
  4602. \begin{lstlisting}
  4603. (assign |$\itm{lhs}$| (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|)))
  4604. |$\Longrightarrow$|
  4605. (movq (global-value free_ptr) |$\itm{lhs}'$|)
  4606. (addq (int |$8(\itm{len}+1)$|) (global-value free_ptr))
  4607. (movq |$\itm{lhs}'$| (reg r11))
  4608. (movq (int |$\itm{tag}$|) (deref r11 0))
  4609. \end{lstlisting}
  4610. The \code{collect} form is compiled to a call to the \code{collect}
  4611. function in the runtime. The arguments to \code{collect} are the top
  4612. of the root stack and the number of bytes that need to be allocated.
  4613. We shall use a dedicated register, \code{r15}, to store the pointer to
  4614. the top of the root stack. So \code{r15} is not available for use by
  4615. the register allocator.
  4616. \begin{lstlisting}
  4617. (collect |$\itm{bytes}$|)
  4618. |$\Longrightarrow$|
  4619. (movq (reg r15) (reg rdi))
  4620. (movq |\itm{bytes}| (reg rsi))
  4621. (callq collect)
  4622. \end{lstlisting}
  4623. \begin{figure}[tp]
  4624. \fbox{
  4625. \begin{minipage}{0.96\textwidth}
  4626. \[
  4627. \begin{array}{lcl}
  4628. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\itm{register}}
  4629. \mid (\key{deref}\,\itm{register}\,\Int) } \\
  4630. &\mid& \gray{ (\key{byte-reg}\; \itm{register}) }
  4631. \mid (\key{global-value}\; \itm{name}) \\
  4632. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  4633. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  4634. (\key{subq} \; \Arg\; \Arg) \mid
  4635. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  4636. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  4637. (\key{pushq}\;\Arg) \mid
  4638. (\key{popq}\;\Arg) \mid
  4639. (\key{retq})} \\
  4640. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  4641. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  4642. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  4643. \mid (\key{jmp} \; \itm{label})
  4644. \mid (\key{jmp-if}\itm{cc} \; \itm{label})}\\
  4645. &\mid& \gray{(\key{label} \; \itm{label}) } \\
  4646. x86_2 &::= & \gray{ (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+}) }
  4647. \end{array}
  4648. \]
  4649. \end{minipage}
  4650. }
  4651. \caption{The x86$_2$ language (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  4652. \label{fig:x86-2}
  4653. \end{figure}
  4654. The syntax of the $x86_2$ language is defined in
  4655. Figure~\ref{fig:x86-2}. It differs from $x86_1$ just in the addition
  4656. of the form for global variables.
  4657. %
  4658. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  4659. \code{select-instructions} pass on the running example.
  4660. \begin{figure}[tbp]
  4661. \centering
  4662. \begin{minipage}{0.75\textwidth}
  4663. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4664. (program
  4665. ((locals . ((tmp54 . Integer) (tmp51 . Integer) (tmp53 . Integer)
  4666. (alloc43 . (Vector Integer)) (tmp55 . Integer)
  4667. (initret45 . Void) (alloc47 . (Vector (Vector Integer)))
  4668. (collectret46 . Void) (vecinit48 . (Vector Integer))
  4669. (tmp52 . Integer) (tmp57 Vector Integer) (vecinit44 . Integer)
  4670. (tmp56 . Integer) (initret49 . Void) (collectret50 . Void))))
  4671. ((block63 . (block ()
  4672. (movq (reg r15) (reg rdi))
  4673. (movq (int 16) (reg rsi))
  4674. (callq collect)
  4675. (jmp block61)))
  4676. (block62 . (block () (movq (int 0) (var collectret46)) (jmp block61)))
  4677. (block61 . (block ()
  4678. (movq (global-value free_ptr) (var alloc43))
  4679. (addq (int 16) (global-value free_ptr))
  4680. (movq (var alloc43) (reg r11))
  4681. (movq (int 3) (deref r11 0))
  4682. (movq (var alloc43) (reg r11))
  4683. (movq (var vecinit44) (deref r11 8))
  4684. (movq (int 0) (var initret45))
  4685. (movq (var alloc43) (var vecinit48))
  4686. (movq (global-value free_ptr) (var tmp54))
  4687. (movq (var tmp54) (var tmp55))
  4688. (addq (int 16) (var tmp55))
  4689. (movq (global-value fromspace_end) (var tmp56))
  4690. (cmpq (var tmp56) (var tmp55))
  4691. (jmp-if l block59)
  4692. (jmp block60)))
  4693. (block60 . (block ()
  4694. (movq (reg r15) (reg rdi))
  4695. (movq (int 16) (reg rsi))
  4696. (callq collect)
  4697. (jmp block58))
  4698. (block59 . (block ()
  4699. (movq (int 0) (var collectret50))
  4700. (jmp block58)))
  4701. (block58 . (block ()
  4702. (movq (global-value free_ptr) (var alloc47))
  4703. (addq (int 16) (global-value free_ptr))
  4704. (movq (var alloc47) (reg r11))
  4705. (movq (int 131) (deref r11 0))
  4706. (movq (var alloc47) (reg r11))
  4707. (movq (var vecinit48) (deref r11 8))
  4708. (movq (int 0) (var initret49))
  4709. (movq (var alloc47) (reg r11))
  4710. (movq (deref r11 8) (var tmp57))
  4711. (movq (var tmp57) (reg r11))
  4712. (movq (deref r11 8) (reg rax))
  4713. (jmp conclusion)))
  4714. (start . (block ()
  4715. (movq (int 42) (var vecinit44))
  4716. (movq (global-value free_ptr) (var tmp51))
  4717. (movq (var tmp51) (var tmp52))
  4718. (addq (int 16) (var tmp52))
  4719. (movq (global-value fromspace_end) (var tmp53))
  4720. (cmpq (var tmp53) (var tmp52))
  4721. (jmp-if l block62)
  4722. (jmp block63))))))
  4723. \end{lstlisting}
  4724. \end{minipage}
  4725. \caption{Output of the \code{select-instructions} pass.}
  4726. \label{fig:select-instr-output-gc}
  4727. \end{figure}
  4728. \clearpage
  4729. \section{Register Allocation}
  4730. \label{sec:reg-alloc-gc}
  4731. As discussed earlier in this chapter, the garbage collector needs to
  4732. access all the pointers in the root set, that is, all variables that
  4733. are vectors. It will be the responsibility of the register allocator
  4734. to make sure that:
  4735. \begin{enumerate}
  4736. \item the root stack is used for spilling vector-typed variables, and
  4737. \item if a vector-typed variable is live during a call to the
  4738. collector, it must be spilled to ensure it is visible to the
  4739. collector.
  4740. \end{enumerate}
  4741. The later responsibility can be handled during construction of the
  4742. inference graph, by adding interference edges between the call-live
  4743. vector-typed variables and all the callee-saved registers. (They
  4744. already interfere with the caller-saved registers.) The type
  4745. information for variables is in the \code{program} form, so we
  4746. recommend adding another parameter to the \code{build-interference}
  4747. function to communicate this association list.
  4748. The spilling of vector-typed variables to the root stack can be
  4749. handled after graph coloring, when choosing how to assign the colors
  4750. (integers) to registers and stack locations. The \code{program} output
  4751. of this pass changes to also record the number of spills to the root
  4752. stack.
  4753. % build-interference
  4754. %
  4755. % callq
  4756. % extra parameter for var->type assoc. list
  4757. % update 'program' and 'if'
  4758. % allocate-registers
  4759. % allocate spilled vectors to the rootstack
  4760. % don't change color-graph
  4761. \section{Print x86}
  4762. \label{sec:print-x86-gc}
  4763. \margincomment{\scriptsize We need to show the translation to x86 and what
  4764. to do about global-value. \\ --Jeremy}
  4765. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  4766. \code{print-x86} pass on the running example. In the prelude and
  4767. conclusion of the \code{main} function, we treat the root stack very
  4768. much like the regular stack in that we move the root stack pointer
  4769. (\code{r15}) to make room for all of the spills to the root stack,
  4770. except that the root stack grows up instead of down. For the running
  4771. example, there was just one spill so we increment \code{r15} by 8
  4772. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  4773. One issue that deserves special care is that there may be a call to
  4774. \code{collect} prior to the initializing assignments for all the
  4775. variables in the root stack. We do not want the garbage collector to
  4776. accidentaly think that some uninitialized variable is a pointer that
  4777. needs to be followed. Thus, we zero-out all locations on the root
  4778. stack in the prelude of \code{main}. In
  4779. Figure~\ref{fig:print-x86-output-gc}, the instruction
  4780. %
  4781. \lstinline{movq $0, (%r15)}
  4782. %
  4783. accomplishes this task. The garbage collector tests each root to see
  4784. if it is null prior to dereferencing it.
  4785. \begin{figure}[htbp]
  4786. \begin{minipage}[t]{0.5\textwidth}
  4787. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4788. _block58:
  4789. movq _free_ptr(%rip), %rcx
  4790. addq $16, _free_ptr(%rip)
  4791. movq %rcx, %r11
  4792. movq $131, 0(%r11)
  4793. movq %rcx, %r11
  4794. movq -8(%r15), %rax
  4795. movq %rax, 8(%r11)
  4796. movq $0, %rdx
  4797. movq %rcx, %r11
  4798. movq 8(%r11), %rcx
  4799. movq %rcx, %r11
  4800. movq 8(%r11), %rax
  4801. jmp _conclusion
  4802. _block59:
  4803. movq $0, %rcx
  4804. jmp _block58
  4805. _block62:
  4806. movq $0, %rcx
  4807. jmp _block61
  4808. _block60:
  4809. movq %r15, %rdi
  4810. movq $16, %rsi
  4811. callq _collect
  4812. jmp _block58
  4813. _block63:
  4814. movq %r15, %rdi
  4815. movq $16, %rsi
  4816. callq _collect
  4817. jmp _block61
  4818. _start:
  4819. movq $42, %rbx
  4820. movq _free_ptr(%rip), %rdx
  4821. addq $16, %rdx
  4822. movq _fromspace_end(%rip), %rcx
  4823. cmpq %rcx, %rdx
  4824. jl _block62
  4825. jmp _block63
  4826. \end{lstlisting}
  4827. \end{minipage}
  4828. \begin{minipage}[t]{0.45\textwidth}
  4829. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4830. _block61:
  4831. movq _free_ptr(%rip), %rcx
  4832. addq $16, _free_ptr(%rip)
  4833. movq %rcx, %r11
  4834. movq $3, 0(%r11)
  4835. movq %rcx, %r11
  4836. movq %rbx, 8(%r11)
  4837. movq $0, %rdx
  4838. movq %rcx, -8(%r15)
  4839. movq _free_ptr(%rip), %rcx
  4840. addq $16, %rcx
  4841. movq _fromspace_end(%rip), %rdx
  4842. cmpq %rdx, %rcx
  4843. jl _block59
  4844. jmp _block60
  4845. .globl _main
  4846. _main:
  4847. pushq %rbp
  4848. movq %rsp, %rbp
  4849. pushq %r12
  4850. pushq %rbx
  4851. pushq %r13
  4852. pushq %r14
  4853. subq $0, %rsp
  4854. movq $16384, %rdi
  4855. movq $16, %rsi
  4856. callq _initialize
  4857. movq _rootstack_begin(%rip), %r15
  4858. movq $0, (%r15)
  4859. addq $8, %r15
  4860. jmp _start
  4861. _conclusion:
  4862. subq $8, %r15
  4863. addq $0, %rsp
  4864. popq %r14
  4865. popq %r13
  4866. popq %rbx
  4867. popq %r12
  4868. popq %rbp
  4869. retq
  4870. \end{lstlisting}
  4871. \end{minipage}
  4872. \caption{Output of the \code{print-x86} pass.}
  4873. \label{fig:print-x86-output-gc}
  4874. \end{figure}
  4875. \margincomment{\scriptsize Suggest an implementation strategy
  4876. in which the students first do the code gen and test that
  4877. without GC (just use a big heap), then after that is debugged,
  4878. implement the GC. \\ --Jeremy}
  4879. \begin{figure}[p]
  4880. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4881. \node (R3) at (0,2) {\large $R_3$};
  4882. \node (R3-2) at (3,2) {\large $R_3$};
  4883. \node (R3-3) at (6,2) {\large $R_3$};
  4884. \node (R3-4) at (9,2) {\large $R_3$};
  4885. \node (R3-5) at (12,2) {\large $R_3$};
  4886. \node (C2-4) at (3,0) {\large $C_2$};
  4887. \node (C2-3) at (6,0) {\large $C_2$};
  4888. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_2$};
  4889. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_2$};
  4890. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}_2$};
  4891. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}_2$};
  4892. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}_2$};
  4893. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}_2$};
  4894. \path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R3-2);
  4895. \path[->,bend left=15] (R3-2) edge [above] node {\ttfamily\footnotesize uniquify} (R3-3);
  4896. \path[->,bend left=15] (R3-3) edge [above] node {\ttfamily\footnotesize\color{red} expose-alloc.} (R3-4);
  4897. \path[->,bend left=15] (R3-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R3-5);
  4898. \path[->,bend left=20] (R3-5) edge [right] node {\ttfamily\footnotesize explicate-control} (C2-3);
  4899. \path[->,bend right=15] (C2-3) edge [above] node {\ttfamily\footnotesize\color{red} uncover-locals} (C2-4);
  4900. \path[->,bend right=15] (C2-4) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  4901. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  4902. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  4903. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4904. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  4905. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  4906. \end{tikzpicture}
  4907. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  4908. \label{fig:R3-passes}
  4909. \end{figure}
  4910. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  4911. for the compilation of $R_3$.
  4912. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4913. \chapter{Functions}
  4914. \label{ch:functions}
  4915. This chapter studies the compilation of functions at the level of
  4916. abstraction of the C language. This corresponds to a subset of Typed
  4917. Racket in which only top-level function definitions are allowed. These
  4918. kind of functions are an important stepping stone to implementing
  4919. lexically-scoped functions in the form of \key{lambda} abstractions,
  4920. which is the topic of Chapter~\ref{ch:lambdas}.
  4921. \section{The $R_4$ Language}
  4922. The syntax for function definitions and function application is shown
  4923. in Figure~\ref{fig:r4-syntax}, where we define the $R_4$ language.
  4924. Programs in $R_4$ start with zero or more function definitions. The
  4925. function names from these definitions are in-scope for the entire
  4926. program, including all other function definitions (so the ordering of
  4927. function definitions does not matter). The syntax for function
  4928. application does not include an explicit keyword, which is error prone
  4929. when using \code{match}. To alleviate this problem, we change the
  4930. syntax from $(\Exp \; \Exp^{*})$ to $(\key{app}\; \Exp \; \Exp^{*})$
  4931. during type checking.
  4932. Functions are first-class in the sense that a function pointer is data
  4933. and can be stored in memory or passed as a parameter to another
  4934. function. Thus, we introduce a function type, written
  4935. \begin{lstlisting}
  4936. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  4937. \end{lstlisting}
  4938. for a function whose $n$ parameters have the types $\Type_1$ through
  4939. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  4940. these functions (with respect to Racket functions) is that they are
  4941. not lexically scoped. That is, the only external entities that can be
  4942. referenced from inside a function body are other globally-defined
  4943. functions. The syntax of $R_4$ prevents functions from being nested
  4944. inside each other.
  4945. \begin{figure}[tp]
  4946. \centering
  4947. \fbox{
  4948. \begin{minipage}{0.96\textwidth}
  4949. \[
  4950. \begin{array}{lcl}
  4951. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  4952. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} } \mid (\Type^{*} \; \key{->}\; \Type) \\
  4953. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4954. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp)} \\
  4955. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  4956. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  4957. \mid (\key{and}\;\Exp\;\Exp)
  4958. \mid (\key{or}\;\Exp\;\Exp)
  4959. \mid (\key{not}\;\Exp)} \\
  4960. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  4961. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  4962. (\key{vector-ref}\;\Exp\;\Int)} \\
  4963. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  4964. &\mid& (\Exp \; \Exp^{*}) \\
  4965. \Def &::=& (\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  4966. R_4 &::=& (\key{program} \;\itm{info}\; \Def^{*} \; \Exp)
  4967. \end{array}
  4968. \]
  4969. \end{minipage}
  4970. }
  4971. \caption{Syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-syntax})
  4972. with functions.}
  4973. \label{fig:r4-syntax}
  4974. \end{figure}
  4975. The program in Figure~\ref{fig:r4-function-example} is a
  4976. representative example of defining and using functions in $R_4$. We
  4977. define a function \code{map-vec} that applies some other function
  4978. \code{f} to both elements of a vector (a 2-tuple) and returns a new
  4979. vector containing the results. We also define a function \code{add1}
  4980. that does what its name suggests. The program then applies
  4981. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  4982. \code{(vector 1 42)}, from which we return the \code{42}.
  4983. \begin{figure}[tbp]
  4984. \begin{lstlisting}
  4985. (program ()
  4986. (define (map-vec [f : (Integer -> Integer)]
  4987. [v : (Vector Integer Integer)])
  4988. : (Vector Integer Integer)
  4989. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  4990. (define (add1 [x : Integer]) : Integer
  4991. (+ x 1))
  4992. (vector-ref (map-vec add1 (vector 0 41)) 1)
  4993. )
  4994. \end{lstlisting}
  4995. \caption{Example of using functions in $R_4$.}
  4996. \label{fig:r4-function-example}
  4997. \end{figure}
  4998. The definitional interpreter for $R_4$ is in
  4999. Figure~\ref{fig:interp-R4}. The case for the \code{program} form is
  5000. responsible for setting up the mutual recursion between the top-level
  5001. function definitions. We use the classic backpatching approach that
  5002. uses mutable variables and makes two passes over the function
  5003. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  5004. top-level environment using a mutable cons cell for each function
  5005. definition. Note that the \code{lambda} value for each function is
  5006. incomplete; it does not yet include the environment. Once the
  5007. top-level environment is constructed, we then iterate over it and
  5008. update the \code{lambda} value's to use the top-level environment.
  5009. \begin{figure}[tp]
  5010. \begin{lstlisting}
  5011. (define (interp-exp env)
  5012. (lambda (e)
  5013. (define recur (interp-exp env))
  5014. (match e
  5015. ...
  5016. [`(,fun ,args ...)
  5017. (define arg-vals (for/list ([e args]) (recur e)))
  5018. (define fun-val (recur fun))
  5019. (match fun-val
  5020. [`(lambda (,xs ...) ,body ,fun-env)
  5021. (define new-env (append (map cons xs arg-vals) fun-env))
  5022. ((interp-exp new-env) body)]
  5023. [else (error "interp-exp, expected function, not" fun-val)])]
  5024. [else (error 'interp-exp "unrecognized expression")]
  5025. )))
  5026. (define (interp-def d)
  5027. (match d
  5028. [`(define (,f [,xs : ,ps] ...) : ,rt ,body)
  5029. (mcons f `(lambda ,xs ,body ()))]
  5030. ))
  5031. (define (interp-R4 p)
  5032. (match p
  5033. [`(program ,ds ... ,body)
  5034. (let ([top-level (for/list ([d ds]) (interp-def d))])
  5035. (for/list ([b top-level])
  5036. (set-mcdr! b (match (mcdr b)
  5037. [`(lambda ,xs ,body ())
  5038. `(lambda ,xs ,body ,top-level)])))
  5039. ((interp-exp top-level) body))]
  5040. ))
  5041. \end{lstlisting}
  5042. \caption{Interpreter for the $R_4$ language.}
  5043. \label{fig:interp-R4}
  5044. \end{figure}
  5045. \section{Functions in x86}
  5046. \label{sec:fun-x86}
  5047. \margincomment{\tiny Make sure callee-saved registers are discussed
  5048. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  5049. \margincomment{\tiny Talk about the return address on the
  5050. stack and what callq and retq does.\\ --Jeremy }
  5051. The x86 architecture provides a few features to support the
  5052. implementation of functions. We have already seen that x86 provides
  5053. labels so that one can refer to the location of an instruction, as is
  5054. needed for jump instructions. Labels can also be used to mark the
  5055. beginning of the instructions for a function. Going further, we can
  5056. obtain the address of a label by using the \key{leaq} instruction and
  5057. \key{rip}-relative addressing. For example, the following puts the
  5058. address of the \code{add1} label into the \code{rbx} register.
  5059. \begin{lstlisting}
  5060. leaq add1(%rip), %rbx
  5061. \end{lstlisting}
  5062. In Section~\ref{sec:x86} we saw the use of the \code{callq}
  5063. instruction for jumping to a function whose location is given by a
  5064. label. Here we instead will be jumping to a function whose location is
  5065. given by an address, that is, we need to make an \emph{indirect
  5066. function call}. The x86 syntax is to give the register name prefixed
  5067. with an asterisk.
  5068. \begin{lstlisting}
  5069. callq *%rbx
  5070. \end{lstlisting}
  5071. \subsection{Calling Conventions}
  5072. The \code{callq} instruction provides partial support for implementing
  5073. functions, but it does not handle (1) parameter passing, (2) saving
  5074. and restoring frames on the procedure call stack, or (3) determining
  5075. how registers are shared by different functions. These issues require
  5076. coordination between the caller and the callee, which is often
  5077. assembly code written by different programmers or generated by
  5078. different compilers. As a result, people have developed
  5079. \emph{conventions} that govern how functions calls are performed.
  5080. Here we shall use the same conventions used by the \code{gcc}
  5081. compiler~\citep{Matz:2013aa}.
  5082. Regarding (1) parameter passing, the convention is to use the
  5083. following six registers: \code{rdi}, \code{rsi}, \code{rdx},
  5084. \code{rcx}, \code{r8}, and \code{r9}, in that order. If there are more
  5085. than six arguments, then the convention is to use space on the frame
  5086. of the caller for the rest of the arguments. However, to ease the
  5087. implementation of efficient tail calls (Section~\ref{sec:tail-call}),
  5088. we shall arrange to never have more than six arguments.
  5089. %
  5090. The register \code{rax} is for the return value of the function.
  5091. Regarding (2) frames and the procedure call stack, the convention is
  5092. that the stack grows down, with each function call using a chunk of
  5093. space called a frame. The caller sets the stack pointer, register
  5094. \code{rsp}, to the last data item in its frame. The callee must not
  5095. change anything in the caller's frame, that is, anything that is at or
  5096. above the stack pointer. The callee is free to use locations that are
  5097. below the stack pointer.
  5098. Regarding (3) the sharing of registers between different functions,
  5099. recall from Section~\ref{sec:calling-conventions} that the registers
  5100. are divided into two groups, the caller-saved registers and the
  5101. callee-saved registers. The caller should assume that all the
  5102. caller-saved registers get overwritten with arbitrary values by the
  5103. callee. Thus, the caller should either 1) not put values that are live
  5104. across a call in caller-saved registers, or 2) save and restore values
  5105. that are live across calls. We shall recommend option 1). On the flip
  5106. side, if the callee wants to use a callee-saved register, the callee
  5107. must save the contents of those registers on their stack frame and
  5108. then put them back prior to returning to the caller. The base
  5109. pointer, register \code{rbp}, is used as a point-of-reference within a
  5110. frame, so that each local variable can be accessed at a fixed offset
  5111. from the base pointer.
  5112. %
  5113. Figure~\ref{fig:call-frames} shows the layout of the caller and callee
  5114. frames.
  5115. %% If we were to use stack arguments, they would be between the
  5116. %% caller locals and the callee return address.
  5117. \begin{figure}[tbp]
  5118. \centering
  5119. \begin{tabular}{r|r|l|l} \hline
  5120. Caller View & Callee View & Contents & Frame \\ \hline
  5121. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  5122. 0(\key{\%rbp}) & & old \key{rbp} \\
  5123. -8(\key{\%rbp}) & & callee-saved $1$ \\
  5124. \ldots & & \ldots \\
  5125. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  5126. $-8(j+1)$(\key{\%rbp}) & & local $1$ \\
  5127. \ldots & & \ldots \\
  5128. $-8(j+k)$(\key{\%rbp}) & & local $k$ \\
  5129. %% & & \\
  5130. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  5131. %% & \ldots & \ldots \\
  5132. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  5133. \hline
  5134. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  5135. & 0(\key{\%rbp}) & old \key{rbp} \\
  5136. & -8(\key{\%rbp}) & callee-saved $1$ \\
  5137. & \ldots & \ldots \\
  5138. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  5139. & $-8(n+1)$(\key{\%rbp}) & local $1$ \\
  5140. & \ldots & \ldots \\
  5141. & $-8(n+m)$(\key{\%rsp}) & local $m$\\ \hline
  5142. \end{tabular}
  5143. \caption{Memory layout of caller and callee frames.}
  5144. \label{fig:call-frames}
  5145. \end{figure}
  5146. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  5147. %% local variables and for storing the values of callee-saved registers
  5148. %% (we shall refer to all of these collectively as ``locals''), and that
  5149. %% at the beginning of a function we move the stack pointer \code{rsp}
  5150. %% down to make room for them.
  5151. %% We recommend storing the local variables
  5152. %% first and then the callee-saved registers, so that the local variables
  5153. %% can be accessed using \code{rbp} the same as before the addition of
  5154. %% functions.
  5155. %% To make additional room for passing arguments, we shall
  5156. %% move the stack pointer even further down. We count how many stack
  5157. %% arguments are needed for each function call that occurs inside the
  5158. %% body of the function and find their maximum. Adding this number to the
  5159. %% number of locals gives us how much the \code{rsp} should be moved at
  5160. %% the beginning of the function. In preparation for a function call, we
  5161. %% offset from \code{rsp} to set up the stack arguments. We put the first
  5162. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  5163. %% so on.
  5164. %% Upon calling the function, the stack arguments are retrieved by the
  5165. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  5166. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  5167. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  5168. %% the layout of the caller and callee frames. Notice how important it is
  5169. %% that we correctly compute the maximum number of arguments needed for
  5170. %% function calls; if that number is too small then the arguments and
  5171. %% local variables will smash into each other!
  5172. \subsection{Efficient Tail Calls}
  5173. \label{sec:tail-call}
  5174. In general, the amount of stack space used by a program is determined
  5175. by the longest chain of nested function calls. That is, if function
  5176. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  5177. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  5178. $n$ can grow quite large in the case of recursive or mutually
  5179. recursive functions. However, in some cases we can arrange to use only
  5180. constant space, i.e. $O(1)$, instead of $O(n)$.
  5181. If a function call is the last action in a function body, then that
  5182. call is said to be a \emph{tail call}. In such situations, the frame
  5183. of the caller is no longer needed, so we can pop the caller's frame
  5184. before making the tail call. With this approach, a recursive function
  5185. that only makes tail calls will only use $O(1)$ stack space.
  5186. Functional languages like Racket typically rely heavily on recursive
  5187. functions, so they typically guarantee that all tail calls will be
  5188. optimized in this way.
  5189. However, some care is needed with regards to argument passing in tail
  5190. calls. As mentioned above, for arguments beyond the sixth, the
  5191. convention is to use space in the caller's frame for passing
  5192. arguments. But here we've popped the caller's frame and can no longer
  5193. use it. Another alternative is to use space in the callee's frame for
  5194. passing arguments. However, this option is also problematic because
  5195. the caller and callee's frame overlap in memory. As we begin to copy
  5196. the arguments from their sources in the caller's frame, the target
  5197. locations in the callee's frame might overlap with the sources for
  5198. later arguments! We solve this problem by not using the stack for
  5199. paramter passing but instead use the heap, as we describe in the next
  5200. section.
  5201. As briefly mentioned above, for a tail call we pop the caller's frame
  5202. prior to making the tail call. The instructions for popping a frame
  5203. are the instructions that we usually place in the conclusion of a
  5204. function. Thus, we also need to place such code immediately before
  5205. each tail call. These instructions include restoring the callee-saved
  5206. registers, so it is good that the argument passing registers are all
  5207. caller-saved registers.
  5208. One last note regarding which instruction to use to make the tail
  5209. call. When the callee is finished, it should not return to the current
  5210. function, but it should return to the function that called the current
  5211. one. Thus, the return address that is already on the stack is the
  5212. right one, and we should not use \key{callq} to make the tail call, as
  5213. that would unnecessarily overwrite the return address. Instead we can
  5214. simply use the \key{jmp} instruction. Like the indirect function call,
  5215. we write an indirect jump with a register prefixed with an asterisk.
  5216. We recommend using \code{rax} to hold the jump target because the
  5217. preceeding ``conclusion'' overwrites just about everything else.
  5218. \begin{lstlisting}
  5219. jmp *%rax
  5220. \end{lstlisting}
  5221. %% Now that we have a good understanding of functions as they appear in
  5222. %% $R_4$ and the support for functions in x86, we need to plan the
  5223. %% changes to our compiler, that is, do we need any new passes and/or do
  5224. %% we need to change any existing passes? Also, do we need to add new
  5225. %% kinds of AST nodes to any of the intermediate languages?
  5226. \section{Shrink $R_4$}
  5227. \label{sec:shrink-r4}
  5228. The \code{shrink} pass performs a couple minor modifications to the
  5229. grammar to ease the later passes. This pass adds an empty $\itm{info}$
  5230. field to each function definition:
  5231. \begin{lstlisting}
  5232. (define (|$f$| [|$x_1 : \Type_1$| ...) : |$\Type_r$| |$\Exp$|)
  5233. |$\Rightarrow$| (define (|$f$| [|$x_1 : \Type_1$| ...) : |$\Type_r$| () |$\Exp$|)
  5234. \end{lstlisting}
  5235. and introduces an explicit \code{main} function.\\
  5236. \begin{tabular}{lll}
  5237. \begin{minipage}{0.45\textwidth}
  5238. \begin{lstlisting}
  5239. (program |$\itm{info}$| |$ds$| ... |$\Exp$|)
  5240. \end{lstlisting}
  5241. \end{minipage}
  5242. &
  5243. $\Rightarrow$
  5244. &
  5245. \begin{minipage}{0.45\textwidth}
  5246. \begin{lstlisting}
  5247. (program |$\itm{info}$| |$ds'$| |$\itm{mainDef}$|)
  5248. \end{lstlisting}
  5249. \end{minipage}
  5250. \end{tabular} \\
  5251. where $\itm{mainDef}$ is
  5252. \begin{lstlisting}
  5253. (define (main) : Integer () |$\Exp'$|)
  5254. \end{lstlisting}
  5255. \section{Reveal Functions}
  5256. \label{sec:reveal-functions-r4}
  5257. Going forward, the syntax of $R_4$ is inconvenient for purposes of
  5258. compilation because it conflates the use of function names and local
  5259. variables. This is a problem because we need to compile the use of a
  5260. function name differently than the use of a local variable; we need to
  5261. use \code{leaq} to convert the function name (a label in x86) to an
  5262. address in a register. Thus, it is a good idea to create a new pass
  5263. that changes function references from just a symbol $f$ to
  5264. \code{(fun-ref $f$)}. A good name for this pass is
  5265. \code{reveal-functions} and the output language, $F_1$, is defined in
  5266. Figure~\ref{fig:f1-syntax}.
  5267. \begin{figure}[tp]
  5268. \centering
  5269. \fbox{
  5270. \begin{minipage}{0.96\textwidth}
  5271. \[
  5272. \begin{array}{lcl}
  5273. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  5274. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} \mid (\Type^{*} \; \key{->}\; \Type)} \\
  5275. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  5276. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  5277. &\mid& \gray{ \key{\#t} \mid \key{\#f} \mid
  5278. (\key{not}\;\Exp)} \mid \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5279. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5280. (\key{vector-ref}\;\Exp\;\Int)} \\
  5281. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void}) \mid
  5282. (\key{app}\; \Exp \; \Exp^{*})} \\
  5283. &\mid& (\key{fun-ref}\, \itm{label}) \\
  5284. \Def &::=& \gray{(\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5285. F_1 &::=& \gray{(\key{program}\;\itm{info} \; \Def^{*})}
  5286. \end{array}
  5287. \]
  5288. \end{minipage}
  5289. }
  5290. \caption{The $F_1$ language, an extension of $R_4$
  5291. (Figure~\ref{fig:r4-syntax}).}
  5292. \label{fig:f1-syntax}
  5293. \end{figure}
  5294. %% Distinguishing between calls in tail position and non-tail position
  5295. %% requires the pass to have some notion of context. We recommend using
  5296. %% two mutually recursive functions, one for processing expressions in
  5297. %% tail position and another for the rest.
  5298. Placing this pass after \code{uniquify} is a good idea, because it
  5299. will make sure that there are no local variables and functions that
  5300. share the same name. On the other hand, \code{reveal-functions} needs
  5301. to come before the \code{explicate-control} pass because that pass
  5302. will help us compile \code{fun-ref} into assignment statements.
  5303. \section{Limit Functions}
  5304. \label{sec:limit-functions-r4}
  5305. This pass transforms functions so that they have at most six
  5306. parameters and transforms all function calls so that they pass at most
  5307. six arguments. A simple strategy for imposing an argument limit of
  5308. length $n$ is to take all arguments $i$ where $i \geq n$ and pack them
  5309. into a vector, making that subsequent vector the $n$th argument.
  5310. \begin{tabular}{lll}
  5311. \begin{minipage}{0.2\textwidth}
  5312. \begin{lstlisting}
  5313. (|$f$| |$x_1$| |$\ldots$| |$x_n$|)
  5314. \end{lstlisting}
  5315. \end{minipage}
  5316. &
  5317. $\Rightarrow$
  5318. &
  5319. \begin{minipage}{0.4\textwidth}
  5320. \begin{lstlisting}
  5321. (|$f$| |$x_1$| |$\ldots$| |$x_5$| (vector |$x_6$| |$\ldots$| |$x_n$|))
  5322. \end{lstlisting}
  5323. \end{minipage}
  5324. \end{tabular}
  5325. In the body of the function, all occurrances of the $i$th argument in
  5326. which $i>5$ must be replaced with a \code{vector-ref}.
  5327. \section{Remove Complex Operators and Operands}
  5328. \label{sec:rco-r4}
  5329. The primary decisions to make for this pass is whether to classify
  5330. \code{fun-ref} and \code{app} as either simple or complex
  5331. expressions. Recall that a simple expression will eventually end up as
  5332. just an ``immediate'' argument of an x86 instruction. Function
  5333. application will be translated to a sequence of instructions, so
  5334. \code{app} must be classified as complex expression. Regarding
  5335. \code{fun-ref}, as discussed above, the function label needs to
  5336. be converted to an address using the \code{leaq} instruction. Thus,
  5337. even though \code{fun-ref} seems rather simple, it needs to be
  5338. classified as a complex expression so that we generate an assignment
  5339. statement with a left-hand side that can serve as the target of the
  5340. \code{leaq}.
  5341. \section{Explicate Control and the $C_3$ language}
  5342. \label{sec:explicate-control-r4}
  5343. Figure~\ref{fig:c3-syntax} defines the syntax for $C_3$, the output of
  5344. \key{explicate-control}. The three mutually recursive functions for
  5345. this pass, for assignment, tail, and predicate contexts, must all be
  5346. updated with cases for \code{fun-ref} and \code{app}. In
  5347. assignment and predicate contexts, \code{app} becomes \code{call},
  5348. whereas in tail position \code{app} becomes \code{tailcall}. We
  5349. recommend defining a new function for processing function definitions.
  5350. This code is similar to the case for \code{program} in $R_3$. The
  5351. top-level \code{explicate-control} function that handles the
  5352. \code{program} form of $R_4$ can then apply this new function to all
  5353. the function definitions.
  5354. \begin{figure}[tp]
  5355. \fbox{
  5356. \begin{minipage}{0.96\textwidth}
  5357. \[
  5358. \begin{array}{lcl}
  5359. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  5360. \\
  5361. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5362. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  5363. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  5364. &\mid& \gray{ (\key{allocate}\,\Int\,\Type)
  5365. \mid (\key{vector-ref}\, \Arg\, \Int) } \\
  5366. &\mid& \gray{ (\key{vector-set!}\,\Arg\,\Int\,\Arg) \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) } \\
  5367. &\mid& (\key{fun-ref}\,\itm{label}) \mid (\key{call} \,\Arg\,\Arg^{*}) \\
  5368. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  5369. \mid (\key{collect} \,\itm{int}) }\\
  5370. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  5371. &\mid& \gray{(\key{goto}\,\itm{label})
  5372. \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  5373. &\mid& (\key{tailcall} \,\Arg\,\Arg^{*}) \\
  5374. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; ((\itm{label}\,\key{.}\,\Tail)^{+})) \\
  5375. C_3 & ::= & (\key{program}\;\itm{info}\;\Def^{*})
  5376. \end{array}
  5377. \]
  5378. \end{minipage}
  5379. }
  5380. \caption{The $C_3$ language, extending $C_2$ (Figure~\ref{fig:c2-syntax}) with functions.}
  5381. \label{fig:c3-syntax}
  5382. \end{figure}
  5383. \section{Uncover Locals}
  5384. \label{sec:uncover-locals-r4}
  5385. The function for processing $\Tail$ should be updated with a case for
  5386. \code{tailcall}. We also recommend creating a new function for
  5387. processing function definitions. Each function definition in $C_3$ has
  5388. its own set of local variables, so the code for function definitions
  5389. should be similar to the case for the \code{program} form in $C_2$.
  5390. \section{Select Instructions}
  5391. \label{sec:select-r4}
  5392. The output of select instructions is a program in the x86$_3$
  5393. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  5394. \begin{figure}[tp]
  5395. \fbox{
  5396. \begin{minipage}{0.96\textwidth}
  5397. \[
  5398. \begin{array}{lcl}
  5399. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\itm{register}}
  5400. \mid (\key{deref}\,\itm{register}\,\Int) } \\
  5401. &\mid& \gray{ (\key{byte-reg}\; \itm{register})
  5402. \mid (\key{global-value}\; \itm{name}) } \\
  5403. &\mid& (\key{fun-ref}\; \itm{label})\\
  5404. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  5405. \Instr &::=& \gray{ (\key{addq} \; \Arg\; \Arg) \mid
  5406. (\key{subq} \; \Arg\; \Arg) \mid
  5407. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) } \\
  5408. &\mid& \gray{ (\key{callq} \; \mathit{label}) \mid
  5409. (\key{pushq}\;\Arg) \mid
  5410. (\key{popq}\;\Arg) \mid
  5411. (\key{retq}) } \\
  5412. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  5413. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  5414. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  5415. \mid (\key{jmp} \; \itm{label})
  5416. \mid (\key{j}\itm{cc} \; \itm{label})
  5417. \mid (\key{label} \; \itm{label}) } \\
  5418. &\mid& (\key{indirect-callq}\;\Arg ) \mid (\key{tail-jmp}\;\Arg) \\
  5419. &\mid& (\key{leaq}\;\Arg\;\Arg)\\
  5420. \Block &::= & \gray{(\key{block} \;\itm{info}\; \Instr^{+})} \\
  5421. \Def &::= & (\key{define} \; (\itm{label}) \;\itm{info}\; ((\itm{label} \,\key{.}\, \Block)^{+}))\\
  5422. x86_3 &::= & (\key{program} \;\itm{info} \;\Def^{*})
  5423. \end{array}
  5424. \]
  5425. \end{minipage}
  5426. }
  5427. \caption{The x86$_3$ language (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  5428. \label{fig:x86-3}
  5429. \end{figure}
  5430. An assignment of \code{fun-ref} becomes a \code{leaq} instruction
  5431. as follows: \\
  5432. \begin{tabular}{lll}
  5433. \begin{minipage}{0.45\textwidth}
  5434. \begin{lstlisting}
  5435. (assign |$\itm{lhs}$| (fun-ref |$f$|))
  5436. \end{lstlisting}
  5437. \end{minipage}
  5438. &
  5439. $\Rightarrow$
  5440. &
  5441. \begin{minipage}{0.4\textwidth}
  5442. \begin{lstlisting}
  5443. (leaq (fun-ref |$f$|) |$\itm{lhs}$|)
  5444. \end{lstlisting}
  5445. \end{minipage}
  5446. \end{tabular} \\
  5447. Regarding function definitions, we need to remove their parameters and
  5448. instead perform parameter passing in terms of the conventions
  5449. discussed in Section~\ref{sec:fun-x86}. That is, the arguments will be
  5450. in the argument passing registers, and inside the function we should
  5451. generate a \code{movq} instruction for each parameter, to move the
  5452. argument value from the appropriate register to a new local variable
  5453. with the same name as the old parameter.
  5454. Next, consider the compilation of function calls, which have the
  5455. following form upon input to \code{select-instructions}.
  5456. \begin{lstlisting}
  5457. (assign |\itm{lhs}| (call |\itm{fun}| |\itm{args}| |$\ldots$|))
  5458. \end{lstlisting}
  5459. In the mirror image of handling the parameters of function
  5460. definitions, the arguments \itm{args} need to be moved to the argument
  5461. passing registers.
  5462. %
  5463. Once the instructions for parameter passing have been generated, the
  5464. function call itself can be performed with an indirect function call,
  5465. for which I recommend creating the new instruction
  5466. \code{indirect-callq}. Of course, the return value from the function
  5467. is stored in \code{rax}, so it needs to be moved into the \itm{lhs}.
  5468. \begin{lstlisting}
  5469. (indirect-callq |\itm{fun}|)
  5470. (movq (reg rax) |\itm{lhs}|)
  5471. \end{lstlisting}
  5472. Regarding tail calls, the parameter passing is the same as non-tail
  5473. calls: generate instructions to move the arguments into to the
  5474. argument passing registers. After that we need to pop the frame from
  5475. the procedure call stack. However, we do not yet know how big the
  5476. frame is; that gets determined during register allocation. So instead
  5477. of generating those instructions here, we invent a new instruction
  5478. that means ``pop the frame and then do an indirect jump'', which we
  5479. name \code{tail-jmp}.
  5480. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  5481. using the label \code{start} for the initial block of a program, and
  5482. in Section~\ref{sec:select-r1} we recommended labelling the conclusion
  5483. of the program with \code{conclusion}, so that $(\key{return}\;\Arg)$
  5484. can be compiled to an assignment to \code{rax} followed by a jump to
  5485. \code{conclusion}. With the addition of function definitions, we will
  5486. have a starting block and conclusion for each function, but their
  5487. labels need to be unique. We recommend prepending the function's name
  5488. to \code{start} and \code{conclusion}, respectively, to obtain unique
  5489. labels. (Alternatively, one could \code{gensym} labels for the start
  5490. and conclusion and store them in the $\itm{info}$ field of the
  5491. function definition.)
  5492. \section{Uncover Live}
  5493. %% The rest of the passes need only minor modifications to handle the new
  5494. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  5495. %% \code{leaq}.
  5496. Inside \code{uncover-live}, when computing the $W$ set (written
  5497. variables) for an \code{indirect-callq} instruction, we recommend
  5498. including all the caller-saved registers, which will have the affect
  5499. of making sure that no caller-saved register actually needs to be
  5500. saved.
  5501. \section{Build Interference Graph}
  5502. With the addition of function definitions, we compute an interference
  5503. graph for each function (not just one for the whole program).
  5504. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  5505. spill vector-typed variables that are live during a call to the
  5506. \code{collect}. With the addition of functions to our language, we
  5507. need to revisit this issue. Many functions will perform allocation and
  5508. therefore have calls to the collector inside of them. Thus, we should
  5509. not only spill a vector-typed variable when it is live during a call
  5510. to \code{collect}, but we should spill the variable if it is live
  5511. during any function call. Thus, in the \code{build-interference} pass,
  5512. we recommend adding interference edges between call-live vector-typed
  5513. variables and the callee-saved registers (in addition to the usual
  5514. addition of edges between call-live variables and the caller-saved
  5515. registers).
  5516. \section{Patch Instructions}
  5517. In \code{patch-instructions}, you should deal with the x86
  5518. idiosyncrasy that the destination argument of \code{leaq} must be a
  5519. register. Additionally, you should ensure that the argument of
  5520. \code{tail-jmp} is \itm{rax}, our reserved register---this is to make
  5521. code generation more convenient, because we will be trampling many
  5522. registers before the tail call (as explained below).
  5523. \section{Print x86}
  5524. For the \code{print-x86} pass, we recommend the following translations:
  5525. \begin{lstlisting}
  5526. (fun-ref |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  5527. (indirect-callq |\itm{arg}|) |$\Rightarrow$| callq *|\itm{arg}|
  5528. \end{lstlisting}
  5529. Handling \code{tail-jmp} requires a bit more care. A straightforward
  5530. translation of \code{tail-jmp} would be \code{jmp *$\itm{arg}$}, which
  5531. is what we will want to do, but before the jump we need to pop the
  5532. current frame. So we need to restore the state of the registers to the
  5533. point they were at when the current function was called. This
  5534. sequence of instructions is the same as the code for the conclusion of
  5535. a function.
  5536. Note that your \code{print-x86} pass needs to add the code for saving
  5537. and restoring callee-saved registers, if you have not already
  5538. implemented that. This is necessary when generating code for function
  5539. definitions.
  5540. \section{An Example Translation}
  5541. Figure~\ref{fig:add-fun} shows an example translation of a simple
  5542. function in $R_4$ to x86. The figure also includes the results of the
  5543. \code{explicate-control} and \code{select-instructions} passes. We
  5544. have ommited the \code{has-type} AST nodes for readability. Can you
  5545. see any ways to improve the translation?
  5546. \begin{figure}[tbp]
  5547. \begin{tabular}{ll}
  5548. \begin{minipage}{0.45\textwidth}
  5549. % s3_2.rkt
  5550. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5551. (program
  5552. (define (add [x : Integer]
  5553. [y : Integer])
  5554. : Integer (+ x y))
  5555. (add 40 2))
  5556. \end{lstlisting}
  5557. $\Downarrow$
  5558. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5559. (program ()
  5560. (define (add86 [x87 : Integer]
  5561. [y88 : Integer]) : Integer ()
  5562. ((add86start . (return (+ x87 y88)))))
  5563. (define (main) : Integer ()
  5564. ((mainstart .
  5565. (seq (assign tmp89 (fun-ref add86))
  5566. (tailcall tmp89 40 2))))))
  5567. \end{lstlisting}
  5568. \end{minipage}
  5569. &
  5570. $\Rightarrow$
  5571. \begin{minipage}{0.5\textwidth}
  5572. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5573. (program ()
  5574. (define (add86)
  5575. ((locals (x87 . Integer) (y88 . Integer))
  5576. (num-params . 2))
  5577. ((add86start .
  5578. (block ()
  5579. (movq (reg rcx) (var x87))
  5580. (movq (reg rdx) (var y88))
  5581. (movq (var x87) (reg rax))
  5582. (addq (var y88) (reg rax))
  5583. (jmp add86conclusion)))))
  5584. (define (main)
  5585. ((locals . ((tmp89 . (Integer Integer -> Integer))))
  5586. (num-params . 0))
  5587. ((mainstart .
  5588. (block ()
  5589. (leaq (fun-ref add86) (var tmp89))
  5590. (movq (int 40) (reg rcx))
  5591. (movq (int 2) (reg rdx))
  5592. (tail-jmp (var tmp89))))))
  5593. \end{lstlisting}
  5594. $\Downarrow$
  5595. \end{minipage}
  5596. \end{tabular}
  5597. \begin{tabular}{lll}
  5598. \begin{minipage}{0.3\textwidth}
  5599. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5600. _add90start:
  5601. movq %rcx, %rsi
  5602. movq %rdx, %rcx
  5603. movq %rsi, %rax
  5604. addq %rcx, %rax
  5605. jmp _add90conclusion
  5606. .globl _add90
  5607. .align 16
  5608. _add90:
  5609. pushq %rbp
  5610. movq %rsp, %rbp
  5611. pushq %r12
  5612. pushq %rbx
  5613. pushq %r13
  5614. pushq %r14
  5615. subq $0, %rsp
  5616. jmp _add90start
  5617. _add90conclusion:
  5618. addq $0, %rsp
  5619. popq %r14
  5620. popq %r13
  5621. popq %rbx
  5622. popq %r12
  5623. subq $0, %r15
  5624. popq %rbp
  5625. retq
  5626. \end{lstlisting}
  5627. \end{minipage}
  5628. &
  5629. \begin{minipage}{0.3\textwidth}
  5630. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5631. _mainstart:
  5632. leaq _add90(%rip), %rsi
  5633. movq $40, %rcx
  5634. movq $2, %rdx
  5635. movq %rsi, %rax
  5636. addq $0, %rsp
  5637. popq %r14
  5638. popq %r13
  5639. popq %rbx
  5640. popq %r12
  5641. subq $0, %r15
  5642. popq %rbp
  5643. jmp *%rax
  5644. .globl _main
  5645. .align 16
  5646. _main:
  5647. pushq %rbp
  5648. movq %rsp, %rbp
  5649. pushq %r12
  5650. pushq %rbx
  5651. pushq %r13
  5652. pushq %r14
  5653. subq $0, %rsp
  5654. movq $16384, %rdi
  5655. movq $16, %rsi
  5656. callq _initialize
  5657. movq _rootstack_begin(%rip), %r15
  5658. jmp _mainstart
  5659. \end{lstlisting}
  5660. \end{minipage}
  5661. &
  5662. \begin{minipage}{0.3\textwidth}
  5663. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5664. _mainconclusion:
  5665. addq $0, %rsp
  5666. popq %r14
  5667. popq %r13
  5668. popq %rbx
  5669. popq %r12
  5670. subq $0, %r15
  5671. popq %rbp
  5672. retq
  5673. \end{lstlisting}
  5674. \end{minipage}
  5675. \end{tabular}
  5676. \caption{Example compilation of a simple function to x86.}
  5677. \label{fig:add-fun}
  5678. \end{figure}
  5679. \begin{exercise}\normalfont
  5680. Expand your compiler to handle $R_4$ as outlined in this section.
  5681. Create 5 new programs that use functions, including examples that pass
  5682. functions and return functions from other functions and including
  5683. recursive functions. Test your compiler on these new programs and all
  5684. of your previously created test programs.
  5685. \end{exercise}
  5686. \begin{figure}[p]
  5687. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5688. \node (R4) at (0,2) {\large $R_4$};
  5689. \node (R4-2) at (3,2) {\large $R_4$};
  5690. \node (R4-3) at (6,2) {\large $R_4$};
  5691. \node (F1-1) at (12,0) {\large $F_1$};
  5692. \node (F1-2) at (9,0) {\large $F_1$};
  5693. \node (F1-3) at (6,0) {\large $F_1$};
  5694. \node (F1-4) at (3,0) {\large $F_1$};
  5695. \node (C3-1) at (6,-2) {\large $C_3$};
  5696. \node (C3-2) at (3,-2) {\large $C_3$};
  5697. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  5698. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  5699. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  5700. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  5701. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  5702. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  5703. \path[->,bend left=15] (R4) edge [above] node
  5704. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  5705. \path[->,bend left=15] (R4-2) edge [above] node
  5706. {\ttfamily\footnotesize uniquify} (R4-3);
  5707. \path[->,bend left=15] (R4-3) edge [right] node
  5708. {\ttfamily\footnotesize\color{red} reveal-functions} (F1-1);
  5709. \path[->,bend left=15] (F1-1) edge [below] node
  5710. {\ttfamily\footnotesize\color{red} limit-functions} (F1-2);
  5711. \path[->,bend right=15] (F1-2) edge [above] node
  5712. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  5713. \path[->,bend right=15] (F1-3) edge [above] node
  5714. {\ttfamily\footnotesize\color{red} remove-complex.} (F1-4);
  5715. \path[->,bend left=15] (F1-4) edge [right] node
  5716. {\ttfamily\footnotesize\color{red} explicate-control} (C3-1);
  5717. \path[->,bend left=15] (C3-1) edge [below] node
  5718. {\ttfamily\footnotesize\color{red} uncover-locals} (C3-2);
  5719. \path[->,bend right=15] (C3-2) edge [left] node
  5720. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  5721. \path[->,bend left=15] (x86-2) edge [left] node
  5722. {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  5723. \path[->,bend right=15] (x86-2-1) edge [below] node
  5724. {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  5725. \path[->,bend right=15] (x86-2-2) edge [left] node
  5726. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  5727. \path[->,bend left=15] (x86-3) edge [above] node
  5728. {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  5729. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  5730. \end{tikzpicture}
  5731. \caption{Diagram of the passes for $R_4$, a language with functions.}
  5732. \label{fig:R4-passes}
  5733. \end{figure}
  5734. Figure~\ref{fig:R4-passes} gives an overview of the passes needed for
  5735. the compilation of $R_4$.
  5736. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5737. \chapter{Lexically Scoped Functions}
  5738. \label{ch:lambdas}
  5739. This chapter studies lexically scoped functions as they appear in
  5740. functional languages such as Racket. By lexical scoping we mean that a
  5741. function's body may refer to variables whose binding site is outside
  5742. of the function, in an enclosing scope.
  5743. %
  5744. Consider the example in Figure~\ref{fig:lexical-scoping} featuring an
  5745. anonymous function defined using the \key{lambda} form. The body of
  5746. the \key{lambda}, refers to three variables: \code{x}, \code{y}, and
  5747. \code{z}. The binding sites for \code{x} and \code{y} are outside of
  5748. the \key{lambda}. Variable \code{y} is bound by the enclosing
  5749. \key{let} and \code{x} is a parameter of \code{f}. The \key{lambda} is
  5750. returned from the function \code{f}. Below the definition of \code{f},
  5751. we have two calls to \code{f} with different arguments for \code{x},
  5752. first \code{5} then \code{3}. The functions returned from \code{f} are
  5753. bound to variables \code{g} and \code{h}. Even though these two
  5754. functions were created by the same \code{lambda}, they are really
  5755. different functions because they use different values for
  5756. \code{x}. Finally, we apply \code{g} to \code{11} (producing
  5757. \code{20}) and apply \code{h} to \code{15} (producing \code{22}) so
  5758. the result of this program is \code{42}.
  5759. \begin{figure}[btp]
  5760. % s4_6.rkt
  5761. \begin{lstlisting}
  5762. (define (f [x : Integer]) : (Integer -> Integer)
  5763. (let ([y 4])
  5764. (lambda: ([z : Integer]) : Integer
  5765. (+ x (+ y z)))))
  5766. (let ([g (f 5)])
  5767. (let ([h (f 3)])
  5768. (+ (g 11) (h 15))))
  5769. \end{lstlisting}
  5770. \caption{Example of a lexically scoped function.}
  5771. \label{fig:lexical-scoping}
  5772. \end{figure}
  5773. \section{The $R_5$ Language}
  5774. The syntax for this language with anonymous functions and lexical
  5775. scoping, $R_5$, is defined in Figure~\ref{fig:r5-syntax}. It adds the
  5776. \key{lambda} form to the grammar for $R_4$, which already has syntax
  5777. for function application. In this chapter we shall descibe how to
  5778. compile $R_5$ back into $R_4$, compiling lexically-scoped functions
  5779. into a combination of functions (as in $R_4$) and tuples (as in
  5780. $R_3$).
  5781. \begin{figure}[tp]
  5782. \centering
  5783. \fbox{
  5784. \begin{minipage}{0.96\textwidth}
  5785. \[
  5786. \begin{array}{lcl}
  5787. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  5788. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}
  5789. \mid (\Type^{*} \; \key{->}\; \Type)} \\
  5790. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  5791. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  5792. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}}\\
  5793. &\mid& \gray{\key{\#t} \mid \key{\#f}
  5794. \mid (\key{and}\;\Exp\;\Exp)
  5795. \mid (\key{or}\;\Exp\;\Exp)
  5796. \mid (\key{not}\;\Exp) } \\
  5797. &\mid& \gray{(\key{eq?}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5798. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5799. (\key{vector-ref}\;\Exp\;\Int)} \\
  5800. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  5801. &\mid& \gray{(\Exp \; \Exp^{*})} \\
  5802. &\mid& (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  5803. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5804. R_5 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  5805. \end{array}
  5806. \]
  5807. \end{minipage}
  5808. }
  5809. \caption{Syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax})
  5810. with \key{lambda}.}
  5811. \label{fig:r5-syntax}
  5812. \end{figure}
  5813. To compile lexically-scoped functions to top-level function
  5814. definitions, the compiler will need to provide special treatment to
  5815. variable occurences such as \code{x} and \code{y} in the body of the
  5816. \code{lambda} of Figure~\ref{fig:lexical-scoping}, for the functions
  5817. of $R_4$ may not refer to variables defined outside the function. To
  5818. identify such variable occurences, we review the standard notion of
  5819. free variable.
  5820. \begin{definition}
  5821. A variable is \emph{free with respect to an expression} $e$ if the
  5822. variable occurs inside $e$ but does not have an enclosing binding in
  5823. $e$.
  5824. \end{definition}
  5825. For example, the variables \code{x}, \code{y}, and \code{z} are all
  5826. free with respect to the expression \code{(+ x (+ y z))}. On the
  5827. other hand, only \code{x} and \code{y} are free with respect to the
  5828. following expression becuase \code{z} is bound by the \code{lambda}.
  5829. \begin{lstlisting}
  5830. (lambda: ([z : Integer]) : Integer
  5831. (+ x (+ y z)))
  5832. \end{lstlisting}
  5833. Once we have identified the free variables of a \code{lambda}, we need
  5834. to arrange for some way to transport, at runtime, the values of those
  5835. variables from the point where the \code{lambda} was created to the
  5836. point where the \code{lambda} is applied. Referring again to
  5837. Figure~\ref{fig:lexical-scoping}, the binding of \code{x} to \code{5}
  5838. needs to be used in the application of \code{g} to \code{11}, but the
  5839. binding of \code{x} to \code{3} needs to be used in the application of
  5840. \code{h} to \code{15}. The solution is to bundle the values of the
  5841. free variables together with the function pointer for the lambda's
  5842. code into a data structure called a \emph{closure}. Fortunately, we
  5843. already have the appropriate ingredients to make closures,
  5844. Chapter~\ref{ch:tuples} gave us tuples and Chapter~\ref{ch:functions}
  5845. gave us function pointers. The function pointer shall reside at index
  5846. $0$ and the values for free variables will fill in the rest of the
  5847. tuple. Figure~\ref{fig:closures} depicts the two closures created by
  5848. the two calls to \code{f} in Figure~\ref{fig:lexical-scoping}.
  5849. Because the two closures came from the same \key{lambda}, they share
  5850. the same code but differ in the values for free variable \code{x}.
  5851. \begin{figure}[tbp]
  5852. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  5853. \caption{Example closure representation for the \key{lambda}'s
  5854. in Figure~\ref{fig:lexical-scoping}.}
  5855. \label{fig:closures}
  5856. \end{figure}
  5857. \section{Interpreting $R_5$}
  5858. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  5859. $R_5$. The clause for \key{lambda} saves the current environment
  5860. inside the returned \key{lambda}. Then the clause for \key{app} uses
  5861. the environment from the \key{lambda}, the \code{lam-env}, when
  5862. interpreting the body of the \key{lambda}. The \code{lam-env}
  5863. environment is extended with the mapping of parameters to argument
  5864. values.
  5865. \begin{figure}[tbp]
  5866. \begin{lstlisting}
  5867. (define (interp-exp env)
  5868. (lambda (e)
  5869. (define recur (interp-exp env))
  5870. (match e
  5871. ...
  5872. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  5873. `(lambda ,xs ,body ,env)]
  5874. [`(app ,fun ,args ...)
  5875. (define fun-val ((interp-exp env) fun))
  5876. (define arg-vals (map (interp-exp env) args))
  5877. (match fun-val
  5878. [`(lambda (,xs ...) ,body ,lam-env)
  5879. (define new-env (append (map cons xs arg-vals) lam-env))
  5880. ((interp-exp new-env) body)]
  5881. [else (error "interp-exp, expected function, not" fun-val)])]
  5882. [else (error 'interp-exp "unrecognized expression")]
  5883. )))
  5884. \end{lstlisting}
  5885. \caption{Interpreter for $R_5$.}
  5886. \label{fig:interp-R5}
  5887. \end{figure}
  5888. \section{Type Checking $R_5$}
  5889. Figure~\ref{fig:typecheck-R5} shows how to type check the new
  5890. \key{lambda} form. The body of the \key{lambda} is checked in an
  5891. environment that includes the current environment (because it is
  5892. lexically scoped) and also includes the \key{lambda}'s parameters. We
  5893. require the body's type to match the declared return type.
  5894. \begin{figure}[tbp]
  5895. \begin{lstlisting}
  5896. (define (typecheck-R5 env)
  5897. (lambda (e)
  5898. (match e
  5899. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  5900. (define new-env (append (map cons xs Ts) env))
  5901. (define bodyT ((typecheck-R5 new-env) body))
  5902. (cond [(equal? rT bodyT)
  5903. `(,@Ts -> ,rT)]
  5904. [else
  5905. (error "mismatch in return type" bodyT rT)])]
  5906. ...
  5907. )))
  5908. \end{lstlisting}
  5909. \caption{Type checking the \key{lambda}'s in $R_5$.}
  5910. \label{fig:typecheck-R5}
  5911. \end{figure}
  5912. \section{Closure Conversion}
  5913. The compiling of lexically-scoped functions into top-level function
  5914. definitions is accomplished in the pass \code{convert-to-closures}
  5915. that comes after \code{reveal-functions} and before
  5916. \code{limit-functions}.
  5917. As usual, we shall implement the pass as a recursive function over the
  5918. AST. All of the action is in the clauses for \key{lambda} and
  5919. \key{app}. We transform a \key{lambda} expression into an expression
  5920. that creates a closure, that is, creates a vector whose first element
  5921. is a function pointer and the rest of the elements are the free
  5922. variables of the \key{lambda}. The \itm{name} is a unique symbol
  5923. generated to identify the function.
  5924. \begin{tabular}{lll}
  5925. \begin{minipage}{0.4\textwidth}
  5926. \begin{lstlisting}
  5927. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  5928. \end{lstlisting}
  5929. \end{minipage}
  5930. &
  5931. $\Rightarrow$
  5932. &
  5933. \begin{minipage}{0.4\textwidth}
  5934. \begin{lstlisting}
  5935. (vector |\itm{name}| |\itm{fvs}| ...)
  5936. \end{lstlisting}
  5937. \end{minipage}
  5938. \end{tabular} \\
  5939. %
  5940. In addition to transforming each \key{lambda} into a \key{vector}, we
  5941. must create a top-level function definition for each \key{lambda}, as
  5942. shown below.\\
  5943. \begin{minipage}{0.8\textwidth}
  5944. \begin{lstlisting}
  5945. (define (|\itm{name}| [clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps}| ...)
  5946. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  5947. ...
  5948. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  5949. |\itm{body'}|)...))
  5950. \end{lstlisting}
  5951. \end{minipage}\\
  5952. The \code{clos} parameter refers to the closure. The $\itm{ps}$
  5953. parameters are the normal parameters of the \key{lambda}. The types
  5954. $\itm{fvts}$ are the types of the free variables in the lambda and the
  5955. underscore is a dummy type because it is rather difficult to give a
  5956. type to the function in the closure's type, and it does not matter.
  5957. The sequence of \key{let} forms bind the free variables to their
  5958. values obtained from the closure.
  5959. We transform function application into code that retreives the
  5960. function pointer from the closure and then calls the function, passing
  5961. in the closure as the first argument. We bind $e'$ to a temporary
  5962. variable to avoid code duplication.
  5963. \begin{tabular}{lll}
  5964. \begin{minipage}{0.3\textwidth}
  5965. \begin{lstlisting}
  5966. (app |$e$| |\itm{es}| ...)
  5967. \end{lstlisting}
  5968. \end{minipage}
  5969. &
  5970. $\Rightarrow$
  5971. &
  5972. \begin{minipage}{0.5\textwidth}
  5973. \begin{lstlisting}
  5974. (let ([|\itm{tmp}| |$e'$|])
  5975. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  5976. \end{lstlisting}
  5977. \end{minipage}
  5978. \end{tabular} \\
  5979. There is also the question of what to do with top-level function
  5980. definitions. To maintain a uniform translation of function
  5981. application, we turn function references into closures.
  5982. \begin{tabular}{lll}
  5983. \begin{minipage}{0.3\textwidth}
  5984. \begin{lstlisting}
  5985. (fun-ref |$f$|)
  5986. \end{lstlisting}
  5987. \end{minipage}
  5988. &
  5989. $\Rightarrow$
  5990. &
  5991. \begin{minipage}{0.5\textwidth}
  5992. \begin{lstlisting}
  5993. (vector (fun-ref |$f$|))
  5994. \end{lstlisting}
  5995. \end{minipage}
  5996. \end{tabular} \\
  5997. %
  5998. The top-level function definitions need to be updated as well to take
  5999. an extra closure parameter.
  6000. \section{An Example Translation}
  6001. \label{sec:example-lambda}
  6002. Figure~\ref{fig:lexical-functions-example} shows the result of closure
  6003. conversion for the example program demonstrating lexical scoping that
  6004. we discussed at the beginning of this chapter.
  6005. \begin{figure}[h]
  6006. \begin{minipage}{0.8\textwidth}
  6007. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6008. (program
  6009. (define (f [x : Integer]) : (Integer -> Integer)
  6010. (let ([y 4])
  6011. (lambda: ([z : Integer]) : Integer
  6012. (+ x (+ y z)))))
  6013. (let ([g (f 5)])
  6014. (let ([h (f 3)])
  6015. (+ (g 11) (h 15)))))
  6016. \end{lstlisting}
  6017. $\Downarrow$
  6018. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6019. (program (type Integer)
  6020. (define (f (x : Integer)) : (Integer -> Integer)
  6021. (let ((y 4))
  6022. (lambda: ((z : Integer)) : Integer
  6023. (+ x (+ y z)))))
  6024. (let ((g (app (fun-ref f) 5)))
  6025. (let ((h (app (fun-ref f) 3)))
  6026. (+ (app g 11) (app h 15)))))
  6027. \end{lstlisting}
  6028. $\Downarrow$
  6029. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6030. (program (type Integer)
  6031. (define (f (clos.1 : _) (x : Integer)) : (Integer -> Integer)
  6032. (let ((y 4))
  6033. (vector (fun-ref lam.1) x y)))
  6034. (define (lam.1 (clos.2 : _) (z : Integer)) : Integer
  6035. (let ((x (vector-ref clos.2 1)))
  6036. (let ((y (vector-ref clos.2 2)))
  6037. (+ x (+ y z)))))
  6038. (let ((g (let ((t.1 (vector (fun-ref f))))
  6039. (app (vector-ref t.1 0) t.1 5))))
  6040. (let ((h (let ((t.2 (vector (fun-ref f))))
  6041. (app (vector-ref t.2 0) t.2 3))))
  6042. (+ (let ((t.3 g)) (app (vector-ref t.3 0) t.3 11))
  6043. (let ((t.4 h)) (app (vector-ref t.4 0) t.4 15))))))
  6044. \end{lstlisting}
  6045. \end{minipage}
  6046. \caption{Example of closure conversion.}
  6047. \label{fig:lexical-functions-example}
  6048. \end{figure}
  6049. \begin{figure}[p]
  6050. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6051. \node (R4) at (0,2) {\large $R_4$};
  6052. \node (R4-2) at (3,2) {\large $R_4$};
  6053. \node (R4-3) at (6,2) {\large $R_4$};
  6054. \node (F1-1) at (12,0) {\large $F_1$};
  6055. \node (F1-2) at (9,0) {\large $F_1$};
  6056. \node (F1-3) at (6,0) {\large $F_1$};
  6057. \node (F1-4) at (3,0) {\large $F_1$};
  6058. \node (F1-5) at (0,0) {\large $F_1$};
  6059. \node (C3-1) at (6,-2) {\large $C_3$};
  6060. \node (C3-2) at (3,-2) {\large $C_3$};
  6061. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  6062. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  6063. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  6064. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  6065. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  6066. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  6067. \path[->,bend left=15] (R4) edge [above] node
  6068. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  6069. \path[->,bend left=15] (R4-2) edge [above] node
  6070. {\ttfamily\footnotesize uniquify} (R4-3);
  6071. \path[->] (R4-3) edge [right] node
  6072. {\ttfamily\footnotesize reveal-functions} (F1-1);
  6073. \path[->,bend left=15] (F1-1) edge [below] node
  6074. {\ttfamily\footnotesize\color{red} convert-to-clos.} (F1-2);
  6075. \path[->,bend right=15] (F1-2) edge [above] node
  6076. {\ttfamily\footnotesize limit-functions} (F1-3);
  6077. \path[->,bend right=15] (F1-3) edge [above] node
  6078. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  6079. \path[->,bend right=15] (F1-4) edge [above] node
  6080. {\ttfamily\footnotesize remove-complex.} (F1-5);
  6081. \path[->] (F1-5) edge [left] node
  6082. {\ttfamily\footnotesize explicate-control} (C3-1);
  6083. \path[->,bend left=15] (C3-1) edge [below] node
  6084. {\ttfamily\footnotesize uncover-locals} (C3-2);
  6085. \path[->,bend right=15] (C3-2) edge [left] node
  6086. {\ttfamily\footnotesize select-instr.} (x86-2);
  6087. \path[->,bend left=15] (x86-2) edge [left] node
  6088. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6089. \path[->,bend right=15] (x86-2-1) edge [below] node
  6090. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  6091. \path[->,bend right=15] (x86-2-2) edge [left] node
  6092. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6093. \path[->,bend left=15] (x86-3) edge [above] node
  6094. {\ttfamily\footnotesize patch-instr.} (x86-4);
  6095. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  6096. \end{tikzpicture}
  6097. \caption{Diagram of the passes for $R_5$, a language with lexically-scoped
  6098. functions.}
  6099. \label{fig:R5-passes}
  6100. \end{figure}
  6101. Figure~\ref{fig:R5-passes} provides an overview of all the passes needed
  6102. for the compilation of $R_5$.
  6103. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6104. \chapter{Dynamic Typing}
  6105. \label{ch:type-dynamic}
  6106. In this chapter we discuss the compilation of a dynamically typed
  6107. language, named $R_7$, that is a subset of the Racket
  6108. language. (Recall that in the previous chapters we have studied
  6109. subsets of the \emph{Typed} Racket language.) In dynamically typed
  6110. languages, an expression may produce values of differing
  6111. type. Consider the following example with a conditional expression
  6112. that may return a Boolean or an integer depending on the input to the
  6113. program.
  6114. \begin{lstlisting}
  6115. (not (if (eq? (read) 1) #f 0))
  6116. \end{lstlisting}
  6117. Languages that allow expressions to produce different kinds of values
  6118. are called \emph{polymorphic}. There are many kinds of polymorphism,
  6119. such as subtype polymorphism and parametric
  6120. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism are
  6121. talking about here does not have a special name, but it is the usual
  6122. kind that arrises in dynamically typed languages.
  6123. Another characteristic of dynamically typed languages is that
  6124. primitive operations, such as \code{not}, are often defined to operate
  6125. on many different types of values. In fact, in Racket, the \code{not}
  6126. operator produces a result for any kind of value: given \code{\#f} it
  6127. returns \code{\#t} and given anything else it returns \code{\#f}.
  6128. Furthermore, even when primitive operations restrict their inputs to
  6129. values of a certain type, this restriction is enforced at runtime
  6130. instead of during compilation. For example, the following vector
  6131. reference results in a run-time contract violation.
  6132. \begin{lstlisting}
  6133. (vector-ref (vector 42) #t)
  6134. \end{lstlisting}
  6135. \begin{figure}[tp]
  6136. \centering
  6137. \fbox{
  6138. \begin{minipage}{0.97\textwidth}
  6139. \[
  6140. \begin{array}{rcl}
  6141. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  6142. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6143. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp) \\
  6144. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  6145. &\mid& \key{\#t} \mid \key{\#f}
  6146. \mid (\key{and}\;\Exp\;\Exp)
  6147. \mid (\key{or}\;\Exp\;\Exp)
  6148. \mid (\key{not}\;\Exp) \\
  6149. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  6150. &\mid& (\key{vector}\;\Exp^{+}) \mid
  6151. (\key{vector-ref}\;\Exp\;\Exp) \\
  6152. &\mid& (\key{vector-set!}\;\Exp\;\Exp\;\Exp) \mid (\key{void}) \\
  6153. &\mid& (\Exp \; \Exp^{*}) \mid (\key{lambda}\; (\Var^{*}) \; \Exp) \\
  6154. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  6155. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  6156. \Def &::=& (\key{define}\; (\Var \; \Var^{*}) \; \Exp) \\
  6157. R_7 &::=& (\key{program} \; \Def^{*}\; \Exp)
  6158. \end{array}
  6159. \]
  6160. \end{minipage}
  6161. }
  6162. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  6163. \label{fig:r7-syntax}
  6164. \end{figure}
  6165. The syntax of $R_7$, our subset of Racket, is defined in
  6166. Figure~\ref{fig:r7-syntax}.
  6167. %
  6168. The definitional interpreter for $R_7$ is given in
  6169. Figure~\ref{fig:interp-R7}.
  6170. \begin{figure}[tbp]
  6171. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6172. (define (get-tagged-type v) (match v [`(tagged ,v1 ,ty) ty]))
  6173. (define (valid-op? op) (member op '(+ - and or not)))
  6174. (define (interp-r7 env)
  6175. (lambda (ast)
  6176. (define recur (interp-r7 env))
  6177. (match ast
  6178. [(? symbol?) (lookup ast env)]
  6179. [(? integer?) `(inject ,ast Integer)]
  6180. [#t `(inject #t Boolean)]
  6181. [#f `(inject #f Boolean)]
  6182. [`(read) `(inject ,(read-fixnum) Integer)]
  6183. [`(lambda (,xs ...) ,body)
  6184. `(inject (lambda ,xs ,body ,env) (,@(map (lambda (x) 'Any) xs) -> Any))]
  6185. [`(define (,f ,xs ...) ,body)
  6186. (mcons f `(lambda ,xs ,body))]
  6187. [`(program ,ds ... ,body)
  6188. (let ([top-level (for/list ([d ds]) ((interp-r7 '()) d))])
  6189. (for/list ([b top-level])
  6190. (set-mcdr! b (match (mcdr b)
  6191. [`(lambda ,xs ,body)
  6192. `(inject (lambda ,xs ,body ,top-level)
  6193. (,@(map (lambda (x) 'Any) xs) -> Any))])))
  6194. ((interp-r7 top-level) body))]
  6195. [`(vector ,(app recur elts) ...)
  6196. (define tys (map get-tagged-type elts))
  6197. `(inject ,(apply vector elts) (Vector ,@tys))]
  6198. [`(vector-set! ,(app recur v1) ,n ,(app recur v2))
  6199. (match v1
  6200. [`(inject ,vec ,ty)
  6201. (vector-set! vec n v2)
  6202. `(inject (void) Void)])]
  6203. [`(vector-ref ,(app recur v) ,n)
  6204. (match v [`(inject ,vec ,ty) (vector-ref vec n)])]
  6205. [`(let ([,x ,(app recur v)]) ,body)
  6206. ((interp-r7 (cons (cons x v) env)) body)]
  6207. [`(,op ,es ...) #:when (valid-op? op)
  6208. (interp-r7-op op (for/list ([e es]) (recur e)))]
  6209. [`(eq? ,(app recur l) ,(app recur r))
  6210. `(inject ,(equal? l r) Boolean)]
  6211. [`(if ,(app recur q) ,t ,f)
  6212. (match q
  6213. [`(inject #f Boolean) (recur f)]
  6214. [else (recur t)])]
  6215. [`(,(app recur f-val) ,(app recur vs) ...)
  6216. (match f-val
  6217. [`(inject (lambda (,xs ...) ,body ,lam-env) ,ty)
  6218. (define new-env (append (map cons xs vs) lam-env))
  6219. ((interp-r7 new-env) body)]
  6220. [else (error "interp-r7, expected function, not" f-val)])])))
  6221. \end{lstlisting}
  6222. \caption{Interpreter for the $R_7$ language. UPDATE ME -Jeremy}
  6223. \label{fig:interp-R7}
  6224. \end{figure}
  6225. Let us consider how we might compile $R_7$ to x86, thinking about the
  6226. first example above. Our bit-level representation of the Boolean
  6227. \code{\#f} is zero and similarly for the integer \code{0}. However,
  6228. \code{(not \#f)} should produce \code{\#t} whereas \code{(not 0)}
  6229. should produce \code{\#f}. Furthermore, the behavior of \code{not}, in
  6230. general, cannot be determined at compile time, but depends on the
  6231. runtime type of its input, as in the example above that depends on the
  6232. result of \code{(read)}.
  6233. The way around this problem is to include information about a value's
  6234. runtime type in the value itself, so that this information can be
  6235. inspected by operators such as \code{not}. In particular, we shall
  6236. steal the 3 right-most bits from our 64-bit values to encode the
  6237. runtime type. We shall use $001$ to identify integers, $100$ for
  6238. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  6239. void value. We shall refer to these 3 bits as the \emph{tag} and we
  6240. define the following auxilliary function.
  6241. \begin{align*}
  6242. \itm{tagof}(\key{Integer}) &= 001 \\
  6243. \itm{tagof}(\key{Boolean}) &= 100 \\
  6244. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  6245. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  6246. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  6247. \itm{tagof}(\key{Void}) &= 101
  6248. \end{align*}
  6249. (We shall say more about the new \key{Vectorof} type shortly.)
  6250. This stealing of 3 bits comes at some
  6251. price: our integers are reduced to ranging from $-2^{60}$ to
  6252. $2^{60}$. The stealing does not adversely affect vectors and
  6253. procedures because those values are addresses, and our addresses are
  6254. 8-byte aligned so the rightmost 3 bits are unused, they are always
  6255. $000$. Thus, we do not lose information by overwriting the rightmost 3
  6256. bits with the tag and we can simply zero-out the tag to recover the
  6257. original address.
  6258. In some sense, these tagged values are a new kind of value. Indeed,
  6259. we can extend our \emph{typed} language with tagged values by adding a
  6260. new type to classify them, called \key{Any}, and with operations for
  6261. creating and using tagged values, yielding the $R_6$ language that we
  6262. define in Section~\ref{sec:r6-lang}. The $R_6$ language provides the
  6263. fundamental support for polymorphism and runtime types that we need to
  6264. support dynamic typing.
  6265. We shall implement our untyped language $R_7$ by compiling it to $R_6$
  6266. (Section~\ref{sec:compile-r7}), but first we describe the how to
  6267. extend our compiler to handle the new features of $R_6$
  6268. (Sections~\ref{sec:shrink-r6} and \ref{sec:select-r6}).
  6269. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  6270. \label{sec:r6-lang}
  6271. \begin{figure}[tp]
  6272. \centering
  6273. \fbox{
  6274. \begin{minipage}{0.97\textwidth}
  6275. \[
  6276. \begin{array}{lcl}
  6277. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6278. \mid (\key{Vector}\;\Type^{+}) \mid (\key{Vectorof}\;\Type) \mid \key{Void}} \\
  6279. &\mid& \gray{(\Type^{*} \; \key{->}\; \Type)} \mid \key{Any} \\
  6280. \FType &::=& \key{Integer} \mid \key{Boolean} \mid (\key{Vectorof}\;\key{Any})
  6281. \mid (\key{Any}^{*} \; \key{->}\; \key{Any})\\
  6282. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  6283. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6284. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  6285. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  6286. &\mid& \gray{\key{\#t} \mid \key{\#f}
  6287. \mid (\key{and}\;\Exp\;\Exp)
  6288. \mid (\key{or}\;\Exp\;\Exp)
  6289. \mid (\key{not}\;\Exp)} \\
  6290. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6291. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  6292. (\key{vector-ref}\;\Exp\;\Int)} \\
  6293. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  6294. &\mid& \gray{(\Exp \; \Exp^{*})
  6295. \mid (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6296. & \mid & (\key{inject}\; \Exp \; \FType) \mid (\key{project}\;\Exp\;\FType) \\
  6297. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  6298. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  6299. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6300. R_6 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  6301. \end{array}
  6302. \]
  6303. \end{minipage}
  6304. }
  6305. \caption{Syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax})
  6306. with \key{Any}.}
  6307. \label{fig:r6-syntax}
  6308. \end{figure}
  6309. The syntax of $R_6$ is defined in Figure~\ref{fig:r6-syntax}. The
  6310. $(\key{inject}\; e\; T)$ form converts the value produced by
  6311. expression $e$ of type $T$ into a tagged value. The
  6312. $(\key{project}\;e\;T)$ form converts the tagged value produced by
  6313. expression $e$ into a value of type $T$ or else halts the program if
  6314. the type tag does not match $T$. Note that in both \key{inject} and
  6315. \key{project}, the type $T$ is restricted to the flat types $\FType$,
  6316. which simplifies the implementation and corresponds with what is
  6317. needed for compiling untyped Racket. The type predicates,
  6318. $(\key{boolean?}\,e)$ etc., expect a tagged value and return \key{\#t}
  6319. if the tag corresponds to the predicate, and return \key{\#t}
  6320. otherwise.
  6321. %
  6322. Selctions from the type checker for $R_6$ are shown in
  6323. Figure~\ref{fig:typecheck-R6} and the definitional interpreter for
  6324. $R_6$ is in Figure~\ref{fig:interp-R6}.
  6325. \begin{figure}[btp]
  6326. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6327. (define (typecheck-R6 env)
  6328. (lambda (e)
  6329. (define recur (typecheck-R6 env))
  6330. (match e
  6331. [`(inject ,e ,ty)
  6332. (define-values (new-e e-ty) (recur e))
  6333. (cond
  6334. [(equal? e-ty ty)
  6335. (values `(inject ,new-e ,ty) 'Any)]
  6336. [else
  6337. (error "inject expected ~a to have type ~a" e ty)])]
  6338. [`(project ,e ,ty)
  6339. (define-values (new-e e-ty) (recur e))
  6340. (cond
  6341. [(equal? e-ty 'Any)
  6342. (values `(project ,new-e ,ty) ty)]
  6343. [else
  6344. (error "project expected ~a to have type Any" e)])]
  6345. [`(vector-ref ,e ,i)
  6346. (define-values (new-e e-ty) (recur e))
  6347. (match e-ty
  6348. [`(Vector ,ts ...) ...]
  6349. [`(Vectorof ,ty)
  6350. (unless (exact-nonnegative-integer? i)
  6351. (error 'type-check "invalid index ~a" i))
  6352. (values `(vector-ref ,new-e ,i) ty)]
  6353. [else (error "expected a vector in vector-ref, not" e-ty)])]
  6354. ...
  6355. )))
  6356. \end{lstlisting}
  6357. \caption{Type checker for parts of the $R_6$ language.}
  6358. \label{fig:typecheck-R6}
  6359. \end{figure}
  6360. % to do: add rules for vector-ref, etc. for Vectorof
  6361. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  6362. \begin{figure}[tbp]
  6363. \begin{lstlisting}
  6364. (define primitives (set 'boolean? ...))
  6365. (define (interp-op op)
  6366. (match op
  6367. ['boolean? (lambda (v)
  6368. (match v
  6369. [`(tagged ,v1 Boolean) #t]
  6370. [else #f]))]
  6371. ...))
  6372. (define (interp-R6 env)
  6373. (lambda (ast)
  6374. (match ast
  6375. [`(inject ,e ,t)
  6376. `(tagged ,((interp-R6 env) e) ,t)]
  6377. [`(project ,e ,t2)
  6378. (define v ((interp-R6 env) e))
  6379. (match v
  6380. [`(tagged ,v1 ,t1)
  6381. (cond [(equal? t1 t2)
  6382. v1]
  6383. [else
  6384. (error "in project, type mismatch" t1 t2)])]
  6385. [else
  6386. (error "in project, expected tagged value" v)])]
  6387. ...)))
  6388. \end{lstlisting}
  6389. \caption{Interpreter for $R_6$.}
  6390. \label{fig:interp-R6}
  6391. \end{figure}
  6392. \clearpage
  6393. %\section{The $R_7$ Language: Untyped Racket}
  6394. %\label{sec:r7-lang}
  6395. %% \section{Compiling $R_6$}
  6396. %% \label{sec:compile-r6}
  6397. %% Most of the compiler passes only require straightforward changes. The
  6398. %% interesting part is in instruction selection.
  6399. \section{Shrinking $R_6$}
  6400. \label{sec:shrink-r6}
  6401. In the \code{shrink} pass we recommend compiling \code{project} into
  6402. an explicit \code{if} expression that uses three new operations:
  6403. \code{tag-of-any}, \code{value-of-any}, and \code{exit}. The
  6404. \code{tag-of-any} operation retrieves the type tag from a tagged value
  6405. of type \code{Any}. The \code{value-of-any} retrieves the underlying
  6406. value from a tagged value. Finally, the \code{exit} operation ends the
  6407. execution of the program by invoking the operating system's
  6408. \code{exit} function. So the translation for \code{project} is as
  6409. follows. (We have ommitted the \code{has-type} AST nodes to make this
  6410. output more readable.)
  6411. \begin{tabular}{lll}
  6412. \begin{minipage}{0.3\textwidth}
  6413. \begin{lstlisting}
  6414. (project |$e$| |$\Type$|)
  6415. \end{lstlisting}
  6416. \end{minipage}
  6417. &
  6418. $\Rightarrow$
  6419. &
  6420. \begin{minipage}{0.5\textwidth}
  6421. \begin{lstlisting}
  6422. (let ([|$\itm{tmp}$| |$e'$|])
  6423. (if (eq? (tag-of-any |$\itm{tmp}$|) |$\itm{tag}$|)
  6424. (value-of-any |$\itm{tmp}$|)
  6425. (exit)))
  6426. \end{lstlisting}
  6427. \end{minipage}
  6428. \end{tabular} \\
  6429. Similarly, we recommend translating the type predicates
  6430. (\code{boolean?}, etc.) into uses of \code{tag-of-any} and \code{eq?}.
  6431. \section{Instruction Selection for $R_6$}
  6432. \label{sec:select-r6}
  6433. \paragraph{Inject}
  6434. We recommend compiling an \key{inject} as follows if the type is
  6435. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  6436. destination to the left by the number of bits specified by the source
  6437. ($2$) and it preserves the sign of the integer. We use the \key{orq}
  6438. instruction to combine the tag and the value to form the tagged value.
  6439. \\
  6440. \begin{tabular}{lll}
  6441. \begin{minipage}{0.4\textwidth}
  6442. \begin{lstlisting}
  6443. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  6444. \end{lstlisting}
  6445. \end{minipage}
  6446. &
  6447. $\Rightarrow$
  6448. &
  6449. \begin{minipage}{0.5\textwidth}
  6450. \begin{lstlisting}
  6451. (movq |$e'$| |\itm{lhs}'|)
  6452. (salq (int 2) |\itm{lhs}'|)
  6453. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  6454. \end{lstlisting}
  6455. \end{minipage}
  6456. \end{tabular} \\
  6457. The instruction selection for vectors and procedures is different
  6458. because their is no need to shift them to the left. The rightmost 3
  6459. bits are already zeros as described above. So we combine the value and
  6460. the tag using
  6461. \key{orq}. \\
  6462. \begin{tabular}{lll}
  6463. \begin{minipage}{0.4\textwidth}
  6464. \begin{lstlisting}
  6465. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  6466. \end{lstlisting}
  6467. \end{minipage}
  6468. &
  6469. $\Rightarrow$
  6470. &
  6471. \begin{minipage}{0.5\textwidth}
  6472. \begin{lstlisting}
  6473. (movq |$e'$| |\itm{lhs}'|)
  6474. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  6475. \end{lstlisting}
  6476. \end{minipage}
  6477. \end{tabular} \\
  6478. \paragraph{Project}
  6479. The instruction selection for \key{project} is a bit more involved.
  6480. Like \key{inject}, the instructions are different depending on whether
  6481. the type $T$ is a pointer (vector or procedure) or not (Integer or
  6482. Boolean). The following shows the instruction selection for Integer
  6483. and Boolean. We first check to see if the tag on the tagged value
  6484. matches the tag of the target type $T$. If not, we halt the program by
  6485. calling the \code{exit} function. If we have a match, we need to
  6486. produce an untagged value by shifting it to the right by 2 bits.
  6487. %
  6488. \\
  6489. \begin{tabular}{lll}
  6490. \begin{minipage}{0.4\textwidth}
  6491. \begin{lstlisting}
  6492. (assign |\itm{lhs}| (project |$e$| |$T$|))
  6493. \end{lstlisting}
  6494. \end{minipage}
  6495. &
  6496. $\Rightarrow$
  6497. &
  6498. \begin{minipage}{0.5\textwidth}
  6499. \begin{lstlisting}
  6500. (movq |$e'$| |\itm{lhs}'|)
  6501. (andq (int 3) |\itm{lhs}'|)
  6502. (if (eq? |\itm{lhs}'| (int |$\itm{tagof}(T)$|))
  6503. ((movq |$e'$| |\itm{lhs}'|)
  6504. (sarq (int 2) |\itm{lhs}'|))
  6505. ((callq exit)))
  6506. \end{lstlisting}
  6507. \end{minipage}
  6508. \end{tabular} \\
  6509. %
  6510. The case for vectors and procedures begins in a similar way, checking
  6511. that the runtime tag matches the target type $T$ and exiting if there
  6512. is a mismatch. However, the way in which we convert the tagged value
  6513. to a value is different, as there is no need to shift. Instead we need
  6514. to zero-out the rightmost 2 bits. We accomplish this by creating the
  6515. bit pattern $\ldots 0011$, applying \code{notq} to obtain $\ldots
  6516. 1100$, and then applying \code{andq} with the tagged value get the
  6517. desired result. \\
  6518. %
  6519. \begin{tabular}{lll}
  6520. \begin{minipage}{0.4\textwidth}
  6521. \begin{lstlisting}
  6522. (assign |\itm{lhs}| (project |$e$| |$T$|))
  6523. \end{lstlisting}
  6524. \end{minipage}
  6525. &
  6526. $\Rightarrow$
  6527. &
  6528. \begin{minipage}{0.5\textwidth}
  6529. \begin{lstlisting}
  6530. (movq |$e'$| |\itm{lhs}'|)
  6531. (andq (int 3) |\itm{lhs}'|)
  6532. (if (eq? |\itm{lhs}'| (int |$\itm{tagof}(T)$|))
  6533. ((movq (int 3) |\itm{lhs}'|)
  6534. (notq |\itm{lhs}'|)
  6535. (andq |$e'$| |\itm{lhs}'|))
  6536. ((callq exit)))
  6537. \end{lstlisting}
  6538. \end{minipage}
  6539. \end{tabular} \\
  6540. \paragraph{Type Predicates} We leave it to the reader to
  6541. devise a sequence of instructions to implement the type predicates
  6542. \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  6543. \section{Compiling $R_7$ to $R_6$}
  6544. \label{sec:compile-r7}
  6545. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  6546. $R_7$ forms into $R_6$. An important invariant of this pass is that
  6547. given a subexpression $e$ of $R_7$, the pass will produce an
  6548. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  6549. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  6550. the Boolean \code{\#t}, which must be injected to produce an
  6551. expression of type \key{Any}.
  6552. %
  6553. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  6554. addition, is representative of compilation for many operations: the
  6555. arguments have type \key{Any} and must be projected to \key{Integer}
  6556. before the addition can be performed.
  6557. %
  6558. The compilation of \key{lambda} (third row of
  6559. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  6560. produce type annotations, we simply use \key{Any}.
  6561. %
  6562. The compilation of \code{if}, \code{eq?}, and \code{and} all
  6563. demonstrate how this pass has to account for some differences in
  6564. behavior between $R_7$ and $R_6$. The $R_7$ language is more
  6565. permissive than $R_6$ regarding what kind of values can be used in
  6566. various places. For example, the condition of an \key{if} does not
  6567. have to be a Boolean. Similarly, the arguments of \key{and} do not
  6568. need to be Boolean. For \key{eq?}, the arguments need not be of the
  6569. same type.
  6570. \begin{figure}[tbp]
  6571. \centering
  6572. \begin{tabular}{|lll|} \hline
  6573. \begin{minipage}{0.25\textwidth}
  6574. \begin{lstlisting}
  6575. #t
  6576. \end{lstlisting}
  6577. \end{minipage}
  6578. &
  6579. $\Rightarrow$
  6580. &
  6581. \begin{minipage}{0.6\textwidth}
  6582. \begin{lstlisting}
  6583. (inject #t Boolean)
  6584. \end{lstlisting}
  6585. \end{minipage}
  6586. \\[2ex]\hline
  6587. \begin{minipage}{0.25\textwidth}
  6588. \begin{lstlisting}
  6589. (+ |$e_1$| |$e_2$|)
  6590. \end{lstlisting}
  6591. \end{minipage}
  6592. &
  6593. $\Rightarrow$
  6594. &
  6595. \begin{minipage}{0.6\textwidth}
  6596. \begin{lstlisting}
  6597. (inject
  6598. (+ (project |$e'_1$| Integer)
  6599. (project |$e'_2$| Integer))
  6600. Integer)
  6601. \end{lstlisting}
  6602. \end{minipage}
  6603. \\[2ex]\hline
  6604. \begin{minipage}{0.25\textwidth}
  6605. \begin{lstlisting}
  6606. (lambda (|$x_1 \ldots$|) |$e$|)
  6607. \end{lstlisting}
  6608. \end{minipage}
  6609. &
  6610. $\Rightarrow$
  6611. &
  6612. \begin{minipage}{0.6\textwidth}
  6613. \begin{lstlisting}
  6614. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  6615. (Any|$\ldots$|Any -> Any))
  6616. \end{lstlisting}
  6617. \end{minipage}
  6618. \\[2ex]\hline
  6619. \begin{minipage}{0.25\textwidth}
  6620. \begin{lstlisting}
  6621. (app |$e_0$| |$e_1 \ldots e_n$|)
  6622. \end{lstlisting}
  6623. \end{minipage}
  6624. &
  6625. $\Rightarrow$
  6626. &
  6627. \begin{minipage}{0.6\textwidth}
  6628. \begin{lstlisting}
  6629. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  6630. |$e'_1 \ldots e'_n$|)
  6631. \end{lstlisting}
  6632. \end{minipage}
  6633. \\[2ex]\hline
  6634. \begin{minipage}{0.25\textwidth}
  6635. \begin{lstlisting}
  6636. (vector-ref |$e_1$| |$e_2$|)
  6637. \end{lstlisting}
  6638. \end{minipage}
  6639. &
  6640. $\Rightarrow$
  6641. &
  6642. \begin{minipage}{0.6\textwidth}
  6643. \begin{lstlisting}
  6644. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  6645. (let ([tmp2 (project |$e'_2$| Integer)])
  6646. (vector-ref tmp1 tmp2)))
  6647. \end{lstlisting}
  6648. \end{minipage}
  6649. \\[2ex]\hline
  6650. \begin{minipage}{0.25\textwidth}
  6651. \begin{lstlisting}
  6652. (if |$e_1$| |$e_2$| |$e_3$|)
  6653. \end{lstlisting}
  6654. \end{minipage}
  6655. &
  6656. $\Rightarrow$
  6657. &
  6658. \begin{minipage}{0.6\textwidth}
  6659. \begin{lstlisting}
  6660. (if (eq? |$e'_1$| (inject #f Boolean))
  6661. |$e'_3$|
  6662. |$e'_2$|)
  6663. \end{lstlisting}
  6664. \end{minipage}
  6665. \\[2ex]\hline
  6666. \begin{minipage}{0.25\textwidth}
  6667. \begin{lstlisting}
  6668. (eq? |$e_1$| |$e_2$|)
  6669. \end{lstlisting}
  6670. \end{minipage}
  6671. &
  6672. $\Rightarrow$
  6673. &
  6674. \begin{minipage}{0.6\textwidth}
  6675. \begin{lstlisting}
  6676. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  6677. \end{lstlisting}
  6678. \end{minipage}
  6679. \\[2ex]\hline
  6680. \begin{minipage}{0.25\textwidth}
  6681. \begin{lstlisting}
  6682. (and |$e_1$| |$e_2$|)
  6683. \end{lstlisting}
  6684. \end{minipage}
  6685. &
  6686. $\Rightarrow$
  6687. &
  6688. \begin{minipage}{0.6\textwidth}
  6689. \begin{lstlisting}
  6690. (let ([tmp |$e'_1$|])
  6691. (if (eq? tmp (inject #f Boolean))
  6692. tmp
  6693. |$e'_2$|))
  6694. \end{lstlisting}
  6695. \end{minipage} \\\hline
  6696. \end{tabular} \\
  6697. \caption{Compiling $R_7$ to $R_6$.}
  6698. \label{fig:compile-r7-r6}
  6699. \end{figure}
  6700. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6701. \chapter{Gradual Typing}
  6702. \label{ch:gradual-typing}
  6703. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  6704. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6705. \chapter{Parametric Polymorphism}
  6706. \label{ch:parametric-polymorphism}
  6707. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  6708. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  6709. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6710. \chapter{High-level Optimization}
  6711. \label{ch:high-level-optimization}
  6712. This chapter will present a procedure inlining pass based on the
  6713. algorithm of \citet{Waddell:1997fk}.
  6714. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6715. \chapter{Appendix}
  6716. \section{Interpreters}
  6717. \label{appendix:interp}
  6718. We provide several interpreters in the \key{interp.rkt} file. The
  6719. \key{interp-scheme} function takes an AST in one of the Racket-like
  6720. languages considered in this book ($R_1, R_2, \ldots$) and interprets
  6721. the program, returning the result value. The \key{interp-C} function
  6722. interprets an AST for a program in one of the C-like languages ($C_0,
  6723. C_1, \ldots$), and the \code{interp-x86} function interprets an AST
  6724. for an x86 program.
  6725. \section{Utility Functions}
  6726. \label{appendix:utilities}
  6727. The utility function described in this section can be found in the
  6728. \key{utilities.rkt} file.
  6729. The \key{read-program} function takes a file path and parses that file
  6730. (it must be a Racket program) into an abstract syntax tree (as an
  6731. S-expression) with a \key{program} AST at the top.
  6732. The \key{assert} function displays the error message \key{msg} if the
  6733. Boolean \key{bool} is false.
  6734. \begin{lstlisting}
  6735. (define (assert msg bool) ...)
  6736. \end{lstlisting}
  6737. The \key{lookup} function takes a key and an association list (a list
  6738. of key-value pairs), and returns the first value that is associated
  6739. with the given key, if there is one. If not, an error is triggered.
  6740. The association list may contain both immutable pairs (built with
  6741. \key{cons}) and mutable mapirs (built with \key{mcons}).
  6742. The \key{map2} function ...
  6743. %% \subsection{Graphs}
  6744. %% \begin{itemize}
  6745. %% \item The \code{make-graph} function takes a list of vertices
  6746. %% (symbols) and returns a graph.
  6747. %% \item The \code{add-edge} function takes a graph and two vertices and
  6748. %% adds an edge to the graph that connects the two vertices. The graph
  6749. %% is updated in-place. There is no return value for this function.
  6750. %% \item The \code{adjacent} function takes a graph and a vertex and
  6751. %% returns the set of vertices that are adjacent to the given
  6752. %% vertex. The return value is a Racket \code{hash-set} so it can be
  6753. %% used with functions from the \code{racket/set} module.
  6754. %% \item The \code{vertices} function takes a graph and returns the list
  6755. %% of vertices in the graph.
  6756. %% \end{itemize}
  6757. \subsection{Testing}
  6758. The \key{interp-tests} function takes a compiler name (a string), a
  6759. description of the passes, an interpreter for the source language, a
  6760. test family name (a string), and a list of test numbers, and runs the
  6761. compiler passes and the interpreters to check whether the passes
  6762. correct. The description of the passes is a list with one entry per
  6763. pass. An entry is a list with three things: a string giving the name
  6764. of the pass, the function that implements the pass (a translator from
  6765. AST to AST), and a function that implements the interpreter (a
  6766. function from AST to result value) for the language of the output of
  6767. the pass. The interpreters from Appendix~\ref{appendix:interp} make a
  6768. good choice. The \key{interp-tests} function assumes that the
  6769. subdirectory \key{tests} has a bunch of Scheme programs whose names
  6770. all start with the family name, followed by an underscore and then the
  6771. test number, ending in \key{.scm}. Also, for each Scheme program there
  6772. is a file with the same number except that it ends with \key{.in} that
  6773. provides the input for the Scheme program.
  6774. \begin{lstlisting}
  6775. (define (interp-tests name passes test-family test-nums) ...
  6776. \end{lstlisting}
  6777. The compiler-tests function takes a compiler name (a string) a
  6778. description of the passes (see the comment for \key{interp-tests}) a
  6779. test family name (a string), and a list of test numbers (see the
  6780. comment for interp-tests), and runs the compiler to generate x86 (a
  6781. \key{.s} file) and then runs gcc to generate machine code. It runs
  6782. the machine code and checks that the output is 42.
  6783. \begin{lstlisting}
  6784. (define (compiler-tests name passes test-family test-nums) ...)
  6785. \end{lstlisting}
  6786. The compile-file function takes a description of the compiler passes
  6787. (see the comment for \key{interp-tests}) and returns a function that,
  6788. given a program file name (a string ending in \key{.scm}), applies all
  6789. of the passes and writes the output to a file whose name is the same
  6790. as the program file name but with \key{.scm} replaced with \key{.s}.
  6791. \begin{lstlisting}
  6792. (define (compile-file passes)
  6793. (lambda (prog-file-name) ...))
  6794. \end{lstlisting}
  6795. \section{x86 Instruction Set Quick-Reference}
  6796. \label{sec:x86-quick-reference}
  6797. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  6798. do. We write $A \to B$ to mean that the value of $A$ is written into
  6799. location $B$. Address offsets are given in bytes. The instruction
  6800. arguments $A, B, C$ can be immediate constants (such as $\$4$),
  6801. registers (such as $\%rax$), or memory references (such as
  6802. $-4(\%ebp)$). Most x86 instructions only allow at most one memory
  6803. reference per instruction. Other operands must be immediates or
  6804. registers.
  6805. \begin{table}[tbp]
  6806. \centering
  6807. \begin{tabular}{l|l}
  6808. \textbf{Instruction} & \textbf{Operation} \\ \hline
  6809. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  6810. \texttt{negq} $A$ & $- A \to A$ \\
  6811. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  6812. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  6813. \texttt{callq} *$A$ & Calls the function at the address $A$. \\
  6814. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  6815. \texttt{retq} & Pops the return address and jumps to it \\
  6816. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  6817. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  6818. \texttt{leaq} $A$,$B$ & $A \to B$ ($C$ must be a register) \\
  6819. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register \\
  6820. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  6821. matches the condition code of the instruction, otherwise go to the
  6822. next instructions. The condition codes are \key{e} for ``equal'',
  6823. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  6824. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  6825. \texttt{jl} $L$ & \\
  6826. \texttt{jle} $L$ & \\
  6827. \texttt{jg} $L$ & \\
  6828. \texttt{jge} $L$ & \\
  6829. \texttt{jmp} $L$ & Jump to label $L$ \\
  6830. \texttt{movq} $A$, $B$ & $A \to B$ \\
  6831. \texttt{movzbq} $A$, $B$ &
  6832. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  6833. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  6834. and the extra bytes of $B$ are set to zero.} \\
  6835. & \\
  6836. & \\
  6837. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  6838. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  6839. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  6840. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  6841. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  6842. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  6843. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  6844. description of the condition codes. $A$ must be a single byte register
  6845. (e.g., \texttt{al} or \texttt{cl}).} \\
  6846. \texttt{setl} $A$ & \\
  6847. \texttt{setle} $A$ & \\
  6848. \texttt{setg} $A$ & \\
  6849. \texttt{setge} $A$ &
  6850. \end{tabular}
  6851. \vspace{5pt}
  6852. \caption{Quick-reference for the x86 instructions used in this book.}
  6853. \label{tab:x86-instr}
  6854. \end{table}
  6855. \bibliographystyle{plainnat}
  6856. \bibliography{all}
  6857. \end{document}
  6858. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  6859. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  6860. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  6861. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  6862. %% LocalWords: ast sexp Reynold's reynolds interp cond fx evaluator
  6863. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  6864. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  6865. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  6866. %% LocalWords: allocator gensym alist subdirectory scm rkt tmp lhs
  6867. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  6868. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  6869. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  6870. %% LocalWords: boolean typecheck notq cmpq sete movzbq jmp al xorq
  6871. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  6872. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  6873. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  6874. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  6875. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  6876. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  6877. %% LocalWords: len prev rootlen heaplen setl lt