book.tex 294 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743
  1. % Why direct style instead of continuation passing style?
  2. %% Student project ideas:
  3. %% * high-level optimizations like procedure inlining, etc.
  4. %% * closure optimization
  5. %% * adding letrec to the language
  6. %% (Thought: in the book and regular course, replace top-level defines
  7. %% with letrec.)
  8. %% * alternative back ends (ARM, LLVM)
  9. %% * alternative calling convention (a la Dybvig)
  10. %% * lazy evaluation
  11. %% * gradual typing
  12. %% * continuations (frames in heap a la SML or segmented stack a la Dybvig)
  13. %% * exceptions
  14. %% * self hosting
  15. %% * I/O
  16. %% * foreign function interface
  17. %% * quasi-quote and unquote
  18. %% * macros (too difficult?)
  19. %% * alternative garbage collector
  20. %% * alternative register allocator
  21. %% * parametric polymorphism
  22. %% * type classes (too difficulty?)
  23. %% * loops (too easy? combine with something else?)
  24. %% * loop optimization (fusion, etc.)
  25. %% * deforestation
  26. %% * records and subtyping
  27. %% * object-oriented features
  28. %% - objects, object types, and structural subtyping (e.g. Abadi & Cardelli)
  29. %% - class-based objects and nominal subtyping (e.g. Featherweight Java)
  30. %% * multi-threading, fork join, futures, implicit parallelism
  31. %% * dataflow analysis, type analysis and specialization
  32. \documentclass[11pt]{book}
  33. \usepackage[T1]{fontenc}
  34. \usepackage[utf8]{inputenc}
  35. \usepackage{lmodern}
  36. \usepackage{hyperref}
  37. \usepackage{graphicx}
  38. \usepackage[english]{babel}
  39. \usepackage{listings}
  40. \usepackage{amsmath}
  41. \usepackage{amsthm}
  42. \usepackage{amssymb}
  43. \usepackage{natbib}
  44. \usepackage{stmaryrd}
  45. \usepackage{xypic}
  46. \usepackage{semantic}
  47. \usepackage{wrapfig}
  48. \usepackage{multirow}
  49. \usepackage{color}
  50. \definecolor{lightgray}{gray}{1}
  51. \newcommand{\black}[1]{{\color{black} #1}}
  52. \newcommand{\gray}[1]{{\color{lightgray} #1}}
  53. %% For pictures
  54. \usepackage{tikz}
  55. \usetikzlibrary{arrows.meta}
  56. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  57. % Computer Modern is already the default. -Jeremy
  58. %\renewcommand{\ttdefault}{cmtt}
  59. \definecolor{comment-red}{rgb}{0.8,0,0}
  60. \if{0}
  61. % Peanut gallery comments:
  62. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  63. \newcommand{\margincomment}[1]{\marginpar{#1}}
  64. \else
  65. \newcommand{\rn}[1]{}
  66. \newcommand{\margincomment}[1]{}
  67. \fi
  68. \lstset{%
  69. language=Lisp,
  70. basicstyle=\ttfamily\small,
  71. morekeywords={seq,assign,program,block,define,lambda,match},
  72. escapechar=|,
  73. columns=flexible,
  74. moredelim=[is][\color{red}]{~}{~}
  75. }
  76. \newtheorem{theorem}{Theorem}
  77. \newtheorem{lemma}[theorem]{Lemma}
  78. \newtheorem{corollary}[theorem]{Corollary}
  79. \newtheorem{proposition}[theorem]{Proposition}
  80. \newtheorem{constraint}[theorem]{Constraint}
  81. \newtheorem{definition}[theorem]{Definition}
  82. \newtheorem{exercise}[theorem]{Exercise}
  83. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  84. % 'dedication' environment: To add a dedication paragraph at the start of book %
  85. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  86. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  87. \newenvironment{dedication}
  88. {
  89. \cleardoublepage
  90. \thispagestyle{empty}
  91. \vspace*{\stretch{1}}
  92. \hfill\begin{minipage}[t]{0.66\textwidth}
  93. \raggedright
  94. }
  95. {
  96. \end{minipage}
  97. \vspace*{\stretch{3}}
  98. \clearpage
  99. }
  100. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  101. % Chapter quote at the start of chapter %
  102. % Source: http://tex.stackexchange.com/a/53380 %
  103. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  104. \makeatletter
  105. \renewcommand{\@chapapp}{}% Not necessary...
  106. \newenvironment{chapquote}[2][2em]
  107. {\setlength{\@tempdima}{#1}%
  108. \def\chapquote@author{#2}%
  109. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  110. \itshape}
  111. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  112. \makeatother
  113. \input{defs}
  114. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  115. \title{\Huge \textbf{Essentials of Compilation} \\
  116. \huge An Incremental Approach}
  117. \author{\textsc{Jeremy G. Siek} \\
  118. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  119. Indiana University \\
  120. \\
  121. with contributions from: \\
  122. Carl Factora \\
  123. Andre Kuhlenschmidt \\
  124. Ryan R. Newton \\
  125. Ryan Scott \\
  126. Cameron Swords \\
  127. Michael M. Vitousek \\
  128. Michael Vollmer
  129. }
  130. \begin{document}
  131. \frontmatter
  132. \maketitle
  133. \begin{dedication}
  134. This book is dedicated to the programming language wonks at Indiana
  135. University.
  136. \end{dedication}
  137. \tableofcontents
  138. \listoffigures
  139. %\listoftables
  140. \mainmatter
  141. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  142. \chapter*{Preface}
  143. The tradition of compiler writing at Indiana University goes back to
  144. research and courses about programming languages by Daniel Friedman in
  145. the 1970's and 1980's. Dan conducted research on lazy
  146. evaluation~\citep{Friedman:1976aa} in the context of
  147. Lisp~\citep{McCarthy:1960dz} and then studied
  148. continuations~\citep{Felleisen:kx} and
  149. macros~\citep{Kohlbecker:1986dk} in the context of the
  150. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  151. of those courses, Kent Dybvig, went on to build Chez
  152. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  153. compiler for Scheme. After completing his Ph.D. at the University of
  154. North Carolina, Kent returned to teach at Indiana University.
  155. Throughout the 1990's and 2000's, Kent continued development of Chez
  156. Scheme and taught the compiler course.
  157. The compiler course evolved to incorporate novel pedagogical ideas
  158. while also including elements of effective real-world compilers. One
  159. of Dan's ideas was to split the compiler into many small ``passes'' so
  160. that the code for each pass would be easy to understood in isolation.
  161. (In contrast, most compilers of the time were organized into only a
  162. few monolithic passes for reasons of compile-time efficiency.) Kent,
  163. with later help from his students Dipanwita Sarkar and Andrew Keep,
  164. developed infrastructure to support this approach and evolved the
  165. course, first to use micro-sized passes and then into even smaller
  166. nano passes~\citep{Sarkar:2004fk,Keep:2012aa}. Jeremy Siek was a
  167. student in this compiler course in the early 2000's, as part of his
  168. Ph.D. studies at Indiana University. Needless to say, Jeremy enjoyed
  169. the course immensely!
  170. During that time, another student named Abdulaziz Ghuloum observed
  171. that the front-to-back organization of the course made it difficult
  172. for students to understand the rationale for the compiler
  173. design. Abdulaziz proposed an incremental approach in which the
  174. students build the compiler in stages; they start by implementing a
  175. complete compiler for a very small subset of the input language and in
  176. each subsequent stage they add a language feature and add or modify
  177. passes to handle the new feature~\citep{Ghuloum:2006bh}. In this way,
  178. the students see how the language features motivate aspects of the
  179. compiler design.
  180. After graduating from Indiana University in 2005, Jeremy went on to
  181. teach at the University of Colorado. He adapted the nano pass and
  182. incremental approaches to compiling a subset of the Python
  183. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  184. on the surface but there is a large overlap in the compiler techniques
  185. required for the two languages. Thus, Jeremy was able to teach much of
  186. the same content from the Indiana compiler course. He very much
  187. enjoyed teaching the course organized in this way, and even better,
  188. many of the students learned a lot and got excited about compilers.
  189. Jeremy returned to teach at Indiana University in 2013. In his
  190. absence the compiler course had switched from the front-to-back
  191. organization to a back-to-front organization. Seeing how well the
  192. incremental approach worked at Colorado, he started porting and
  193. adapting the structure of the Colorado course back into the land of
  194. Scheme. In the meantime Indiana had moved on from Scheme to Racket, so
  195. the course is now about compiling a subset of Racket (and Typed
  196. Racket) to the x86 assembly language. The compiler is implemented in
  197. Racket 7.1~\citep{plt-tr}.
  198. This is the textbook for the incremental version of the compiler
  199. course at Indiana University (Spring 2016 - present) and it is the
  200. first open textbook for an Indiana compiler course. With this book we
  201. hope to make the Indiana compiler course available to people that have
  202. not had the chance to study in Bloomington in person. Many of the
  203. compiler design decisions in this book are drawn from the assignment
  204. descriptions of \cite{Dybvig:2010aa}. We have captured what we think
  205. are the most important topics from \cite{Dybvig:2010aa} but we have
  206. omitted topics that we think are less interesting conceptually and we
  207. have made simplifications to reduce complexity. In this way, this
  208. book leans more towards pedagogy than towards the efficiency of the
  209. generated code. Also, the book differs in places where we saw the
  210. opportunity to make the topics more fun, such as in relating register
  211. allocation to Sudoku (Chapter~\ref{ch:register-allocation-r1}).
  212. \section*{Prerequisites}
  213. The material in this book is challenging but rewarding. It is meant to
  214. prepare students for a lifelong career in programming languages.
  215. The book uses the Racket language both for the implementation of the
  216. compiler and for the language that is compiled, so a student should be
  217. proficient with Racket (or Scheme) prior to reading this book. There
  218. are many excellent resources for learning Scheme and
  219. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. It
  220. is helpful but not necessary for the student to have prior exposure to
  221. the x86 (or x86-64) assembly language~\citep{Intel:2015aa}, as one might
  222. obtain from a computer systems
  223. course~\citep{Bryant:2005aa,Bryant:2010aa}. This book introduces the
  224. parts of x86-64 assembly language that are needed.
  225. %\section*{Structure of book}
  226. % You might want to add short description about each chapter in this book.
  227. %\section*{About the companion website}
  228. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  229. %\begin{itemize}
  230. % \item A link to (freely downlodable) latest version of this document.
  231. % \item Link to download LaTeX source for this document.
  232. % \item Miscellaneous material (e.g. suggested readings etc).
  233. %\end{itemize}
  234. \section*{Acknowledgments}
  235. Many people have contributed to the ideas, techniques, organization,
  236. and teaching of the materials in this book. We especially thank the
  237. following people.
  238. \begin{itemize}
  239. \item Bor-Yuh Evan Chang
  240. \item Kent Dybvig
  241. \item Daniel P. Friedman
  242. \item Ronald Garcia
  243. \item Abdulaziz Ghuloum
  244. \item Jay McCarthy
  245. \item Dipanwita Sarkar
  246. \item Andrew Keep
  247. \item Oscar Waddell
  248. \item Michael Wollowski
  249. \end{itemize}
  250. \mbox{}\\
  251. \noindent Jeremy G. Siek \\
  252. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  253. %\noindent Spring 2016
  254. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  255. \chapter{Preliminaries}
  256. \label{ch:trees-recur}
  257. In this chapter we review the basic tools that are needed to implement
  258. a compiler. We use \emph{abstract syntax trees} (ASTs), which are data
  259. structures in computer memory, in contrast to how programs are
  260. typically stored in text files on disk, as \emph{concrete syntax}.
  261. %
  262. ASTs can be represented in many different ways, depending on the programming
  263. language used to write the compiler.
  264. %
  265. Because this book uses Racket (\url{http://racket-lang.org}), a
  266. descendant of Lisp, we can use S-expressions to conveniently represent
  267. ASTs (Section~\ref{sec:ast}). We use grammars to defined the abstract
  268. syntax of programming languages (Section~\ref{sec:grammar}) and
  269. pattern matching to inspect individual nodes in an AST
  270. (Section~\ref{sec:pattern-matching}). We use recursion to construct
  271. and deconstruct entire ASTs (Section~\ref{sec:recursion}). This
  272. chapter provides an brief introduction to these ideas.
  273. \section{Abstract Syntax Trees and S-expressions}
  274. \label{sec:ast}
  275. The primary data structure that is commonly used for representing
  276. programs is the \emph{abstract syntax tree} (AST). When considering
  277. some part of a program, a compiler needs to ask what kind of thing it
  278. is and what sub-parts it contains. For example, the program on the
  279. left, represented by an S-expression, corresponds to the AST on the
  280. right.
  281. \begin{center}
  282. \begin{minipage}{0.4\textwidth}
  283. \begin{lstlisting}
  284. (+ (read) (- 8))
  285. \end{lstlisting}
  286. \end{minipage}
  287. \begin{minipage}{0.4\textwidth}
  288. \begin{equation}
  289. \begin{tikzpicture}
  290. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  291. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  292. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  293. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  294. \draw[->] (plus) to (read);
  295. \draw[->] (plus) to (minus);
  296. \draw[->] (minus) to (8);
  297. \end{tikzpicture}
  298. \label{eq:arith-prog}
  299. \end{equation}
  300. \end{minipage}
  301. \end{center}
  302. We shall use the standard terminology for trees: each circle above is
  303. called a \emph{node}. The arrows connect a node to its \emph{children}
  304. (which are also nodes). The top-most node is the \emph{root}. Every
  305. node except for the root has a \emph{parent} (the node it is the child
  306. of). If a node has no children, it is a \emph{leaf} node. Otherwise
  307. it is an \emph{internal} node.
  308. Recall that an \emph{symbolic expression} (S-expression) is either
  309. \begin{enumerate}
  310. \item an atom, or
  311. \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  312. where $e_1$ and $e_2$ are each an S-expression.
  313. \end{enumerate}
  314. An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  315. null value \code{'()}, etc. We can create an S-expression in Racket
  316. simply by writing a backquote (called a quasi-quote in Racket)
  317. followed by the textual representation of the S-expression. It is
  318. quite common to use S-expressions to represent a list, such as $a, b
  319. ,c$ in the following way:
  320. \begin{lstlisting}
  321. `(a . (b . (c . ())))
  322. \end{lstlisting}
  323. Each element of the list is in the first slot of a pair, and the
  324. second slot is either the rest of the list or the null value, to mark
  325. the end of the list. Such lists are so common that Racket provides
  326. special notation for them that removes the need for the periods
  327. and so many parenthesis:
  328. \begin{lstlisting}
  329. `(a b c)
  330. \end{lstlisting}
  331. The following expression creates an S-expression that represents AST
  332. \eqref{eq:arith-prog}.
  333. \begin{lstlisting}
  334. `(+ (read) (- 8))
  335. \end{lstlisting}
  336. When using S-expressions to represent ASTs, the convention is to
  337. represent each AST node as a list and to put the operation symbol at
  338. the front of the list. The rest of the list contains the children. So
  339. in the above case, the root AST node has operation \code{`+} and its
  340. two children are \code{`(read)} and \code{`(- 8)}, just as in the
  341. diagram \eqref{eq:arith-prog}.
  342. To build larger S-expressions one often needs to splice together
  343. several smaller S-expressions. Racket provides the comma operator to
  344. splice an S-expression into a larger one. For example, instead of
  345. creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  346. we could have first created an S-expression for AST
  347. \eqref{eq:arith-neg8} and then spliced that into the addition
  348. S-expression.
  349. \begin{lstlisting}
  350. (define ast1.4 `(- 8))
  351. (define ast1.1 `(+ (read) ,ast1.4))
  352. \end{lstlisting}
  353. In general, the Racket expression that follows the comma (splice)
  354. can be any expression that produces an S-expression.
  355. When deciding how to compile program \eqref{eq:arith-prog}, we need to
  356. know that the operation associated with the root node is addition and
  357. that it has two children: \texttt{read} and a negation. The AST data
  358. structure directly supports these queries, as we shall see in
  359. Section~\ref{sec:pattern-matching}, and hence is a good choice for use
  360. in compilers. In this book, we often write down the S-expression
  361. representation of a program even when we really have in mind the AST
  362. because the S-expression is more concise. We recommend that, in your
  363. mind, you always think of programs as abstract syntax trees.
  364. \section{Grammars}
  365. \label{sec:grammar}
  366. A programming language can be thought of as a \emph{set} of programs.
  367. The set is typically infinite (one can always create larger and larger
  368. programs), so one cannot simply describe a language by listing all of
  369. the programs in the language. Instead we write down a set of rules, a
  370. \emph{grammar}, for building programs. We shall write our rules in a
  371. variant of Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  372. As an example, we describe a small language, named $R_0$, that
  373. consists of integers and arithmetic operations. The first grammar rule
  374. says that any integer is an expression:
  375. \begin{equation}
  376. \Exp ::= \Int \label{eq:arith-int}
  377. \end{equation}
  378. %
  379. Each rule has a left-hand-side and a right-hand-side. The way to read
  380. a rule is that if you have all the program parts on the
  381. right-hand-side, then you can create an AST node and categorize it
  382. according to the left-hand-side.
  383. %
  384. A name such as $\Exp$ that is
  385. defined by the grammar rules is a \emph{non-terminal}.
  386. %
  387. The name $\Int$ is a also a non-terminal, however, we do not define
  388. $\Int$ because the reader already knows what an integer is.
  389. %
  390. Further, we make the simplifying design decision that all of the languages in
  391. this book only handle machine-representable integers. On most modern machines
  392. this corresponds to integers represented with 64-bits, i.e., the in range
  393. $-2^{63}$ to $2^{63}-1$.
  394. %
  395. However, we restrict this range further to match the Racket \texttt{fixnum}
  396. datatype, which allows 63-bit integers on a 64-bit machine.
  397. The second grammar rule is the \texttt{read} operation that receives
  398. an input integer from the user of the program.
  399. \begin{equation}
  400. \Exp ::= (\key{read}) \label{eq:arith-read}
  401. \end{equation}
  402. The third rule says that, given an $\Exp$ node, you can build another
  403. $\Exp$ node by negating it.
  404. \begin{equation}
  405. \Exp ::= (\key{-} \; \Exp) \label{eq:arith-neg}
  406. \end{equation}
  407. Symbols in typewriter font such as \key{-} and \key{read} are
  408. \emph{terminal} symbols and must literally appear in the program for
  409. the rule to be applicable.
  410. We can apply the rules to build ASTs in the $R_0$
  411. language. For example, by rule \eqref{eq:arith-int}, \texttt{8} is an
  412. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  413. an $\Exp$.
  414. \begin{center}
  415. \begin{minipage}{0.25\textwidth}
  416. \begin{lstlisting}
  417. (- 8)
  418. \end{lstlisting}
  419. \end{minipage}
  420. \begin{minipage}{0.25\textwidth}
  421. \begin{equation}
  422. \begin{tikzpicture}
  423. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  424. \node[draw, circle] (8) at (0, -1.2) {$8$};
  425. \draw[->] (minus) to (8);
  426. \end{tikzpicture}
  427. \label{eq:arith-neg8}
  428. \end{equation}
  429. \end{minipage}
  430. \end{center}
  431. The next grammar rule defines addition expressions:
  432. \begin{equation}
  433. \Exp ::= (\key{+} \; \Exp \; \Exp) \label{eq:arith-add}
  434. \end{equation}
  435. We can now see that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  436. $R_0$. We know that \lstinline{(read)} is an $\Exp$ by rule
  437. \eqref{eq:arith-read} and we have shown that \texttt{(- 8)} is an
  438. $\Exp$, so we can apply rule \eqref{eq:arith-add} to show that
  439. \texttt{(+ (read) (- 8))} is an $\Exp$ in the $R_0$ language.
  440. If you have an AST for which the above rules do not apply, then the
  441. AST is not in $R_0$. For example, the AST \texttt{(- (read) (+ 8))} is
  442. not in $R_0$ because there are no rules for \key{+} with only one
  443. argument, nor for \key{-} with two arguments. Whenever we define a
  444. language with a grammar, we mean for the language to only include
  445. those programs that are justified by the rules.
  446. The last grammar rule for $R_0$ states that there is a \key{program}
  447. node to mark the top of the whole program:
  448. \[
  449. R_0 ::= (\key{program} \; \Exp)
  450. \]
  451. The \code{read-program} function provided in \code{utilities.rkt}
  452. reads programs in from a file (the sequence of characters in the
  453. concrete syntax of Racket) and parses them into the abstract syntax
  454. tree. The concrete syntax does not include a \key{program} form; that
  455. is added by the \code{read-program} function as it creates the
  456. AST. See the description of \code{read-program} in
  457. Appendix~\ref{appendix:utilities} for more details.
  458. It is common to have many rules with the same left-hand side, such as
  459. $\Exp$ in the grammar for $R_0$, so there is a vertical bar notation
  460. for gathering several rules, as shown in
  461. Figure~\ref{fig:r0-syntax}. Each clause between a vertical bar is
  462. called an {\em alternative}.
  463. \begin{figure}[tp]
  464. \fbox{
  465. \begin{minipage}{0.96\textwidth}
  466. \[
  467. \begin{array}{rcl}
  468. \Exp &::=& \Int \mid ({\tt \key{read}}) \mid (\key{-} \; \Exp) \mid
  469. (\key{+} \; \Exp \; \Exp) \\
  470. R_0 &::=& (\key{program} \; \Exp)
  471. \end{array}
  472. \]
  473. \end{minipage}
  474. }
  475. \caption{The syntax of $R_0$, a language of integer arithmetic.}
  476. \label{fig:r0-syntax}
  477. \end{figure}
  478. \section{Pattern Matching}
  479. \label{sec:pattern-matching}
  480. As mentioned above, compilers often need to access the children of an
  481. AST node. Racket provides the \texttt{match} form to access the parts
  482. of an S-expression. Consider the following example and the output on
  483. the right.
  484. \begin{center}
  485. \begin{minipage}{0.5\textwidth}
  486. \begin{lstlisting}
  487. (match ast1.1
  488. [`(,op ,child1 ,child2)
  489. (print op) (newline)
  490. (print child1) (newline)
  491. (print child2)])
  492. \end{lstlisting}
  493. \end{minipage}
  494. \vrule
  495. \begin{minipage}{0.25\textwidth}
  496. \begin{lstlisting}
  497. '+
  498. '(read)
  499. '(- 8)
  500. \end{lstlisting}
  501. \end{minipage}
  502. \end{center}
  503. The \texttt{match} form takes AST \eqref{eq:arith-prog} and binds its
  504. parts to the three variables \texttt{op}, \texttt{child1}, and
  505. \texttt{child2}. In general, a match clause consists of a
  506. \emph{pattern} and a \emph{body}. The pattern is a quoted S-expression
  507. that may also contain pattern-variables (each one preceded by a comma).
  508. %
  509. The pattern is not the same thing as a quasiquote expression used to
  510. \emph{construct} ASTs, however, the similarity is intentional:
  511. constructing and deconstructing ASTs uses similar syntax.
  512. %
  513. While the pattern uses a restricted syntax, the body of the match
  514. clause may contain any Racket code whatsoever.
  515. A \code{match} form may contain several clauses, as in the following
  516. function \code{leaf?} that recognizes when an $R_0$ node is
  517. a leaf. The \code{match} proceeds through the clauses in order,
  518. checking whether the pattern can match the input S-expression. The
  519. body of the first clause that matches is executed. The output of
  520. \code{leaf?} for several S-expressions is shown on the right. In the
  521. below \code{match}, we see another form of pattern: the
  522. pattern \code{(? fixnum?)} applies the predicate \code{fixnum?} to the input
  523. S-expression to see if it is a machine-representable integer.
  524. \begin{center}
  525. \begin{minipage}{0.5\textwidth}
  526. \begin{lstlisting}
  527. (define (leaf? arith)
  528. (match arith
  529. [(? fixnum?) #t]
  530. [`(read) #t]
  531. [`(- ,c1) #f]
  532. [`(+ ,c1 ,c2) #f]))
  533. (leaf? `(read))
  534. (leaf? `(- 8))
  535. (leaf? `(+ (read) (- 8)))
  536. \end{lstlisting}
  537. \end{minipage}
  538. \vrule
  539. \begin{minipage}{0.25\textwidth}
  540. \begin{lstlisting}
  541. #t
  542. #f
  543. #f
  544. \end{lstlisting}
  545. \end{minipage}
  546. \end{center}
  547. When writing a \code{match}, we always refer to the grammar definition
  548. for the language and identify which non-terminal we're expecting to
  549. match against, then we make sure that 1) we have one clause for each
  550. alternative of that non-terminal and 2) that the pattern in each
  551. clause corresponds to the corresponding right-hand side of a grammar
  552. rule. For the \code{match} in the \code{leaf?} function, we refer to
  553. the grammar for $R\_0$ in Figure~\ref{fig:r0-syntax}. The $\Exp$
  554. non-terminal has 4 alternatives, so the \code{match} has 4 clauses.
  555. The pattern in each clause corresponds to the right-hand side of a
  556. grammar rule. For example, the pattern \code{`(+ ,c1 ,c2)} corresponds
  557. to the right-hand side $(\key{+} \; \Exp \; \Exp)$. When translating
  558. from grammars to patterns, replace non-terminals such as $\Exp$ with
  559. pattern variables (a comma followed by a variable name of your
  560. choice).
  561. \section{Recursion}
  562. \label{sec:recursion}
  563. Programs are inherently recursive. For example, an $R_0$ expression is
  564. often made of smaller expressions. Thus, the natural way to process an
  565. entire program is with a recursive function. As a first example of
  566. such a recursive function, we define \texttt{exp?} below, which takes
  567. an arbitrary S-expression and determines whether or not it is an $R_0$
  568. expression. As discussed in the previous section, each match clause
  569. corresponds to one grammar rule. The body of each clause makes a
  570. recursive call for each child node. This kind of recursive function is
  571. so common that it has a name: \emph{structural recursion}. In
  572. general, when a recursive function is defined using a sequence of
  573. match clauses that correspond to a grammar, and the body of each
  574. clause makes a recursive call on each child node, then we say the
  575. function is defined by structural recursion\footnote{This principle of
  576. structuring code according to the data definition is advocated in
  577. the book \emph{How to Design Programs}
  578. \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}. Below we also
  579. define a second function, named \code{R0?}, that determines whether an
  580. S-expression is an $R_0$ program. In general we can expect to write
  581. one recursive function to handle each non-terminal in the grammar.
  582. %
  583. \begin{center}
  584. \begin{minipage}{0.7\textwidth}
  585. \begin{lstlisting}
  586. (define (exp? sexp)
  587. (match sexp
  588. [(? fixnum?) #t]
  589. [`(read) #t]
  590. [`(- ,e) (exp? e)]
  591. [`(+ ,e1 ,e2)
  592. (and (exp? e1) (exp? e2))]
  593. [else #f]))
  594. (define (R0? sexp)
  595. (match sexp
  596. [`(program ,e) (exp? e)]
  597. [else #f]))
  598. (R0? `(program (+ (read) (- 8))))
  599. (R0? `(program (- (read) (+ 8))))
  600. \end{lstlisting}
  601. \end{minipage}
  602. \vrule
  603. \begin{minipage}{0.25\textwidth}
  604. \begin{lstlisting}
  605. #t
  606. #f
  607. \end{lstlisting}
  608. \end{minipage}
  609. \end{center}
  610. You may be tempted to merge the two functions into one, like this:
  611. \begin{center}
  612. \begin{minipage}{0.5\textwidth}
  613. \begin{lstlisting}
  614. (define (R0? sexp)
  615. (match sexp
  616. [(? fixnum?) #t]
  617. [`(read) #t]
  618. [`(- ,e) (R0? e)]
  619. [`(+ ,e1 ,e2) (and (R0? e1) (R0? e2))]
  620. [`(program ,e) (R0? e)]
  621. [else #f]))
  622. \end{lstlisting}
  623. \end{minipage}
  624. \end{center}
  625. %
  626. Sometimes such a trick will save a few lines of code, especially when it comes
  627. to the {\tt program} wrapper. Yet this style is generally \emph{not}
  628. recommended because it can get you into trouble.
  629. %
  630. For instance, the above function is subtly wrong:
  631. \lstinline{(R0? `(program (program 3)))} will return true, when it
  632. should return false.
  633. %% NOTE FIXME - must check for consistency on this issue throughout.
  634. \section{Interpreters}
  635. \label{sec:interp-R0}
  636. The meaning, or semantics, of a program is typically defined in the
  637. specification of the language. For example, the Scheme language is
  638. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  639. defined in its reference manual~\citep{plt-tr}. In this book we use an
  640. interpreter to define the meaning of each language that we consider,
  641. following Reynolds' advice in this
  642. regard~\citep{reynolds72:_def_interp}. An interpreter that is
  643. designated (by some people) as the definition of a language is called
  644. a \emph{definitional interpreter}. Here we warm up by creating a
  645. definitional interpreter for the $R_0$ language, which serves as a
  646. second example of structural recursion. The \texttt{interp-R0}
  647. function is defined in Figure~\ref{fig:interp-R0}. The body of the
  648. function is a match on the input program followed by a call to the
  649. \lstinline{interp-exp} helper function, which in turn has one match
  650. clause per grammar rule for $R_0$ expressions.
  651. \begin{figure}[tbp]
  652. \begin{lstlisting}
  653. (define (interp-exp e)
  654. (match e
  655. [(? fixnum?) e]
  656. [`(read)
  657. (let ([r (read)])
  658. (cond [(fixnum? r) r]
  659. [else (error 'interp-R0 "input not an integer" r)]))]
  660. [`(- ,e1) (fx- 0 (interp-exp e1))]
  661. [`(+ ,e1 ,e2) (fx+ (interp-exp e1) (interp-exp e2))]
  662. ))
  663. (define (interp-R0 p)
  664. (match p
  665. [`(program ,e) (interp-exp e)]))
  666. \end{lstlisting}
  667. \caption{Interpreter for the $R_0$ language.}
  668. \label{fig:interp-R0}
  669. \end{figure}
  670. Let us consider the result of interpreting a few $R_0$ programs. The
  671. following program adds two integers.
  672. \begin{lstlisting}
  673. (+ 10 32)
  674. \end{lstlisting}
  675. The result is \key{42}. (We wrote the above program in concrete syntax,
  676. whereas the parsed abstract syntax is \lstinline{(program (+ 10 32))}.)
  677. The next example demonstrates that expressions may be nested within
  678. each other, in this case nesting several additions and negations.
  679. \begin{lstlisting}
  680. (+ 10 (- (+ 12 20)))
  681. \end{lstlisting}
  682. What is the result of the above program?
  683. As mentioned previously, the $R_0$ language does not support
  684. arbitrarily-large integers, but only $63$-bit integers, so we
  685. interpret the arithmetic operations of $R_0$ using fixnum arithmetic
  686. in Racket. What happens when we run the following program?
  687. \begin{lstlisting}
  688. (define large 999999999999999999)
  689. (interp-R0 `(program (+ (+ (+ ,large ,large) (+ ,large ,large))
  690. (+ (+ ,large ,large) (+ ,large ,large)))))
  691. \end{lstlisting}
  692. It produces an error:
  693. \begin{lstlisting}
  694. fx+: result is not a fixnum
  695. \end{lstlisting}
  696. We establish the convention that if running the definitional
  697. interpreter on a program produces an error, then the meaning of that
  698. program is \emph{unspecified}. That means a compiler for the language
  699. is under no obligations regarding that program; it may or may not
  700. produce an executable, and if it does, that executable can do
  701. anything. This convention applies to the languages defined in this
  702. book, as a way to simplify the student's task of implementing them,
  703. but this convention is not applicable to all programming languages.
  704. Moving on to the last feature of the $R_0$ language, the \key{read}
  705. operation prompts the user of the program for an integer. Recall that
  706. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  707. \code{8}. So if we run
  708. \begin{lstlisting}
  709. (interp-R0 ast1.1)
  710. \end{lstlisting}
  711. and the input the integer \code{50} we get the answer to life, the
  712. universe, and everything: \code{42}.
  713. We include the \key{read} operation in $R_0$ so a clever student
  714. cannot implement a compiler for $R_0$ that simply runs the interpreter
  715. during compilation to obtain the output and then generates the trivial
  716. code to produce the output. (Yes, a clever student did this in a
  717. previous version of the course.)
  718. The job of a compiler is to translate a program in one language into a
  719. program in another language so that the output program behaves the
  720. same way as the input program does according to its definitional
  721. interpreter. This idea is depicted in the following diagram. Suppose
  722. we have two languages, $\mathcal{L}_1$ and $\mathcal{L}_2$, and an
  723. interpreter for each language. Suppose that the compiler translates
  724. program $P_1$ in language $\mathcal{L}_1$ into program $P_2$ in
  725. language $\mathcal{L}_2$. Then interpreting $P_1$ and $P_2$ on their
  726. respective interpreters with input $i$ should yield the same output
  727. $o$.
  728. \begin{equation} \label{eq:compile-correct}
  729. \begin{tikzpicture}[baseline=(current bounding box.center)]
  730. \node (p1) at (0, 0) {$P_1$};
  731. \node (p2) at (3, 0) {$P_2$};
  732. \node (o) at (3, -2.5) {$o$};
  733. \path[->] (p1) edge [above] node {compile} (p2);
  734. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  735. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  736. \end{tikzpicture}
  737. \end{equation}
  738. In the next section we see our first example of a compiler.
  739. \section{Example Compiler: a Partial Evaluator}
  740. \label{sec:partial-evaluation}
  741. In this section we consider a compiler that translates $R_0$
  742. programs into $R_0$ programs that may be more efficient, that is,
  743. this compiler is an optimizer. Our optimizer will accomplish this by
  744. trying to eagerly compute the parts of the program that do not depend
  745. on any inputs. For example, given the following program
  746. \begin{lstlisting}
  747. (+ (read) (- (+ 5 3)))
  748. \end{lstlisting}
  749. our compiler will translate it into the program
  750. \begin{lstlisting}
  751. (+ (read) -8)
  752. \end{lstlisting}
  753. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  754. evaluator for the $R_0$ language. The output of the partial evaluator
  755. is an $R_0$ program. In Figure~\ref{fig:pe-arith}, the structural
  756. recursion over $\Exp$ is captured in the \code{pe-exp} function
  757. whereas the code for partially evaluating the negation and addition
  758. operations is factored into two separate helper functions:
  759. \code{pe-neg} and \code{pe-add}. The input to these helper
  760. functions is the output of partially evaluating the children.
  761. \begin{figure}[tbp]
  762. \begin{lstlisting}
  763. (define (pe-neg r)
  764. (cond [(fixnum? r) (fx- 0 r)]
  765. [else `(- ,r)]))
  766. (define (pe-add r1 r2)
  767. (cond [(and (fixnum? r1) (fixnum? r2)) (fx+ r1 r2)]
  768. [else `(+ ,r1 ,r2)]))
  769. (define (pe-exp e)
  770. (match e
  771. [(? fixnum?) e]
  772. [`(read) `(read)]
  773. [`(- ,e1) (pe-neg (pe-exp e1))]
  774. [`(+ ,e1 ,e2) (pe-add (pe-exp e1) (pe-exp e2))]
  775. ))
  776. (define (pe-R0 p)
  777. (match p
  778. [`(program ,e) `(program ,(pe-exp e))]
  779. ))
  780. \end{lstlisting}
  781. \caption{A partial evaluator for $R_0$ expressions.}
  782. \label{fig:pe-arith}
  783. \end{figure}
  784. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  785. arguments are integers and if they are, perform the appropriate
  786. arithmetic. Otherwise, they use quasiquote to create an AST node for
  787. the operation (either negation or addition) and use comma to splice in
  788. the children.
  789. To gain some confidence that the partial evaluator is correct, we can
  790. test whether it produces programs that get the same result as the
  791. input programs. That is, we can test whether it satisfies Diagram
  792. \eqref{eq:compile-correct}. The following code runs the partial
  793. evaluator on several examples and tests the output program. The
  794. \texttt{assert} function is defined in Appendix~\ref{appendix:utilities}.
  795. \begin{lstlisting}
  796. (define (test-pe p)
  797. (assert "testing pe-R0"
  798. (equal? (interp-R0 p) (interp-R0 (pe-R0 p)))))
  799. (test-pe `(+ (read) (- (+ 5 3))))
  800. (test-pe `(+ 1 (+ (read) 1)))
  801. (test-pe `(- (+ (read) (- 5))))
  802. \end{lstlisting}
  803. \begin{exercise}
  804. \normalfont
  805. % I don't like the italics for exercises. -Jeremy
  806. Improve on the partial evaluator in Figure~\ref{fig:pe-arith} by
  807. replacing the \texttt{pe-neg} and \texttt{pe-add} helper functions
  808. with functions that know more about arithmetic. For example, your
  809. partial evaluator should translate
  810. \begin{lstlisting}
  811. (+ 1 (+ (read) 1))
  812. \end{lstlisting}
  813. into
  814. \begin{lstlisting}
  815. (+ 2 (read))
  816. \end{lstlisting}
  817. To accomplish this, we recommend that your partial evaluator produce
  818. output in the form of the $\itm{residual}$ non-terminal of the
  819. following grammar.
  820. \[
  821. \begin{array}{lcl}
  822. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-} \;(\key{read}))
  823. \mid (\key{+} \; \Exp \; \Exp)\\
  824. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \Exp) \mid \Exp
  825. \end{array}
  826. \]
  827. \end{exercise}
  828. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  829. \chapter{Integers and Variables}
  830. \label{ch:int-exp}
  831. This chapter is about compiling the subset of Racket that includes
  832. integer arithmetic and local variable binding, which we name $R_1$, to
  833. x86-64 assembly code~\citep{Intel:2015aa}. Henceforth we shall refer
  834. to x86-64 simply as x86. The chapter begins with a description of the
  835. $R_1$ language (Section~\ref{sec:s0}) followed by a description of x86
  836. (Section~\ref{sec:x86}). The x86 assembly language is quite large, so
  837. we discuss only what is needed for compiling $R_1$. We introduce more
  838. of x86 in later chapters. Once we have introduced $R_1$ and x86, we
  839. reflect on their differences and come up with a plan to break down the
  840. translation from $R_1$ to x86 into a handful of steps
  841. (Section~\ref{sec:plan-s0-x86}). The rest of the sections in this
  842. chapter give detailed hints regarding each step
  843. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  844. to give enough hints that the well-prepared reader, together with some
  845. friends, can implement a compiler from $R_1$ to x86 in a couple weeks
  846. while at the same time leaving room for some fun and creativity. To
  847. give the reader a feeling for the scale of this first compiler, the
  848. instructor solution for the $R_1$ compiler is approximately 500 lines
  849. of code.
  850. \section{The $R_1$ Language}
  851. \label{sec:s0}
  852. The $R_1$ language extends the $R_0$ language
  853. (Figure~\ref{fig:r0-syntax}) with variable definitions. The syntax of
  854. the $R_1$ language is defined by the grammar in
  855. Figure~\ref{fig:r1-syntax}. The non-terminal \Var{} may be any Racket
  856. identifier. As in $R_0$, \key{read} is a nullary operator, \key{-} is
  857. a unary operator, and \key{+} is a binary operator. Similar to $R_0$,
  858. the $R_1$ language includes the \key{program} construct to mark the
  859. top of the program, which is helpful in some of the compiler passes.
  860. The $\itm{info}$ field of the \key{program} construct contains an
  861. association list that is used to communicate auxiliary data from one
  862. compiler pass the next. Despite the simplicity of the $R_1$ language,
  863. it is rich enough to exhibit several compilation techniques.
  864. \begin{figure}[btp]
  865. \centering
  866. \fbox{
  867. \begin{minipage}{0.96\textwidth}
  868. \[
  869. \begin{array}{rcl}
  870. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \\
  871. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  872. R_1 &::=& (\key{program} \;\itm{info}\; \Exp)
  873. \end{array}
  874. \]
  875. \end{minipage}
  876. }
  877. \caption{The syntax of $R_1$, a language of integers and variables.}
  878. \label{fig:r1-syntax}
  879. \end{figure}
  880. Let us dive further into the syntax and semantics of the $R_1$
  881. language. The \key{let} construct defines a variable for use within
  882. its body and initializes the variable with the value of an expression.
  883. So the following program initializes \code{x} to \code{32} and then
  884. evaluates the body \code{(+ 10 x)}, producing \code{42}.
  885. \begin{lstlisting}
  886. (program ()
  887. (let ([x (+ 12 20)]) (+ 10 x)))
  888. \end{lstlisting}
  889. When there are multiple \key{let}'s for the same variable, the closest
  890. enclosing \key{let} is used. That is, variable definitions overshadow
  891. prior definitions. Consider the following program with two \key{let}'s
  892. that define variables named \code{x}. Can you figure out the result?
  893. \begin{lstlisting}
  894. (program ()
  895. (let ([x 32]) (+ (let ([x 10]) x) x)))
  896. \end{lstlisting}
  897. For the purposes of showing which variable uses correspond to which
  898. definitions, the following shows the \code{x}'s annotated with subscripts
  899. to distinguish them. Double check that your answer for the above is
  900. the same as your answer for this annotated version of the program.
  901. \begin{lstlisting}
  902. (program ()
  903. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|)))
  904. \end{lstlisting}
  905. The initializing expression is always evaluated before the body of the
  906. \key{let}, so in the following, the \key{read} for \code{x} is
  907. performed before the \key{read} for \code{y}. Given the input
  908. \code{52} then \code{10}, the following produces \code{42} (and not
  909. \code{-42}).
  910. \begin{lstlisting}
  911. (program ()
  912. (let ([x (read)]) (let ([y (read)]) (+ x (- y)))))
  913. \end{lstlisting}
  914. Figure~\ref{fig:interp-R1} shows the definitional interpreter for the
  915. $R_1$ language. It extends the interpreter for $R_0$ with two new
  916. \key{match} clauses for variables and for \key{let}. For \key{let},
  917. we need a way to communicate the value of a variable to all the uses
  918. of a variable. To accomplish this, we maintain a mapping from
  919. variables to values, which is called an \emph{environment}. For
  920. simplicity, here we use an association list to represent the
  921. environment. The \code{interp-R1} function takes the current
  922. environment, \code{env}, as an extra parameter. When the interpreter
  923. encounters a variable, it finds the corresponding value using the
  924. \code{lookup} function (Appendix~\ref{appendix:utilities}). When the
  925. interpreter encounters a \key{let}, it evaluates the initializing
  926. expression, extends the environment with the result value bound to the
  927. variable, then evaluates the body of the \key{let}.
  928. \begin{figure}[tbp]
  929. \begin{lstlisting}
  930. (define (interp-exp env)
  931. (lambda (e)
  932. (match e
  933. [(? fixnum?) e]
  934. [`(read)
  935. (define r (read))
  936. (cond [(fixnum? r) r]
  937. [else (error 'interp-R1 "expected an integer" r)])]
  938. [`(- ,e)
  939. (define v ((interp-exp env) e))
  940. (fx- 0 v)]
  941. [`(+ ,e1 ,e2)
  942. (define v1 ((interp-exp env) e1))
  943. (define v2 ((interp-exp env) e2))
  944. (fx+ v1 v2)]
  945. [(? symbol?) (lookup e env)]
  946. [`(let ([,x ,e]) ,body)
  947. (define new-env (cons (cons x ((interp-exp env) e)) env))
  948. ((interp-exp new-env) body)]
  949. )))
  950. (define (interp-R1 env)
  951. (lambda (p)
  952. (match p
  953. [`(program ,info ,e) ((interp-exp '()) e)])))
  954. \end{lstlisting}
  955. \caption{Interpreter for the $R_1$ language.}
  956. \label{fig:interp-R1}
  957. \end{figure}
  958. The goal for this chapter is to implement a compiler that translates
  959. any program $P_1$ written in the $R_1$ language into an x86 assembly
  960. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  961. computer as the $P_1$ program interpreted by \code{interp-R1}. That
  962. is, they both output the same integer $n$. We depict this correctness
  963. criteria in the following diagram.
  964. \[
  965. \begin{tikzpicture}[baseline=(current bounding box.center)]
  966. \node (p1) at (0, 0) {$P_1$};
  967. \node (p2) at (4, 0) {$P_2$};
  968. \node (o) at (4, -2) {$n$};
  969. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  970. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  971. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  972. \end{tikzpicture}
  973. \]
  974. In the next section we introduce enough of the x86 assembly
  975. language to compile $R_1$.
  976. \section{The x86 Assembly Language}
  977. \label{sec:x86}
  978. Figure~\ref{fig:x86-a} defines the syntax for the
  979. subset of the x86 assembly language needed for this chapter.
  980. %
  981. An x86 program is a sequence of instructions. The program is stored in
  982. the computer's memory and the computer has a \emph{program counter}
  983. that points to the address of the next instruction to be executed. For
  984. most instructions, once the instruction is executed, the program
  985. counter is incremented to point to the immediately following
  986. instruction in memory. Most x86 instructions take two operands, where
  987. each operand is either an integer constant (called \emph{immediate
  988. value}), a \emph{register}, or a \emph{memory} location. A register
  989. is a special kind of variable. Each one holds a 64-bit value; there
  990. are 16 registers in the computer and their names are given in
  991. Figure~\ref{fig:x86-a}. The computer's memory as a mapping of 64-bit
  992. addresses to 64-bit values%
  993. \footnote{This simple story suffices for describing how sequential
  994. programs access memory but is not sufficient for multi-threaded
  995. programs. However, multi-threaded execution is beyond the scope of
  996. this book.}.
  997. %
  998. We use the AT\&T syntax expected by the GNU assembler, which comes
  999. with the \key{gcc} compiler that we use for compiling assembly code to
  1000. machine code.
  1001. %
  1002. Appendix~\ref{sec:x86-quick-reference} is a quick-reference of all the
  1003. x86 instructions used in this book with a short explanation of what
  1004. they do.
  1005. % to do: finish treatment of imulq
  1006. % it's needed for vector's in R6/R7
  1007. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1008. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1009. && \key{r8} \mid \key{r9} \mid \key{r10}
  1010. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1011. \mid \key{r14} \mid \key{r15}}
  1012. \begin{figure}[tp]
  1013. \fbox{
  1014. \begin{minipage}{0.96\textwidth}
  1015. \[
  1016. \begin{array}{lcl}
  1017. \Reg &::=& \allregisters{} \\
  1018. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int(\key{\%}\Reg) \\
  1019. \Instr &::=& \key{addq} \; \Arg, \Arg \mid
  1020. \key{subq} \; \Arg, \Arg \mid
  1021. \key{negq} \; \Arg \mid \key{movq} \; \Arg, \Arg \mid \\
  1022. && \key{callq} \; \mathit{label} \mid
  1023. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \itm{label}\key{:}\; \Instr \\
  1024. \Prog &::= & \key{.globl main}\\
  1025. & & \key{main:} \; \Instr^{+}
  1026. \end{array}
  1027. \]
  1028. \end{minipage}
  1029. }
  1030. \caption{A subset of the x86 assembly language (AT\&T syntax).}
  1031. \label{fig:x86-a}
  1032. \end{figure}
  1033. An immediate value is written using the notation \key{\$}$n$ where $n$
  1034. is an integer.
  1035. %
  1036. A register is written with a \key{\%} followed by the register name,
  1037. such as \key{\%rax}.
  1038. %
  1039. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1040. which obtains the address stored in register $r$ and then adds $n$
  1041. bytes to the address. The resulting address is used to either load or
  1042. store to memory depending on whether it occurs as a source or
  1043. destination argument of an instruction.
  1044. An arithmetic instruction such as $\key{addq}\,s,\,d$ reads from the
  1045. source $s$ and destination $d$, applies the arithmetic operation, then
  1046. writes the result back to the destination $d$.
  1047. %
  1048. The move instruction $\key{movq}\,s\,d$ reads from $s$ and stores the
  1049. result in $d$.
  1050. %
  1051. The $\key{callq}\,\mathit{label}$ instruction executes the procedure
  1052. specified by the label. We discuss procedure calls in more detail
  1053. later in this chapter and in Chapter~\ref{ch:functions}.
  1054. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  1055. to \code{(+ 10 32)}. The \key{globl} directive says that the
  1056. \key{main} procedure is externally visible, which is necessary so
  1057. that the operating system can call it. The label \key{main:}
  1058. indicates the beginning of the \key{main} procedure which is where
  1059. the operating system starts executing this program. The instruction
  1060. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  1061. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  1062. $10$ in \key{rax} and puts the result, $42$, back into
  1063. \key{rax}.
  1064. %
  1065. The last instruction, \key{retq}, finishes the \key{main} function by
  1066. returning the integer in \key{rax} to the operating system. The
  1067. operating system interprets this integer as the program's exit
  1068. code. By convention, an exit code of 0 indicates the program was
  1069. successful, and all other exit codes indicate various errors.
  1070. Nevertheless, we return the result of the program as the exit code.
  1071. %\begin{wrapfigure}{r}{2.25in}
  1072. \begin{figure}[tbp]
  1073. \begin{lstlisting}
  1074. .globl main
  1075. main:
  1076. movq $10, %rax
  1077. addq $32, %rax
  1078. retq
  1079. \end{lstlisting}
  1080. \caption{An x86 program equivalent to $\BINOP{+}{10}{32}$.}
  1081. \label{fig:p0-x86}
  1082. %\end{wrapfigure}
  1083. \end{figure}
  1084. Unfortunately, x86 varies in a couple ways depending on what operating
  1085. system it is assembled in. The code examples shown here are correct on
  1086. Linux and most Unix-like platforms, but when assembled on Mac OS X,
  1087. labels like \key{main} must be prefixed with an underscore, as in
  1088. \key{\_main}.
  1089. We exhibit the use of memory for storing intermediate results in the
  1090. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1091. equivalent to $\BINOP{+}{52}{ \UNIOP{-}{10} }$. This program uses a
  1092. region of memory called the \emph{procedure call stack} (or
  1093. \emph{stack} for short). The stack consists of a separate \emph{frame}
  1094. for each procedure call. The memory layout for an individual frame is
  1095. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1096. \emph{stack pointer} and points to the item at the top of the
  1097. stack. The stack grows downward in memory, so we increase the size of
  1098. the stack by subtracting from the stack pointer. Some operating
  1099. systems require the frame size to be a multiple of 16 bytes. In the
  1100. context of a procedure call, the \emph{return address} is the next
  1101. instruction after the call instruction on the caller side. During a
  1102. function call, the return address is pushed onto the stack. The
  1103. register \key{rbp} is the \emph{base pointer} which serves two
  1104. purposes: 1) it saves the location of the stack pointer for the
  1105. calling procedure and 2) it is used to access variables associated
  1106. with the current procedure. The base pointer of the calling procedure
  1107. is pushed onto the stack after the return address. We number the
  1108. variables from $1$ to $n$. Variable $1$ is stored at address
  1109. $-8\key{(\%rbp)}$, variable $2$ at $-16\key{(\%rbp)}$, etc.
  1110. \begin{figure}[tbp]
  1111. \begin{lstlisting}
  1112. start:
  1113. movq $10, -8(%rbp)
  1114. negq -8(%rbp)
  1115. movq -8(%rbp), %rax
  1116. addq $52, %rax
  1117. jmp conclusion
  1118. .globl main
  1119. main:
  1120. pushq %rbp
  1121. movq %rsp, %rbp
  1122. subq $16, %rsp
  1123. jmp start
  1124. conclusion:
  1125. addq $16, %rsp
  1126. popq %rbp
  1127. retq
  1128. \end{lstlisting}
  1129. \caption{An x86 program equivalent to $\BINOP{+}{52}{\UNIOP{-}{10} }$.}
  1130. \label{fig:p1-x86}
  1131. \end{figure}
  1132. \begin{figure}[tbp]
  1133. \centering
  1134. \begin{tabular}{|r|l|} \hline
  1135. Position & Contents \\ \hline
  1136. 8(\key{\%rbp}) & return address \\
  1137. 0(\key{\%rbp}) & old \key{rbp} \\
  1138. -8(\key{\%rbp}) & variable $1$ \\
  1139. -16(\key{\%rbp}) & variable $2$ \\
  1140. \ldots & \ldots \\
  1141. 0(\key{\%rsp}) & variable $n$\\ \hline
  1142. \end{tabular}
  1143. \caption{Memory layout of a frame.}
  1144. \label{fig:frame}
  1145. \end{figure}
  1146. Getting back to the program in Figure~\ref{fig:p1-x86}, the first
  1147. three instructions are the typical \emph{prelude} for a procedure.
  1148. The instruction \key{pushq \%rbp} saves the base pointer for the
  1149. caller onto the stack and subtracts $8$ from the stack pointer. The
  1150. second instruction \key{movq \%rsp, \%rbp} changes the base pointer to
  1151. the top of the stack. The instruction \key{subq \$16, \%rsp} moves the
  1152. stack pointer down to make enough room for storing variables. This
  1153. program needs one variable ($8$ bytes) but because the frame size is
  1154. required to be a multiple of 16 bytes, the space for variables is
  1155. rounded to 16 bytes.
  1156. The four instructions under the label \code{start} carry out the work
  1157. of computing $\BINOP{+}{52}{\UNIOP{-}{10} }$. The first instruction
  1158. \key{movq \$10, -8(\%rbp)} stores $10$ in variable $1$. The
  1159. instruction \key{negq -8(\%rbp)} changes variable $1$ to $-10$. The
  1160. instruction \key{movq \$52, \%rax} places $52$ in the register \key{rax} and
  1161. finally \key{addq -8(\%rbp), \%rax} adds the contents of variable $1$ to
  1162. \key{rax}, at which point \key{rax} contains $42$.
  1163. The three instructions under the label \code{conclusion} are the
  1164. typical \emph{finale} of a procedure. The first two instructions are
  1165. necessary to get the state of the machine back to where it was at the
  1166. beginning of the procedure. The instruction \key{addq \$16, \%rsp}
  1167. moves the stack pointer back to point at the old base pointer. The
  1168. amount added here needs to match the amount that was subtracted in the
  1169. prelude of the procedure. Then \key{popq \%rbp} returns the old base
  1170. pointer to \key{rbp} and adds $8$ to the stack pointer. The last
  1171. instruction, \key{retq}, jumps back to the procedure that called this
  1172. one and adds 8 to the stack pointer, which returns the stack pointer
  1173. to where it was prior to the procedure call.
  1174. The compiler will need a convenient representation for manipulating
  1175. x86 programs, so we define an abstract syntax for x86 in
  1176. Figure~\ref{fig:x86-ast-a}. We refer to this language as $x86_0$ with
  1177. a subscript $0$ because later we introduce extended versions of this
  1178. assembly language. The main difference compared to the concrete syntax
  1179. of x86 (Figure~\ref{fig:x86-a}) is that it does not allow labeled
  1180. instructions to appear anywhere, but instead organizes instructions
  1181. into groups called \emph{blocks} and associates a label with every
  1182. block, which is why the \key{program} form includes an association
  1183. list mapping labels to blocks. The reason for this organization
  1184. becomes apparent in Chapter~\ref{ch:bool-types}.
  1185. \begin{figure}[tp]
  1186. \fbox{
  1187. \begin{minipage}{0.96\textwidth}
  1188. \[
  1189. \begin{array}{lcl}
  1190. \itm{register} &::=& \allregisters{} \\
  1191. \Arg &::=& \INT{\Int} \mid \REG{\itm{register}}
  1192. \mid (\key{deref}\;\itm{register}\;\Int) \\
  1193. \Instr &::=& (\key{addq} \; \Arg\; \Arg) \mid
  1194. (\key{subq} \; \Arg\; \Arg) \mid
  1195. (\key{movq} \; \Arg\; \Arg) \mid
  1196. (\key{retq})\\
  1197. &\mid& (\key{negq} \; \Arg) \mid
  1198. (\key{callq} \; \mathit{label}) \mid
  1199. (\key{pushq}\;\Arg) \mid
  1200. (\key{popq}\;\Arg) \\
  1201. \Block &::= & (\key{block} \;\itm{info}\; \Instr^{+}) \\
  1202. x86_0 &::= & (\key{program} \;\itm{info} \; ((\itm{label} \,\key{.}\, \Block)^{+}))
  1203. \end{array}
  1204. \]
  1205. \end{minipage}
  1206. }
  1207. \caption{Abstract syntax for $x86_0$ assembly.}
  1208. \label{fig:x86-ast-a}
  1209. \end{figure}
  1210. \section{Planning the trip to x86 via the $C_0$ language}
  1211. \label{sec:plan-s0-x86}
  1212. To compile one language to another it helps to focus on the
  1213. differences between the two languages because the compiler will need
  1214. to bridge those differences. What are the differences between $R_1$
  1215. and x86 assembly? Here we list some of the most important ones.
  1216. \begin{enumerate}
  1217. \item[(a)] x86 arithmetic instructions typically have two arguments
  1218. and update the second argument in place. In contrast, $R_1$
  1219. arithmetic operations take two arguments and produce a new value.
  1220. An x86 instruction may have at most one memory-accessing argument.
  1221. Furthermore, some instructions place special restrictions on their
  1222. arguments.
  1223. \item[(b)] An argument to an $R_1$ operator can be any expression,
  1224. whereas x86 instructions restrict their arguments to be integers
  1225. constants, registers, and memory locations.
  1226. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1227. sequence of instructions and jumps to labeled positions, whereas in
  1228. $R_1$ the order of evaluation is a left-to-right depth-first
  1229. traversal of the abstract syntax tree.
  1230. \item[(d)] An $R_1$ program can have any number of variables whereas
  1231. x86 has 16 registers and the procedure calls stack.
  1232. \item[(e)] Variables in $R_1$ can overshadow other variables with the
  1233. same name. The registers and memory locations of x86 all have unique
  1234. names or addresses.
  1235. \end{enumerate}
  1236. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1237. the problem into several steps, dealing with the above differences one
  1238. at a time. Each of these steps is called a \emph{pass} of the
  1239. compiler, because step traverses (passes over) the AST of the program.
  1240. %
  1241. We begin by sketching how we might implement each pass, and give them
  1242. names. We then figure out an ordering of the passes and the
  1243. input/output language for each pass. The very first pass has $R_1$ as
  1244. its input language and the last pass has x86 as its output
  1245. language. In between we can choose whichever language is most
  1246. convenient for expressing the output of each pass, whether that be
  1247. $R_1$, x86, or new \emph{intermediate languages} of our own design.
  1248. Finally, to implement each pass we write one recursive function per
  1249. non-terminal in the grammar of the input language of the pass.
  1250. \begin{description}
  1251. \item[Pass \key{select-instructions}] To handle the difference between
  1252. $R_1$ operations and x86 instructions we shall convert each $R_1$
  1253. operation to a short sequence of instructions that accomplishes the
  1254. same task.
  1255. \item[Pass \key{remove-complex-opera*}] To ensure that each
  1256. subexpression (i.e. operator and operand, and hence \key{opera*}) is
  1257. a \emph{simple expression} (a variable or integer), we shall
  1258. introduce temporary variables to hold the results of subexpressions.
  1259. \item[Pass \key{explicate-control}] To make the execution order of the
  1260. program explicit, we shall convert from the abstract syntax tree
  1261. representation into a \emph{control-flow graph} in which each node
  1262. contains a sequence of statements and the edges between nodes say
  1263. where to go next.
  1264. \item[Pass \key{assign-homes}] To handle the difference between the
  1265. variables in $R_1$ versus the registers and stack location in x86,
  1266. we assignment of each variable to a register or stack location.
  1267. \item[Pass \key{uniquify}] This pass deals with the shadowing of variables
  1268. by renaming every variable to a unique name, so that shadowing no
  1269. longer occurs.
  1270. \end{description}
  1271. The next question is: in what order should we apply these passes? This
  1272. question can be challenging because it is difficult to know ahead of
  1273. time which orders will be better (easier to implement, produce more
  1274. efficient code, etc.) so often some trial-and-error is
  1275. involved. Nevertheless, we can try to plan ahead and make educated
  1276. choices regarding the ordering.
  1277. Let us consider the ordering of \key{uniquify} and
  1278. \key{remove-complex-opera*}. The assignment of subexpressions to
  1279. temporary variables involves introducing new variables and moving
  1280. subexpressions, which might change the shadowing of variables and
  1281. inadvertently change the behavior of the program. But if we apply
  1282. \key{uniquify} first, this will not be an issue. Of course, this means
  1283. that in \key{remove-complex-opera*}, we need to ensure that the
  1284. temporary variables that it creates are unique.
  1285. What should be the ordering of \key{explicate-control} with respect to
  1286. \key{uniquify}? The \key{uniquify} pass should come first because
  1287. \key{explicate-control} changes all the \key{let}-bound variables to
  1288. become local variables whose scope is the entire program, which would
  1289. confuse variables with the same name.
  1290. %
  1291. Likewise, we place \key{explicate-control} after
  1292. \key{remove-complex-opera*} because \key{explicate-control} removes
  1293. the \key{let} form, but it is convenient to use \key{let} in the
  1294. output of \key{remove-complex-opera*}.
  1295. %
  1296. Regarding \key{assign-homes}, it is helpful to place
  1297. \key{explicate-control} first because \key{explicate-control} changes
  1298. \key{let}-bound variables into program-scope variables. Instead of
  1299. traversing the entire program for \key{let}-bound variables,
  1300. \key{assign-homes} can read them off from the $\itm{info}$ of the
  1301. \key{program} AST node.
  1302. Last, we need to decide on the ordering of \key{select-instructions}
  1303. and \key{assign-homes}. These two passes are intertwined, creating a
  1304. Gordian Knot. To do a good job of assigning homes, it is helpful to
  1305. have already determined which instructions will be used, because x86
  1306. instructions have restrictions about which of their arguments can be
  1307. registers versus stack locations. For example, one can give
  1308. preferential treatment to variables that occur in register-argument
  1309. positions. On the other hand, it may turn out to be impossible to make
  1310. sure that all such variables are assigned to registers, and then one
  1311. must redo the selection of instructions. Some compilers handle this
  1312. problem by iteratively repeating these two passes until a good
  1313. solution is found. We shall use a simpler approach in which
  1314. \key{select-instructions} comes first, followed by the
  1315. \key{assign-homes}, followed by a third pass, named
  1316. \key{patch-instructions}, that uses a reserved register to patch-up
  1317. outstanding problems regarding instructions with too many memory
  1318. accesses. The disadvantage of this approach a reduction in runtime
  1319. efficiency.
  1320. \begin{figure}[tbp]
  1321. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1322. \node (R1) at (0,2) {\large $R_1$};
  1323. \node (R1-2) at (3,2) {\large $R_1$};
  1324. \node (R1-3) at (6,2) {\large $R_1$};
  1325. %\node (C0-1) at (6,0) {\large $C_0$};
  1326. \node (C0-2) at (3,0) {\large $C_0$};
  1327. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_0$};
  1328. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_0$};
  1329. \node (x86-4) at (9,-2) {\large $\text{x86}_0$};
  1330. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}_0$};
  1331. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1332. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  1333. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-2);
  1334. %\path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  1335. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1336. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1337. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1338. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1339. \end{tikzpicture}
  1340. \caption{Overview of the passes for compiling $R_1$. }
  1341. \label{fig:R1-passes}
  1342. \end{figure}
  1343. Figure~\ref{fig:R1-passes} presents the ordering of the compiler
  1344. passes in the form of a graph. Each pass is an edge and the
  1345. input/output language of each pass is a node in the graph. The output
  1346. of \key{uniquify} and \key{remove-complex-opera*} are programs that
  1347. are still in the $R_1$ language, but the output of the pass
  1348. \key{explicate-control} is in a different language that is designed to
  1349. make the order of evaluation explicit in its syntax, which we
  1350. introduce in the next section. The last pass in
  1351. Figure~\ref{fig:R1-passes} is \key{print-x86}, which converts from the
  1352. abstract syntax of $\text{x86}_0$ to the concrete (textual) syntax of
  1353. x86.
  1354. In the next sections we discuss the $C_0$ language and the
  1355. $\text{x86}^{*}_0$ and $\text{x86}^{\dagger}_0$ dialects of x86. The
  1356. remainder of this chapter gives hints regarding the implementation of
  1357. each of the compiler passes in Figure~\ref{fig:R1-passes}.
  1358. \subsection{The $C_0$ Intermediate Language}
  1359. The output of \key{explicate-control} is similar to the $C$
  1360. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1361. categories for expressions and statements, so we name it $C_0$. The
  1362. syntax for $C_0$ is defined in Figure~\ref{fig:c0-syntax}.
  1363. %
  1364. The $C_0$ language supports the same operators as $R_1$ but the
  1365. arguments of operators are now restricted to just variables and
  1366. integers, thanks to the \key{remove-complex-opera*} pass. In the
  1367. literature this style of intermediate language is called
  1368. administrative normal form, or ANF for
  1369. short~\citep{Danvy:1991fk,Flanagan:1993cg}. Instead of \key{let}
  1370. expressions, $C_0$ has assignment statements which can be executed in
  1371. sequence using the \key{seq} construct. A sequence of statements
  1372. always ends with \key{return}, a guarantee that is baked into the
  1373. grammar rules for the \itm{tail} non-terminal. The naming of this
  1374. non-terminal comes from the term \emph{tail position}, which refers to
  1375. an expression that is the last one to execute within a function. (A
  1376. expression in tail position may contain subexpressions, and those may
  1377. or may not be in tail position depending on the kind of expression.)
  1378. A $C_0$ program consists of an association list mapping labels to
  1379. tails. This is overkill for the present chapter, as we do not yet need
  1380. to introduce \key{goto} for jumping to labels, but it saves us from
  1381. having to change the syntax of the program construct in
  1382. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1383. \key{start}, and the whole program is it's tail.
  1384. %
  1385. The $\itm{info}$ field of the program construct, after the
  1386. \key{explicate-control} pass, contains a mapping from the symbol
  1387. \key{locals} to a list of variables, that is, a list of all the
  1388. variables used in the program. At the start of the program, these
  1389. variables are uninitialized; they become initialized on their first
  1390. assignment.
  1391. \begin{figure}[tbp]
  1392. \fbox{
  1393. \begin{minipage}{0.96\textwidth}
  1394. \[
  1395. \begin{array}{lcl}
  1396. \Arg &::=& \Int \mid \Var \\
  1397. \Exp &::=& \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)\\
  1398. \Stmt &::=& \ASSIGN{\Var}{\Exp} \\
  1399. \Tail &::= & \RETURN{\Exp} \mid (\key{seq}\; \Stmt\; \Tail) \\
  1400. C_0 & ::= & (\key{program}\;\itm{info}\;((\itm{label}\,\key{.}\,\Tail)^{+}))
  1401. \end{array}
  1402. \]
  1403. \end{minipage}
  1404. }
  1405. \caption{The $C_0$ intermediate language.}
  1406. \label{fig:c0-syntax}
  1407. \end{figure}
  1408. %% The \key{select-instructions} pass is optimistic in the sense that it
  1409. %% treats variables as if they were all mapped to registers. The
  1410. %% \key{select-instructions} pass generates a program that consists of
  1411. %% x86 instructions but that still uses variables, so it is an
  1412. %% intermediate language that is technically different than x86, which
  1413. %% explains the asterisks in the diagram above.
  1414. %% In this Chapter we shall take the easy road to implementing
  1415. %% \key{assign-homes} and simply map all variables to stack locations.
  1416. %% The topic of Chapter~\ref{ch:register-allocation-r1} is implementing a
  1417. %% smarter approach in which we make a best-effort to map variables to
  1418. %% registers, resorting to the stack only when necessary.
  1419. %% Once variables have been assigned to their homes, we can finalize the
  1420. %% instruction selection by dealing with an idiosyncrasy of x86
  1421. %% assembly. Many x86 instructions have two arguments but only one of the
  1422. %% arguments may be a memory reference (and the stack is a part of
  1423. %% memory). Because some variables may get mapped to stack locations,
  1424. %% some of our generated instructions may violate this restriction. The
  1425. %% purpose of the \key{patch-instructions} pass is to fix this problem by
  1426. %% replacing every violating instruction with a short sequence of
  1427. %% instructions that use the \key{rax} register. Once we have implemented
  1428. %% a good register allocator (Chapter~\ref{ch:register-allocation-r1}), the
  1429. %% need to patch instructions will be relatively rare.
  1430. \subsection{The dialects of x86}
  1431. The x86$^{*}_0$ language, pronounced ``pseudo-x86'', is the output of
  1432. the pass \key{select-instructions}. It extends $x86_0$ with an unbound
  1433. number program-scope variables and has looser rules regarding
  1434. instruction arguments. The x86$^{\dagger}$ language, the output of
  1435. \key{print-x86}, is the concrete syntax for x86.
  1436. \section{Uniquify Variables}
  1437. \label{sec:uniquify-s0}
  1438. The \code{uniquify} pass compiles arbitrary $R_1$ programs into $R_1$
  1439. programs in which every \key{let} uses a unique variable name. For
  1440. example, the \code{uniquify} pass should translate the program on the
  1441. left into the program on the right. \\
  1442. \begin{tabular}{lll}
  1443. \begin{minipage}{0.4\textwidth}
  1444. \begin{lstlisting}
  1445. (program ()
  1446. (let ([x 32])
  1447. (+ (let ([x 10]) x) x)))
  1448. \end{lstlisting}
  1449. \end{minipage}
  1450. &
  1451. $\Rightarrow$
  1452. &
  1453. \begin{minipage}{0.4\textwidth}
  1454. \begin{lstlisting}
  1455. (program ()
  1456. (let ([x.1 32])
  1457. (+ (let ([x.2 10]) x.2) x.1)))
  1458. \end{lstlisting}
  1459. \end{minipage}
  1460. \end{tabular} \\
  1461. %
  1462. The following is another example translation, this time of a program
  1463. with a \key{let} nested inside the initializing expression of another
  1464. \key{let}.\\
  1465. \begin{tabular}{lll}
  1466. \begin{minipage}{0.4\textwidth}
  1467. \begin{lstlisting}
  1468. (program ()
  1469. (let ([x (let ([x 4])
  1470. (+ x 1))])
  1471. (+ x 2)))
  1472. \end{lstlisting}
  1473. \end{minipage}
  1474. &
  1475. $\Rightarrow$
  1476. &
  1477. \begin{minipage}{0.4\textwidth}
  1478. \begin{lstlisting}
  1479. (program ()
  1480. (let ([x.2 (let ([x.1 4])
  1481. (+ x.1 1))])
  1482. (+ x.2 2)))
  1483. \end{lstlisting}
  1484. \end{minipage}
  1485. \end{tabular}
  1486. We recommend implementing \code{uniquify} as a structurally recursive
  1487. function that mostly copies the input program. However, when
  1488. encountering a \key{let}, it should generate a unique name for the
  1489. variable (the Racket function \code{gensym} is handy for this) and
  1490. associate the old name with the new unique name in an association
  1491. list. The \code{uniquify} function will need to access this
  1492. association list when it gets to a variable reference, so we add
  1493. another parameter to \code{uniquify} for the association list. It is
  1494. quite common for a compiler pass to need a map to store extra
  1495. information about variables. Such maps are traditionally called
  1496. \emph{symbol tables}.
  1497. The skeleton of the \code{uniquify} function is shown in
  1498. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1499. convenient to partially apply it to an association list and then apply
  1500. it to different expressions, as in the last clause for primitive
  1501. operations in Figure~\ref{fig:uniquify-s0}. In the last \key{match}
  1502. clause for the primitive operators, note the use of the comma-\code{@}
  1503. operator to splice a list of S-expressions into an enclosing
  1504. S-expression.
  1505. \begin{exercise}
  1506. \normalfont % I don't like the italics for exercises. -Jeremy
  1507. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1508. implement the clauses for variables and for the \key{let} construct.
  1509. \end{exercise}
  1510. \begin{figure}[tbp]
  1511. \begin{lstlisting}
  1512. (define (uniquify-exp alist)
  1513. (lambda (e)
  1514. (match e
  1515. [(? symbol?) ___]
  1516. [(? integer?) e]
  1517. [`(let ([,x ,e]) ,body) ___]
  1518. [`(,op ,es ...)
  1519. `(,op ,@(for/list ([e es]) ((uniquify-exp alist) e)))]
  1520. )))
  1521. (define (uniquify alist)
  1522. (lambda (e)
  1523. (match e
  1524. [`(program ,info ,e)
  1525. `(program ,info ,((uniquify-exp alist) e))]
  1526. )))
  1527. \end{lstlisting}
  1528. \caption{Skeleton for the \key{uniquify} pass.}
  1529. \label{fig:uniquify-s0}
  1530. \end{figure}
  1531. \begin{exercise}
  1532. \normalfont % I don't like the italics for exercises. -Jeremy
  1533. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1534. and checking whether the output programs produce the same result as
  1535. the input programs. The $R_1$ programs should be designed to test the
  1536. most interesting parts of the \key{uniquify} pass, that is, the
  1537. programs should include \key{let} constructs, variables, and variables
  1538. that overshadow each other. The five programs should be in a
  1539. subdirectory named \key{tests} and they should have the same file name
  1540. except for a different integer at the end of the name, followed by the
  1541. ending \key{.rkt}. Use the \key{interp-tests} function
  1542. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1543. your \key{uniquify} pass on the example programs.
  1544. \end{exercise}
  1545. \section{Remove Complex Operands}
  1546. \label{sec:remove-complex-opera-r1}
  1547. The \code{remove-complex-opera*} pass compiles $R_1$ programs into
  1548. $R_1$ programs in which the arguments of operations are simple
  1549. expressions. Put another way, this pass removes complex operands,
  1550. such as the expression \code{(- 10)} in the program below. This is
  1551. accomplished by introducing a new \key{let}-bound variable, binding
  1552. the complex operand to the new variable, and then using the new
  1553. variable in place of the complex operand, as shown in the output of
  1554. \code{remove-complex-opera*} on the right.\\
  1555. \begin{tabular}{lll}
  1556. \begin{minipage}{0.4\textwidth}
  1557. % s0_19.rkt
  1558. \begin{lstlisting}
  1559. (program ()
  1560. (+ 52 (- 10)))
  1561. \end{lstlisting}
  1562. \end{minipage}
  1563. &
  1564. $\Rightarrow$
  1565. &
  1566. \begin{minipage}{0.4\textwidth}
  1567. \begin{lstlisting}
  1568. (program ()
  1569. (let ([tmp.1 (- 10)])
  1570. (+ 52 tmp.1)))
  1571. \end{lstlisting}
  1572. \end{minipage}
  1573. \end{tabular}
  1574. We recommend implementing this pass with two mutually recursive
  1575. functions, \code{rco-arg} and \code{rco-exp}. The idea is to apply
  1576. \code{rco-arg} to subexpressions that need to become simple and to
  1577. apply \code{rco-exp} to subexpressions can stay complex. Both
  1578. functions take an $R_1$ expression as input. The \code{rco-exp}
  1579. function returns an expression. The \code{rco-arg} function returns
  1580. two things: a simple expression and association list mapping temporary
  1581. variables to complex subexpressions. You can return multiple things
  1582. from a function using Racket's \key{values} form and you can receive
  1583. multiple things from a function call using the \key{define-values}
  1584. form. If you are not familiar with these constructs, review the Racket
  1585. documentation. Also, the \key{for/lists} construct is useful for
  1586. applying a function to each element of a list, in the case where the
  1587. function returns multiple values.
  1588. The following shows the output of \code{rco-arg} on the expression
  1589. \code{(- 10)}.
  1590. \begin{tabular}{lll}
  1591. \begin{minipage}{0.4\textwidth}
  1592. \begin{lstlisting}
  1593. (rco-arg `(- 10))
  1594. \end{lstlisting}
  1595. \end{minipage}
  1596. &
  1597. $\Rightarrow$
  1598. &
  1599. \begin{minipage}{0.4\textwidth}
  1600. \begin{lstlisting}
  1601. (values `tmp.1
  1602. `((tmp.1 . (- 10))))
  1603. \end{lstlisting}
  1604. \end{minipage}
  1605. \end{tabular}
  1606. Take special care of programs such as the next one that \key{let}-bind
  1607. variables with integers or other variables. You should leave them
  1608. unchanged, as shown in to the program on the right \\
  1609. \begin{tabular}{lll}
  1610. \begin{minipage}{0.4\textwidth}
  1611. % s0_20.rkt
  1612. \begin{lstlisting}
  1613. (program ()
  1614. (let ([a 42])
  1615. (let ([b a])
  1616. b)))
  1617. \end{lstlisting}
  1618. \end{minipage}
  1619. &
  1620. $\Rightarrow$
  1621. &
  1622. \begin{minipage}{0.4\textwidth}
  1623. \begin{lstlisting}
  1624. (program ()
  1625. (let ([a 42])
  1626. (let ([b a])
  1627. b)))
  1628. \end{lstlisting}
  1629. \end{minipage}
  1630. \end{tabular} \\
  1631. A careless implementation of \key{rco-exp} and \key{rco-arg} might
  1632. produce the following output.\\
  1633. \begin{minipage}{0.4\textwidth}
  1634. \begin{lstlisting}
  1635. (program ()
  1636. (let ([tmp.1 42])
  1637. (let ([a tmp.1])
  1638. (let ([tmp.2 a])
  1639. (let ([b tmp.2])
  1640. b)))))
  1641. \end{lstlisting}
  1642. \end{minipage}
  1643. \begin{exercise}
  1644. \normalfont Implement the \code{remove-complex-opera*} pass and test
  1645. it on all of the example programs that you created to test the
  1646. \key{uniquify} pass and create three new example programs that are
  1647. designed to exercise all of the interesting code in the
  1648. \code{remove-complex-opera*} pass. Use the \key{interp-tests} function
  1649. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1650. your passes on the example programs.
  1651. \end{exercise}
  1652. \section{Explicate Control}
  1653. \label{sec:explicate-control-r1}
  1654. The \code{explicate-control} pass compiles $R_1$ programs into $C_0$
  1655. programs that make the order of execution explicit in their
  1656. syntax. For now this amounts to flattening \key{let} constructs into a
  1657. sequence of assignment statements. For example, consider the following
  1658. $R_1$ program.
  1659. % s0_11.rkt
  1660. \begin{lstlisting}
  1661. (program ()
  1662. (let ([y (let ([x 20])
  1663. (+ x (let ([x 22]) x)))])
  1664. y))
  1665. \end{lstlisting}
  1666. %
  1667. The output of the previous pass and of \code{explicate-control} is
  1668. shown below. Recall that the right-hand-side of a \key{let} executes
  1669. before its body, so the order of evaluation for this program is to
  1670. assign \code{20} to \code{x.1}, assign \code{22} to \code{x.2}, assign
  1671. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  1672. output of \code{explicate-control} makes this ordering explicit.\\
  1673. \begin{tabular}{lll}
  1674. \begin{minipage}{0.4\textwidth}
  1675. \begin{lstlisting}
  1676. (program ()
  1677. (let ([y (let ([x.1 20])
  1678. (let ([x.2 22])
  1679. (+ x.1 x.2)))])
  1680. y))
  1681. \end{lstlisting}
  1682. \end{minipage}
  1683. &
  1684. $\Rightarrow$
  1685. &
  1686. \begin{minipage}{0.4\textwidth}
  1687. \begin{lstlisting}
  1688. (program ((locals . (y x.1 x.2)))
  1689. ((start .
  1690. (seq (assign x.1 20)
  1691. (seq (assign x.2 22)
  1692. (seq (assign y (+ x.1 x.2))
  1693. (return y)))))))
  1694. \end{lstlisting}
  1695. \end{minipage}
  1696. \end{tabular}
  1697. We recommend implementing \code{explicate-control} using two mutually
  1698. recursive functions: \code{explicate-control-tail} and
  1699. \code{explicate-control-assign}. The \code{explicate-control-tail}
  1700. function should be applied to expressions in tail position whereas
  1701. \code{explicate-control-assign} should be applied to expressions that
  1702. occur on the right-hand-side of a \key{let}. The function
  1703. \code{explicate-control-tail} takes an $R_1$ expression as input and
  1704. produces a $C_0$ $\Tail$ (see the grammar in
  1705. Figure~\ref{fig:c0-syntax}) and a list of formerly \key{let}-bound
  1706. variables. The \code{explicate-control-assign} function takes an $R_1$
  1707. expression, the variable that it is to be assigned to, and $C_0$ code
  1708. (a $\Tail$) that should come after the assignment (e.g., the code
  1709. generated for the body of the \key{let}). It returns a $\Tail$ and a
  1710. list of variables. The top-level \code{explicate-control} function
  1711. should invoke \code{explicate-control-tail} on the body of the
  1712. \key{program} and then associate the \code{locals} symbol with the
  1713. resulting list of variables in the $\itm{info}$ field, as in the above
  1714. example.
  1715. %% \section{Uncover Locals}
  1716. %% \label{sec:uncover-locals-r1}
  1717. %% The pass \code{uncover-locals} simply collects all of the variables in
  1718. %% the program and places then in the $\itm{info}$ of the program
  1719. %% construct. Here is the output for the example program of the last
  1720. %% section.
  1721. %% \begin{minipage}{0.4\textwidth}
  1722. %% \begin{lstlisting}
  1723. %% (program ((locals . (x.1 x.2 y)))
  1724. %% ((start .
  1725. %% (seq (assign x.1 20)
  1726. %% (seq (assign x.2 22)
  1727. %% (seq (assign y (+ x.1 x.2))
  1728. %% (return y)))))))
  1729. %% \end{lstlisting}
  1730. %% \end{minipage}
  1731. \section{Select Instructions}
  1732. \label{sec:select-r1}
  1733. In the \code{select-instructions} pass we begin the work of
  1734. translating from $C_0$ to $\text{x86}^{*}_0$. The target language of
  1735. this pass is a pseudo-x86 language that still uses variables, so we
  1736. add an AST node of the form $\VAR{\itm{var}}$ to the $\text{x86}_0$
  1737. abstract syntax of Figure~\ref{fig:x86-ast-a}. We recommend
  1738. implementing the \code{select-instructions} in terms of three
  1739. auxiliary functions, one for each of the non-terminals of $C_0$:
  1740. $\Arg$, $\Stmt$, and $\Tail$.
  1741. The cases for $\itm{arg}$ are straightforward, simply put variables
  1742. and integer literals into the s-expression format expected of
  1743. pseudo-x86, \code{(var $x$)} and \code{(int $n$)}, respectively.
  1744. Next we consider the cases for $\itm{stmt}$, starting with arithmetic
  1745. operations. For example, in $C_0$ an addition operation can take the
  1746. form below, to the left of the $\Rightarrow$. To translate to x86, we
  1747. need to use the \key{addq} instruction which does an in-place
  1748. update. So we must first move \code{10} to \code{x}. \\
  1749. \begin{tabular}{lll}
  1750. \begin{minipage}{0.4\textwidth}
  1751. \begin{lstlisting}
  1752. (assign x (+ 10 32))
  1753. \end{lstlisting}
  1754. \end{minipage}
  1755. &
  1756. $\Rightarrow$
  1757. &
  1758. \begin{minipage}{0.4\textwidth}
  1759. \begin{lstlisting}
  1760. (movq (int 10) (var x))
  1761. (addq (int 32) (var x))
  1762. \end{lstlisting}
  1763. \end{minipage}
  1764. \end{tabular} \\
  1765. %
  1766. There are cases that require special care to avoid generating
  1767. needlessly complicated code. If one of the arguments of the addition
  1768. is the same as the left-hand side of the assignment, then there is no
  1769. need for the extra move instruction. For example, the following
  1770. assignment statement can be translated into a single \key{addq}
  1771. instruction.\\
  1772. \begin{tabular}{lll}
  1773. \begin{minipage}{0.4\textwidth}
  1774. \begin{lstlisting}
  1775. (assign x (+ 10 x))
  1776. \end{lstlisting}
  1777. \end{minipage}
  1778. &
  1779. $\Rightarrow$
  1780. &
  1781. \begin{minipage}{0.4\textwidth}
  1782. \begin{lstlisting}
  1783. (addq (int 10) (var x))
  1784. \end{lstlisting}
  1785. \end{minipage}
  1786. \end{tabular} \\
  1787. The \key{read} operation does not have a direct counterpart in x86
  1788. assembly, so we have instead implemented this functionality in the C
  1789. language, with the function \code{read\_int} in the file
  1790. \code{runtime.c}. In general, we refer to all of the functionality in
  1791. this file as the \emph{runtime system}, or simply the \emph{runtime}
  1792. for short. When compiling your generated x86 assembly code, you need
  1793. to compile \code{runtime.c} to \code{runtime.o} (an ``object file'',
  1794. using \code{gcc} option \code{-c}) and link it into the
  1795. executable. For our purposes of code generation, all you need to do is
  1796. translate an assignment of \key{read} into some variable $\itm{lhs}$
  1797. (for left-hand side) into a call to the \code{read\_int} function
  1798. followed by a move from \code{rax} to the left-hand side. The move
  1799. from \code{rax} is needed because the return value from
  1800. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  1801. \begin{tabular}{lll}
  1802. \begin{minipage}{0.4\textwidth}
  1803. \begin{lstlisting}
  1804. (assign |$\itm{lhs}$| (read))
  1805. \end{lstlisting}
  1806. \end{minipage}
  1807. &
  1808. $\Rightarrow$
  1809. &
  1810. \begin{minipage}{0.4\textwidth}
  1811. \begin{lstlisting}
  1812. (callq read_int)
  1813. (movq (reg rax) (var |$\itm{lhs}$|))
  1814. \end{lstlisting}
  1815. \end{minipage}
  1816. \end{tabular} \\
  1817. There are two cases for the $\Tail$ non-terminal: \key{return} and
  1818. \key{seq}. Regarding \RETURN{e}, we recommend treating it as an
  1819. assignment to the \key{rax} register followed by a jump to the
  1820. conclusion of the program (so the conclusion needs to be labeled).
  1821. For $(\key{seq}\,s\,t)$, we the statement $s$ and tail $t$ recursively
  1822. and append the resulting instructions.
  1823. \begin{exercise}
  1824. \normalfont
  1825. Implement the \key{select-instructions} pass and test it on all of the
  1826. example programs that you created for the previous passes and create
  1827. three new example programs that are designed to exercise all of the
  1828. interesting code in this pass. Use the \key{interp-tests} function
  1829. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1830. your passes on the example programs.
  1831. \end{exercise}
  1832. \section{Assign Homes}
  1833. \label{sec:assign-r1}
  1834. The \key{assign-homes} pass compiles $\text{x86}^{*}_0$ programs to
  1835. $\text{x86}^{*}_0$ programs that no longer use program variables.
  1836. Thus, the \key{assign-homes} pass is responsible for placing all of
  1837. the program variables in registers or on the stack. For runtime
  1838. efficiency, it is better to place variables in registers, but as there
  1839. are only 16 registers, some programs must necessarily place some
  1840. variables on the stack. In this chapter we focus on the mechanics of
  1841. placing variables on the stack. We study an algorithm for placing
  1842. variables in registers in Chapter~\ref{ch:register-allocation-r1}.
  1843. Consider again the following $R_1$ program.
  1844. % s0_20.rkt
  1845. \begin{lstlisting}
  1846. (program ()
  1847. (let ([a 42])
  1848. (let ([b a])
  1849. b)))
  1850. \end{lstlisting}
  1851. For reference, we repeat the output of \code{select-instructions} on
  1852. the left and show the output of \code{assign-homes} on the right.
  1853. Recall that \key{explicate-control} associated the list of
  1854. variables with the \code{locals} symbol in the program's $\itm{info}$
  1855. field, so \code{assign-homes} has convenient access to the them. In
  1856. this example, we assign variable \code{a} to stack location
  1857. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.\\
  1858. \begin{tabular}{l}
  1859. \begin{minipage}{0.4\textwidth}
  1860. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1861. (program ((locals . (a b)))
  1862. ((start .
  1863. (block ()
  1864. (movq (int 42) (var a))
  1865. (movq (var a) (var b))
  1866. (movq (var b) (reg rax))
  1867. (jmp conclusion)))))
  1868. \end{lstlisting}
  1869. \end{minipage}
  1870. {$\Rightarrow$}
  1871. \begin{minipage}{0.4\textwidth}
  1872. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1873. (program ((stack-space . 16))
  1874. ((start .
  1875. (block ()
  1876. (movq (int 42) (deref rbp -8))
  1877. (movq (deref rbp -8) (deref rbp -16))
  1878. (movq (deref rbp -16) (reg rax))
  1879. (jmp conclusion)))))
  1880. \end{lstlisting}
  1881. \end{minipage}
  1882. \end{tabular} \\
  1883. In the process of assigning variables to stack locations, it is
  1884. convenient to compute and store the size of the frame (in bytes) in
  1885. the $\itm{info}$ field of the \key{program} node, with the key
  1886. \code{stack-space}, which will be needed later to generate the
  1887. procedure conclusion. Some operating systems place restrictions on
  1888. the frame size. For example, Mac OS X requires the frame size to be a
  1889. multiple of 16 bytes.
  1890. \begin{exercise}
  1891. \normalfont Implement the \key{assign-homes} pass and test it on all
  1892. of the example programs that you created for the previous passes pass.
  1893. We recommend that \key{assign-homes} take an extra parameter that is a
  1894. mapping of variable names to homes (stack locations for now). Use the
  1895. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  1896. \key{utilities.rkt} to test your passes on the example programs.
  1897. \end{exercise}
  1898. \section{Patch Instructions}
  1899. \label{sec:patch-s0}
  1900. The \code{patch-instructions} pass compiles $\text{x86}^{*}_0$
  1901. programs to $\text{x86}_0$ programs by making sure that each
  1902. instruction adheres to the restrictions of the x86 assembly language.
  1903. In particular, at most one argument of an instruction may be a memory
  1904. reference.
  1905. We return to the following running example.
  1906. % s0_20.rkt
  1907. \begin{lstlisting}
  1908. (let ([a 42])
  1909. (let ([b a])
  1910. b))
  1911. \end{lstlisting}
  1912. After the \key{assign-homes} pass, the above program has been translated to
  1913. the following. \\
  1914. \begin{minipage}{0.5\textwidth}
  1915. \begin{lstlisting}
  1916. (program ((stack-space . 16))
  1917. ((start .
  1918. (block ()
  1919. (movq (int 42) (deref rbp -8))
  1920. (movq (deref rbp -8) (deref rbp -16))
  1921. (movq (deref rbp -16) (reg rax))
  1922. (jmp conclusion)))))
  1923. \end{lstlisting}
  1924. \end{minipage}\\
  1925. The second \key{movq} instruction is problematic because both
  1926. arguments are stack locations. We suggest fixing this problem by
  1927. moving from the source location to the register \key{rax} and then
  1928. from \key{rax} to the destination location, as follows.
  1929. \begin{lstlisting}
  1930. (movq (deref rbp -8) (reg rax))
  1931. (movq (reg rax) (deref rbp -16))
  1932. \end{lstlisting}
  1933. \begin{exercise}
  1934. \normalfont
  1935. Implement the \key{patch-instructions} pass and test it on all of the
  1936. example programs that you created for the previous passes and create
  1937. three new example programs that are designed to exercise all of the
  1938. interesting code in this pass. Use the \key{interp-tests} function
  1939. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1940. your passes on the example programs.
  1941. \end{exercise}
  1942. \section{Print x86}
  1943. \label{sec:print-x86}
  1944. The last step of the compiler from $R_1$ to x86 is to convert the
  1945. $\text{x86}_0$ AST (defined in Figure~\ref{fig:x86-ast-a}) to the
  1946. string representation (defined in Figure~\ref{fig:x86-a}). The Racket
  1947. \key{format} and \key{string-append} functions are useful in this
  1948. regard. The main work that this step needs to perform is to create the
  1949. \key{main} function and the standard instructions for its prelude and
  1950. conclusion, as shown in Figure~\ref{fig:p1-x86} of
  1951. Section~\ref{sec:x86}. You need to know the number of stack-allocated
  1952. variables, so we suggest computing it in the \key{assign-homes} pass
  1953. (Section~\ref{sec:assign-r1}) and storing it in the $\itm{info}$ field
  1954. of the \key{program} node.
  1955. %% Your compiled code should print the result of the program's execution
  1956. %% by using the \code{print\_int} function provided in
  1957. %% \code{runtime.c}. If your compiler has been implemented correctly so
  1958. %% far, this final result should be stored in the \key{rax} register.
  1959. %% We'll talk more about how to perform function calls with arguments in
  1960. %% general later on, but for now, place the following after the compiled
  1961. %% code for the $R_1$ program but before the conclusion:
  1962. %% \begin{lstlisting}
  1963. %% movq %rax, %rdi
  1964. %% callq print_int
  1965. %% \end{lstlisting}
  1966. %% These lines move the value in \key{rax} into the \key{rdi} register, which
  1967. %% stores the first argument to be passed into \key{print\_int}.
  1968. If you want your program to run on Mac OS X, your code needs to
  1969. determine whether or not it is running on a Mac, and prefix
  1970. underscores to labels like \key{main}. You can determine the platform
  1971. with the Racket call \code{(system-type 'os)}, which returns
  1972. \code{'macosx}, \code{'unix}, or \code{'windows}.
  1973. %% In addition to
  1974. %% placing underscores on \key{main}, you need to put them in front of
  1975. %% \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  1976. %% \_print\_int}).
  1977. \begin{exercise}
  1978. \normalfont Implement the \key{print-x86} pass and test it on all of
  1979. the example programs that you created for the previous passes. Use the
  1980. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  1981. \key{utilities.rkt} to test your complete compiler on the example
  1982. programs.
  1983. % The following is specific to P423/P523. -Jeremy
  1984. %Mac support is optional, but your compiler has to output
  1985. %valid code for Unix machines.
  1986. \end{exercise}
  1987. \margincomment{\footnotesize To do: add a challenge section. Perhaps
  1988. extending the partial evaluation to $R_0$? \\ --Jeremy}
  1989. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1990. \chapter{Register Allocation}
  1991. \label{ch:register-allocation-r1}
  1992. In Chapter~\ref{ch:int-exp} we simplified the generation of x86
  1993. assembly by placing all variables on the stack. We can improve the
  1994. performance of the generated code considerably if we instead place as
  1995. many variables as possible into registers. The CPU can access a
  1996. register in a single cycle, whereas accessing the stack takes many
  1997. cycles to go to cache or many more to access main memory.
  1998. Figure~\ref{fig:reg-eg} shows a program with four variables that
  1999. serves as a running example. We show the source program and also the
  2000. output of instruction selection. At that point the program is almost
  2001. x86 assembly but not quite; it still contains variables instead of
  2002. stack locations or registers.
  2003. \begin{figure}
  2004. \begin{minipage}{0.45\textwidth}
  2005. $R_1$ program:
  2006. % s0_22.rkt
  2007. \begin{lstlisting}
  2008. (program ()
  2009. (let ([v 1])
  2010. (let ([w 46])
  2011. (let ([x (+ v 7)])
  2012. (let ([y (+ 4 x)])
  2013. (let ([z (+ x w)])
  2014. (+ z (- y))))))))
  2015. \end{lstlisting}
  2016. \end{minipage}
  2017. \begin{minipage}{0.45\textwidth}
  2018. After instruction selection:
  2019. \begin{lstlisting}
  2020. (program
  2021. ((locals . (v w x y z t.1)))
  2022. ((start .
  2023. (block ()
  2024. (movq (int 1) (var v))
  2025. (movq (int 46) (var w))
  2026. (movq (var v) (var x))
  2027. (addq (int 7) (var x))
  2028. (movq (var x) (var y))
  2029. (addq (int 4) (var y))
  2030. (movq (var x) (var z))
  2031. (addq (var w) (var z))
  2032. (movq (var y) (var t.1))
  2033. (negq (var t.1))
  2034. (movq (var z) (reg rax))
  2035. (addq (var t.1) (reg rax))
  2036. (jmp conclusion)))))
  2037. \end{lstlisting}
  2038. \end{minipage}
  2039. \caption{An example program for register allocation.}
  2040. \label{fig:reg-eg}
  2041. \end{figure}
  2042. The goal of register allocation is to fit as many variables into
  2043. registers as possible. It is often the case that we have more
  2044. variables than registers, so we cannot map each variable to a
  2045. different register. Fortunately, it is common for different variables
  2046. to be needed during different periods of time, and in such cases
  2047. several variables can be mapped to the same register. Consider
  2048. variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}. After the
  2049. variable \code{x} is moved to \code{z} it is no longer needed.
  2050. Variable \code{y}, on the other hand, is used only after this point,
  2051. so \code{x} and \code{y} could share the same register. The topic of
  2052. Section~\ref{sec:liveness-analysis-r1} is how we compute where a variable
  2053. is needed. Once we have that information, we compute which variables
  2054. are needed at the same time, i.e., which ones \emph{interfere}, and
  2055. represent this relation as graph whose vertices are variables and
  2056. edges indicate when two variables interfere with each other
  2057. (Section~\ref{sec:build-interference}). We then model register
  2058. allocation as a graph coloring problem, which we discuss in
  2059. Section~\ref{sec:graph-coloring}.
  2060. In the event that we run out of registers despite these efforts, we
  2061. place the remaining variables on the stack, similar to what we did in
  2062. Chapter~\ref{ch:int-exp}. It is common to say that when a variable
  2063. that is assigned to a stack location, it has been \emph{spilled}. The
  2064. process of spilling variables is handled as part of the graph coloring
  2065. process described in \ref{sec:graph-coloring}.
  2066. \section{Registers and Calling Conventions}
  2067. \label{sec:calling-conventions}
  2068. As we perform register allocation, we will need to be aware of the
  2069. conventions that govern the way in which registers interact with
  2070. function calls. The convention for x86 is that the caller is
  2071. responsible for freeing up some registers, the \emph{caller-saved
  2072. registers}, prior to the function call, and the callee is
  2073. responsible for saving and restoring some other registers, the
  2074. \emph{callee-saved registers}, before and after using them. The
  2075. caller-saved registers are
  2076. \begin{lstlisting}
  2077. rax rdx rcx rsi rdi r8 r9 r10 r11
  2078. \end{lstlisting}
  2079. while the callee-saved registers are
  2080. \begin{lstlisting}
  2081. rsp rbp rbx r12 r13 r14 r15
  2082. \end{lstlisting}
  2083. Another way to think about this caller/callee convention is the
  2084. following. The caller should assume that all the caller-saved registers
  2085. get overwritten with arbitrary values by the callee. On the other
  2086. hand, the caller can safely assume that all the callee-saved registers
  2087. contain the same values after the call that they did before the call.
  2088. The callee can freely use any of the caller-saved registers. However,
  2089. if the callee wants to use a callee-saved register, the callee must
  2090. arrange to put the original value back in the register prior to
  2091. returning to the caller, which is usually accomplished by saving and
  2092. restoring the value from the stack.
  2093. \section{Liveness Analysis}
  2094. \label{sec:liveness-analysis-r1}
  2095. A variable is \emph{live} if the variable is used at some later point
  2096. in the program and there is not an intervening assignment to the
  2097. variable.
  2098. %
  2099. To understand the latter condition, consider the following code
  2100. fragment in which there are two writes to \code{b}. Are \code{a} and
  2101. \code{b} both live at the same time?
  2102. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2103. (movq (int 5) (var a))
  2104. (movq (int 30) (var b))
  2105. (movq (var a) (var c))
  2106. (movq (int 10) (var b))
  2107. (addq (var b) (var c))
  2108. \end{lstlisting}
  2109. The answer is no because the value \code{30} written to \code{b} on
  2110. line 2 is never used. The variable \code{b} is read on line 5 and
  2111. there is an intervening write to \code{b} on line 4, so the read on
  2112. line 5 receives the value written on line 4, not line 2.
  2113. The live variables can be computed by traversing the instruction
  2114. sequence back to front (i.e., backwards in execution order). Let
  2115. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2116. $L_{\mathsf{after}}(k)$ for the set of live variables after
  2117. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2118. variables before instruction $I_k$. The live variables after an
  2119. instruction are always the same as the live variables before the next
  2120. instruction.
  2121. \begin{equation*}
  2122. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2123. \end{equation*}
  2124. To start things off, there are no live variables after the last
  2125. instruction, so
  2126. \begin{equation*}
  2127. L_{\mathsf{after}}(n) = \emptyset
  2128. \end{equation*}
  2129. We then apply the following rule repeatedly, traversing the
  2130. instruction sequence back to front.
  2131. \begin{equation*}
  2132. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2133. \end{equation*}
  2134. where $W(k)$ are the variables written to by instruction $I_k$ and
  2135. $R(k)$ are the variables read by instruction $I_k$.
  2136. Figure~\ref{fig:live-eg} shows the results of live variables analysis
  2137. for the running example, with each instruction aligned with its
  2138. $L_{\mathtt{after}}$ set to make the figure easy to read.
  2139. \margincomment{JM: I think you should walk through the explanation of this formula,
  2140. connecting it back to the example from before. \\
  2141. JS: Agreed.}
  2142. \begin{figure}[tbp]
  2143. \hspace{20pt}
  2144. \begin{minipage}{0.45\textwidth}
  2145. \begin{lstlisting}[numbers=left]
  2146. (block ()
  2147. (movq (int 1) (var v))
  2148. (movq (int 46) (var w))
  2149. (movq (var v) (var x))
  2150. (addq (int 7) (var x))
  2151. (movq (var x) (var y))
  2152. (addq (int 4) (var y))
  2153. (movq (var x) (var z))
  2154. (addq (var w) (var z))
  2155. (movq (var y) (var t.1))
  2156. (negq (var t.1))
  2157. (movq (var z) (reg rax))
  2158. (addq (var t.1) (reg rax))
  2159. (jmp conclusion))
  2160. \end{lstlisting}
  2161. \end{minipage}
  2162. \vrule\hspace{10pt}
  2163. \begin{minipage}{0.45\textwidth}
  2164. \begin{lstlisting}
  2165. |$\{\}$|
  2166. |$\{v \}$|
  2167. |$\{v,w\}$|
  2168. |$\{w,x\}$|
  2169. |$\{w,x\}$|
  2170. |$\{w,x,y\}$|
  2171. |$\{w,x,y\}$|
  2172. |$\{w,y,z\}$|
  2173. |$\{y,z\}$|
  2174. |$\{z,t.1\}$|
  2175. |$\{z,t.1\}$|
  2176. |$\{t.1\}$|
  2177. |$\{\}$|
  2178. |$\{\}$|
  2179. \end{lstlisting}
  2180. \end{minipage}
  2181. \caption{An example block annotated with live-after sets.}
  2182. \label{fig:live-eg}
  2183. \end{figure}
  2184. \begin{exercise}\normalfont
  2185. Implement the compiler pass named \code{uncover-live} that computes
  2186. the live-after sets. We recommend storing the live-after sets (a list
  2187. of lists of variables) in the $\itm{info}$ field of the \key{block}
  2188. construct.
  2189. %
  2190. We recommend organizing your code to use a helper function that takes
  2191. a list of instructions and an initial live-after set (typically empty)
  2192. and returns the list of live-after sets.
  2193. %
  2194. We recommend creating helper functions to 1) compute the set of
  2195. variables that appear in an argument (of an instruction), 2) compute
  2196. the variables read by an instruction which corresponds to the $R$
  2197. function discussed above, and 3) the variables written by an
  2198. instruction which corresponds to $W$.
  2199. \end{exercise}
  2200. \section{Building the Interference Graph}
  2201. \label{sec:build-interference}
  2202. Based on the liveness analysis, we know where each variable is needed.
  2203. However, during register allocation, we need to answer questions of
  2204. the specific form: are variables $u$ and $v$ live at the same time?
  2205. (And therefore cannot be assigned to the same register.) To make this
  2206. question easier to answer, we create an explicit data structure, an
  2207. \emph{interference graph}. An interference graph is an undirected
  2208. graph that has an edge between two variables if they are live at the
  2209. same time, that is, if they interfere with each other.
  2210. The most obvious way to compute the interference graph is to look at
  2211. the set of live variables between each statement in the program, and
  2212. add an edge to the graph for every pair of variables in the same set.
  2213. This approach is less than ideal for two reasons. First, it can be
  2214. rather expensive because it takes $O(n^2)$ time to look at every pair
  2215. in a set of $n$ live variables. Second, there is a special case in
  2216. which two variables that are live at the same time do not actually
  2217. interfere with each other: when they both contain the same value
  2218. because we have assigned one to the other.
  2219. A better way to compute the interference graph is to focus on the
  2220. writes. That is, for each instruction, create an edge between the
  2221. variable being written to and all the \emph{other} live variables.
  2222. (One should not create self edges.) For a \key{callq} instruction,
  2223. think of all caller-saved registers as being written to, so and edge
  2224. must be added between every live variable and every caller-saved
  2225. register. For \key{movq}, we deal with the above-mentioned special
  2226. case by not adding an edge between a live variable $v$ and destination
  2227. $d$ if $v$ matches the source of the move. So we have the following
  2228. three rules.
  2229. \begin{enumerate}
  2230. \item If instruction $I_k$ is an arithmetic instruction such as
  2231. (\key{addq} $s$\, $d$), then add the edge $(d,v)$ for every $v \in
  2232. L_{\mathsf{after}}(k)$ unless $v = d$.
  2233. \item If instruction $I_k$ is of the form (\key{callq}
  2234. $\mathit{label}$), then add an edge $(r,v)$ for every caller-saved
  2235. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2236. \item If instruction $I_k$ is a move: (\key{movq} $s$\, $d$), then add
  2237. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  2238. d$ or $v = s$.
  2239. \end{enumerate}
  2240. \margincomment{JM: I think you could give examples of each one of these
  2241. using the example program and use those to help explain why these
  2242. rules are correct.\\
  2243. JS: Agreed.}
  2244. Working from the top to bottom of Figure~\ref{fig:live-eg}, we obtain
  2245. the following interference for the instruction at the specified line
  2246. number.
  2247. \begin{quote}
  2248. Line 2: no interference,\\
  2249. Line 3: $w$ interferes with $v$,\\
  2250. Line 4: $x$ interferes with $w$,\\
  2251. Line 5: $x$ interferes with $w$,\\
  2252. Line 6: $y$ interferes with $w$,\\
  2253. Line 7: $y$ interferes with $w$ and $x$,\\
  2254. Line 8: $z$ interferes with $w$ and $y$,\\
  2255. Line 9: $z$ interferes with $y$, \\
  2256. Line 10: $t.1$ interferes with $z$, \\
  2257. Line 11: $t.1$ interferes with $z$, \\
  2258. Line 12: no interference, \\
  2259. Line 13: no interference. \\
  2260. Line 14: no interference.
  2261. \end{quote}
  2262. The resulting interference graph is shown in
  2263. Figure~\ref{fig:interfere}.
  2264. \begin{figure}[tbp]
  2265. \large
  2266. \[
  2267. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2268. \node (v) at (0,0) {$v$};
  2269. \node (w) at (2,0) {$w$};
  2270. \node (x) at (4,0) {$x$};
  2271. \node (t1) at (6,-2) {$t.1$};
  2272. \node (y) at (2,-2) {$y$};
  2273. \node (z) at (4,-2) {$z$};
  2274. \draw (v) to (w);
  2275. \foreach \i in {w,x,y}
  2276. {
  2277. \foreach \j in {w,x,y}
  2278. {
  2279. \draw (\i) to (\j);
  2280. }
  2281. }
  2282. \draw (z) to (w);
  2283. \draw (z) to (y);
  2284. \draw (t1) to (z);
  2285. \end{tikzpicture}
  2286. \]
  2287. \caption{The interference graph of the example program.}
  2288. \label{fig:interfere}
  2289. \end{figure}
  2290. %% Our next concern is to choose a data structure for representing the
  2291. %% interference graph. There are many choices for how to represent a
  2292. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2293. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2294. %% data structure is to study the algorithm that uses the data structure,
  2295. %% determine what operations need to be performed, and then choose the
  2296. %% data structure that provide the most efficient implementations of
  2297. %% those operations. Often times the choice of data structure can have an
  2298. %% effect on the time complexity of the algorithm, as it does here. If
  2299. %% you skim the next section, you will see that the register allocation
  2300. %% algorithm needs to ask the graph for all of its vertices and, given a
  2301. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2302. %% correct choice of graph representation is that of an adjacency
  2303. %% list. There are helper functions in \code{utilities.rkt} for
  2304. %% representing graphs using the adjacency list representation:
  2305. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2306. %% (Appendix~\ref{appendix:utilities}).
  2307. %% %
  2308. %% \margincomment{\footnotesize To do: change to use the
  2309. %% Racket graph library. \\ --Jeremy}
  2310. %% %
  2311. %% In particular, those functions use a hash table to map each vertex to
  2312. %% the set of adjacent vertices, and the sets are represented using
  2313. %% Racket's \key{set}, which is also a hash table.
  2314. \begin{exercise}\normalfont
  2315. Implement the compiler pass named \code{build-interference} according
  2316. to the algorithm suggested above. We recommend using the Racket
  2317. \code{graph} package to create and inspect the interference graph.
  2318. The output graph of this pass should be stored in the $\itm{info}$
  2319. field of the program, under the key \code{conflicts}.
  2320. \end{exercise}
  2321. \section{Graph Coloring via Sudoku}
  2322. \label{sec:graph-coloring}
  2323. We now come to the main event, mapping variables to registers (or to
  2324. stack locations in the event that we run out of registers). We need
  2325. to make sure not to map two variables to the same register if the two
  2326. variables interfere with each other. In terms of the interference
  2327. graph, this means that adjacent vertices must be mapped to different
  2328. registers. If we think of registers as colors, the register
  2329. allocation problem becomes the widely-studied graph coloring
  2330. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2331. The reader may be more familiar with the graph coloring problem than he
  2332. or she realizes; the popular game of Sudoku is an instance of the
  2333. graph coloring problem. The following describes how to build a graph
  2334. out of an initial Sudoku board.
  2335. \begin{itemize}
  2336. \item There is one vertex in the graph for each Sudoku square.
  2337. \item There is an edge between two vertices if the corresponding squares
  2338. are in the same row, in the same column, or if the squares are in
  2339. the same $3\times 3$ region.
  2340. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2341. \item Based on the initial assignment of numbers to squares in the
  2342. Sudoku board, assign the corresponding colors to the corresponding
  2343. vertices in the graph.
  2344. \end{itemize}
  2345. If you can color the remaining vertices in the graph with the nine
  2346. colors, then you have also solved the corresponding game of Sudoku.
  2347. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2348. the corresponding graph with colored vertices. We map the Sudoku
  2349. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2350. sampling of the vertices (those that are colored) because showing
  2351. edges for all of the vertices would make the graph unreadable.
  2352. \begin{figure}[tbp]
  2353. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2354. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2355. \caption{A Sudoku game board and the corresponding colored graph.}
  2356. \label{fig:sudoku-graph}
  2357. \end{figure}
  2358. Given that Sudoku is an instance of graph coloring, one can use Sudoku
  2359. strategies to come up with an algorithm for allocating registers. For
  2360. example, one of the basic techniques for Sudoku is called Pencil
  2361. Marks. The idea is that you use a process of elimination to determine
  2362. what numbers no longer make sense for a square, and write down those
  2363. numbers in the square (writing very small). For example, if the number
  2364. $1$ is assigned to a square, then by process of elimination, you can
  2365. write the pencil mark $1$ in all the squares in the same row, column,
  2366. and region. Many Sudoku computer games provide automatic support for
  2367. Pencil Marks.
  2368. %
  2369. The Pencil Marks technique corresponds to the notion of color
  2370. \emph{saturation} due to \cite{Brelaz:1979eu}. The saturation of a
  2371. vertex, in Sudoku terms, is the set of colors that are no longer
  2372. available. In graph terminology, we have the following definition:
  2373. \begin{equation*}
  2374. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  2375. \text{ and } \mathrm{color}(v) = c \}
  2376. \end{equation*}
  2377. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  2378. edge with $u$.
  2379. Using the Pencil Marks technique leads to a simple strategy for
  2380. filling in numbers: if there is a square with only one possible number
  2381. left, then write down that number! But what if there are no squares
  2382. with only one possibility left? One brute-force approach is to just
  2383. make a guess. If that guess ultimately leads to a solution, great. If
  2384. not, backtrack to the guess and make a different guess. One good
  2385. thing about Pencil Marks is that it reduces the degree of branching in
  2386. the search tree. Nevertheless, backtracking can be horribly time
  2387. consuming. One way to reduce the amount of backtracking is to use the
  2388. most-constrained-first heuristic. That is, when making a guess, always
  2389. choose a square with the fewest possibilities left (the vertex with
  2390. the highest saturation). The idea is that choosing highly constrained
  2391. squares earlier rather than later is better because later there may
  2392. not be any possibilities.
  2393. In some sense, register allocation is easier than Sudoku because we
  2394. can always cheat and add more numbers by mapping variables to the
  2395. stack. We say that a variable is \emph{spilled} when we decide to map
  2396. it to a stack location. We would like to minimize the time needed to
  2397. color the graph, and backtracking is expensive. Thus, it makes sense
  2398. to keep the most-constrained-first heuristic but drop the backtracking
  2399. in favor of greedy search (guess and just keep going).
  2400. Figure~\ref{fig:satur-algo} gives the pseudo-code for this simple
  2401. greedy algorithm for register allocation based on saturation and the
  2402. most-constrained-first heuristic, which is roughly equivalent to the
  2403. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2404. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just
  2405. as in Sudoku, the algorithm represents colors with integers, with the
  2406. first $k$ colors corresponding to the $k$ registers in a given machine
  2407. and the rest of the integers corresponding to stack locations.
  2408. \begin{figure}[btp]
  2409. \centering
  2410. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2411. Algorithm: DSATUR
  2412. Input: a graph |$G$|
  2413. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  2414. |$W \gets \mathit{vertices}(G)$|
  2415. while |$W \neq \emptyset$| do
  2416. pick a vertex |$u$| from |$W$| with the highest saturation,
  2417. breaking ties randomly
  2418. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  2419. |$\mathrm{color}[u] \gets c$|
  2420. |$W \gets W - \{u\}$|
  2421. \end{lstlisting}
  2422. \caption{The saturation-based greedy graph coloring algorithm.}
  2423. \label{fig:satur-algo}
  2424. \end{figure}
  2425. With this algorithm in hand, let us return to the running example and
  2426. consider how to color the interference graph in
  2427. Figure~\ref{fig:interfere}. We shall not use register \key{rax} for
  2428. register allocation because we use it to patch instructions, so we
  2429. remove that vertex from the graph. Initially, all of the vertices are
  2430. not yet colored and they are unsaturated, so we annotate each of them
  2431. with a dash for their color and an empty set for the saturation.
  2432. \[
  2433. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2434. \node (v) at (0,0) {$v:-,\{\}$};
  2435. \node (w) at (3,0) {$w:-,\{\}$};
  2436. \node (x) at (6,0) {$x:-,\{\}$};
  2437. \node (y) at (3,-1.5) {$y:-,\{\}$};
  2438. \node (z) at (6,-1.5) {$z:-,\{\}$};
  2439. \node (t1) at (9,-1.5) {$t.1:-,\{\}$};
  2440. \draw (v) to (w);
  2441. \foreach \i in {w,x,y}
  2442. {
  2443. \foreach \j in {w,x,y}
  2444. {
  2445. \draw (\i) to (\j);
  2446. }
  2447. }
  2448. \draw (z) to (w);
  2449. \draw (z) to (y);
  2450. \draw (t1) to (z);
  2451. \end{tikzpicture}
  2452. \]
  2453. We select a maximally saturated vertex and color it $0$. In this case we
  2454. have a 7-way tie, so we arbitrarily pick $t.1$. The then mark color $0$
  2455. as no longer available for $z$ because it interferes
  2456. with $t.1$.
  2457. \[
  2458. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2459. \node (v) at (0,0) {$v:-,\{\}$};
  2460. \node (w) at (3,0) {$w:-,\{\}$};
  2461. \node (x) at (6,0) {$x:-,\{\}$};
  2462. \node (y) at (3,-1.5) {$y:-,\{\}$};
  2463. \node (z) at (6,-1.5) {$z:-,\{\mathbf{0}\}$};
  2464. \node (t1) at (9,-1.5) {$t.1:\mathbf{0},\{\}$};
  2465. \draw (v) to (w);
  2466. \foreach \i in {w,x,y}
  2467. {
  2468. \foreach \j in {w,x,y}
  2469. {
  2470. \draw (\i) to (\j);
  2471. }
  2472. }
  2473. \draw (z) to (w);
  2474. \draw (z) to (y);
  2475. \draw (t1) to (z);
  2476. \end{tikzpicture}
  2477. \]
  2478. Now we repeat the process, selecting another maximally saturated
  2479. vertex, which in this case is $z$. We color $z$ with $1$.
  2480. \[
  2481. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2482. \node (v) at (0,0) {$v:-,\{\}$};
  2483. \node (w) at (3,0) {$w:-,\{\mathbf{1}\}$};
  2484. \node (x) at (6,0) {$x:-,\{\}$};
  2485. \node (y) at (3,-1.5) {$y:-,\{\mathbf{1}\}$};
  2486. \node (z) at (6,-1.5) {$z:\mathbf{1},\{0\}$};
  2487. \node (t1) at (9,-1.5) {$t.1:0,\{\mathbf{1}\}$};
  2488. \draw (t1) to (z);
  2489. \draw (v) to (w);
  2490. \foreach \i in {w,x,y}
  2491. {
  2492. \foreach \j in {w,x,y}
  2493. {
  2494. \draw (\i) to (\j);
  2495. }
  2496. }
  2497. \draw (z) to (w);
  2498. \draw (z) to (y);
  2499. \end{tikzpicture}
  2500. \]
  2501. The most saturated vertices are now $w$ and $y$. We color $y$ with the
  2502. first available color, which is $0$.
  2503. \[
  2504. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2505. \node (v) at (0,0) {$v:-,\{\}$};
  2506. \node (w) at (3,0) {$w:-,\{\mathbf{0},1\}$};
  2507. \node (x) at (6,0) {$x:-,\{\mathbf{0},\}$};
  2508. \node (y) at (3,-1.5) {$y:\mathbf{0},\{1\}$};
  2509. \node (z) at (6,-1.5) {$z:1,\{\mathbf{0}\}$};
  2510. \node (t1) at (9,-1.5) {$t.1:0,\{1\}$};
  2511. \draw (t1) to (z);
  2512. \draw (v) to (w);
  2513. \foreach \i in {w,x,y}
  2514. {
  2515. \foreach \j in {w,x,y}
  2516. {
  2517. \draw (\i) to (\j);
  2518. }
  2519. }
  2520. \draw (z) to (w);
  2521. \draw (z) to (y);
  2522. \end{tikzpicture}
  2523. \]
  2524. Vertex $w$ is now the most highly saturated, so we color $w$ with $2$.
  2525. \[
  2526. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2527. \node (v) at (0,0) {$v:-,\{2\}$};
  2528. \node (w) at (3,0) {$w:\mathbf{2},\{0,1\}$};
  2529. \node (x) at (6,0) {$x:-,\{0,\mathbf{2}\}$};
  2530. \node (y) at (3,-1.5) {$y:0,\{1,\mathbf{2}\}$};
  2531. \node (z) at (6,-1.5) {$z:1,\{0,\mathbf{2}\}$};
  2532. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2533. \draw (t1) to (z);
  2534. \draw (v) to (w);
  2535. \foreach \i in {w,x,y}
  2536. {
  2537. \foreach \j in {w,x,y}
  2538. {
  2539. \draw (\i) to (\j);
  2540. }
  2541. }
  2542. \draw (z) to (w);
  2543. \draw (z) to (y);
  2544. \end{tikzpicture}
  2545. \]
  2546. Now $x$ has the highest saturation, so we color it $1$.
  2547. \[
  2548. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2549. \node (v) at (0,0) {$v:-,\{2\}$};
  2550. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  2551. \node (x) at (6,0) {$x:\mathbf{1},\{0,2\}$};
  2552. \node (y) at (3,-1.5) {$y:0,\{\mathbf{1},2\}$};
  2553. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2554. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2555. \draw (t1) to (z);
  2556. \draw (v) to (w);
  2557. \foreach \i in {w,x,y}
  2558. {
  2559. \foreach \j in {w,x,y}
  2560. {
  2561. \draw (\i) to (\j);
  2562. }
  2563. }
  2564. \draw (z) to (w);
  2565. \draw (z) to (y);
  2566. \end{tikzpicture}
  2567. \]
  2568. In the last step of the algorithm, we color $v$ with $0$.
  2569. \[
  2570. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2571. \node (v) at (0,0) {$v:\mathbf{0},\{2\}$};
  2572. \node (w) at (3,0) {$w:2,\{\mathbf{0},1\}$};
  2573. \node (x) at (6,0) {$x:1,\{0,2\}$};
  2574. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2575. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2576. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2577. \draw (t1) to (z);
  2578. \draw (v) to (w);
  2579. \foreach \i in {w,x,y}
  2580. {
  2581. \foreach \j in {w,x,y}
  2582. {
  2583. \draw (\i) to (\j);
  2584. }
  2585. }
  2586. \draw (z) to (w);
  2587. \draw (z) to (y);
  2588. \end{tikzpicture}
  2589. \]
  2590. With the coloring complete, we can finalize the assignment of
  2591. variables to registers and stack locations. Recall that if we have $k$
  2592. registers, we map the first $k$ colors to registers and the rest to
  2593. stack locations. Suppose for the moment that we have just one
  2594. register to use for register allocation, \key{rcx}. Then the following
  2595. is the mapping of colors to registers and stack allocations.
  2596. \[
  2597. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)}, \ldots \}
  2598. \]
  2599. Putting this mapping together with the above coloring of the variables, we
  2600. arrive at the assignment:
  2601. \begin{gather*}
  2602. \{ v \mapsto \key{\%rcx}, \,
  2603. w \mapsto \key{-16(\%rbp)}, \,
  2604. x \mapsto \key{-8(\%rbp)}, \\
  2605. y \mapsto \key{\%rcx}, \,
  2606. z\mapsto \key{-8(\%rbp)},
  2607. t.1\mapsto \key{\%rcx} \}
  2608. \end{gather*}
  2609. Applying this assignment to our running example, on the left, yields
  2610. the program on the right.\\
  2611. % why frame size of 32? -JGS
  2612. \begin{minipage}{0.4\textwidth}
  2613. \begin{lstlisting}
  2614. (block ()
  2615. (movq (int 1) (var v))
  2616. (movq (int 46) (var w))
  2617. (movq (var v) (var x))
  2618. (addq (int 7) (var x))
  2619. (movq (var x) (var y))
  2620. (addq (int 4) (var y))
  2621. (movq (var x) (var z))
  2622. (addq (var w) (var z))
  2623. (movq (var y) (var t.1))
  2624. (negq (var t.1))
  2625. (movq (var z) (reg rax))
  2626. (addq (var t.1) (reg rax))
  2627. (jmp conclusion))
  2628. \end{lstlisting}
  2629. \end{minipage}
  2630. $\Rightarrow$
  2631. \begin{minipage}{0.45\textwidth}
  2632. \begin{lstlisting}
  2633. (block ()
  2634. (movq (int 1) (reg rcx))
  2635. (movq (int 46) (deref rbp -16))
  2636. (movq (reg rcx) (deref rbp -8))
  2637. (addq (int 7) (deref rbp -8))
  2638. (movq (deref rbp -8) (reg rcx))
  2639. (addq (int 4) (reg rcx))
  2640. (movq (deref rbp -8) (deref rbp -8))
  2641. (addq (deref rbp -16) (deref rbp -8))
  2642. (movq (reg rcx) (reg rcx))
  2643. (negq (reg rcx))
  2644. (movq (deref rbp -8) (reg rax))
  2645. (addq (reg rcx) (reg rax))
  2646. (jmp conclusion))
  2647. \end{lstlisting}
  2648. \end{minipage}
  2649. The resulting program is almost an x86 program. The remaining step
  2650. is to apply the patch instructions pass. In this example, the trivial
  2651. move of \code{-8(\%rbp)} to itself is deleted and the addition of
  2652. \code{-16(\%rbp)} to \key{-8(\%rbp)} is fixed by going through
  2653. \code{rax} as follows.
  2654. \begin{lstlisting}
  2655. (movq (deref rbp -16) (reg rax)
  2656. (addq (reg rax) (deref rbp -8))
  2657. \end{lstlisting}
  2658. An overview of all of the passes involved in register allocation is
  2659. shown in Figure~\ref{fig:reg-alloc-passes}.
  2660. \begin{figure}[tbp]
  2661. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2662. \node (R1) at (0,2) {\large $R_1$};
  2663. \node (R1-2) at (3,2) {\large $R_1$};
  2664. \node (R1-3) at (6,2) {\large $R_1$};
  2665. \node (C0-1) at (6,0) {\large $C_0$};
  2666. \node (C0-2) at (3,0) {\large $C_0$};
  2667. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  2668. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  2669. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  2670. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  2671. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  2672. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  2673. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  2674. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  2675. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  2676. \path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  2677. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  2678. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  2679. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  2680. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  2681. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  2682. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  2683. \end{tikzpicture}
  2684. \caption{Diagram of the passes for $R_1$ with register allocation.}
  2685. \label{fig:reg-alloc-passes}
  2686. \end{figure}
  2687. \begin{exercise}\normalfont
  2688. Implement the pass \code{allocate-registers}, which should come
  2689. after the \code{build-interference} pass. The three new passes,
  2690. \code{uncover-live}, \code{build-interference}, and
  2691. \code{allocate-registers} replace the \code{assign-homes} pass of
  2692. Section~\ref{sec:assign-r1}.
  2693. We recommend that you create a helper function named
  2694. \code{color-graph} that takes an interference graph and a list of
  2695. all the variables in the program. This function should return a
  2696. mapping of variables to their colors (represented as natural
  2697. numbers). By creating this helper function, you will be able to
  2698. reuse it in Chapter~\ref{ch:functions} when you add support for
  2699. functions.
  2700. Once you have obtained the coloring from \code{color-graph}, you can
  2701. assign the variables to registers or stack locations and then reuse
  2702. code from the \code{assign-homes} pass from
  2703. Section~\ref{sec:assign-r1} to replace the variables with their
  2704. assigned location.
  2705. Test your updated compiler by creating new example programs that
  2706. exercise all of the register allocation algorithm, such as forcing
  2707. variables to be spilled to the stack.
  2708. \end{exercise}
  2709. \section{Print x86 and Conventions for Registers}
  2710. \label{sec:print-x86-reg-alloc}
  2711. Recall the \code{print-x86} pass generates the prelude and
  2712. conclusion instructions for the \code{main} function.
  2713. %
  2714. The prelude saved the values in \code{rbp} and \code{rsp} and the
  2715. conclusion returned those values to \code{rbp} and \code{rsp}. The
  2716. reason for this is that our \code{main} function must adhere to the
  2717. x86 calling conventions that we described in
  2718. Section~\ref{sec:calling-conventions}. In addition, the \code{main}
  2719. function needs to restore (in the conclusion) any callee-saved
  2720. registers that get used during register allocation. The simplest
  2721. approach is to save and restore all of the callee-saved registers. The
  2722. more efficient approach is to keep track of which callee-saved
  2723. registers were used and only save and restore them. Either way, make
  2724. sure to take this use of stack space into account when you are
  2725. calculating the size of the frame. Also, don't forget that the size of
  2726. the frame needs to be a multiple of 16 bytes.
  2727. \section{Challenge: Move Biasing$^{*}$}
  2728. \label{sec:move-biasing}
  2729. This section describes an optional enhancement to register allocation
  2730. for those students who are looking for an extra challenge or who have
  2731. a deeper interest in register allocation.
  2732. We return to the running example, but we remove the supposition that
  2733. we only have one register to use. So we have the following mapping of
  2734. color numbers to registers.
  2735. \[
  2736. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx}, \ldots \}
  2737. \]
  2738. Using the same assignment that was produced by register allocator
  2739. described in the last section, we get the following program.
  2740. \begin{minipage}{0.45\textwidth}
  2741. \begin{lstlisting}
  2742. (block ()
  2743. (movq (int 1) (var v))
  2744. (movq (int 46) (var w))
  2745. (movq (var v) (var x))
  2746. (addq (int 7) (var x))
  2747. (movq (var x) (var y))
  2748. (addq (int 4) (var y))
  2749. (movq (var x) (var z))
  2750. (addq (var w) (var z))
  2751. (movq (var y) (var t.1))
  2752. (negq (var t.1))
  2753. (movq (var z) (reg rax))
  2754. (addq (var t.1) (reg rax))
  2755. (jmp conclusion))
  2756. \end{lstlisting}
  2757. \end{minipage}
  2758. $\Rightarrow$
  2759. \begin{minipage}{0.45\textwidth}
  2760. \begin{lstlisting}
  2761. (block ()
  2762. (movq (int 1) (reg rbx))
  2763. (movq (int 46) (reg rdx))
  2764. (movq (reg rbx) (reg rcx))
  2765. (addq (int 7) (reg rcx))
  2766. (movq (reg rcx) (reg rbx))
  2767. (addq (int 4) (reg rbx))
  2768. (movq (reg rcx) (reg rcx))
  2769. (addq (reg rdx) (reg rcx))
  2770. (movq (reg rbx) (reg rbx))
  2771. (negq (reg rbx))
  2772. (movq (reg rcx) (reg rax))
  2773. (addq (reg rbx) (reg rax))
  2774. (jmp conclusion))
  2775. \end{lstlisting}
  2776. \end{minipage}
  2777. While this allocation is quite good, we could do better. For example,
  2778. the variables \key{v} and \key{x} ended up in different registers, but
  2779. if they had been placed in the same register, then the move from
  2780. \key{v} to \key{x} could be removed.
  2781. We say that two variables $p$ and $q$ are \emph{move related} if they
  2782. participate together in a \key{movq} instruction, that is, \key{movq}
  2783. $p$, $q$ or \key{movq} $q$, $p$. When the register allocator chooses a
  2784. color for a variable, it should prefer a color that has already been
  2785. used for a move-related variable (assuming that they do not
  2786. interfere). Of course, this preference should not override the
  2787. preference for registers over stack locations, but should only be used
  2788. as a tie breaker when choosing between registers or when choosing
  2789. between stack locations.
  2790. We recommend that you represent the move relationships in a graph,
  2791. similar to how we represented interference. The following is the
  2792. \emph{move graph} for our running example.
  2793. \[
  2794. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2795. \node (v) at (0,0) {$v$};
  2796. \node (w) at (3,0) {$w$};
  2797. \node (x) at (6,0) {$x$};
  2798. \node (y) at (3,-1.5) {$y$};
  2799. \node (z) at (6,-1.5) {$z$};
  2800. \node (t1) at (9,-1.5) {$t.1$};
  2801. \draw[bend left=15] (t1) to (y);
  2802. \draw[bend left=15] (v) to (x);
  2803. \draw (x) to (y);
  2804. \draw (x) to (z);
  2805. \end{tikzpicture}
  2806. \]
  2807. Now we replay the graph coloring, pausing to see the coloring of $x$
  2808. and $v$. So we have the following coloring and the most saturated
  2809. vertex is $x$.
  2810. \[
  2811. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2812. \node (v) at (0,0) {$v:-,\{2\}$};
  2813. \node (w) at (3,0) {$w:2,\{0,1\}$};
  2814. \node (x) at (6,0) {$x:-,\{0,2\}$};
  2815. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2816. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2817. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2818. \draw (t1) to (z);
  2819. \draw (v) to (w);
  2820. \foreach \i in {w,x,y}
  2821. {
  2822. \foreach \j in {w,x,y}
  2823. {
  2824. \draw (\i) to (\j);
  2825. }
  2826. }
  2827. \draw (z) to (w);
  2828. \draw (z) to (y);
  2829. \end{tikzpicture}
  2830. \]
  2831. Last time we chose to color $x$ with $1$,
  2832. %
  2833. which so happens to be the color of $z$, and $x$ is move related to
  2834. $z$. This was rather lucky, and if the program had been a little
  2835. different, and say $z$ had been already assigned to $2$, then $x$
  2836. would still get $1$ and our luck would have run out. With move
  2837. biasing, we use the fact that $x$ and $z$ are move related to
  2838. influence the choice of color for $x$, in this case choosing $1$
  2839. because that's the color of $z$.
  2840. \[
  2841. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2842. \node (v) at (0,0) {$v:-,\{2\}$};
  2843. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  2844. \node (x) at (6,0) {$x:\mathbf{1},\{0,2\}$};
  2845. \node (y) at (3,-1.5) {$y:0,\{\mathbf{1},2\}$};
  2846. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2847. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2848. \draw (t1) to (z);
  2849. \draw (v) to (w);
  2850. \foreach \i in {w,x,y}
  2851. {
  2852. \foreach \j in {w,x,y}
  2853. {
  2854. \draw (\i) to (\j);
  2855. }
  2856. }
  2857. \draw (z) to (w);
  2858. \draw (z) to (y);
  2859. \end{tikzpicture}
  2860. \]
  2861. Next we consider coloring the variable $v$, and we just need to avoid
  2862. choosing $2$ because of the interference with $w$. Last time we choose
  2863. the color $0$, simply because it was the lowest, but this time we know
  2864. that $v$ is move related to $x$, so we choose the color $1$.
  2865. \[
  2866. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2867. \node (v) at (0,0) {$v:\mathbf{1},\{2\}$};
  2868. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  2869. \node (x) at (6,0) {$x:1,\{0,2\}$};
  2870. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2871. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2872. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2873. \draw (t1) to (z);
  2874. \draw (v) to (w);
  2875. \foreach \i in {w,x,y}
  2876. {
  2877. \foreach \j in {w,x,y}
  2878. {
  2879. \draw (\i) to (\j);
  2880. }
  2881. }
  2882. \draw (z) to (w);
  2883. \draw (z) to (y);
  2884. \end{tikzpicture}
  2885. \]
  2886. We apply this register assignment to the running example, on the left,
  2887. to obtain the code on right.
  2888. \begin{minipage}{0.45\textwidth}
  2889. \begin{lstlisting}
  2890. (block ()
  2891. (movq (int 1) (var v))
  2892. (movq (int 46) (var w))
  2893. (movq (var v) (var x))
  2894. (addq (int 7) (var x))
  2895. (movq (var x) (var y))
  2896. (addq (int 4) (var y))
  2897. (movq (var x) (var z))
  2898. (addq (var w) (var z))
  2899. (movq (var y) (var t.1))
  2900. (negq (var t.1))
  2901. (movq (var z) (reg rax))
  2902. (addq (var t.1) (reg rax))
  2903. (jmp conclusion))
  2904. \end{lstlisting}
  2905. \end{minipage}
  2906. $\Rightarrow$
  2907. \begin{minipage}{0.45\textwidth}
  2908. \begin{lstlisting}
  2909. (block ()
  2910. (movq (int 1) (reg rcx))
  2911. (movq (int 46) (reg rbx))
  2912. (movq (reg rcx) (reg rcx))
  2913. (addq (int 7) (reg rcx))
  2914. (movq (reg rcx) (reg rdx))
  2915. (addq (int 4) (reg rdx))
  2916. (movq (reg rcx) (reg rcx))
  2917. (addq (reg rbx) (reg rcx))
  2918. (movq (reg rdx) (reg rbx))
  2919. (negq (reg rbx))
  2920. (movq (reg rcx) (reg rax))
  2921. (addq (reg rbx) (reg rax))
  2922. (jmp conclusion))
  2923. \end{lstlisting}
  2924. \end{minipage}
  2925. The \code{patch-instructions} then removes the trivial moves from
  2926. \key{v} to \key{x} and from \key{x} to \key{z} to obtain the following
  2927. result.
  2928. \begin{minipage}{0.45\textwidth}
  2929. \begin{lstlisting}
  2930. (block ()
  2931. (movq (int 1) (reg rcx))
  2932. (movq (int 46) (reg rbx))
  2933. (addq (int 7) (reg rcx))
  2934. (movq (reg rcx) (reg rdx))
  2935. (addq (int 4) (reg rdx))
  2936. (addq (reg rbx) (reg rcx))
  2937. (movq (reg rdx) (reg rbx))
  2938. (negq (reg rbx))
  2939. (movq (reg rcx) (reg rax))
  2940. (addq (reg rbx) (reg rax))
  2941. (jmp conclusion))
  2942. \end{lstlisting}
  2943. \end{minipage}
  2944. \begin{exercise}\normalfont
  2945. Change your implementation of \code{allocate-registers} to take move
  2946. biasing into account. Make sure that your compiler still passes all of
  2947. the previous tests. Create two new tests that include at least one
  2948. opportunity for move biasing and visually inspect the output x86
  2949. programs to make sure that your move biasing is working properly.
  2950. \end{exercise}
  2951. \margincomment{\footnotesize To do: another neat challenge would be to do
  2952. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  2953. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2954. \chapter{Booleans and Control Flow}
  2955. \label{ch:bool-types}
  2956. The $R_0$ and $R_1$ languages only had a single kind of value, the
  2957. integers. In this Chapter we add a second kind of value, the Booleans,
  2958. to create the $R_2$ language. The Boolean values \emph{true} and
  2959. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  2960. Racket. We also introduce several operations that involve Booleans
  2961. (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the conditional
  2962. \key{if} expression. With the addition of \key{if} expressions,
  2963. programs can have non-trivial control flow which has an impact on
  2964. several parts of the compiler. Also, because we now have two kinds of
  2965. values, we need to worry about programs that apply an operation to the
  2966. wrong kind of value, such as \code{(not 1)}.
  2967. There are two language design options for such situations. One option
  2968. is to signal an error and the other is to provide a wider
  2969. interpretation of the operation. The Racket language uses a mixture of
  2970. these two options, depending on the operation and the kind of
  2971. value. For example, the result of \code{(not 1)} in Racket is
  2972. \code{\#f} because Racket treats non-zero integers like \code{\#t}. On
  2973. the other hand, \code{(car 1)} results in a run-time error in Racket
  2974. stating that \code{car} expects a pair.
  2975. The Typed Racket language makes similar design choices as Racket,
  2976. except much of the error detection happens at compile time instead of
  2977. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  2978. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  2979. reports a compile-time error because Typed Racket expects the type of
  2980. the argument to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  2981. For the $R_2$ language we choose to be more like Typed Racket in that
  2982. we shall perform type checking during compilation. In
  2983. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  2984. is, how to compile a dynamically typed language like Racket. The
  2985. $R_2$ language is a subset of Typed Racket but by no means includes
  2986. all of Typed Racket. Furthermore, for many of the operations we shall
  2987. take a narrower interpretation than Typed Racket, for example,
  2988. rejecting \code{(not 1)}.
  2989. This chapter is organized as follows. We begin by defining the syntax
  2990. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  2991. then introduce the idea of type checking and build a type checker for
  2992. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  2993. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  2994. Section~\ref{sec:c1}. The remaining sections of this Chapter discuss
  2995. how our compiler passes need to change to accommodate Booleans and
  2996. conditional control flow.
  2997. \section{The $R_2$ Language}
  2998. \label{sec:r2-lang}
  2999. The syntax of the $R_2$ language is defined in
  3000. Figure~\ref{fig:r2-syntax}. It includes all of $R_1$ (shown in gray),
  3001. the Boolean literals \code{\#t} and \code{\#f}, and the conditional
  3002. \code{if} expression. Also, we expand the operators to include
  3003. subtraction, \key{and}, \key{or} and \key{not}, the \key{eq?}
  3004. operations for comparing two integers or two Booleans, and the
  3005. \key{<}, \key{<=}, \key{>}, and \key{>=} operations for comparing
  3006. integers.
  3007. \begin{figure}[tp]
  3008. \centering
  3009. \fbox{
  3010. \begin{minipage}{0.96\textwidth}
  3011. \[
  3012. \begin{array}{lcl}
  3013. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3014. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \mid (\key{-}\;\Exp\;\Exp) \\
  3015. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  3016. &\mid& \key{\#t} \mid \key{\#f}
  3017. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  3018. \mid (\key{not}\;\Exp) \\
  3019. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  3020. R_2 &::=& (\key{program} \; \itm{info}\; \Exp)
  3021. \end{array}
  3022. \]
  3023. \end{minipage}
  3024. }
  3025. \caption{The syntax of $R_2$, extending $R_1$
  3026. (Figure~\ref{fig:r1-syntax}) with Booleans and conditionals.}
  3027. \label{fig:r2-syntax}
  3028. \end{figure}
  3029. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  3030. the parts that are the same as the interpreter for $R_1$
  3031. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  3032. simply evaluate to themselves. The conditional expression $(\key{if}\,
  3033. \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates the Boolean expression
  3034. \itm{cnd} and then either evaluates \itm{thn} or \itm{els} depending
  3035. on whether \itm{cnd} produced \code{\#t} or \code{\#f}. The logical
  3036. operations \code{not} and \code{and} behave as you might expect, but
  3037. note that the \code{and} operation is short-circuiting. That is, given
  3038. the expression $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not
  3039. evaluated if $e_1$ evaluates to \code{\#f}.
  3040. With the addition of the comparison operations, there are quite a few
  3041. primitive operations and the interpreter code for them is somewhat
  3042. repetitive. In Figure~\ref{fig:interp-R2} we factor out the different
  3043. parts into the \code{interp-op} function and the similar parts into
  3044. the one match clause shown in Figure~\ref{fig:interp-R2}. We do not
  3045. use \code{interp-op} for the \code{and} operation because of the
  3046. short-circuiting behavior in the order of evaluation of its arguments.
  3047. \begin{figure}[tbp]
  3048. \begin{lstlisting}
  3049. (define primitives (set '+ '- 'eq? '< '<= '> '>= 'not 'read))
  3050. (define (interp-op op)
  3051. (match op
  3052. ...
  3053. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  3054. ['eq? (lambda (v1 v2)
  3055. (cond [(or (and (fixnum? v1) (fixnum? v2))
  3056. (and (boolean? v1) (boolean? v2)))
  3057. (eq? v1 v2)]))]
  3058. ['< (lambda (v1 v2)
  3059. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  3060. ['<= (lambda (v1 v2)
  3061. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  3062. ['> (lambda (v1 v2)
  3063. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  3064. ['>= (lambda (v1 v2)
  3065. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  3066. [else (error 'interp-op "unknown operator")]))
  3067. (define (interp-exp env)
  3068. (lambda (e)
  3069. (define recur (interp-exp env))
  3070. (match e
  3071. ...
  3072. [(? boolean?) e]
  3073. [`(if ,cnd ,thn ,els)
  3074. (define b (recur cnd))
  3075. (match b
  3076. [#t (recur thn)]
  3077. [#f (recur els)])]
  3078. [`(and ,e1 ,e2)
  3079. (define v1 (recur e1))
  3080. (match v1
  3081. [#t (match (recur e2) [#t #t] [#f #f])]
  3082. [#f #f])]
  3083. [`(,op ,args ...)
  3084. #:when (set-member? primitives op)
  3085. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  3086. )))
  3087. (define (interp-R2 env)
  3088. (lambda (p)
  3089. (match p
  3090. [`(program ,info ,e)
  3091. ((interp-exp '()) e)])))
  3092. \end{lstlisting}
  3093. \caption{Interpreter for the $R_2$ language.}
  3094. \label{fig:interp-R2}
  3095. \end{figure}
  3096. \section{Type Checking $R_2$ Programs}
  3097. \label{sec:type-check-r2}
  3098. It is helpful to think about type checking in two complementary
  3099. ways. A type checker predicts the \emph{type} of value that will be
  3100. produced by each expression in the program. For $R_2$, we have just
  3101. two types, \key{Integer} and \key{Boolean}. So a type checker should
  3102. predict that
  3103. \begin{lstlisting}
  3104. (+ 10 (- (+ 12 20)))
  3105. \end{lstlisting}
  3106. produces an \key{Integer} while
  3107. \begin{lstlisting}
  3108. (and (not #f) #t)
  3109. \end{lstlisting}
  3110. produces a \key{Boolean}.
  3111. As mentioned at the beginning of this chapter, a type checker also
  3112. rejects programs that apply operators to the wrong type of value. Our
  3113. type checker for $R_2$ will signal an error for the following
  3114. expression because, as we have seen above, the expression \code{(+ 10
  3115. ...)} has type \key{Integer}, and we require the argument of a
  3116. \code{not} to have type \key{Boolean}.
  3117. \begin{lstlisting}
  3118. (not (+ 10 (- (+ 12 20))))
  3119. \end{lstlisting}
  3120. The type checker for $R_2$ is best implemented as a structurally
  3121. recursive function over the AST. Figure~\ref{fig:type-check-R2} shows
  3122. many of the clauses for the \code{type-check-exp} function. Given an
  3123. input expression \code{e}, the type checker either returns the type
  3124. (\key{Integer} or \key{Boolean}) or it signals an error. Of course,
  3125. the type of an integer literal is \code{Integer} and the type of a
  3126. Boolean literal is \code{Boolean}. To handle variables, the type
  3127. checker, like the interpreter, uses an association list. However, in
  3128. this case the association list maps variables to types instead of
  3129. values. Consider the clause for \key{let}. We type check the
  3130. initializing expression to obtain its type \key{T} and then associate
  3131. type \code{T} with the variable \code{x}. When the type checker
  3132. encounters the use of a variable, it can find its type in the
  3133. association list.
  3134. \begin{figure}[tbp]
  3135. \begin{lstlisting}
  3136. (define (type-check-exp env)
  3137. (lambda (e)
  3138. (define recur (type-check-exp env))
  3139. (match e
  3140. [(? fixnum?) 'Integer]
  3141. [(? boolean?) 'Boolean]
  3142. [(? symbol? x) (dict-ref env x)]
  3143. [`(read) 'Integer]
  3144. [`(let ([,x ,e]) ,body)
  3145. (define T (recur e))
  3146. (define new-env (cons (cons x T) env))
  3147. (type-check-exp new-env body)]
  3148. ...
  3149. [`(not ,e)
  3150. (match (recur e)
  3151. ['Boolean 'Boolean]
  3152. [else (error 'type-check-exp "'not' expects a Boolean" e)])]
  3153. ...
  3154. )))
  3155. (define (type-check-R2 env)
  3156. (lambda (e)
  3157. (match e
  3158. [`(program ,info ,body)
  3159. (define ty ((type-check-exp '()) body))
  3160. `(program ,info ,body)]
  3161. )))
  3162. \end{lstlisting}
  3163. \caption{Skeleton of a type checker for the $R_2$ language.}
  3164. \label{fig:type-check-R2}
  3165. \end{figure}
  3166. %% To print the resulting value correctly, the overall type of the
  3167. %% program must be threaded through the remainder of the passes. We can
  3168. %% store the type within the \key{program} form as shown in Figure
  3169. %% \ref{fig:type-check-R2}. Let $R^\dagger_2$ be the name for the
  3170. %% intermediate language produced by the type checker, which we define as
  3171. %% follows: \\[1ex]
  3172. %% \fbox{
  3173. %% \begin{minipage}{0.87\textwidth}
  3174. %% \[
  3175. %% \begin{array}{lcl}
  3176. %% R^\dagger_2 &::=& (\key{program}\;(\key{type}\;\itm{type})\; \Exp)
  3177. %% \end{array}
  3178. %% \]
  3179. %% \end{minipage}
  3180. %% }
  3181. \begin{exercise}\normalfont
  3182. Complete the implementation of \code{type-check-R2} and test it on 10
  3183. new example programs in $R_2$ that you choose based on how thoroughly
  3184. they test the type checking algorithm. Half of the example programs
  3185. should have a type error, to make sure that your type checker properly
  3186. rejects them. The other half of the example programs should not have
  3187. type errors. Your testing should check that the result of the type
  3188. checker agrees with the value returned by the interpreter, that is, if
  3189. the type checker returns \key{Integer}, then the interpreter should
  3190. return an integer. Likewise, if the type checker returns
  3191. \key{Boolean}, then the interpreter should return \code{\#t} or
  3192. \code{\#f}. Note that if your type checker does not signal an error
  3193. for a program, then interpreting that program should not encounter an
  3194. error. If it does, there is something wrong with your type checker.
  3195. \end{exercise}
  3196. \section{Shrink the $R_2$ Language}
  3197. \label{sec:shrink-r2}
  3198. The $R_2$ language includes several operators that are easily
  3199. expressible in terms of other operators. For example, subtraction is
  3200. expressible in terms of addition and negation.
  3201. \[
  3202. (\key{-}\; e_1 \; e_2) \quad \Rightarrow \quad (\key{+} \; e_1 \; (\key{-} \; e_2))
  3203. \]
  3204. Several of the comparison operations are expressible in terms of
  3205. less-than and logical negation.
  3206. \[
  3207. (\key{<=}\; e_1 \; e_2) \quad \Rightarrow \quad
  3208. \LET{t_1}{e_1}{(\key{not}\;(\key{<}\;e_2\;t_1))}
  3209. \]
  3210. By performing these translations near the front-end of the compiler,
  3211. the later passes of the compiler will not need to deal with these
  3212. constructs, making those passes shorter. On the other hand, sometimes
  3213. these translations make it more difficult to generate the most
  3214. efficient code with respect to the number of instructions. However,
  3215. these differences typically do not affect the number of accesses to
  3216. memory, which is the primary factor that determines execution time on
  3217. modern computer architectures.
  3218. \begin{exercise}\normalfont
  3219. Implement the pass \code{shrink} that removes subtraction,
  3220. \key{and}, \key{or}, \key{<=}, \key{>}, and \key{>=} from the language
  3221. by translating them to other constructs in $R_2$. Create tests to
  3222. make sure that the behavior of all of these constructs stays the
  3223. same after translation.
  3224. \end{exercise}
  3225. \section{XOR, Comparisons, and Control Flow in x86}
  3226. \label{sec:x86-1}
  3227. To implement the new logical operations, the comparison operations,
  3228. and the \key{if} expression, we need to delve further into the x86
  3229. language. Figure~\ref{fig:x86-1} defines the abstract syntax for a
  3230. larger subset of x86 that includes instructions for logical
  3231. operations, comparisons, and jumps.
  3232. One small challenge is that x86 does not provide an instruction that
  3233. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  3234. However, the \code{xorq} instruction can be used to encode \code{not}.
  3235. The \key{xorq} instruction takes two arguments, performs a pairwise
  3236. exclusive-or operation on each bit of its arguments, and writes the
  3237. results into its second argument. Recall the truth table for
  3238. exclusive-or:
  3239. \begin{center}
  3240. \begin{tabular}{l|cc}
  3241. & 0 & 1 \\ \hline
  3242. 0 & 0 & 1 \\
  3243. 1 & 1 & 0
  3244. \end{tabular}
  3245. \end{center}
  3246. For example, $0011 \mathrel{\mathrm{XOR}} 0101 = 0110$. Notice that
  3247. in row of the table for the bit $1$, the result is the opposite of the
  3248. second bit. Thus, the \code{not} operation can be implemented by
  3249. \code{xorq} with $1$ as the first argument: $0001
  3250. \mathrel{\mathrm{XOR}} 0000 = 0001$ and $0001 \mathrel{\mathrm{XOR}}
  3251. 0001 = 0000$.
  3252. \begin{figure}[tp]
  3253. \fbox{
  3254. \begin{minipage}{0.96\textwidth}
  3255. \[
  3256. \begin{array}{lcl}
  3257. \Arg &::=& \gray{\INT{\Int} \mid \REG{\itm{register}}
  3258. \mid (\key{deref}\,\itm{register}\,\Int)} \\
  3259. &\mid& (\key{byte-reg}\; \itm{register}) \\
  3260. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3261. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  3262. (\key{subq} \; \Arg\; \Arg) \mid
  3263. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  3264. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  3265. (\key{pushq}\;\Arg) \mid
  3266. (\key{popq}\;\Arg) \mid
  3267. (\key{retq})} \\
  3268. &\mid& (\key{xorq} \; \Arg\;\Arg)
  3269. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\;\itm{cc} \; \Arg) \\
  3270. &\mid& (\key{movzbq}\;\Arg\;\Arg)
  3271. \mid (\key{jmp} \; \itm{label})
  3272. \mid (\key{jmp-if}\; \itm{cc} \; \itm{label}) \\
  3273. &\mid& (\key{label} \; \itm{label}) \\
  3274. x86_1 &::= & (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+})
  3275. \end{array}
  3276. \]
  3277. \end{minipage}
  3278. }
  3279. \caption{The x86$_1$ language (extends x86$_0$ of Figure~\ref{fig:x86-ast-a}).}
  3280. \label{fig:x86-1}
  3281. \end{figure}
  3282. Next we consider the x86 instructions that are relevant for
  3283. compiling the comparison operations. The \key{cmpq} instruction
  3284. compares its two arguments to determine whether one argument is less
  3285. than, equal, or greater than the other argument. The \key{cmpq}
  3286. instruction is unusual regarding the order of its arguments and where
  3287. the result is placed. The argument order is backwards: if you want to
  3288. test whether $x < y$, then write \code{cmpq y, x}. The result of
  3289. \key{cmpq} is placed in the special EFLAGS register. This register
  3290. cannot be accessed directly but it can be queried by a number of
  3291. instructions, including the \key{set} instruction. The \key{set}
  3292. instruction puts a \key{1} or \key{0} into its destination depending
  3293. on whether the comparison came out according to the condition code
  3294. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  3295. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  3296. The set instruction has an annoying quirk in that its destination
  3297. argument must be single byte register, such as \code{al}, which is
  3298. part of the \code{rax} register. Thankfully, the \key{movzbq}
  3299. instruction can then be used to move from a single byte register to a
  3300. normal 64-bit register.
  3301. For compiling the \key{if} expression, the x86 instructions for
  3302. jumping are relevant. The \key{jmp} instruction updates the program
  3303. counter to point to the instruction after the indicated label. The
  3304. \key{jmp-if} instruction updates the program counter to point to the
  3305. instruction after the indicated label depending on whether the result
  3306. in the EFLAGS register matches the condition code \itm{cc}, otherwise
  3307. the \key{jmp-if} instruction falls through to the next
  3308. instruction. Because the \key{jmp-if} instruction relies on the EFLAGS
  3309. register, it is quite common for the \key{jmp-if} to be immediately
  3310. preceded by a \key{cmpq} instruction, to set the EFLAGS register.
  3311. Our abstract syntax for \key{jmp-if} differs from the concrete syntax
  3312. for x86 to separate the instruction name from the condition code. For
  3313. example, \code{(jmp-if le foo)} corresponds to \code{jle foo}.
  3314. \section{The $C_1$ Intermediate Language}
  3315. \label{sec:c1}
  3316. As with $R_1$, we shall compile $R_2$ to a C-like intermediate
  3317. language, but we need to grow that intermediate language to handle the
  3318. new features in $R_2$: Booleans and conditional expressions.
  3319. Figure~\ref{fig:c1-syntax} shows the new features of $C_1$; we add
  3320. logic and comparison operators to the $\Exp$ non-terminal, the
  3321. literals \key{\#t} and \key{\#f} to the $\Arg$ non-terminal.
  3322. Regarding control flow, $C_1$ differs considerably from $R_2$.
  3323. Instead of \key{if} expressions, $C_1$ has goto's and conditional
  3324. goto's in the grammar for $\Tail$. This means that a sequence of
  3325. statements may now end with a \code{goto} or a conditional
  3326. \code{goto}, which jumps to one of two labeled pieces of code
  3327. depending on the outcome of the comparison. In
  3328. Section~\ref{sec:explicate-control-r2} we discuss how to translate
  3329. from $R_2$ to $C_1$, bridging this gap between \key{if} expressions
  3330. and \key{goto}'s.
  3331. \begin{figure}[tp]
  3332. \fbox{
  3333. \begin{minipage}{0.96\textwidth}
  3334. \[
  3335. \begin{array}{lcl}
  3336. \Arg &::=& \gray{\Int \mid \Var} \mid \key{\#t} \mid \key{\#f} \\
  3337. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3338. \Exp &::= & \gray{\Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)}
  3339. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) \\
  3340. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} } \\
  3341. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  3342. &\mid& (\key{goto}\,\itm{label}) \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})} \\
  3343. C_1 & ::= & (\key{program}\;\itm{info}\; ((\itm{label}\,\key{.}\,\Tail)^{+}))
  3344. \end{array}
  3345. \]
  3346. \end{minipage}
  3347. }
  3348. \caption{The $C_1$ language, extending $C_0$ with Booleans and conditionals.}
  3349. \label{fig:c1-syntax}
  3350. \end{figure}
  3351. \section{Explicate Control}
  3352. \label{sec:explicate-control-r2}
  3353. Recall that the purpose of \code{explicate-control} is to make the
  3354. order of evaluation explicit in the syntax of the program. With the
  3355. addition of \key{if} in $R_2$, things get more interesting.
  3356. As a motivating example, consider the following program that has an
  3357. \key{if} expression nested in the predicate of another \key{if}.
  3358. % s1_38.rkt
  3359. \begin{lstlisting}
  3360. (program ()
  3361. (if (if (eq? (read) 1)
  3362. (eq? (read) 0)
  3363. (eq? (read) 2))
  3364. (+ 10 32)
  3365. (+ 700 77)))
  3366. \end{lstlisting}
  3367. %
  3368. The naive way to compile \key{if} and \key{eq?} would be to handle
  3369. each of them in isolation, regardless of their context. Each
  3370. \key{eq?} would be translated into a \key{cmpq} instruction followed
  3371. by a couple instructions to move the result from the EFLAGS register
  3372. into a general purpose register or stack location. Each \key{if} would
  3373. be translated into the combination of a \key{cmpq} and \key{jmp-if}.
  3374. However, if we take context into account we can do better and reduce
  3375. the use of \key{cmpq} and EFLAG-accessing instructions.
  3376. One idea is to try and reorganize the code at the level of $R_2$,
  3377. pushing the outer \key{if} inside the inner one. This would yield the
  3378. following code.
  3379. \begin{lstlisting}
  3380. (if (eq? (read) 1)
  3381. (if (eq? (read) 0)
  3382. (+ 10 32)
  3383. (+ 700 77))
  3384. (if (eq? (read) 2))
  3385. (+ 10 32)
  3386. (+ 700 77))
  3387. \end{lstlisting}
  3388. Unfortunately, this approach duplicates the two branches, and a
  3389. compiler must never duplicate code!
  3390. We need a way to perform the above transformation, but without
  3391. duplicating code. The solution is straightforward if we think at the
  3392. level of x86 assembly: we can label the code for each of the branches
  3393. and insert \key{goto}'s in all the places that need to execute the
  3394. branches. Put another way, we need to move away from abstract syntax
  3395. \emph{trees} and instead use \emph{graphs}. In particular, we shall
  3396. use a standard program representation called a \emph{control flow
  3397. graph} (CFG), due to Frances Elizabeth \citet{Allen:1970uq}. Each
  3398. vertex is a labeled sequence of code, called a \emph{basic block}, and
  3399. each edge represents a jump to another block. The \key{program}
  3400. construct of $C_0$ and $C_1$ represents a control flow graph as an
  3401. association list mapping labels to basic blocks. Each block is
  3402. represented by the $\Tail$ non-terminal.
  3403. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  3404. \code{remove-complex-opera*} pass and then the
  3405. \code{explicate-control} pass on the example program. We shall walk
  3406. through the output program and then discuss the algorithm.
  3407. %
  3408. Following the order of evaluation in the output of
  3409. \code{remove-complex-opera*}, we first have the \code{(read)} and
  3410. comparison to \code{1} from the predicate of the inner \key{if}. In
  3411. the output of \code{explicate-control}, in the \code{start} block,
  3412. this becomes a \code{(read)} followed by a conditional goto to either
  3413. \code{block61} or \code{block62}. Each of these contains the
  3414. translations of the code \code{(eq? (read) 0)} and \code{(eq? (read)
  3415. 1)}, respectively. Regarding \code{block61}, we start with the
  3416. \code{(read)} and comparison to \code{0} and then have a conditional
  3417. goto, either to \code{block59} or \code{block60}, which indirectly
  3418. take us to \code{block55} and \code{block56}, the two branches of the
  3419. outer \key{if}, i.e., \code{(+ 10 32)} and \code{(+ 700 77)}. The
  3420. story for \code{block62} is similar.
  3421. \begin{figure}[tbp]
  3422. \begin{tabular}{lll}
  3423. \begin{minipage}{0.4\textwidth}
  3424. \begin{lstlisting}
  3425. (program ()
  3426. (if (if (eq? (read) 1)
  3427. (eq? (read) 0)
  3428. (eq? (read) 2))
  3429. (+ 10 32)
  3430. (+ 700 77)))
  3431. \end{lstlisting}
  3432. \hspace{40pt}$\Downarrow$
  3433. \begin{lstlisting}
  3434. (program ()
  3435. (if (if (let ([tmp52 (read)])
  3436. (eq? tmp52 1))
  3437. (let ([tmp53 (read)])
  3438. (eq? tmp53 0))
  3439. (let ([tmp54 (read)])
  3440. (eq? tmp54 2)))
  3441. (+ 10 32)
  3442. (+ 700 77)))
  3443. \end{lstlisting}
  3444. \end{minipage}
  3445. &
  3446. $\Rightarrow$
  3447. &
  3448. \begin{minipage}{0.55\textwidth}
  3449. \begin{lstlisting}
  3450. (program ()
  3451. ((block62 .
  3452. (seq (assign tmp54 (read))
  3453. (if (eq? tmp54 2)
  3454. (goto block59)
  3455. (goto block60))))
  3456. (block61 .
  3457. (seq (assign tmp53 (read))
  3458. (if (eq? tmp53 0)
  3459. (goto block57)
  3460. (goto block58))))
  3461. (block60 . (goto block56))
  3462. (block59 . (goto block55))
  3463. (block58 . (goto block56))
  3464. (block57 . (goto block55))
  3465. (block56 . (return (+ 700 77)))
  3466. (block55 . (return (+ 10 32)))
  3467. (start .
  3468. (seq (assign tmp52 (read))
  3469. (if (eq? tmp52 1)
  3470. (goto block61)
  3471. (goto block62))))))
  3472. \end{lstlisting}
  3473. \end{minipage}
  3474. \end{tabular}
  3475. \caption{Example translation from $R_2$ to $C_1$
  3476. via the \code{explicate-control}.}
  3477. \label{fig:explicate-control-s1-38}
  3478. \end{figure}
  3479. The nice thing about the output of \code{explicate-control} is that
  3480. there are no unnecessary uses of \code{eq?} and every use of
  3481. \code{eq?} is part of a conditional jump. The down-side of this output
  3482. is that it includes trivial blocks, such as \code{block57} through
  3483. \code{block60}, that only jump to another block. We discuss a solution
  3484. to this problem in Section~\ref{sec:opt-jumps}.
  3485. Recall that in Section~\ref{sec:explicate-control-r1} we implement the
  3486. \code{explicate-control} pass for $R_1$ using two mutually recursive
  3487. functions, \code{explicate-control-tail} and
  3488. \code{explicate-control-assign}. The former function translated
  3489. expressions in tail position whereas the later function translated
  3490. expressions on the right-hand-side of a \key{let}. With the addition
  3491. of \key{if} expression in $R_2$ we have a new kind of context to deal
  3492. with: the predicate position of the \key{if}. So we shall need another
  3493. function, \code{explicate-control-pred}, that takes an $R_2$
  3494. expression and two pieces of $C_1$ code (two $\Tail$'s) for the
  3495. then-branch and else-branch. The output of
  3496. \code{explicate-control-pred} is a $C_1$ $\Tail$. However, these
  3497. three functions also need to construct the control-flow graph, which we
  3498. recommend they do via updates to a global variable. Next we consider
  3499. the specific additions to the tail and assign functions, and some of
  3500. cases for the pred function.
  3501. The \code{explicate-control-tail} function needs an additional case
  3502. for \key{if}. The branches of the \key{if} inherit the current
  3503. context, so they are in tail position. Let $B_1$ be the result of
  3504. \code{explicate-control-tail} on the $\itm{thn}$ branch and $B_2$ be
  3505. the result of apply \code{explicate-control-tail} to the $\itm{else}$
  3506. branch. Then the \key{if} translates to the block $B_3$ which is the
  3507. result of applying \code{explicate-control-pred} to the predicate
  3508. $\itm{cnd}$ and the blocks $B_1$ and $B_2$.
  3509. \[
  3510. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  3511. \]
  3512. Next we consider the case for \key{if} in the
  3513. \code{explicate-control-assign} function. So the context of the
  3514. \key{if} is an assignment to some variable $x$ and then the control
  3515. continues to some block $B_1$. The code that we generate for both the
  3516. $\itm{thn}$ and $\itm{els}$ branches shall both need to continue to
  3517. $B_1$, so we add $B_1$ to the control flow graph with a fresh label
  3518. $\ell_1$. Again, the branches of the \key{if} inherit the current
  3519. context, so that are in assignment positions. Let $B_2$ be the result
  3520. of applying \code{explicate-control-assign} to the $\itm{thn}$ branch,
  3521. variable $x$, and the block \code{(goto $\ell_1$)}. Let $B_3$ be the
  3522. result of applying \code{explicate-control-assign} to the $\itm{else}$
  3523. branch, variable $x$, and the block \code{(goto $\ell_1$)}. The
  3524. \key{if} translates to the block $B_4$ which is the result of applying
  3525. \code{explicate-control-pred} to the predicate $\itm{cnd}$ and the
  3526. blocks $B_2$ and $B_3$.
  3527. \[
  3528. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  3529. \]
  3530. The function \code{explicate-control-pred} will need a case for every
  3531. expression that can have type \code{Boolean}. We detail a few cases
  3532. here and leave the rest for the reader. The input to this function is
  3533. an expression and two blocks, $B_1$ and $B_2$, for the branches of the
  3534. enclosing \key{if}. One of the base cases of this function is when the
  3535. expression is a less-than comparison. We translate it to a
  3536. conditional \code{goto}. We need labels for the two branches $B_1$ and
  3537. $B_2$, so we add them to the control flow graph and obtain some labels
  3538. $\ell_1$ and $\ell_2$. The translation of the less-than comparison is
  3539. as follows.
  3540. \[
  3541. (\key{<}\;e_1\;e_2) \quad\Rightarrow\quad
  3542. (\key{if}\;(\key{<}\;e_1\;e_2)\;(\key{goto}\;\ell_1)\;(\key{goto}\;\ell_2))
  3543. \]
  3544. The case for \key{if} in \code{explicate-control-pred} is particularly
  3545. illuminating, as it deals with the challenges that we discussed above
  3546. regarding the example of the nested \key{if} expressions. Again, we
  3547. add the two input branches $B_1$ and $B_2$ to the control flow graph
  3548. and obtain the labels $\ell_1$ and $\ell_2$. The branches $\itm{thn}$
  3549. and $\itm{els}$ of the current \key{if} inherit their context from the
  3550. current one, i.e., predicate context. So we apply
  3551. \code{explicate-control-pred} to $\itm{thn}$ with the two blocks
  3552. \code{(goto $\ell_1$)} and \code{(goto $\ell_2$)}, to obtain $B_3$.
  3553. Similarly for the $\itm{els}$ branch, to obtain $B_4$.
  3554. Finally, we apply \code{explicate-control-pred} to
  3555. the predicate $\itm{cnd}$ and the blocks $B_3$ and $B_4$
  3556. to obtain the result $B_5$.
  3557. \[
  3558. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  3559. \quad\Rightarrow\quad
  3560. B_5
  3561. \]
  3562. \begin{exercise}\normalfont
  3563. Implement the pass \code{explicate-code} by adding the cases for
  3564. \key{if} to the functions for tail and assignment contexts, and
  3565. implement the function for predicate contexts. Create test cases
  3566. that exercise all of the new cases in the code for this pass.
  3567. \end{exercise}
  3568. \section{Select Instructions}
  3569. \label{sec:select-r2}
  3570. Recall that the \code{select-instructions} pass lowers from our
  3571. $C$-like intermediate representation to the pseudo-x86 language, which
  3572. is suitable for conducting register allocation. The pass is
  3573. implemented using three auxiliary functions, one for each of the
  3574. non-terminals $\Arg$, $\Stmt$, and $\Tail$.
  3575. For $\Arg$, we have new cases for the Booleans. We take the usual
  3576. approach of encoding them as integers, with true as 1 and false as 0.
  3577. \[
  3578. \key{\#t} \Rightarrow \key{1}
  3579. \qquad
  3580. \key{\#f} \Rightarrow \key{0}
  3581. \]
  3582. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  3583. be implemented in terms of \code{xorq} as we discussed at the
  3584. beginning of this section. Given an assignment \code{(assign
  3585. $\itm{lhs}$ (not $\Arg$))}, if the left-hand side $\itm{lhs}$ is
  3586. the same as $\Arg$, then just the \code{xorq} suffices:
  3587. \[
  3588. (\key{assign}\; x\; (\key{not}\; x))
  3589. \quad\Rightarrow\quad
  3590. ((\key{xorq}\;(\key{int}\;1)\;x'))
  3591. \]
  3592. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  3593. semantics of x86. Let $\Arg'$ be the result of recursively processing
  3594. $\Arg$. Then we have
  3595. \[
  3596. (\key{assign}\; \itm{lhs}\; (\key{not}\; \Arg))
  3597. \quad\Rightarrow\quad
  3598. ((\key{movq}\; \Arg'\; \itm{lhs}') \; (\key{xorq}\;(\key{int}\;1)\;\itm{lhs}'))
  3599. \]
  3600. Next consider the cases for \code{eq?} and less-than comparison.
  3601. Translating these operations to x86 is slightly involved due to the
  3602. unusual nature of the \key{cmpq} instruction discussed above. We
  3603. recommend translating an assignment from \code{eq?} into the following
  3604. sequence of three instructions. \\
  3605. \begin{tabular}{lll}
  3606. \begin{minipage}{0.4\textwidth}
  3607. \begin{lstlisting}
  3608. (assign |$\itm{lhs}$| (eq? |$\Arg_1$| |$\Arg_2$|))
  3609. \end{lstlisting}
  3610. \end{minipage}
  3611. &
  3612. $\Rightarrow$
  3613. &
  3614. \begin{minipage}{0.4\textwidth}
  3615. \begin{lstlisting}
  3616. (cmpq |$\Arg'_2$| |$\Arg'_1$|)
  3617. (set e (byte-reg al))
  3618. (movzbq (byte-reg al) |$\itm{lhs}'$|)
  3619. \end{lstlisting}
  3620. \end{minipage}
  3621. \end{tabular} \\
  3622. Regarding the $\Tail$ non-terminal, we have two new cases, for
  3623. \key{goto} and conditional \key{goto}. Both are straightforward
  3624. to handle. A \key{goto} becomes a jump instruction.
  3625. \[
  3626. (\key{goto}\; \ell) \quad \Rightarrow \quad ((\key{jmp} \;\ell))
  3627. \]
  3628. A conditional \key{goto} becomes a compare instruction followed
  3629. by a conditional jump (for ``then'') and the fall-through is
  3630. to a regular jump (for ``else'').\\
  3631. \begin{tabular}{lll}
  3632. \begin{minipage}{0.4\textwidth}
  3633. \begin{lstlisting}
  3634. (if (eq? |$\Arg_1$| |$\Arg_2$|)
  3635. (goto |$\ell_1$|)
  3636. (goto |$\ell_2$|))
  3637. \end{lstlisting}
  3638. \end{minipage}
  3639. &
  3640. $\Rightarrow$
  3641. &
  3642. \begin{minipage}{0.4\textwidth}
  3643. \begin{lstlisting}
  3644. ((cmpq |$\Arg'_2$| |$\Arg'_1$|)
  3645. (jmp-if e |$\ell_1$|)
  3646. (jmp |$\ell_2$|))
  3647. \end{lstlisting}
  3648. \end{minipage}
  3649. \end{tabular} \\
  3650. \begin{exercise}\normalfont
  3651. Expand your \code{select-instructions} pass to handle the new features
  3652. of the $R_2$ language. Test the pass on all the examples you have
  3653. created and make sure that you have some test programs that use the
  3654. \code{eq?} and \code{<} operators, creating some if necessary. Test
  3655. the output using the \code{interp-x86} interpreter
  3656. (Appendix~\ref{appendix:interp}).
  3657. \end{exercise}
  3658. \section{Register Allocation}
  3659. \label{sec:register-allocation-r2}
  3660. The changes required for $R_2$ affect the liveness analysis, building
  3661. the interference graph, and assigning homes, but the graph coloring
  3662. algorithm itself does not need to change.
  3663. \subsection{Liveness Analysis}
  3664. \label{sec:liveness-analysis-r2}
  3665. Recall that for $R_1$ we implemented liveness analysis for a single
  3666. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  3667. addition of \key{if} expressions to $R_2$, \code{explicate-control}
  3668. now produces many basic blocks arranged in a control-flow graph. The
  3669. first question we need to consider is in what order should we process
  3670. the basic blocks? Recall that to perform liveness analysis, we need to
  3671. know the live-after set. If a basic block has no successor blocks,
  3672. then it has an empty live-after set and we can immediately apply
  3673. liveness analysis to it. If a basic block has some successors, then we
  3674. need to complete liveness analysis on those blocks first.
  3675. Furthermore, we know that the control flow graph does not contain any
  3676. cycles (it is a DAG, that is, a directed acyclic graph)\footnote{If we
  3677. were to add loops to the language, then the CFG could contain cycles
  3678. and we would instead need to use the classic worklist algorithm for
  3679. computing the fixed point of the liveness
  3680. analysis~\citep{Aho:1986qf}.}. What all this amounts to is that we
  3681. need to process the basic blocks in reverse topological order. We
  3682. recommend using the \code{tsort} and \code{transpose} functions of the
  3683. Racket \code{graph} package to obtain this ordering.
  3684. The next question is how to compute the live-after set of a block
  3685. given the live-before sets of all its successor blocks. During
  3686. compilation we do not know which way the branch will go, so we do not
  3687. know which of the successor's live-before set to use. The solution
  3688. comes from the observation that there is no harm in identifying more
  3689. variables as live than absolutely necessary. Thus, we can take the
  3690. union of the live-before sets from all the successors to be the
  3691. live-after set for the block. Once we have computed the live-after
  3692. set, we can proceed to perform liveness analysis on the block just as
  3693. we did in Section~\ref{sec:liveness-analysis-r1}.
  3694. The helper functions for computing the variables in an instruction's
  3695. argument and for computing the variables read-from ($R$) or written-to
  3696. ($W$) by an instruction need to be updated to handle the new kinds of
  3697. arguments and instructions in x86$_1$.
  3698. \subsection{Build Interference}
  3699. \label{sec:build-interference-r2}
  3700. Many of the new instructions in x86$_1$ can be handled in the same way
  3701. as the instructions in x86$_0$. Thus, if your code was already quite
  3702. general, it will not need to be changed to handle the new
  3703. instructions. If not, I recommend that you change your code to be more
  3704. general. The \key{movzbq} instruction should be handled like the
  3705. \key{movq} instruction.
  3706. %% \subsection{Assign Homes}
  3707. %% \label{sec:assign-homes-r2}
  3708. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  3709. %% to be updated to handle the \key{if} statement, simply by recursively
  3710. %% processing the child nodes. Hopefully your code already handles the
  3711. %% other new instructions, but if not, you can generalize your code.
  3712. \begin{exercise}\normalfont
  3713. Update the \code{register-allocation} pass so that it works for $R_2$
  3714. and test your compiler using your previously created programs on the
  3715. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  3716. \end{exercise}
  3717. %% \section{Lower Conditionals (New Pass)}
  3718. %% \label{sec:lower-conditionals}
  3719. %% In the \code{select-instructions} pass we decided to procrastinate in
  3720. %% the lowering of the \key{if} statement, thereby making liveness
  3721. %% analysis easier. Now we need to make up for that and turn the \key{if}
  3722. %% statement into the appropriate instruction sequence. The following
  3723. %% translation gives the general idea. If the condition is true, we need
  3724. %% to execute the $\itm{thns}$ branch and otherwise we need to execute
  3725. %% the $\itm{elss}$ branch. So we use \key{cmpq} and do a conditional
  3726. %% jump to the $\itm{thenlabel}$, choosing the condition code $cc$ that
  3727. %% is appropriate for the comparison operator \itm{cmp}. If the
  3728. %% condition is false, we fall through to the $\itm{elss}$ branch. At the
  3729. %% end of the $\itm{elss}$ branch we need to take care to not fall
  3730. %% through to the $\itm{thns}$ branch. So we jump to the
  3731. %% $\itm{endlabel}$. All of the labels in the generated code should be
  3732. %% created with \code{gensym}.
  3733. %% \begin{tabular}{lll}
  3734. %% \begin{minipage}{0.4\textwidth}
  3735. %% \begin{lstlisting}
  3736. %% (if (|\itm{cmp}| |$\Arg_1$| |$\Arg_2$|) |$\itm{thns}$| |$\itm{elss}$|)
  3737. %% \end{lstlisting}
  3738. %% \end{minipage}
  3739. %% &
  3740. %% $\Rightarrow$
  3741. %% &
  3742. %% \begin{minipage}{0.4\textwidth}
  3743. %% \begin{lstlisting}
  3744. %% (cmpq |$\Arg_2$| |$\Arg_1$|)
  3745. %% (jmp-if |$cc$| |$\itm{thenlabel}$|)
  3746. %% |$\itm{elss}$|
  3747. %% (jmp |$\itm{endlabel}$|)
  3748. %% (label |$\itm{thenlabel}$|)
  3749. %% |$\itm{thns}$|
  3750. %% (label |$\itm{endlabel}$|)
  3751. %% \end{lstlisting}
  3752. %% \end{minipage}
  3753. %% \end{tabular}
  3754. %% \begin{exercise}\normalfont
  3755. %% Implement the \code{lower-conditionals} pass. Test your compiler using
  3756. %% your previously created programs on the \code{interp-x86} interpreter
  3757. %% (Appendix~\ref{appendix:interp}).
  3758. %% \end{exercise}
  3759. \section{Patch Instructions}
  3760. The second argument of the \key{cmpq} instruction must not be an
  3761. immediate value (such as a literal integer). So if you are comparing
  3762. two immediates, we recommend inserting a \key{movq} instruction to put
  3763. the second argument in \key{rax}.
  3764. %
  3765. The second argument of the \key{movzbq} must be a register.
  3766. %
  3767. There are no special restrictions on the x86 instructions
  3768. \key{jmp-if}, \key{jmp}, and \key{label}.
  3769. \begin{exercise}\normalfont
  3770. Update \code{patch-instructions} to handle the new x86 instructions.
  3771. Test your compiler using your previously created programs on the
  3772. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  3773. \end{exercise}
  3774. \section{An Example Translation}
  3775. Figure~\ref{fig:if-example-x86} shows a simple example program in
  3776. $R_2$ translated to x86, showing the results of
  3777. \code{explicate-control}, \code{select-instructions}, and the final
  3778. x86 assembly code.
  3779. \begin{figure}[tbp]
  3780. \begin{tabular}{lll}
  3781. \begin{minipage}{0.5\textwidth}
  3782. % s1_20.rkt
  3783. \begin{lstlisting}
  3784. (program ()
  3785. (if (eq? (read) 1) 42 0))
  3786. \end{lstlisting}
  3787. $\Downarrow$
  3788. \begin{lstlisting}
  3789. (program ()
  3790. ((block32 . (return 0))
  3791. (block31 . (return 42))
  3792. (start .
  3793. (seq (assign tmp30 (read))
  3794. (if (eq? tmp30 1)
  3795. (goto block31)
  3796. (goto block32))))))
  3797. \end{lstlisting}
  3798. $\Downarrow$
  3799. \begin{lstlisting}
  3800. (program ((locals . (tmp30)))
  3801. ((block32 .
  3802. (block ()
  3803. (movq (int 0) (reg rax))
  3804. (jmp conclusion)))
  3805. (block31 .
  3806. (block ()
  3807. (movq (int 42) (reg rax))
  3808. (jmp conclusion)))
  3809. (start .
  3810. (block ()
  3811. (callq read_int)
  3812. (movq (reg rax) (var tmp30))
  3813. (cmpq (int 1) (var tmp30))
  3814. (jmp-if e block31)
  3815. (jmp block32)))))
  3816. \end{lstlisting}
  3817. \end{minipage}
  3818. &
  3819. $\Rightarrow$
  3820. \begin{minipage}{0.4\textwidth}
  3821. \begin{lstlisting}
  3822. _block31:
  3823. movq $42, %rax
  3824. jmp _conclusion
  3825. _block32:
  3826. movq $0, %rax
  3827. jmp _conclusion
  3828. _start:
  3829. callq _read_int
  3830. movq %rax, %rcx
  3831. cmpq $1, %rcx
  3832. je _block31
  3833. jmp _block32
  3834. .globl _main
  3835. _main:
  3836. pushq %rbp
  3837. movq %rsp, %rbp
  3838. pushq %r12
  3839. pushq %rbx
  3840. pushq %r13
  3841. pushq %r14
  3842. subq $0, %rsp
  3843. jmp _start
  3844. _conclusion:
  3845. addq $0, %rsp
  3846. popq %r14
  3847. popq %r13
  3848. popq %rbx
  3849. popq %r12
  3850. popq %rbp
  3851. retq
  3852. \end{lstlisting}
  3853. \end{minipage}
  3854. \end{tabular}
  3855. \caption{Example compilation of an \key{if} expression to x86.}
  3856. \label{fig:if-example-x86}
  3857. \end{figure}
  3858. \begin{figure}[p]
  3859. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3860. \node (R2) at (0,2) {\large $R_2$};
  3861. \node (R2-2) at (3,2) {\large $R_2$};
  3862. \node (R2-3) at (6,2) {\large $R_2$};
  3863. \node (R2-4) at (9,2) {\large $R_2$};
  3864. \node (R2-5) at (12,2) {\large $R_2$};
  3865. \node (C1-1) at (6,0) {\large $C_1$};
  3866. \node (C1-2) at (3,0) {\large $C_1$};
  3867. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  3868. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  3869. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}$};
  3870. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  3871. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  3872. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  3873. \path[->,bend left=15] (R2) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R2-2);
  3874. \path[->,bend left=15] (R2-2) edge [above] node {\ttfamily\footnotesize\color{red} shrink} (R2-3);
  3875. \path[->,bend left=15] (R2-3) edge [above] node {\ttfamily\footnotesize uniquify} (R2-4);
  3876. \path[->,bend left=15] (R2-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R2-5);
  3877. \path[->,bend left=15] (R2-5) edge [right] node {\ttfamily\footnotesize\color{red} explicate-control} (C1-1);
  3878. \path[->,bend right=15] (C1-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C1-2);
  3879. \path[->,bend right=15] (C1-2) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  3880. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  3881. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  3882. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  3883. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  3884. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize\color{red} print-x86 } (x86-5);
  3885. \end{tikzpicture}
  3886. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  3887. \label{fig:R2-passes}
  3888. \end{figure}
  3889. Figure~\ref{fig:R2-passes} lists all the passes needed for the
  3890. compilation of $R_2$.
  3891. \section{Challenge: Optimize Jumps$^{*}$}
  3892. \label{sec:opt-jumps}
  3893. UNDER CONSTRUCTION
  3894. %% \section{Challenge: Optimizing Conditions$^{*}$}
  3895. %% \label{sec:opt-if}
  3896. %% A close inspection of the x86 code generated in
  3897. %% Figure~\ref{fig:if-example-x86} reveals some redundant computation
  3898. %% regarding the condition of the \key{if}. We compare \key{rcx} to $1$
  3899. %% twice using \key{cmpq} as follows.
  3900. %% % Wierd LaTeX bug if I remove the following. -Jeremy
  3901. %% % Does it have to do with page breaks?
  3902. %% \begin{lstlisting}
  3903. %% \end{lstlisting}
  3904. %% \begin{lstlisting}
  3905. %% cmpq $1, %rcx
  3906. %% sete %al
  3907. %% movzbq %al, %rcx
  3908. %% cmpq $1, %rcx
  3909. %% je then21288
  3910. %% \end{lstlisting}
  3911. %% The reason for this non-optimal code has to do with the \code{flatten}
  3912. %% pass earlier in this Chapter. We recommended flattening the condition
  3913. %% to an $\Arg$ and then comparing with \code{\#t}. But if the condition
  3914. %% is already an \code{eq?} test, then we would like to use that
  3915. %% directly. In fact, for many of the expressions of Boolean type, we can
  3916. %% generate more optimized code. For example, if the condition is
  3917. %% \code{\#t} or \code{\#f}, we do not need to generate an \code{if} at
  3918. %% all. If the condition is a \code{let}, we can optimize based on the
  3919. %% form of its body. If the condition is a \code{not}, then we can flip
  3920. %% the two branches.
  3921. %% %
  3922. %% \margincomment{\tiny We could do even better by converting to basic
  3923. %% blocks.\\ --Jeremy}
  3924. %% %
  3925. %% On the other hand, if the condition is a \code{and}
  3926. %% or another \code{if}, we should flatten them into an $\Arg$ to avoid
  3927. %% code duplication.
  3928. %% Figure~\ref{fig:opt-if} shows an example program and the result of
  3929. %% applying the above suggested optimizations.
  3930. %% \begin{exercise}\normalfont
  3931. %% Change the \code{flatten} pass to improve the code that gets
  3932. %% generated for \code{if} expressions. We recommend writing a helper
  3933. %% function that recursively traverses the condition of the \code{if}.
  3934. %% \end{exercise}
  3935. %% \begin{figure}[tbp]
  3936. %% \begin{tabular}{lll}
  3937. %% \begin{minipage}{0.5\textwidth}
  3938. %% \begin{lstlisting}
  3939. %% (program
  3940. %% (if (let ([x 1])
  3941. %% (not (eq? x (read))))
  3942. %% 777
  3943. %% 42))
  3944. %% \end{lstlisting}
  3945. %% $\Downarrow$
  3946. %% \begin{lstlisting}
  3947. %% (program (x.1 if.2 tmp.3)
  3948. %% (type Integer)
  3949. %% (assign x.1 1)
  3950. %% (assign tmp.3 (read))
  3951. %% (if (eq? x.1 tmp.3)
  3952. %% ((assign if.2 42))
  3953. %% ((assign if.2 777)))
  3954. %% (return if.2))
  3955. %% \end{lstlisting}
  3956. %% $\Downarrow$
  3957. %% \begin{lstlisting}
  3958. %% (program (x.1 if.2 tmp.3)
  3959. %% (type Integer)
  3960. %% (movq (int 1) (var x.1))
  3961. %% (callq read_int)
  3962. %% (movq (reg rax) (var tmp.3))
  3963. %% (if (eq? (var x.1) (var tmp.3))
  3964. %% ((movq (int 42) (var if.2)))
  3965. %% ((movq (int 777) (var if.2))))
  3966. %% (movq (var if.2) (reg rax)))
  3967. %% \end{lstlisting}
  3968. %% \end{minipage}
  3969. %% &
  3970. %% $\Rightarrow$
  3971. %% \begin{minipage}{0.4\textwidth}
  3972. %% \begin{lstlisting}
  3973. %% .globl _main
  3974. %% _main:
  3975. %% pushq %rbp
  3976. %% movq %rsp, %rbp
  3977. %% pushq %r13
  3978. %% pushq %r14
  3979. %% pushq %r12
  3980. %% pushq %rbx
  3981. %% subq $0, %rsp
  3982. %% movq $1, %rbx
  3983. %% callq _read_int
  3984. %% movq %rax, %rcx
  3985. %% cmpq %rcx, %rbx
  3986. %% je then35989
  3987. %% movq $777, %rbx
  3988. %% jmp if_end35990
  3989. %% then35989:
  3990. %% movq $42, %rbx
  3991. %% if_end35990:
  3992. %% movq %rbx, %rax
  3993. %% movq %rax, %rdi
  3994. %% callq _print_int
  3995. %% movq $0, %rax
  3996. %% addq $0, %rsp
  3997. %% popq %rbx
  3998. %% popq %r12
  3999. %% popq %r14
  4000. %% popq %r13
  4001. %% popq %rbp
  4002. %% retq
  4003. %% \end{lstlisting}
  4004. %% \end{minipage}
  4005. %% \end{tabular}
  4006. %% \caption{Example program with optimized conditionals.}
  4007. %% \label{fig:opt-if}
  4008. %% \end{figure}
  4009. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4010. \chapter{Tuples and Garbage Collection}
  4011. \label{ch:tuples}
  4012. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  4013. things to discuss in this chapter. \\ --Jeremy}
  4014. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  4015. all the IR grammars are spelled out! \\ --Jeremy}
  4016. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  4017. but keep type annotations on vector creation and local variables, function
  4018. parameters, etc. \\ --Jeremy}
  4019. \margincomment{\scriptsize Be more explicit about how to deal with
  4020. the root stack. \\ --Jeremy}
  4021. In this chapter we study the implementation of mutable tuples (called
  4022. ``vectors'' in Racket). This language feature is the first to use the
  4023. computer's \emph{heap} because the lifetime of a Racket tuple is
  4024. indefinite, that is, a tuple lives forever from the programmer's
  4025. viewpoint. Of course, from an implementer's viewpoint, it is important
  4026. to reclaim the space associated with a tuple when it is no longer
  4027. needed, which is why we also study \emph{garbage collection}
  4028. techniques in this chapter.
  4029. Section~\ref{sec:r3} introduces the $R_3$ language including its
  4030. interpreter and type checker. The $R_3$ language extends the $R_2$
  4031. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  4032. ``void'' value. The reason for including the later is that the
  4033. \code{vector-set!} operation returns a value of type
  4034. \code{Void}\footnote{This may sound contradictory, but Racket's
  4035. \code{Void} type corresponds to what is more commonly called the
  4036. \code{Unit} type. This type is inhabited by a single value that is
  4037. usually written \code{unit} or \code{()}\citep{Pierce:2002hj}.}.
  4038. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  4039. copying live objects back and forth between two halves of the
  4040. heap. The garbage collector requires coordination with the compiler so
  4041. that it can see all of the \emph{root} pointers, that is, pointers in
  4042. registers or on the procedure call stack.
  4043. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  4044. discuss all the necessary changes and additions to the compiler
  4045. passes, including a new compiler pass named \code{expose-allocation}.
  4046. \section{The $R_3$ Language}
  4047. \label{sec:r3}
  4048. Figure~\ref{fig:r3-syntax} defines the syntax for $R_3$, which
  4049. includes three new forms for creating a tuple, reading an element of a
  4050. tuple, and writing to an element of a tuple. The program in
  4051. Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  4052. create a 3-tuple \code{t} and a 1-tuple. The 1-tuple is stored at
  4053. index $2$ of the 3-tuple, demonstrating that tuples are first-class
  4054. values. The element at index $1$ of \code{t} is \code{\#t}, so the
  4055. ``then'' branch is taken. The element at index $0$ of \code{t} is
  4056. $40$, to which we add the $2$, the element at index $0$ of the
  4057. 1-tuple.
  4058. \begin{figure}[tbp]
  4059. \begin{lstlisting}
  4060. (let ([t (vector 40 #t (vector 2))])
  4061. (if (vector-ref t 1)
  4062. (+ (vector-ref t 0)
  4063. (vector-ref (vector-ref t 2) 0))
  4064. 44))
  4065. \end{lstlisting}
  4066. \caption{Example program that creates tuples and reads from them.}
  4067. \label{fig:vector-eg}
  4068. \end{figure}
  4069. \begin{figure}[tbp]
  4070. \centering
  4071. \fbox{
  4072. \begin{minipage}{0.96\textwidth}
  4073. \[
  4074. \begin{array}{lcl}
  4075. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  4076. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}\\
  4077. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4078. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  4079. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  4080. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  4081. \mid (\key{and}\;\Exp\;\Exp)
  4082. \mid (\key{or}\;\Exp\;\Exp)
  4083. \mid (\key{not}\;\Exp) } \\
  4084. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  4085. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  4086. &\mid& (\key{vector}\;\Exp^{+})
  4087. \mid (\key{vector-ref}\;\Exp\;\Int) \\
  4088. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)\\
  4089. &\mid& (\key{void}) \\
  4090. R_3 &::=& (\key{program} \; \Exp)
  4091. \end{array}
  4092. \]
  4093. \end{minipage}
  4094. }
  4095. \caption{The syntax of $R_3$, extending $R_2$
  4096. (Figure~\ref{fig:r2-syntax}) with tuples.}
  4097. \label{fig:r3-syntax}
  4098. \end{figure}
  4099. Tuples are our first encounter with heap-allocated data, which raises
  4100. several interesting issues. First, variable binding performs a
  4101. shallow-copy when dealing with tuples, which means that different
  4102. variables can refer to the same tuple, i.e., different variables can
  4103. be \emph{aliases} for the same thing. Consider the following example
  4104. in which both \code{t1} and \code{t2} refer to the same tuple. Thus,
  4105. the mutation through \code{t2} is visible when referencing the tuple
  4106. from \code{t1}, so the result of this program is \code{42}.
  4107. \begin{lstlisting}
  4108. (let ([t1 (vector 3 7)])
  4109. (let ([t2 t1])
  4110. (let ([_ (vector-set! t2 0 42)])
  4111. (vector-ref t1 0))))
  4112. \end{lstlisting}
  4113. The next issue concerns the lifetime of tuples. Of course, they are
  4114. created by the \code{vector} form, but when does their lifetime end?
  4115. Notice that the grammar in Figure~\ref{fig:r3-syntax} does not include
  4116. an operation for deleting tuples. Furthermore, the lifetime of a tuple
  4117. is not tied to any notion of static scoping. For example, the
  4118. following program returns \code{3} even though the variable \code{t}
  4119. goes out of scope prior to accessing the vector.
  4120. \begin{lstlisting}
  4121. (vector-ref
  4122. (let ([t (vector 3 7)])
  4123. t)
  4124. 0)
  4125. \end{lstlisting}
  4126. From the perspective of programmer-observable behavior, tuples live
  4127. forever. Of course, if they really lived forever, then many programs
  4128. would run out of memory.\footnote{The $R_3$ language does not have
  4129. looping or recursive function, so it is nigh impossible to write a
  4130. program in $R_3$ that will run out of memory. However, we add
  4131. recursive functions in the next Chapter!} A Racket implementation
  4132. must therefore perform automatic garbage collection.
  4133. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  4134. $R_3$ language and Figure~\ref{fig:typecheck-R3} shows the type
  4135. checker. The additions to the interpreter are straightforward but the
  4136. updates to the type checker deserve some explanation. As we shall see
  4137. in Section~\ref{sec:GC}, we need to know which variables are pointers
  4138. into the heap, that is, which variables are vectors. Also, when
  4139. allocating a vector, we shall need to know which elements of the
  4140. vector are pointers. We can obtain this information during type
  4141. checking and when we uncover local variables. The type checker in
  4142. Figure~\ref{fig:typecheck-R3} not only computes the type of an
  4143. expression, it also wraps every sub-expression $e$ with the form
  4144. $(\key{has-type}\; e\; T)$, where $T$ is $e$'s type. Subsequently, in
  4145. the \code{uncover-locals} pass (Section~\ref{sec:uncover-locals-r3})
  4146. this type information is propagated to all variables (including the
  4147. temporaries generated by \code{remove-complex-opera*}).
  4148. \begin{figure}[tbp]
  4149. \begin{lstlisting}
  4150. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  4151. (define (interp-op op)
  4152. (match op
  4153. ...
  4154. ['vector vector]
  4155. ['vector-ref vector-ref]
  4156. ['vector-set! vector-set!]
  4157. [else (error 'interp-op "unknown operator")]))
  4158. (define (interp-R3 env)
  4159. (lambda (e)
  4160. (match e
  4161. ...
  4162. [else (error 'interp-R3 "unrecognized expression")]
  4163. )))
  4164. \end{lstlisting}
  4165. \caption{Interpreter for the $R_3$ language.}
  4166. \label{fig:interp-R3}
  4167. \end{figure}
  4168. \begin{figure}[tbp]
  4169. \begin{lstlisting}
  4170. (define (type-check-exp env)
  4171. (lambda (e)
  4172. (define recur (type-check-exp env))
  4173. (match e
  4174. ...
  4175. ['(void) (values '(has-type (void) Void) 'Void)]
  4176. [`(vector ,es ...)
  4177. (define-values (e* t*) (for/lists (e* t*) ([e es])
  4178. (recur e)))
  4179. (let ([t `(Vector ,@t*)])
  4180. (debug "vector/type-check-exp finished vector" t)
  4181. (values `(has-type (vector ,@e*) ,t) t))]
  4182. [`(vector-ref ,e ,i)
  4183. (define-values (e^ t) (recur e))
  4184. (match t
  4185. [`(Vector ,ts ...)
  4186. (unless (and (exact-nonnegative-integer? i) (< i (length ts)))
  4187. (error 'type-check-exp "invalid index ~a" i))
  4188. (let ([t (list-ref ts i)])
  4189. (values `(has-type (vector-ref ,e^ (has-type ,i Integer)) ,t)
  4190. t))]
  4191. [else (error "expected a vector in vector-ref, not" t)])]
  4192. [`(eq? ,arg1 ,arg2)
  4193. (define-values (e1 t1) (recur arg1))
  4194. (define-values (e2 t2) (recur arg2))
  4195. (match* (t1 t2)
  4196. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  4197. (values `(has-type (eq? ,e1 ,e2) Boolean) 'Boolean)]
  4198. [(other wise) ((super type-check-exp env) e)])]
  4199. ...
  4200. )))
  4201. \end{lstlisting}
  4202. \caption{Type checker for the $R_3$ language.}
  4203. \label{fig:typecheck-R3}
  4204. \end{figure}
  4205. \section{Garbage Collection}
  4206. \label{sec:GC}
  4207. Here we study a relatively simple algorithm for garbage collection
  4208. that is the basis of state-of-the-art garbage
  4209. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  4210. particular, we describe a two-space copying
  4211. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  4212. perform the
  4213. copy~\citep{Cheney:1970aa}. Figure~\ref{fig:copying-collector} gives a
  4214. coarse-grained depiction of what happens in a two-space collector,
  4215. showing two time steps, prior to garbage collection on the top and
  4216. after garbage collection on the bottom. In a two-space collector, the
  4217. heap is divided into two parts, the FromSpace and the
  4218. ToSpace. Initially, all allocations go to the FromSpace until there is
  4219. not enough room for the next allocation request. At that point, the
  4220. garbage collector goes to work to make more room.
  4221. The garbage collector must be careful not to reclaim tuples that will
  4222. be used by the program in the future. Of course, it is impossible in
  4223. general to predict what a program will do, but we can over approximate
  4224. the will-be-used tuples by preserving all tuples that could be
  4225. accessed by \emph{any} program given the current computer state. A
  4226. program could access any tuple whose address is in a register or on
  4227. the procedure call stack. These addresses are called the \emph{root
  4228. set}. In addition, a program could access any tuple that is
  4229. transitively reachable from the root set. Thus, it is safe for the
  4230. garbage collector to reclaim the tuples that are not reachable in this
  4231. way.
  4232. So the goal of the garbage collector is twofold:
  4233. \begin{enumerate}
  4234. \item preserve all tuple that are reachable from the root set via a
  4235. path of pointers, that is, the \emph{live} tuples, and
  4236. \item reclaim the memory of everything else, that is, the
  4237. \emph{garbage}.
  4238. \end{enumerate}
  4239. A copying collector accomplishes this by copying all of the live
  4240. objects from the FromSpace into the ToSpace and then performs a slight
  4241. of hand, treating the ToSpace as the new FromSpace and the old
  4242. FromSpace as the new ToSpace. In the example of
  4243. Figure~\ref{fig:copying-collector}, there are three pointers in the
  4244. root set, one in a register and two on the stack. All of the live
  4245. objects have been copied to the ToSpace (the right-hand side of
  4246. Figure~\ref{fig:copying-collector}) in a way that preserves the
  4247. pointer relationships. For example, the pointer in the register still
  4248. points to a 2-tuple whose first element is a 3-tuple and second
  4249. element is a 2-tuple. There are four tuples that are not reachable
  4250. from the root set and therefore do not get copied into the ToSpace.
  4251. (The situation in Figure~\ref{fig:copying-collector}, with a
  4252. cycle, cannot be created by a well-typed program in $R_3$. However,
  4253. creating cycles will be possible once we get to $R_6$. We design
  4254. the garbage collector to deal with cycles to begin with, so we will
  4255. not need to revisit this issue.)
  4256. \begin{figure}[tbp]
  4257. \centering
  4258. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  4259. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  4260. \caption{A copying collector in action.}
  4261. \label{fig:copying-collector}
  4262. \end{figure}
  4263. There are many alternatives to copying collectors (and their older
  4264. siblings, the generational collectors) when its comes to garbage
  4265. collection, such as mark-and-sweep and reference counting. The
  4266. strengths of copying collectors are that allocation is fast (just a
  4267. test and pointer increment), there is no fragmentation, cyclic garbage
  4268. is collected, and the time complexity of collection only depends on
  4269. the amount of live data, and not on the amount of
  4270. garbage~\citep{Wilson:1992fk}. The main disadvantage of two-space
  4271. copying collectors is that they use a lot of space, though that
  4272. problem is ameliorated in generational collectors. Racket and Scheme
  4273. programs tend to allocate many small objects and generate a lot of
  4274. garbage, so copying and generational collectors are a good fit. Of
  4275. course, garbage collection is an active research topic, especially
  4276. concurrent garbage collection~\citep{Tene:2011kx}. Researchers are
  4277. continuously developing new techniques and revisiting old
  4278. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa}.
  4279. \subsection{Graph Copying via Cheney's Algorithm}
  4280. \label{sec:cheney}
  4281. Let us take a closer look at how the copy works. The allocated objects
  4282. and pointers can be viewed as a graph and we need to copy the part of
  4283. the graph that is reachable from the root set. To make sure we copy
  4284. all of the reachable vertices in the graph, we need an exhaustive
  4285. graph traversal algorithm, such as depth-first search or breadth-first
  4286. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  4287. take into account the possibility of cycles by marking which vertices
  4288. have already been visited, so as to ensure termination of the
  4289. algorithm. These search algorithms also use a data structure such as a
  4290. stack or queue as a to-do list to keep track of the vertices that need
  4291. to be visited. We shall use breadth-first search and a trick due to
  4292. \citet{Cheney:1970aa} for simultaneously representing the queue and
  4293. copying tuples into the ToSpace.
  4294. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  4295. copy progresses. The queue is represented by a chunk of contiguous
  4296. memory at the beginning of the ToSpace, using two pointers to track
  4297. the front and the back of the queue. The algorithm starts by copying
  4298. all tuples that are immediately reachable from the root set into the
  4299. ToSpace to form the initial queue. When we copy a tuple, we mark the
  4300. old tuple to indicate that it has been visited. (We discuss the
  4301. marking in Section~\ref{sec:data-rep-gc}.) Note that any pointers
  4302. inside the copied tuples in the queue still point back to the
  4303. FromSpace. Once the initial queue has been created, the algorithm
  4304. enters a loop in which it repeatedly processes the tuple at the front
  4305. of the queue and pops it off the queue. To process a tuple, the
  4306. algorithm copies all the tuple that are directly reachable from it to
  4307. the ToSpace, placing them at the back of the queue. The algorithm then
  4308. updates the pointers in the popped tuple so they point to the newly
  4309. copied tuples. Getting back to Figure~\ref{fig:cheney}, in the first
  4310. step we copy the tuple whose second element is $42$ to the back of the
  4311. queue. The other pointer goes to a tuple that has already been copied,
  4312. so we do not need to copy it again, but we do need to update the
  4313. pointer to the new location. This can be accomplished by storing a
  4314. \emph{forwarding} pointer to the new location in the old tuple, back
  4315. when we initially copied the tuple into the ToSpace. This completes
  4316. one step of the algorithm. The algorithm continues in this way until
  4317. the front of the queue is empty, that is, until the front catches up
  4318. with the back.
  4319. \begin{figure}[tbp]
  4320. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  4321. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  4322. \label{fig:cheney}
  4323. \end{figure}
  4324. \subsection{Data Representation}
  4325. \label{sec:data-rep-gc}
  4326. The garbage collector places some requirements on the data
  4327. representations used by our compiler. First, the garbage collector
  4328. needs to distinguish between pointers and other kinds of data. There
  4329. are several ways to accomplish this.
  4330. \begin{enumerate}
  4331. \item Attached a tag to each object that identifies what type of
  4332. object it is~\citep{McCarthy:1960dz}.
  4333. \item Store different types of objects in different
  4334. regions~\citep{Steele:1977ab}.
  4335. \item Use type information from the program to either generate
  4336. type-specific code for collecting or to generate tables that can
  4337. guide the
  4338. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  4339. \end{enumerate}
  4340. Dynamically typed languages, such as Lisp, need to tag objects
  4341. anyways, so option 1 is a natural choice for those languages.
  4342. However, $R_3$ is a statically typed language, so it would be
  4343. unfortunate to require tags on every object, especially small and
  4344. pervasive objects like integers and Booleans. Option 3 is the
  4345. best-performing choice for statically typed languages, but comes with
  4346. a relatively high implementation complexity. To keep this chapter to a
  4347. 2-week time budget, we recommend a combination of options 1 and 2,
  4348. with separate strategies used for the stack and the heap.
  4349. Regarding the stack, we recommend using a separate stack for
  4350. pointers~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}, which
  4351. we call a \emph{root stack} (a.k.a. ``shadow stack''). That is, when a
  4352. local variable needs to be spilled and is of type \code{(Vector
  4353. $\Type_1 \ldots \Type_n$)}, then we put it on the root stack instead
  4354. of the normal procedure call stack. Furthermore, we always spill
  4355. vector-typed variables if they are live during a call to the
  4356. collector, thereby ensuring that no pointers are in registers during a
  4357. collection. Figure~\ref{fig:shadow-stack} reproduces the example from
  4358. Figure~\ref{fig:copying-collector} and contrasts it with the data
  4359. layout using a root stack. The root stack contains the two pointers
  4360. from the regular stack and also the pointer in the second
  4361. register.
  4362. \begin{figure}[tbp]
  4363. \centering \includegraphics[width=0.7\textwidth]{figs/root-stack}
  4364. \caption{Maintaining a root stack to facilitate garbage collection.}
  4365. \label{fig:shadow-stack}
  4366. \end{figure}
  4367. The problem of distinguishing between pointers and other kinds of data
  4368. also arises inside of each tuple. We solve this problem by attaching a
  4369. tag, an extra 64-bits, to each tuple. Figure~\ref{fig:tuple-rep} zooms
  4370. in on the tags for two of the tuples in the example from
  4371. Figure~\ref{fig:copying-collector}. Note that we have drawn the bits
  4372. in a big-endian way, from right-to-left, with bit location 0 (the
  4373. least significant bit) on the far right, which corresponds to the
  4374. directional of the x86 shifting instructions \key{salq} (shift
  4375. left) and \key{sarq} (shift right). Part of each tag is dedicated to
  4376. specifying which elements of the tuple are pointers, the part labeled
  4377. ``pointer mask''. Within the pointer mask, a 1 bit indicates there is
  4378. a pointer and a 0 bit indicates some other kind of data. The pointer
  4379. mask starts at bit location 7. We have limited tuples to a maximum
  4380. size of 50 elements, so we just need 50 bits for the pointer mask. The
  4381. tag also contains two other pieces of information. The length of the
  4382. tuple (number of elements) is stored in bits location 1 through
  4383. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  4384. to be copied to the ToSpace. If the bit has value 1, then this tuple
  4385. has not yet been copied. If the bit has value 0 then the entire tag
  4386. is in fact a forwarding pointer. (The lower 3 bits of an pointer are
  4387. always zero anyways because our tuples are 8-byte aligned.)
  4388. \begin{figure}[tbp]
  4389. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  4390. \caption{Representation for tuples in the heap.}
  4391. \label{fig:tuple-rep}
  4392. \end{figure}
  4393. \subsection{Implementation of the Garbage Collector}
  4394. \label{sec:organize-gz}
  4395. The implementation of the garbage collector needs to do a lot of
  4396. bit-level data manipulation and we need to link it with our
  4397. compiler-generated x86 code. Thus, we recommend implementing the
  4398. garbage collector in C~\citep{Kernighan:1988nx} and putting the code
  4399. in the \code{runtime.c} file. Figure~\ref{fig:gc-header} shows the
  4400. interface to the garbage collector. The \code{initialize} function
  4401. creates the FromSpace, ToSpace, and root stack. The \code{initialize}
  4402. function is meant to be called near the beginning of \code{main},
  4403. before the rest of the program executes. The \code{initialize}
  4404. function puts the address of the beginning of the FromSpace into the
  4405. global variable \code{free\_ptr}. The global \code{fromspace\_end}
  4406. points to the address that is 1-past the last element of the
  4407. FromSpace. (We use half-open intervals to represent chunks of
  4408. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} global
  4409. points to the first element of the root stack.
  4410. As long as there is room left in the FromSpace, your generated code
  4411. can allocate tuples simply by moving the \code{free\_ptr} forward.
  4412. %
  4413. \margincomment{\tiny Should we dedicate a register to the free pointer? \\
  4414. --Jeremy}
  4415. %
  4416. The amount of room left in FromSpace is the difference between the
  4417. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  4418. function should be called when there is not enough room left in the
  4419. FromSpace for the next allocation. The \code{collect} function takes
  4420. a pointer to the current top of the root stack (one past the last item
  4421. that was pushed) and the number of bytes that need to be
  4422. allocated. The \code{collect} function performs the copying collection
  4423. and leaves the heap in a state such that the next allocation will
  4424. succeed.
  4425. \begin{figure}[tbp]
  4426. \begin{lstlisting}
  4427. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  4428. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  4429. int64_t* free_ptr;
  4430. int64_t* fromspace_begin;
  4431. int64_t* fromspace_end;
  4432. int64_t** rootstack_begin;
  4433. \end{lstlisting}
  4434. \caption{The compiler's interface to the garbage collector.}
  4435. \label{fig:gc-header}
  4436. \end{figure}
  4437. \begin{exercise}
  4438. In the file \code{runtime.c} you will find the implementation of
  4439. \code{initialize} and a partial implementation of \code{collect}.
  4440. The \code{collect} function calls another function, \code{cheney},
  4441. to perform the actual copy, and that function is left to the reader
  4442. to implement. The following is the prototype for \code{cheney}.
  4443. \begin{lstlisting}
  4444. static void cheney(int64_t** rootstack_ptr);
  4445. \end{lstlisting}
  4446. The parameter \code{rootstack\_ptr} is a pointer to the top of the
  4447. rootstack (which is an array of pointers). The \code{cheney} function
  4448. also communicates with \code{collect} through the global
  4449. variables \code{fromspace\_begin} and \code{fromspace\_end}
  4450. mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  4451. the ToSpace:
  4452. \begin{lstlisting}
  4453. static int64_t* tospace_begin;
  4454. static int64_t* tospace_end;
  4455. \end{lstlisting}
  4456. The job of the \code{cheney} function is to copy all the live
  4457. objects (reachable from the root stack) into the ToSpace, update
  4458. \code{free\_ptr} to point to the next unused spot in the ToSpace,
  4459. update the root stack so that it points to the objects in the
  4460. ToSpace, and finally to swap the global pointers for the FromSpace
  4461. and ToSpace.
  4462. \end{exercise}
  4463. %% \section{Compiler Passes}
  4464. %% \label{sec:code-generation-gc}
  4465. The introduction of garbage collection has a non-trivial impact on our
  4466. compiler passes. We introduce one new compiler pass called
  4467. \code{expose-allocation} and make non-trivial changes to
  4468. \code{type-check}, \code{flatten}, \code{select-instructions},
  4469. \code{allocate-registers}, and \code{print-x86}. The following
  4470. program will serve as our running example. It creates two tuples, one
  4471. nested inside the other. Both tuples have length one. The example then
  4472. accesses the element in the inner tuple tuple via two vector
  4473. references.
  4474. % tests/s2_17.rkt
  4475. \begin{lstlisting}
  4476. (vector-ref (vector-ref (vector (vector 42)) 0) 0))
  4477. \end{lstlisting}
  4478. Next we proceed to discuss the new \code{expose-allocation} pass.
  4479. \section{Expose Allocation}
  4480. \label{sec:expose-allocation}
  4481. The pass \code{expose-allocation} lowers the \code{vector} creation
  4482. form into a conditional call to the collector followed by the
  4483. allocation. We choose to place the \code{expose-allocation} pass
  4484. before \code{flatten} because \code{expose-allocation} introduces new
  4485. variables, which can be done locally with \code{let}, but \code{let}
  4486. is gone after \code{flatten}. In the following, we show the
  4487. transformation for the \code{vector} form into let-bindings for the
  4488. initializing expressions, by a conditional \code{collect}, an
  4489. \code{allocate}, and the initialization of the vector.
  4490. (The \itm{len} is the length of the vector and \itm{bytes} is how many
  4491. total bytes need to be allocated for the vector, which is 8 for the
  4492. tag plus \itm{len} times 8.)
  4493. \begin{lstlisting}
  4494. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  4495. |$\Longrightarrow$|
  4496. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  4497. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  4498. (global-value fromspace_end))
  4499. (void)
  4500. (collect |\itm{bytes}|))])
  4501. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  4502. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  4503. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  4504. |$v$|) ... )))) ...)
  4505. \end{lstlisting}
  4506. (In the above, we suppressed all of the \code{has-type} forms in the
  4507. output for the sake of readability.) The placement of the initializing
  4508. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and
  4509. the sequence of \code{vector-set!}'s is important, as those expressions
  4510. may trigger garbage collection and we do not want an allocated but
  4511. uninitialized tuple to be present during a garbage collection.
  4512. The output of \code{expose-allocation} is a language that extends
  4513. $R_3$ with the three new forms that we use above in the translation of
  4514. \code{vector}.
  4515. \[
  4516. \begin{array}{lcl}
  4517. \Exp &::=& \cdots
  4518. \mid (\key{collect} \,\itm{int})
  4519. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  4520. \mid (\key{global-value} \,\itm{name})
  4521. \end{array}
  4522. \]
  4523. %% The \code{expose-allocation} inserts an \code{initialize} statement at
  4524. %% the beginning of the program which will instruct the garbage collector
  4525. %% to set up the FromSpace, ToSpace, and all the global variables. The
  4526. %% two arguments of \code{initialize} specify the initial allocated space
  4527. %% for the root stack and for the heap.
  4528. %
  4529. %% The \code{expose-allocation} pass annotates all of the local variables
  4530. %% in the \code{program} form with their type.
  4531. Figure~\ref{fig:expose-alloc-output} shows the output of the
  4532. \code{expose-allocation} pass on our running example.
  4533. \begin{figure}[tbp]
  4534. \begin{lstlisting}
  4535. (program ()
  4536. (vector-ref
  4537. (vector-ref
  4538. (let ((vecinit48
  4539. (let ((vecinit44 42))
  4540. (let ((collectret46
  4541. (if (<
  4542. (+ (global-value free_ptr) 16)
  4543. (global-value fromspace_end))
  4544. (void)
  4545. (collect 16))))
  4546. (let ((alloc43 (allocate 1 (Vector Integer))))
  4547. (let ((initret45 (vector-set! alloc43 0 vecinit44)))
  4548. alloc43))))))
  4549. (let ((collectret50
  4550. (if (< (+ (global-value free_ptr) 16)
  4551. (global-value fromspace_end))
  4552. (void)
  4553. (collect 16))))
  4554. (let ((alloc47 (allocate 1 (Vector (Vector Integer)))))
  4555. (let ((initret49 (vector-set! alloc47 0 vecinit48)))
  4556. alloc47))))
  4557. 0)
  4558. 0))
  4559. \end{lstlisting}
  4560. \caption{Output of the \code{expose-allocation} pass, minus
  4561. all of the \code{has-type} forms.}
  4562. \label{fig:expose-alloc-output}
  4563. \end{figure}
  4564. %\clearpage
  4565. \section{Explicate Control and the $C_2$ language}
  4566. \label{sec:explicate-control-r3}
  4567. \begin{figure}[tp]
  4568. \fbox{
  4569. \begin{minipage}{0.96\textwidth}
  4570. \[
  4571. \begin{array}{lcl}
  4572. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }\\
  4573. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  4574. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  4575. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  4576. &\mid& (\key{allocate} \,\itm{int}\,\itm{type})
  4577. \mid (\key{vector-ref}\, \Arg\, \Int) \\
  4578. &\mid& (\key{vector-set!}\,\Arg\,\Int\,\Arg)
  4579. \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) \\
  4580. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp} }
  4581. \mid (\key{collect} \,\itm{int}) \\
  4582. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  4583. &\mid& \gray{(\key{goto}\,\itm{label})
  4584. \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  4585. C_2 & ::= & (\key{program}\;\itm{info}\; ((\itm{label}\,\key{.}\,\Tail)^{+}))
  4586. \end{array}
  4587. \]
  4588. \end{minipage}
  4589. }
  4590. \caption{The $C_2$ language, extending $C_1$
  4591. (Figure~\ref{fig:c1-syntax}) with vectors.}
  4592. \label{fig:c2-syntax}
  4593. \end{figure}
  4594. The output of \code{explicate-control} is a program in the
  4595. intermediate language $C_2$, whose syntax is defined in
  4596. Figure~\ref{fig:c2-syntax}. The new forms of $C_2$ include the
  4597. \key{allocate}, \key{vector-ref}, and \key{vector-set!}, and
  4598. \key{global-value} expressions and the \code{collect} statement. The
  4599. \code{explicate-control} pass can treat these new forms much like the
  4600. other forms.
  4601. \section{Uncover Locals}
  4602. \label{sec:uncover-locals-r3}
  4603. Recall that the \code{uncover-locals} function collects all of the
  4604. local variables so that it can store them in the $\itm{info}$ field of
  4605. the \code{program} form. Also recall that we need to know the types of
  4606. all the local variables for purposes of identifying the root set for
  4607. the garbage collector. Thus, we change \code{uncover-locals} to
  4608. collect not just the variables, but the variables and their types in
  4609. the form of an association list. Thanks to the \code{has-type} forms,
  4610. the types are readily available. Figure~\ref{fig:uncover-locals-r3}
  4611. lists the output of the \code{uncover-locals} pass on the running
  4612. example.
  4613. \begin{figure}[tbp]
  4614. \begin{lstlisting}
  4615. (program
  4616. ((locals . ((tmp54 . Integer) (tmp51 . Integer) (tmp53 . Integer)
  4617. (alloc43 . (Vector Integer)) (tmp55 . Integer)
  4618. (initret45 . Void) (alloc47 . (Vector (Vector Integer)))
  4619. (collectret46 . Void) (vecinit48 . (Vector Integer))
  4620. (tmp52 . Integer) (tmp57 . (Vector Integer))
  4621. (vecinit44 . Integer) (tmp56 . Integer) (initret49 . Void)
  4622. (collectret50 . Void))))
  4623. ((block63 . (seq (collect 16) (goto block61)))
  4624. (block62 . (seq (assign collectret46 (void)) (goto block61)))
  4625. (block61 . (seq (assign alloc43 (allocate 1 (Vector Integer)))
  4626. (seq (assign initret45 (vector-set! alloc43 0 vecinit44))
  4627. (seq (assign vecinit48 alloc43)
  4628. (seq (assign tmp54 (global-value free_ptr))
  4629. (seq (assign tmp55 (+ tmp54 16))
  4630. (seq (assign tmp56 (global-value fromspace_end))
  4631. (if (< tmp55 tmp56) (goto block59) (goto block60)))))))))
  4632. (block60 . (seq (collect 16) (goto block58)))
  4633. (block59 . (seq (assign collectret50 (void)) (goto block58)))
  4634. (block58 . (seq (assign alloc47 (allocate 1 (Vector (Vector Integer))))
  4635. (seq (assign initret49 (vector-set! alloc47 0 vecinit48))
  4636. (seq (assign tmp57 (vector-ref alloc47 0))
  4637. (return (vector-ref tmp57 0))))))
  4638. (start . (seq (assign vecinit44 42)
  4639. (seq (assign tmp51 (global-value free_ptr))
  4640. (seq (assign tmp52 (+ tmp51 16))
  4641. (seq (assign tmp53 (global-value fromspace_end))
  4642. (if (< tmp52 tmp53) (goto block62) (goto block63)))))))))
  4643. \end{lstlisting}
  4644. \caption{Output of \code{uncover-locals} for the running example.}
  4645. \label{fig:uncover-locals-r3}
  4646. \end{figure}
  4647. \clearpage
  4648. \section{Select Instructions}
  4649. \label{sec:select-instructions-gc}
  4650. %% void (rep as zero)
  4651. %% allocate
  4652. %% collect (callq collect)
  4653. %% vector-ref
  4654. %% vector-set!
  4655. %% global-value (postpone)
  4656. In this pass we generate x86 code for most of the new operations that
  4657. were needed to compile tuples, including \code{allocate},
  4658. \code{collect}, \code{vector-ref}, \code{vector-set!}, and
  4659. \code{(void)}. We postpone \code{global-value} to \code{print-x86}.
  4660. The \code{vector-ref} and \code{vector-set!} forms translate into
  4661. \code{movq} instructions with the appropriate \key{deref}. (The
  4662. plus one is to get past the tag at the beginning of the tuple
  4663. representation.)
  4664. \begin{lstlisting}
  4665. (assign |$\itm{lhs}$| (vector-ref |$\itm{vec}$| |$n$|))
  4666. |$\Longrightarrow$|
  4667. (movq |$\itm{vec}'$| (reg r11))
  4668. (movq (deref r11 |$8(n+1)$|) |$\itm{lhs}$|)
  4669. (assign |$\itm{lhs}$| (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|))
  4670. |$\Longrightarrow$|
  4671. (movq |$\itm{vec}'$| (reg r11))
  4672. (movq |$\itm{arg}'$| (deref r11 |$8(n+1)$|))
  4673. (movq (int 0) |$\itm{lhs}$|)
  4674. \end{lstlisting}
  4675. The $\itm{vec}'$ and $\itm{arg}'$ are obtained by recursively
  4676. processing $\itm{vec}$ and $\itm{arg}$. The move of $\itm{vec}'$ to
  4677. register \code{r11} ensures that offsets are only performed with
  4678. register operands. This requires removing \code{r11} from
  4679. consideration by the register allocating.
  4680. We compile the \code{allocate} form to operations on the
  4681. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  4682. is the next free address in the FromSpace, so we move it into the
  4683. \itm{lhs} and then move it forward by enough space for the tuple being
  4684. allocated, which is $8(\itm{len}+1)$ bytes because each element is 8
  4685. bytes (64 bits) and we use 8 bytes for the tag. Last but not least, we
  4686. initialize the \itm{tag}. Refer to Figure~\ref{fig:tuple-rep} to see
  4687. how the tag is organized. We recommend using the Racket operations
  4688. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag.
  4689. The type annotation in the \code{vector} form is used to determine the
  4690. pointer mask region of the tag.
  4691. \begin{lstlisting}
  4692. (assign |$\itm{lhs}$| (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|)))
  4693. |$\Longrightarrow$|
  4694. (movq (global-value free_ptr) |$\itm{lhs}'$|)
  4695. (addq (int |$8(\itm{len}+1)$|) (global-value free_ptr))
  4696. (movq |$\itm{lhs}'$| (reg r11))
  4697. (movq (int |$\itm{tag}$|) (deref r11 0))
  4698. \end{lstlisting}
  4699. The \code{collect} form is compiled to a call to the \code{collect}
  4700. function in the runtime. The arguments to \code{collect} are the top
  4701. of the root stack and the number of bytes that need to be allocated.
  4702. We shall use a dedicated register, \code{r15}, to store the pointer to
  4703. the top of the root stack. So \code{r15} is not available for use by
  4704. the register allocator.
  4705. \begin{lstlisting}
  4706. (collect |$\itm{bytes}$|)
  4707. |$\Longrightarrow$|
  4708. (movq (reg r15) (reg rdi))
  4709. (movq |\itm{bytes}| (reg rsi))
  4710. (callq collect)
  4711. \end{lstlisting}
  4712. \begin{figure}[tp]
  4713. \fbox{
  4714. \begin{minipage}{0.96\textwidth}
  4715. \[
  4716. \begin{array}{lcl}
  4717. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\itm{register}}
  4718. \mid (\key{deref}\,\itm{register}\,\Int) } \\
  4719. &\mid& \gray{ (\key{byte-reg}\; \itm{register}) }
  4720. \mid (\key{global-value}\; \itm{name}) \\
  4721. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  4722. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  4723. (\key{subq} \; \Arg\; \Arg) \mid
  4724. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  4725. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  4726. (\key{pushq}\;\Arg) \mid
  4727. (\key{popq}\;\Arg) \mid
  4728. (\key{retq})} \\
  4729. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  4730. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  4731. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  4732. \mid (\key{jmp} \; \itm{label})
  4733. \mid (\key{jmp-if}\itm{cc} \; \itm{label})}\\
  4734. &\mid& \gray{(\key{label} \; \itm{label}) } \\
  4735. x86_2 &::= & \gray{ (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+}) }
  4736. \end{array}
  4737. \]
  4738. \end{minipage}
  4739. }
  4740. \caption{The x86$_2$ language (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  4741. \label{fig:x86-2}
  4742. \end{figure}
  4743. The syntax of the $x86_2$ language is defined in
  4744. Figure~\ref{fig:x86-2}. It differs from $x86_1$ just in the addition
  4745. of the form for global variables.
  4746. %
  4747. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  4748. \code{select-instructions} pass on the running example.
  4749. \begin{figure}[tbp]
  4750. \centering
  4751. \begin{minipage}{0.75\textwidth}
  4752. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4753. (program
  4754. ((locals . ((tmp54 . Integer) (tmp51 . Integer) (tmp53 . Integer)
  4755. (alloc43 . (Vector Integer)) (tmp55 . Integer)
  4756. (initret45 . Void) (alloc47 . (Vector (Vector Integer)))
  4757. (collectret46 . Void) (vecinit48 . (Vector Integer))
  4758. (tmp52 . Integer) (tmp57 Vector Integer) (vecinit44 . Integer)
  4759. (tmp56 . Integer) (initret49 . Void) (collectret50 . Void))))
  4760. ((block63 . (block ()
  4761. (movq (reg r15) (reg rdi))
  4762. (movq (int 16) (reg rsi))
  4763. (callq collect)
  4764. (jmp block61)))
  4765. (block62 . (block () (movq (int 0) (var collectret46)) (jmp block61)))
  4766. (block61 . (block ()
  4767. (movq (global-value free_ptr) (var alloc43))
  4768. (addq (int 16) (global-value free_ptr))
  4769. (movq (var alloc43) (reg r11))
  4770. (movq (int 3) (deref r11 0))
  4771. (movq (var alloc43) (reg r11))
  4772. (movq (var vecinit44) (deref r11 8))
  4773. (movq (int 0) (var initret45))
  4774. (movq (var alloc43) (var vecinit48))
  4775. (movq (global-value free_ptr) (var tmp54))
  4776. (movq (var tmp54) (var tmp55))
  4777. (addq (int 16) (var tmp55))
  4778. (movq (global-value fromspace_end) (var tmp56))
  4779. (cmpq (var tmp56) (var tmp55))
  4780. (jmp-if l block59)
  4781. (jmp block60)))
  4782. (block60 . (block ()
  4783. (movq (reg r15) (reg rdi))
  4784. (movq (int 16) (reg rsi))
  4785. (callq collect)
  4786. (jmp block58))
  4787. (block59 . (block ()
  4788. (movq (int 0) (var collectret50))
  4789. (jmp block58)))
  4790. (block58 . (block ()
  4791. (movq (global-value free_ptr) (var alloc47))
  4792. (addq (int 16) (global-value free_ptr))
  4793. (movq (var alloc47) (reg r11))
  4794. (movq (int 131) (deref r11 0))
  4795. (movq (var alloc47) (reg r11))
  4796. (movq (var vecinit48) (deref r11 8))
  4797. (movq (int 0) (var initret49))
  4798. (movq (var alloc47) (reg r11))
  4799. (movq (deref r11 8) (var tmp57))
  4800. (movq (var tmp57) (reg r11))
  4801. (movq (deref r11 8) (reg rax))
  4802. (jmp conclusion)))
  4803. (start . (block ()
  4804. (movq (int 42) (var vecinit44))
  4805. (movq (global-value free_ptr) (var tmp51))
  4806. (movq (var tmp51) (var tmp52))
  4807. (addq (int 16) (var tmp52))
  4808. (movq (global-value fromspace_end) (var tmp53))
  4809. (cmpq (var tmp53) (var tmp52))
  4810. (jmp-if l block62)
  4811. (jmp block63))))))
  4812. \end{lstlisting}
  4813. \end{minipage}
  4814. \caption{Output of the \code{select-instructions} pass.}
  4815. \label{fig:select-instr-output-gc}
  4816. \end{figure}
  4817. \clearpage
  4818. \section{Register Allocation}
  4819. \label{sec:reg-alloc-gc}
  4820. As discussed earlier in this chapter, the garbage collector needs to
  4821. access all the pointers in the root set, that is, all variables that
  4822. are vectors. It will be the responsibility of the register allocator
  4823. to make sure that:
  4824. \begin{enumerate}
  4825. \item the root stack is used for spilling vector-typed variables, and
  4826. \item if a vector-typed variable is live during a call to the
  4827. collector, it must be spilled to ensure it is visible to the
  4828. collector.
  4829. \end{enumerate}
  4830. The later responsibility can be handled during construction of the
  4831. inference graph, by adding interference edges between the call-live
  4832. vector-typed variables and all the callee-saved registers. (They
  4833. already interfere with the caller-saved registers.) The type
  4834. information for variables is in the \code{program} form, so we
  4835. recommend adding another parameter to the \code{build-interference}
  4836. function to communicate this association list.
  4837. The spilling of vector-typed variables to the root stack can be
  4838. handled after graph coloring, when choosing how to assign the colors
  4839. (integers) to registers and stack locations. The \code{program} output
  4840. of this pass changes to also record the number of spills to the root
  4841. stack.
  4842. % build-interference
  4843. %
  4844. % callq
  4845. % extra parameter for var->type assoc. list
  4846. % update 'program' and 'if'
  4847. % allocate-registers
  4848. % allocate spilled vectors to the rootstack
  4849. % don't change color-graph
  4850. \section{Print x86}
  4851. \label{sec:print-x86-gc}
  4852. \margincomment{\scriptsize We need to show the translation to x86 and what
  4853. to do about global-value. \\ --Jeremy}
  4854. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  4855. \code{print-x86} pass on the running example. In the prelude and
  4856. conclusion of the \code{main} function, we treat the root stack very
  4857. much like the regular stack in that we move the root stack pointer
  4858. (\code{r15}) to make room for all of the spills to the root stack,
  4859. except that the root stack grows up instead of down. For the running
  4860. example, there was just one spill so we increment \code{r15} by 8
  4861. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  4862. One issue that deserves special care is that there may be a call to
  4863. \code{collect} prior to the initializing assignments for all the
  4864. variables in the root stack. We do not want the garbage collector to
  4865. accidentally think that some uninitialized variable is a pointer that
  4866. needs to be followed. Thus, we zero-out all locations on the root
  4867. stack in the prelude of \code{main}. In
  4868. Figure~\ref{fig:print-x86-output-gc}, the instruction
  4869. %
  4870. \lstinline{movq $0, (%r15)}
  4871. %
  4872. accomplishes this task. The garbage collector tests each root to see
  4873. if it is null prior to dereferencing it.
  4874. \begin{figure}[htbp]
  4875. \begin{minipage}[t]{0.5\textwidth}
  4876. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4877. _block58:
  4878. movq _free_ptr(%rip), %rcx
  4879. addq $16, _free_ptr(%rip)
  4880. movq %rcx, %r11
  4881. movq $131, 0(%r11)
  4882. movq %rcx, %r11
  4883. movq -8(%r15), %rax
  4884. movq %rax, 8(%r11)
  4885. movq $0, %rdx
  4886. movq %rcx, %r11
  4887. movq 8(%r11), %rcx
  4888. movq %rcx, %r11
  4889. movq 8(%r11), %rax
  4890. jmp _conclusion
  4891. _block59:
  4892. movq $0, %rcx
  4893. jmp _block58
  4894. _block62:
  4895. movq $0, %rcx
  4896. jmp _block61
  4897. _block60:
  4898. movq %r15, %rdi
  4899. movq $16, %rsi
  4900. callq _collect
  4901. jmp _block58
  4902. _block63:
  4903. movq %r15, %rdi
  4904. movq $16, %rsi
  4905. callq _collect
  4906. jmp _block61
  4907. _start:
  4908. movq $42, %rbx
  4909. movq _free_ptr(%rip), %rdx
  4910. addq $16, %rdx
  4911. movq _fromspace_end(%rip), %rcx
  4912. cmpq %rcx, %rdx
  4913. jl _block62
  4914. jmp _block63
  4915. \end{lstlisting}
  4916. \end{minipage}
  4917. \begin{minipage}[t]{0.45\textwidth}
  4918. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  4919. _block61:
  4920. movq _free_ptr(%rip), %rcx
  4921. addq $16, _free_ptr(%rip)
  4922. movq %rcx, %r11
  4923. movq $3, 0(%r11)
  4924. movq %rcx, %r11
  4925. movq %rbx, 8(%r11)
  4926. movq $0, %rdx
  4927. movq %rcx, -8(%r15)
  4928. movq _free_ptr(%rip), %rcx
  4929. addq $16, %rcx
  4930. movq _fromspace_end(%rip), %rdx
  4931. cmpq %rdx, %rcx
  4932. jl _block59
  4933. jmp _block60
  4934. .globl _main
  4935. _main:
  4936. pushq %rbp
  4937. movq %rsp, %rbp
  4938. pushq %r12
  4939. pushq %rbx
  4940. pushq %r13
  4941. pushq %r14
  4942. subq $0, %rsp
  4943. movq $16384, %rdi
  4944. movq $16, %rsi
  4945. callq _initialize
  4946. movq _rootstack_begin(%rip), %r15
  4947. movq $0, (%r15)
  4948. addq $8, %r15
  4949. jmp _start
  4950. _conclusion:
  4951. subq $8, %r15
  4952. addq $0, %rsp
  4953. popq %r14
  4954. popq %r13
  4955. popq %rbx
  4956. popq %r12
  4957. popq %rbp
  4958. retq
  4959. \end{lstlisting}
  4960. \end{minipage}
  4961. \caption{Output of the \code{print-x86} pass.}
  4962. \label{fig:print-x86-output-gc}
  4963. \end{figure}
  4964. \margincomment{\scriptsize Suggest an implementation strategy
  4965. in which the students first do the code gen and test that
  4966. without GC (just use a big heap), then after that is debugged,
  4967. implement the GC. \\ --Jeremy}
  4968. \begin{figure}[p]
  4969. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4970. \node (R3) at (0,2) {\large $R_3$};
  4971. \node (R3-2) at (3,2) {\large $R_3$};
  4972. \node (R3-3) at (6,2) {\large $R_3$};
  4973. \node (R3-4) at (9,2) {\large $R_3$};
  4974. \node (R3-5) at (12,2) {\large $R_3$};
  4975. \node (C2-4) at (3,0) {\large $C_2$};
  4976. \node (C2-3) at (6,0) {\large $C_2$};
  4977. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_2$};
  4978. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_2$};
  4979. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}_2$};
  4980. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}_2$};
  4981. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}_2$};
  4982. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}_2$};
  4983. \path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R3-2);
  4984. \path[->,bend left=15] (R3-2) edge [above] node {\ttfamily\footnotesize uniquify} (R3-3);
  4985. \path[->,bend left=15] (R3-3) edge [above] node {\ttfamily\footnotesize\color{red} expose-alloc.} (R3-4);
  4986. \path[->,bend left=15] (R3-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R3-5);
  4987. \path[->,bend left=20] (R3-5) edge [right] node {\ttfamily\footnotesize explicate-control} (C2-3);
  4988. \path[->,bend right=15] (C2-3) edge [above] node {\ttfamily\footnotesize\color{red} uncover-locals} (C2-4);
  4989. \path[->,bend right=15] (C2-4) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  4990. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  4991. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  4992. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4993. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  4994. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  4995. \end{tikzpicture}
  4996. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  4997. \label{fig:R3-passes}
  4998. \end{figure}
  4999. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  5000. for the compilation of $R_3$.
  5001. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5002. \chapter{Functions}
  5003. \label{ch:functions}
  5004. This chapter studies the compilation of functions at the level of
  5005. abstraction of the C language. This corresponds to a subset of Typed
  5006. Racket in which only top-level function definitions are allowed. These
  5007. kind of functions are an important stepping stone to implementing
  5008. lexically-scoped functions in the form of \key{lambda} abstractions,
  5009. which is the topic of Chapter~\ref{ch:lambdas}.
  5010. \section{The $R_4$ Language}
  5011. The syntax for function definitions and function application is shown
  5012. in Figure~\ref{fig:r4-syntax}, where we define the $R_4$ language.
  5013. Programs in $R_4$ start with zero or more function definitions. The
  5014. function names from these definitions are in-scope for the entire
  5015. program, including all other function definitions (so the ordering of
  5016. function definitions does not matter). The syntax for function
  5017. application does not include an explicit keyword, which is error prone
  5018. when using \code{match}. To alleviate this problem, we change the
  5019. syntax from $(\Exp \; \Exp^{*})$ to $(\key{app}\; \Exp \; \Exp^{*})$
  5020. during type checking.
  5021. Functions are first-class in the sense that a function pointer is data
  5022. and can be stored in memory or passed as a parameter to another
  5023. function. Thus, we introduce a function type, written
  5024. \begin{lstlisting}
  5025. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  5026. \end{lstlisting}
  5027. for a function whose $n$ parameters have the types $\Type_1$ through
  5028. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  5029. these functions (with respect to Racket functions) is that they are
  5030. not lexically scoped. That is, the only external entities that can be
  5031. referenced from inside a function body are other globally-defined
  5032. functions. The syntax of $R_4$ prevents functions from being nested
  5033. inside each other.
  5034. \begin{figure}[tp]
  5035. \centering
  5036. \fbox{
  5037. \begin{minipage}{0.96\textwidth}
  5038. \[
  5039. \begin{array}{lcl}
  5040. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  5041. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} } \mid (\Type^{*} \; \key{->}\; \Type) \\
  5042. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  5043. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp)} \\
  5044. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  5045. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5046. \mid (\key{and}\;\Exp\;\Exp)
  5047. \mid (\key{or}\;\Exp\;\Exp)
  5048. \mid (\key{not}\;\Exp)} \\
  5049. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5050. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5051. (\key{vector-ref}\;\Exp\;\Int)} \\
  5052. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  5053. &\mid& (\Exp \; \Exp^{*}) \\
  5054. \Def &::=& (\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  5055. R_4 &::=& (\key{program} \;\itm{info}\; \Def^{*} \; \Exp)
  5056. \end{array}
  5057. \]
  5058. \end{minipage}
  5059. }
  5060. \caption{Syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-syntax})
  5061. with functions.}
  5062. \label{fig:r4-syntax}
  5063. \end{figure}
  5064. The program in Figure~\ref{fig:r4-function-example} is a
  5065. representative example of defining and using functions in $R_4$. We
  5066. define a function \code{map-vec} that applies some other function
  5067. \code{f} to both elements of a vector (a 2-tuple) and returns a new
  5068. vector containing the results. We also define a function \code{add1}
  5069. that does what its name suggests. The program then applies
  5070. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  5071. \code{(vector 1 42)}, from which we return the \code{42}.
  5072. \begin{figure}[tbp]
  5073. \begin{lstlisting}
  5074. (program ()
  5075. (define (map-vec [f : (Integer -> Integer)]
  5076. [v : (Vector Integer Integer)])
  5077. : (Vector Integer Integer)
  5078. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  5079. (define (add1 [x : Integer]) : Integer
  5080. (+ x 1))
  5081. (vector-ref (map-vec add1 (vector 0 41)) 1)
  5082. )
  5083. \end{lstlisting}
  5084. \caption{Example of using functions in $R_4$.}
  5085. \label{fig:r4-function-example}
  5086. \end{figure}
  5087. The definitional interpreter for $R_4$ is in
  5088. Figure~\ref{fig:interp-R4}. The case for the \code{program} form is
  5089. responsible for setting up the mutual recursion between the top-level
  5090. function definitions. We use the classic back-patching approach that
  5091. uses mutable variables and makes two passes over the function
  5092. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  5093. top-level environment using a mutable cons cell for each function
  5094. definition. Note that the \code{lambda} value for each function is
  5095. incomplete; it does not yet include the environment. Once the
  5096. top-level environment is constructed, we then iterate over it and
  5097. update the \code{lambda} value's to use the top-level environment.
  5098. \begin{figure}[tp]
  5099. \begin{lstlisting}
  5100. (define (interp-exp env)
  5101. (lambda (e)
  5102. (define recur (interp-exp env))
  5103. (match e
  5104. ...
  5105. [`(,fun ,args ...)
  5106. (define arg-vals (for/list ([e args]) (recur e)))
  5107. (define fun-val (recur fun))
  5108. (match fun-val
  5109. [`(lambda (,xs ...) ,body ,fun-env)
  5110. (define new-env (append (map cons xs arg-vals) fun-env))
  5111. ((interp-exp new-env) body)]
  5112. [else (error "interp-exp, expected function, not" fun-val)])]
  5113. [else (error 'interp-exp "unrecognized expression")]
  5114. )))
  5115. (define (interp-def d)
  5116. (match d
  5117. [`(define (,f [,xs : ,ps] ...) : ,rt ,body)
  5118. (mcons f `(lambda ,xs ,body ()))]
  5119. ))
  5120. (define (interp-R4 p)
  5121. (match p
  5122. [`(program ,ds ... ,body)
  5123. (let ([top-level (for/list ([d ds]) (interp-def d))])
  5124. (for/list ([b top-level])
  5125. (set-mcdr! b (match (mcdr b)
  5126. [`(lambda ,xs ,body ())
  5127. `(lambda ,xs ,body ,top-level)])))
  5128. ((interp-exp top-level) body))]
  5129. ))
  5130. \end{lstlisting}
  5131. \caption{Interpreter for the $R_4$ language.}
  5132. \label{fig:interp-R4}
  5133. \end{figure}
  5134. \section{Functions in x86}
  5135. \label{sec:fun-x86}
  5136. \margincomment{\tiny Make sure callee-saved registers are discussed
  5137. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  5138. \margincomment{\tiny Talk about the return address on the
  5139. stack and what callq and retq does.\\ --Jeremy }
  5140. The x86 architecture provides a few features to support the
  5141. implementation of functions. We have already seen that x86 provides
  5142. labels so that one can refer to the location of an instruction, as is
  5143. needed for jump instructions. Labels can also be used to mark the
  5144. beginning of the instructions for a function. Going further, we can
  5145. obtain the address of a label by using the \key{leaq} instruction and
  5146. \key{rip}-relative addressing. For example, the following puts the
  5147. address of the \code{add1} label into the \code{rbx} register.
  5148. \begin{lstlisting}
  5149. leaq add1(%rip), %rbx
  5150. \end{lstlisting}
  5151. In Section~\ref{sec:x86} we saw the use of the \code{callq}
  5152. instruction for jumping to a function whose location is given by a
  5153. label. Here we instead will be jumping to a function whose location is
  5154. given by an address, that is, we need to make an \emph{indirect
  5155. function call}. The x86 syntax is to give the register name prefixed
  5156. with an asterisk.
  5157. \begin{lstlisting}
  5158. callq *%rbx
  5159. \end{lstlisting}
  5160. \subsection{Calling Conventions}
  5161. The \code{callq} instruction provides partial support for implementing
  5162. functions, but it does not handle (1) parameter passing, (2) saving
  5163. and restoring frames on the procedure call stack, or (3) determining
  5164. how registers are shared by different functions. These issues require
  5165. coordination between the caller and the callee, which is often
  5166. assembly code written by different programmers or generated by
  5167. different compilers. As a result, people have developed
  5168. \emph{conventions} that govern how functions calls are performed.
  5169. Here we shall use the same conventions used by the \code{gcc}
  5170. compiler~\citep{Matz:2013aa}.
  5171. Regarding (1) parameter passing, the convention is to use the
  5172. following six registers: \code{rdi}, \code{rsi}, \code{rdx},
  5173. \code{rcx}, \code{r8}, and \code{r9}, in that order. If there are more
  5174. than six arguments, then the convention is to use space on the frame
  5175. of the caller for the rest of the arguments. However, to ease the
  5176. implementation of efficient tail calls (Section~\ref{sec:tail-call}),
  5177. we shall arrange to never have more than six arguments.
  5178. %
  5179. The register \code{rax} is for the return value of the function.
  5180. Regarding (2) frames and the procedure call stack, the convention is
  5181. that the stack grows down, with each function call using a chunk of
  5182. space called a frame. The caller sets the stack pointer, register
  5183. \code{rsp}, to the last data item in its frame. The callee must not
  5184. change anything in the caller's frame, that is, anything that is at or
  5185. above the stack pointer. The callee is free to use locations that are
  5186. below the stack pointer.
  5187. Regarding (3) the sharing of registers between different functions,
  5188. recall from Section~\ref{sec:calling-conventions} that the registers
  5189. are divided into two groups, the caller-saved registers and the
  5190. callee-saved registers. The caller should assume that all the
  5191. caller-saved registers get overwritten with arbitrary values by the
  5192. callee. Thus, the caller should either 1) not put values that are live
  5193. across a call in caller-saved registers, or 2) save and restore values
  5194. that are live across calls. We shall recommend option 1). On the flip
  5195. side, if the callee wants to use a callee-saved register, the callee
  5196. must save the contents of those registers on their stack frame and
  5197. then put them back prior to returning to the caller. The base
  5198. pointer, register \code{rbp}, is used as a point-of-reference within a
  5199. frame, so that each local variable can be accessed at a fixed offset
  5200. from the base pointer.
  5201. %
  5202. Figure~\ref{fig:call-frames} shows the layout of the caller and callee
  5203. frames.
  5204. %% If we were to use stack arguments, they would be between the
  5205. %% caller locals and the callee return address.
  5206. \begin{figure}[tbp]
  5207. \centering
  5208. \begin{tabular}{r|r|l|l} \hline
  5209. Caller View & Callee View & Contents & Frame \\ \hline
  5210. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  5211. 0(\key{\%rbp}) & & old \key{rbp} \\
  5212. -8(\key{\%rbp}) & & callee-saved $1$ \\
  5213. \ldots & & \ldots \\
  5214. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  5215. $-8(j+1)$(\key{\%rbp}) & & local $1$ \\
  5216. \ldots & & \ldots \\
  5217. $-8(j+k)$(\key{\%rbp}) & & local $k$ \\
  5218. %% & & \\
  5219. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  5220. %% & \ldots & \ldots \\
  5221. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  5222. \hline
  5223. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  5224. & 0(\key{\%rbp}) & old \key{rbp} \\
  5225. & -8(\key{\%rbp}) & callee-saved $1$ \\
  5226. & \ldots & \ldots \\
  5227. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  5228. & $-8(n+1)$(\key{\%rbp}) & local $1$ \\
  5229. & \ldots & \ldots \\
  5230. & $-8(n+m)$(\key{\%rsp}) & local $m$\\ \hline
  5231. \end{tabular}
  5232. \caption{Memory layout of caller and callee frames.}
  5233. \label{fig:call-frames}
  5234. \end{figure}
  5235. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  5236. %% local variables and for storing the values of callee-saved registers
  5237. %% (we shall refer to all of these collectively as ``locals''), and that
  5238. %% at the beginning of a function we move the stack pointer \code{rsp}
  5239. %% down to make room for them.
  5240. %% We recommend storing the local variables
  5241. %% first and then the callee-saved registers, so that the local variables
  5242. %% can be accessed using \code{rbp} the same as before the addition of
  5243. %% functions.
  5244. %% To make additional room for passing arguments, we shall
  5245. %% move the stack pointer even further down. We count how many stack
  5246. %% arguments are needed for each function call that occurs inside the
  5247. %% body of the function and find their maximum. Adding this number to the
  5248. %% number of locals gives us how much the \code{rsp} should be moved at
  5249. %% the beginning of the function. In preparation for a function call, we
  5250. %% offset from \code{rsp} to set up the stack arguments. We put the first
  5251. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  5252. %% so on.
  5253. %% Upon calling the function, the stack arguments are retrieved by the
  5254. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  5255. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  5256. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  5257. %% the layout of the caller and callee frames. Notice how important it is
  5258. %% that we correctly compute the maximum number of arguments needed for
  5259. %% function calls; if that number is too small then the arguments and
  5260. %% local variables will smash into each other!
  5261. \subsection{Efficient Tail Calls}
  5262. \label{sec:tail-call}
  5263. In general, the amount of stack space used by a program is determined
  5264. by the longest chain of nested function calls. That is, if function
  5265. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  5266. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  5267. $n$ can grow quite large in the case of recursive or mutually
  5268. recursive functions. However, in some cases we can arrange to use only
  5269. constant space, i.e. $O(1)$, instead of $O(n)$.
  5270. If a function call is the last action in a function body, then that
  5271. call is said to be a \emph{tail call}. In such situations, the frame
  5272. of the caller is no longer needed, so we can pop the caller's frame
  5273. before making the tail call. With this approach, a recursive function
  5274. that only makes tail calls will only use $O(1)$ stack space.
  5275. Functional languages like Racket typically rely heavily on recursive
  5276. functions, so they typically guarantee that all tail calls will be
  5277. optimized in this way.
  5278. However, some care is needed with regards to argument passing in tail
  5279. calls. As mentioned above, for arguments beyond the sixth, the
  5280. convention is to use space in the caller's frame for passing
  5281. arguments. But here we've popped the caller's frame and can no longer
  5282. use it. Another alternative is to use space in the callee's frame for
  5283. passing arguments. However, this option is also problematic because
  5284. the caller and callee's frame overlap in memory. As we begin to copy
  5285. the arguments from their sources in the caller's frame, the target
  5286. locations in the callee's frame might overlap with the sources for
  5287. later arguments! We solve this problem by not using the stack for
  5288. parameter passing but instead use the heap, as we describe in the
  5289. Section~\ref{sec:limit-functions-r4}.
  5290. As mentioned above, for a tail call we pop the caller's frame prior to
  5291. making the tail call. The instructions for popping a frame are the
  5292. instructions that we usually place in the conclusion of a
  5293. function. Thus, we also need to place such code immediately before
  5294. each tail call. These instructions include restoring the callee-saved
  5295. registers, so it is good that the argument passing registers are all
  5296. caller-saved registers.
  5297. One last note regarding which instruction to use to make the tail
  5298. call. When the callee is finished, it should not return to the current
  5299. function, but it should return to the function that called the current
  5300. one. Thus, the return address that is already on the stack is the
  5301. right one, and we should not use \key{callq} to make the tail call, as
  5302. that would unnecessarily overwrite the return address. Instead we can
  5303. simply use the \key{jmp} instruction. Like the indirect function call,
  5304. we write an indirect jump with a register prefixed with an asterisk.
  5305. We recommend using \code{rax} to hold the jump target because the
  5306. preceding ``conclusion'' overwrites just about everything else.
  5307. \begin{lstlisting}
  5308. jmp *%rax
  5309. \end{lstlisting}
  5310. %% Now that we have a good understanding of functions as they appear in
  5311. %% $R_4$ and the support for functions in x86, we need to plan the
  5312. %% changes to our compiler, that is, do we need any new passes and/or do
  5313. %% we need to change any existing passes? Also, do we need to add new
  5314. %% kinds of AST nodes to any of the intermediate languages?
  5315. \section{Shrink $R_4$}
  5316. \label{sec:shrink-r4}
  5317. The \code{shrink} pass performs a couple minor modifications to the
  5318. grammar to ease the later passes. This pass adds an empty $\itm{info}$
  5319. field to each function definition:
  5320. \begin{lstlisting}
  5321. (define (|$f$| [|$x_1 : \Type_1$| ...) : |$\Type_r$| |$\Exp$|)
  5322. |$\Rightarrow$| (define (|$f$| [|$x_1 : \Type_1$| ...) : |$\Type_r$| () |$\Exp$|)
  5323. \end{lstlisting}
  5324. and introduces an explicit \code{main} function.\\
  5325. \begin{tabular}{lll}
  5326. \begin{minipage}{0.45\textwidth}
  5327. \begin{lstlisting}
  5328. (program |$\itm{info}$| |$ds$| ... |$\Exp$|)
  5329. \end{lstlisting}
  5330. \end{minipage}
  5331. &
  5332. $\Rightarrow$
  5333. &
  5334. \begin{minipage}{0.45\textwidth}
  5335. \begin{lstlisting}
  5336. (program |$\itm{info}$| |$ds'$| |$\itm{mainDef}$|)
  5337. \end{lstlisting}
  5338. \end{minipage}
  5339. \end{tabular} \\
  5340. where $\itm{mainDef}$ is
  5341. \begin{lstlisting}
  5342. (define (main) : Integer () |$\Exp'$|)
  5343. \end{lstlisting}
  5344. \section{Reveal Functions}
  5345. \label{sec:reveal-functions-r4}
  5346. Going forward, the syntax of $R_4$ is inconvenient for purposes of
  5347. compilation because it conflates the use of function names and local
  5348. variables. This is a problem because we need to compile the use of a
  5349. function name differently than the use of a local variable; we need to
  5350. use \code{leaq} to convert the function name (a label in x86) to an
  5351. address in a register. Thus, it is a good idea to create a new pass
  5352. that changes function references from just a symbol $f$ to
  5353. \code{(fun-ref $f$)}. A good name for this pass is
  5354. \code{reveal-functions} and the output language, $F_1$, is defined in
  5355. Figure~\ref{fig:f1-syntax}.
  5356. \begin{figure}[tp]
  5357. \centering
  5358. \fbox{
  5359. \begin{minipage}{0.96\textwidth}
  5360. \[
  5361. \begin{array}{lcl}
  5362. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  5363. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} \mid (\Type^{*} \; \key{->}\; \Type)} \\
  5364. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  5365. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  5366. &\mid& \gray{ \key{\#t} \mid \key{\#f} \mid
  5367. (\key{not}\;\Exp)} \mid \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5368. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5369. (\key{vector-ref}\;\Exp\;\Int)} \\
  5370. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void}) \mid
  5371. (\key{app}\; \Exp \; \Exp^{*})} \\
  5372. &\mid& (\key{fun-ref}\, \itm{label}) \\
  5373. \Def &::=& \gray{(\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5374. F_1 &::=& \gray{(\key{program}\;\itm{info} \; \Def^{*})}
  5375. \end{array}
  5376. \]
  5377. \end{minipage}
  5378. }
  5379. \caption{The $F_1$ language, an extension of $R_4$
  5380. (Figure~\ref{fig:r4-syntax}).}
  5381. \label{fig:f1-syntax}
  5382. \end{figure}
  5383. %% Distinguishing between calls in tail position and non-tail position
  5384. %% requires the pass to have some notion of context. We recommend using
  5385. %% two mutually recursive functions, one for processing expressions in
  5386. %% tail position and another for the rest.
  5387. Placing this pass after \code{uniquify} is a good idea, because it
  5388. will make sure that there are no local variables and functions that
  5389. share the same name. On the other hand, \code{reveal-functions} needs
  5390. to come before the \code{explicate-control} pass because that pass
  5391. will help us compile \code{fun-ref} into assignment statements.
  5392. \section{Limit Functions}
  5393. \label{sec:limit-functions-r4}
  5394. This pass transforms functions so that they have at most six
  5395. parameters and transforms all function calls so that they pass at most
  5396. six arguments. A simple strategy for imposing an argument limit of
  5397. length $n$ is to take all arguments $i$ where $i \geq n$ and pack them
  5398. into a vector, making that subsequent vector the $n$th argument.
  5399. \begin{tabular}{lll}
  5400. \begin{minipage}{0.2\textwidth}
  5401. \begin{lstlisting}
  5402. (|$f$| |$x_1$| |$\ldots$| |$x_n$|)
  5403. \end{lstlisting}
  5404. \end{minipage}
  5405. &
  5406. $\Rightarrow$
  5407. &
  5408. \begin{minipage}{0.4\textwidth}
  5409. \begin{lstlisting}
  5410. (|$f$| |$x_1$| |$\ldots$| |$x_5$| (vector |$x_6$| |$\ldots$| |$x_n$|))
  5411. \end{lstlisting}
  5412. \end{minipage}
  5413. \end{tabular}
  5414. In the body of the function, all occurrences of the $i$th argument in
  5415. which $i>5$ must be replaced with a \code{vector-ref}.
  5416. \section{Remove Complex Operators and Operands}
  5417. \label{sec:rco-r4}
  5418. The primary decisions to make for this pass is whether to classify
  5419. \code{fun-ref} and \code{app} as either simple or complex
  5420. expressions. Recall that a simple expression will eventually end up as
  5421. just an ``immediate'' argument of an x86 instruction. Function
  5422. application will be translated to a sequence of instructions, so
  5423. \code{app} must be classified as complex expression. Regarding
  5424. \code{fun-ref}, as discussed above, the function label needs to
  5425. be converted to an address using the \code{leaq} instruction. Thus,
  5426. even though \code{fun-ref} seems rather simple, it needs to be
  5427. classified as a complex expression so that we generate an assignment
  5428. statement with a left-hand side that can serve as the target of the
  5429. \code{leaq}.
  5430. \section{Explicate Control and the $C_3$ language}
  5431. \label{sec:explicate-control-r4}
  5432. Figure~\ref{fig:c3-syntax} defines the syntax for $C_3$, the output of
  5433. \key{explicate-control}. The three mutually recursive functions for
  5434. this pass, for assignment, tail, and predicate contexts, must all be
  5435. updated with cases for \code{fun-ref} and \code{app}. In
  5436. assignment and predicate contexts, \code{app} becomes \code{call},
  5437. whereas in tail position \code{app} becomes \code{tailcall}. We
  5438. recommend defining a new function for processing function definitions.
  5439. This code is similar to the case for \code{program} in $R_3$. The
  5440. top-level \code{explicate-control} function that handles the
  5441. \code{program} form of $R_4$ can then apply this new function to all
  5442. the function definitions.
  5443. \begin{figure}[tp]
  5444. \fbox{
  5445. \begin{minipage}{0.96\textwidth}
  5446. \[
  5447. \begin{array}{lcl}
  5448. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  5449. \\
  5450. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5451. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  5452. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  5453. &\mid& \gray{ (\key{allocate}\,\Int\,\Type)
  5454. \mid (\key{vector-ref}\, \Arg\, \Int) } \\
  5455. &\mid& \gray{ (\key{vector-set!}\,\Arg\,\Int\,\Arg) \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) } \\
  5456. &\mid& (\key{fun-ref}\,\itm{label}) \mid (\key{call} \,\Arg\,\Arg^{*}) \\
  5457. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  5458. \mid (\key{collect} \,\itm{int}) }\\
  5459. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  5460. &\mid& \gray{(\key{goto}\,\itm{label})
  5461. \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  5462. &\mid& (\key{tailcall} \,\Arg\,\Arg^{*}) \\
  5463. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; ((\itm{label}\,\key{.}\,\Tail)^{+})) \\
  5464. C_3 & ::= & (\key{program}\;\itm{info}\;\Def^{*})
  5465. \end{array}
  5466. \]
  5467. \end{minipage}
  5468. }
  5469. \caption{The $C_3$ language, extending $C_2$ (Figure~\ref{fig:c2-syntax}) with functions.}
  5470. \label{fig:c3-syntax}
  5471. \end{figure}
  5472. \section{Uncover Locals}
  5473. \label{sec:uncover-locals-r4}
  5474. The function for processing $\Tail$ should be updated with a case for
  5475. \code{tailcall}. We also recommend creating a new function for
  5476. processing function definitions. Each function definition in $C_3$ has
  5477. its own set of local variables, so the code for function definitions
  5478. should be similar to the case for the \code{program} form in $C_2$.
  5479. \section{Select Instructions}
  5480. \label{sec:select-r4}
  5481. The output of select instructions is a program in the x86$_3$
  5482. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  5483. \begin{figure}[tp]
  5484. \fbox{
  5485. \begin{minipage}{0.96\textwidth}
  5486. \[
  5487. \begin{array}{lcl}
  5488. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\itm{register}}
  5489. \mid (\key{deref}\,\itm{register}\,\Int) } \\
  5490. &\mid& \gray{ (\key{byte-reg}\; \itm{register})
  5491. \mid (\key{global-value}\; \itm{name}) } \\
  5492. &\mid& (\key{fun-ref}\; \itm{label})\\
  5493. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  5494. \Instr &::=& \gray{ (\key{addq} \; \Arg\; \Arg) \mid
  5495. (\key{subq} \; \Arg\; \Arg) \mid
  5496. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) } \\
  5497. &\mid& \gray{ (\key{callq} \; \mathit{label}) \mid
  5498. (\key{pushq}\;\Arg) \mid
  5499. (\key{popq}\;\Arg) \mid
  5500. (\key{retq}) } \\
  5501. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  5502. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  5503. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  5504. \mid (\key{jmp} \; \itm{label})
  5505. \mid (\key{j}\itm{cc} \; \itm{label})
  5506. \mid (\key{label} \; \itm{label}) } \\
  5507. &\mid& (\key{indirect-callq}\;\Arg ) \mid (\key{tail-jmp}\;\Arg) \\
  5508. &\mid& (\key{leaq}\;\Arg\;\Arg)\\
  5509. \Block &::= & \gray{(\key{block} \;\itm{info}\; \Instr^{+})} \\
  5510. \Def &::= & (\key{define} \; (\itm{label}) \;\itm{info}\; ((\itm{label} \,\key{.}\, \Block)^{+}))\\
  5511. x86_3 &::= & (\key{program} \;\itm{info} \;\Def^{*})
  5512. \end{array}
  5513. \]
  5514. \end{minipage}
  5515. }
  5516. \caption{The x86$_3$ language (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  5517. \label{fig:x86-3}
  5518. \end{figure}
  5519. An assignment of \code{fun-ref} becomes a \code{leaq} instruction
  5520. as follows: \\
  5521. \begin{tabular}{lll}
  5522. \begin{minipage}{0.45\textwidth}
  5523. \begin{lstlisting}
  5524. (assign |$\itm{lhs}$| (fun-ref |$f$|))
  5525. \end{lstlisting}
  5526. \end{minipage}
  5527. &
  5528. $\Rightarrow$
  5529. &
  5530. \begin{minipage}{0.4\textwidth}
  5531. \begin{lstlisting}
  5532. (leaq (fun-ref |$f$|) |$\itm{lhs}$|)
  5533. \end{lstlisting}
  5534. \end{minipage}
  5535. \end{tabular} \\
  5536. Regarding function definitions, we need to remove their parameters and
  5537. instead perform parameter passing in terms of the conventions
  5538. discussed in Section~\ref{sec:fun-x86}. That is, the arguments will be
  5539. in the argument passing registers, and inside the function we should
  5540. generate a \code{movq} instruction for each parameter, to move the
  5541. argument value from the appropriate register to a new local variable
  5542. with the same name as the old parameter.
  5543. Next, consider the compilation of function calls, which have the
  5544. following form upon input to \code{select-instructions}.
  5545. \begin{lstlisting}
  5546. (assign |\itm{lhs}| (call |\itm{fun}| |\itm{args}| |$\ldots$|))
  5547. \end{lstlisting}
  5548. In the mirror image of handling the parameters of function
  5549. definitions, the arguments \itm{args} need to be moved to the argument
  5550. passing registers.
  5551. %
  5552. Once the instructions for parameter passing have been generated, the
  5553. function call itself can be performed with an indirect function call,
  5554. for which I recommend creating the new instruction
  5555. \code{indirect-callq}. Of course, the return value from the function
  5556. is stored in \code{rax}, so it needs to be moved into the \itm{lhs}.
  5557. \begin{lstlisting}
  5558. (indirect-callq |\itm{fun}|)
  5559. (movq (reg rax) |\itm{lhs}|)
  5560. \end{lstlisting}
  5561. Regarding tail calls, the parameter passing is the same as non-tail
  5562. calls: generate instructions to move the arguments into to the
  5563. argument passing registers. After that we need to pop the frame from
  5564. the procedure call stack. However, we do not yet know how big the
  5565. frame is; that gets determined during register allocation. So instead
  5566. of generating those instructions here, we invent a new instruction
  5567. that means ``pop the frame and then do an indirect jump'', which we
  5568. name \code{tail-jmp}.
  5569. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  5570. using the label \code{start} for the initial block of a program, and
  5571. in Section~\ref{sec:select-r1} we recommended labeling the conclusion
  5572. of the program with \code{conclusion}, so that $(\key{return}\;\Arg)$
  5573. can be compiled to an assignment to \code{rax} followed by a jump to
  5574. \code{conclusion}. With the addition of function definitions, we will
  5575. have a starting block and conclusion for each function, but their
  5576. labels need to be unique. We recommend prepending the function's name
  5577. to \code{start} and \code{conclusion}, respectively, to obtain unique
  5578. labels. (Alternatively, one could \code{gensym} labels for the start
  5579. and conclusion and store them in the $\itm{info}$ field of the
  5580. function definition.)
  5581. \section{Uncover Live}
  5582. %% The rest of the passes need only minor modifications to handle the new
  5583. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  5584. %% \code{leaq}.
  5585. Inside \code{uncover-live}, when computing the $W$ set (written
  5586. variables) for an \code{indirect-callq} instruction, we recommend
  5587. including all the caller-saved registers, which will have the affect
  5588. of making sure that no caller-saved register actually needs to be
  5589. saved.
  5590. \section{Build Interference Graph}
  5591. With the addition of function definitions, we compute an interference
  5592. graph for each function (not just one for the whole program).
  5593. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  5594. spill vector-typed variables that are live during a call to the
  5595. \code{collect}. With the addition of functions to our language, we
  5596. need to revisit this issue. Many functions will perform allocation and
  5597. therefore have calls to the collector inside of them. Thus, we should
  5598. not only spill a vector-typed variable when it is live during a call
  5599. to \code{collect}, but we should spill the variable if it is live
  5600. during any function call. Thus, in the \code{build-interference} pass,
  5601. we recommend adding interference edges between call-live vector-typed
  5602. variables and the callee-saved registers (in addition to the usual
  5603. addition of edges between call-live variables and the caller-saved
  5604. registers).
  5605. \section{Patch Instructions}
  5606. In \code{patch-instructions}, you should deal with the x86
  5607. idiosyncrasy that the destination argument of \code{leaq} must be a
  5608. register. Additionally, you should ensure that the argument of
  5609. \code{tail-jmp} is \itm{rax}, our reserved register---this is to make
  5610. code generation more convenient, because we will be trampling many
  5611. registers before the tail call (as explained below).
  5612. \section{Print x86}
  5613. For the \code{print-x86} pass, we recommend the following translations:
  5614. \begin{lstlisting}
  5615. (fun-ref |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  5616. (indirect-callq |\itm{arg}|) |$\Rightarrow$| callq *|\itm{arg}|
  5617. \end{lstlisting}
  5618. Handling \code{tail-jmp} requires a bit more care. A straightforward
  5619. translation of \code{tail-jmp} would be \code{jmp *$\itm{arg}$}, which
  5620. is what we will want to do, but before the jump we need to pop the
  5621. current frame. So we need to restore the state of the registers to the
  5622. point they were at when the current function was called. This
  5623. sequence of instructions is the same as the code for the conclusion of
  5624. a function.
  5625. Note that your \code{print-x86} pass needs to add the code for saving
  5626. and restoring callee-saved registers, if you have not already
  5627. implemented that. This is necessary when generating code for function
  5628. definitions.
  5629. \section{An Example Translation}
  5630. Figure~\ref{fig:add-fun} shows an example translation of a simple
  5631. function in $R_4$ to x86. The figure also includes the results of the
  5632. \code{explicate-control} and \code{select-instructions} passes. We
  5633. have omitted the \code{has-type} AST nodes for readability. Can you
  5634. see any ways to improve the translation?
  5635. \begin{figure}[tbp]
  5636. \begin{tabular}{ll}
  5637. \begin{minipage}{0.45\textwidth}
  5638. % s3_2.rkt
  5639. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5640. (program
  5641. (define (add [x : Integer]
  5642. [y : Integer])
  5643. : Integer (+ x y))
  5644. (add 40 2))
  5645. \end{lstlisting}
  5646. $\Downarrow$
  5647. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5648. (program ()
  5649. (define (add86 [x87 : Integer]
  5650. [y88 : Integer]) : Integer ()
  5651. ((add86start . (return (+ x87 y88)))))
  5652. (define (main) : Integer ()
  5653. ((mainstart .
  5654. (seq (assign tmp89 (fun-ref add86))
  5655. (tailcall tmp89 40 2))))))
  5656. \end{lstlisting}
  5657. \end{minipage}
  5658. &
  5659. $\Rightarrow$
  5660. \begin{minipage}{0.5\textwidth}
  5661. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5662. (program ()
  5663. (define (add86)
  5664. ((locals (x87 . Integer) (y88 . Integer))
  5665. (num-params . 2))
  5666. ((add86start .
  5667. (block ()
  5668. (movq (reg rcx) (var x87))
  5669. (movq (reg rdx) (var y88))
  5670. (movq (var x87) (reg rax))
  5671. (addq (var y88) (reg rax))
  5672. (jmp add86conclusion)))))
  5673. (define (main)
  5674. ((locals . ((tmp89 . (Integer Integer -> Integer))))
  5675. (num-params . 0))
  5676. ((mainstart .
  5677. (block ()
  5678. (leaq (fun-ref add86) (var tmp89))
  5679. (movq (int 40) (reg rcx))
  5680. (movq (int 2) (reg rdx))
  5681. (tail-jmp (var tmp89))))))
  5682. \end{lstlisting}
  5683. $\Downarrow$
  5684. \end{minipage}
  5685. \end{tabular}
  5686. \begin{tabular}{lll}
  5687. \begin{minipage}{0.3\textwidth}
  5688. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5689. _add90start:
  5690. movq %rcx, %rsi
  5691. movq %rdx, %rcx
  5692. movq %rsi, %rax
  5693. addq %rcx, %rax
  5694. jmp _add90conclusion
  5695. .globl _add90
  5696. .align 16
  5697. _add90:
  5698. pushq %rbp
  5699. movq %rsp, %rbp
  5700. pushq %r12
  5701. pushq %rbx
  5702. pushq %r13
  5703. pushq %r14
  5704. subq $0, %rsp
  5705. jmp _add90start
  5706. _add90conclusion:
  5707. addq $0, %rsp
  5708. popq %r14
  5709. popq %r13
  5710. popq %rbx
  5711. popq %r12
  5712. subq $0, %r15
  5713. popq %rbp
  5714. retq
  5715. \end{lstlisting}
  5716. \end{minipage}
  5717. &
  5718. \begin{minipage}{0.3\textwidth}
  5719. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5720. _mainstart:
  5721. leaq _add90(%rip), %rsi
  5722. movq $40, %rcx
  5723. movq $2, %rdx
  5724. movq %rsi, %rax
  5725. addq $0, %rsp
  5726. popq %r14
  5727. popq %r13
  5728. popq %rbx
  5729. popq %r12
  5730. subq $0, %r15
  5731. popq %rbp
  5732. jmp *%rax
  5733. .globl _main
  5734. .align 16
  5735. _main:
  5736. pushq %rbp
  5737. movq %rsp, %rbp
  5738. pushq %r12
  5739. pushq %rbx
  5740. pushq %r13
  5741. pushq %r14
  5742. subq $0, %rsp
  5743. movq $16384, %rdi
  5744. movq $16, %rsi
  5745. callq _initialize
  5746. movq _rootstack_begin(%rip), %r15
  5747. jmp _mainstart
  5748. \end{lstlisting}
  5749. \end{minipage}
  5750. &
  5751. \begin{minipage}{0.3\textwidth}
  5752. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5753. _mainconclusion:
  5754. addq $0, %rsp
  5755. popq %r14
  5756. popq %r13
  5757. popq %rbx
  5758. popq %r12
  5759. subq $0, %r15
  5760. popq %rbp
  5761. retq
  5762. \end{lstlisting}
  5763. \end{minipage}
  5764. \end{tabular}
  5765. \caption{Example compilation of a simple function to x86.}
  5766. \label{fig:add-fun}
  5767. \end{figure}
  5768. \begin{exercise}\normalfont
  5769. Expand your compiler to handle $R_4$ as outlined in this section.
  5770. Create 5 new programs that use functions, including examples that pass
  5771. functions and return functions from other functions and including
  5772. recursive functions. Test your compiler on these new programs and all
  5773. of your previously created test programs.
  5774. \end{exercise}
  5775. \begin{figure}[p]
  5776. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5777. \node (R4) at (0,2) {\large $R_4$};
  5778. \node (R4-2) at (3,2) {\large $R_4$};
  5779. \node (R4-3) at (6,2) {\large $R_4$};
  5780. \node (F1-1) at (12,0) {\large $F_1$};
  5781. \node (F1-2) at (9,0) {\large $F_1$};
  5782. \node (F1-3) at (6,0) {\large $F_1$};
  5783. \node (F1-4) at (3,0) {\large $F_1$};
  5784. \node (C3-1) at (6,-2) {\large $C_3$};
  5785. \node (C3-2) at (3,-2) {\large $C_3$};
  5786. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  5787. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  5788. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  5789. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  5790. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  5791. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  5792. \path[->,bend left=15] (R4) edge [above] node
  5793. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  5794. \path[->,bend left=15] (R4-2) edge [above] node
  5795. {\ttfamily\footnotesize uniquify} (R4-3);
  5796. \path[->,bend left=15] (R4-3) edge [right] node
  5797. {\ttfamily\footnotesize\color{red} reveal-functions} (F1-1);
  5798. \path[->,bend left=15] (F1-1) edge [below] node
  5799. {\ttfamily\footnotesize\color{red} limit-functions} (F1-2);
  5800. \path[->,bend right=15] (F1-2) edge [above] node
  5801. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  5802. \path[->,bend right=15] (F1-3) edge [above] node
  5803. {\ttfamily\footnotesize\color{red} remove-complex.} (F1-4);
  5804. \path[->,bend left=15] (F1-4) edge [right] node
  5805. {\ttfamily\footnotesize\color{red} explicate-control} (C3-1);
  5806. \path[->,bend left=15] (C3-1) edge [below] node
  5807. {\ttfamily\footnotesize\color{red} uncover-locals} (C3-2);
  5808. \path[->,bend right=15] (C3-2) edge [left] node
  5809. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  5810. \path[->,bend left=15] (x86-2) edge [left] node
  5811. {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  5812. \path[->,bend right=15] (x86-2-1) edge [below] node
  5813. {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  5814. \path[->,bend right=15] (x86-2-2) edge [left] node
  5815. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  5816. \path[->,bend left=15] (x86-3) edge [above] node
  5817. {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  5818. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  5819. \end{tikzpicture}
  5820. \caption{Diagram of the passes for $R_4$, a language with functions.}
  5821. \label{fig:R4-passes}
  5822. \end{figure}
  5823. Figure~\ref{fig:R4-passes} gives an overview of the passes needed for
  5824. the compilation of $R_4$.
  5825. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5826. \chapter{Lexically Scoped Functions}
  5827. \label{ch:lambdas}
  5828. This chapter studies lexically scoped functions as they appear in
  5829. functional languages such as Racket. By lexical scoping we mean that a
  5830. function's body may refer to variables whose binding site is outside
  5831. of the function, in an enclosing scope.
  5832. %
  5833. Consider the example in Figure~\ref{fig:lexical-scoping} featuring an
  5834. anonymous function defined using the \key{lambda} form. The body of
  5835. the \key{lambda}, refers to three variables: \code{x}, \code{y}, and
  5836. \code{z}. The binding sites for \code{x} and \code{y} are outside of
  5837. the \key{lambda}. Variable \code{y} is bound by the enclosing
  5838. \key{let} and \code{x} is a parameter of \code{f}. The \key{lambda} is
  5839. returned from the function \code{f}. Below the definition of \code{f},
  5840. we have two calls to \code{f} with different arguments for \code{x},
  5841. first \code{5} then \code{3}. The functions returned from \code{f} are
  5842. bound to variables \code{g} and \code{h}. Even though these two
  5843. functions were created by the same \code{lambda}, they are really
  5844. different functions because they use different values for
  5845. \code{x}. Finally, we apply \code{g} to \code{11} (producing
  5846. \code{20}) and apply \code{h} to \code{15} (producing \code{22}) so
  5847. the result of this program is \code{42}.
  5848. \begin{figure}[btp]
  5849. % s4_6.rkt
  5850. \begin{lstlisting}
  5851. (define (f [x : Integer]) : (Integer -> Integer)
  5852. (let ([y 4])
  5853. (lambda: ([z : Integer]) : Integer
  5854. (+ x (+ y z)))))
  5855. (let ([g (f 5)])
  5856. (let ([h (f 3)])
  5857. (+ (g 11) (h 15))))
  5858. \end{lstlisting}
  5859. \caption{Example of a lexically scoped function.}
  5860. \label{fig:lexical-scoping}
  5861. \end{figure}
  5862. \section{The $R_5$ Language}
  5863. The syntax for this language with anonymous functions and lexical
  5864. scoping, $R_5$, is defined in Figure~\ref{fig:r5-syntax}. It adds the
  5865. \key{lambda} form to the grammar for $R_4$, which already has syntax
  5866. for function application. In this chapter we shall describe how to
  5867. compile $R_5$ back into $R_4$, compiling lexically-scoped functions
  5868. into a combination of functions (as in $R_4$) and tuples (as in
  5869. $R_3$).
  5870. \begin{figure}[tp]
  5871. \centering
  5872. \fbox{
  5873. \begin{minipage}{0.96\textwidth}
  5874. \[
  5875. \begin{array}{lcl}
  5876. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  5877. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}
  5878. \mid (\Type^{*} \; \key{->}\; \Type)} \\
  5879. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  5880. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  5881. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}}\\
  5882. &\mid& \gray{\key{\#t} \mid \key{\#f}
  5883. \mid (\key{and}\;\Exp\;\Exp)
  5884. \mid (\key{or}\;\Exp\;\Exp)
  5885. \mid (\key{not}\;\Exp) } \\
  5886. &\mid& \gray{(\key{eq?}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5887. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5888. (\key{vector-ref}\;\Exp\;\Int)} \\
  5889. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  5890. &\mid& \gray{(\Exp \; \Exp^{*})} \\
  5891. &\mid& (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  5892. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5893. R_5 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  5894. \end{array}
  5895. \]
  5896. \end{minipage}
  5897. }
  5898. \caption{Syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax})
  5899. with \key{lambda}.}
  5900. \label{fig:r5-syntax}
  5901. \end{figure}
  5902. To compile lexically-scoped functions to top-level function
  5903. definitions, the compiler will need to provide special treatment to
  5904. variable occurrences such as \code{x} and \code{y} in the body of the
  5905. \code{lambda} of Figure~\ref{fig:lexical-scoping}, for the functions
  5906. of $R_4$ may not refer to variables defined outside the function. To
  5907. identify such variable occurrences, we review the standard notion of
  5908. free variable.
  5909. \begin{definition}
  5910. A variable is \emph{free with respect to an expression} $e$ if the
  5911. variable occurs inside $e$ but does not have an enclosing binding in
  5912. $e$.
  5913. \end{definition}
  5914. For example, the variables \code{x}, \code{y}, and \code{z} are all
  5915. free with respect to the expression \code{(+ x (+ y z))}. On the
  5916. other hand, only \code{x} and \code{y} are free with respect to the
  5917. following expression because \code{z} is bound by the \code{lambda}.
  5918. \begin{lstlisting}
  5919. (lambda: ([z : Integer]) : Integer
  5920. (+ x (+ y z)))
  5921. \end{lstlisting}
  5922. Once we have identified the free variables of a \code{lambda}, we need
  5923. to arrange for some way to transport, at runtime, the values of those
  5924. variables from the point where the \code{lambda} was created to the
  5925. point where the \code{lambda} is applied. Referring again to
  5926. Figure~\ref{fig:lexical-scoping}, the binding of \code{x} to \code{5}
  5927. needs to be used in the application of \code{g} to \code{11}, but the
  5928. binding of \code{x} to \code{3} needs to be used in the application of
  5929. \code{h} to \code{15}. An efficient solution to the problem, due to
  5930. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  5931. free variables together with the function pointer for the lambda's
  5932. code, an arrangement called a \emph{flat closure} (which we shorten to
  5933. just ``closure'') . Fortunately, we have all the ingredients to make
  5934. closures, Chapter~\ref{ch:tuples} gave us vectors and
  5935. Chapter~\ref{ch:functions} gave us function pointers. The function
  5936. pointer shall reside at index $0$ and the values for free variables
  5937. will fill in the rest of the vector. Figure~\ref{fig:closures} depicts
  5938. the two closures created by the two calls to \code{f} in
  5939. Figure~\ref{fig:lexical-scoping}. Because the two closures came from
  5940. the same \key{lambda}, they share the same function pointer but differ
  5941. in the values for the free variable \code{x}.
  5942. \begin{figure}[tbp]
  5943. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  5944. \caption{Example closure representation for the \key{lambda}'s
  5945. in Figure~\ref{fig:lexical-scoping}.}
  5946. \label{fig:closures}
  5947. \end{figure}
  5948. \section{Interpreting $R_5$}
  5949. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  5950. $R_5$. The clause for \key{lambda} saves the current environment
  5951. inside the returned \key{lambda}. Then the clause for \key{app} uses
  5952. the environment from the \key{lambda}, the \code{lam-env}, when
  5953. interpreting the body of the \key{lambda}. The \code{lam-env}
  5954. environment is extended with the mapping of parameters to argument
  5955. values.
  5956. \begin{figure}[tbp]
  5957. \begin{lstlisting}
  5958. (define (interp-exp env)
  5959. (lambda (e)
  5960. (define recur (interp-exp env))
  5961. (match e
  5962. ...
  5963. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  5964. `(lambda ,xs ,body ,env)]
  5965. [`(app ,fun ,args ...)
  5966. (define fun-val ((interp-exp env) fun))
  5967. (define arg-vals (map (interp-exp env) args))
  5968. (match fun-val
  5969. [`(lambda (,xs ...) ,body ,lam-env)
  5970. (define new-env (append (map cons xs arg-vals) lam-env))
  5971. ((interp-exp new-env) body)]
  5972. [else (error "interp-exp, expected function, not" fun-val)])]
  5973. [else (error 'interp-exp "unrecognized expression")]
  5974. )))
  5975. \end{lstlisting}
  5976. \caption{Interpreter for $R_5$.}
  5977. \label{fig:interp-R5}
  5978. \end{figure}
  5979. \section{Type Checking $R_5$}
  5980. Figure~\ref{fig:typecheck-R5} shows how to type check the new
  5981. \key{lambda} form. The body of the \key{lambda} is checked in an
  5982. environment that includes the current environment (because it is
  5983. lexically scoped) and also includes the \key{lambda}'s parameters. We
  5984. require the body's type to match the declared return type.
  5985. \begin{figure}[tbp]
  5986. \begin{lstlisting}
  5987. (define (typecheck-R5 env)
  5988. (lambda (e)
  5989. (match e
  5990. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  5991. (define new-env (append (map cons xs Ts) env))
  5992. (define bodyT ((typecheck-R5 new-env) body))
  5993. (cond [(equal? rT bodyT)
  5994. `(,@Ts -> ,rT)]
  5995. [else
  5996. (error "mismatch in return type" bodyT rT)])]
  5997. ...
  5998. )))
  5999. \end{lstlisting}
  6000. \caption{Type checking the \key{lambda}'s in $R_5$.}
  6001. \label{fig:typecheck-R5}
  6002. \end{figure}
  6003. \section{Closure Conversion}
  6004. The compiling of lexically-scoped functions into top-level function
  6005. definitions is accomplished in the pass \code{convert-to-closures}
  6006. that comes after \code{reveal-functions} and before
  6007. \code{limit-functions}.
  6008. As usual, we shall implement the pass as a recursive function over the
  6009. AST. All of the action is in the clauses for \key{lambda} and
  6010. \key{app}. We transform a \key{lambda} expression into an expression
  6011. that creates a closure, that is, creates a vector whose first element
  6012. is a function pointer and the rest of the elements are the free
  6013. variables of the \key{lambda}. The \itm{name} is a unique symbol
  6014. generated to identify the function.
  6015. \begin{tabular}{lll}
  6016. \begin{minipage}{0.4\textwidth}
  6017. \begin{lstlisting}
  6018. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  6019. \end{lstlisting}
  6020. \end{minipage}
  6021. &
  6022. $\Rightarrow$
  6023. &
  6024. \begin{minipage}{0.4\textwidth}
  6025. \begin{lstlisting}
  6026. (vector |\itm{name}| |\itm{fvs}| ...)
  6027. \end{lstlisting}
  6028. \end{minipage}
  6029. \end{tabular} \\
  6030. %
  6031. In addition to transforming each \key{lambda} into a \key{vector}, we
  6032. must create a top-level function definition for each \key{lambda}, as
  6033. shown below.\\
  6034. \begin{minipage}{0.8\textwidth}
  6035. \begin{lstlisting}
  6036. (define (|\itm{name}| [clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps}| ...)
  6037. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  6038. ...
  6039. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  6040. |\itm{body'}|)...))
  6041. \end{lstlisting}
  6042. \end{minipage}\\
  6043. The \code{clos} parameter refers to the closure. The $\itm{ps}$
  6044. parameters are the normal parameters of the \key{lambda}. The types
  6045. $\itm{fvts}$ are the types of the free variables in the lambda and the
  6046. underscore is a dummy type because it is rather difficult to give a
  6047. type to the function in the closure's type, and it does not matter.
  6048. The sequence of \key{let} forms bind the free variables to their
  6049. values obtained from the closure.
  6050. We transform function application into code that retrieves the
  6051. function pointer from the closure and then calls the function, passing
  6052. in the closure as the first argument. We bind $e'$ to a temporary
  6053. variable to avoid code duplication.
  6054. \begin{tabular}{lll}
  6055. \begin{minipage}{0.3\textwidth}
  6056. \begin{lstlisting}
  6057. (app |$e$| |\itm{es}| ...)
  6058. \end{lstlisting}
  6059. \end{minipage}
  6060. &
  6061. $\Rightarrow$
  6062. &
  6063. \begin{minipage}{0.5\textwidth}
  6064. \begin{lstlisting}
  6065. (let ([|\itm{tmp}| |$e'$|])
  6066. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  6067. \end{lstlisting}
  6068. \end{minipage}
  6069. \end{tabular} \\
  6070. There is also the question of what to do with top-level function
  6071. definitions. To maintain a uniform translation of function
  6072. application, we turn function references into closures.
  6073. \begin{tabular}{lll}
  6074. \begin{minipage}{0.3\textwidth}
  6075. \begin{lstlisting}
  6076. (fun-ref |$f$|)
  6077. \end{lstlisting}
  6078. \end{minipage}
  6079. &
  6080. $\Rightarrow$
  6081. &
  6082. \begin{minipage}{0.5\textwidth}
  6083. \begin{lstlisting}
  6084. (vector (fun-ref |$f$|))
  6085. \end{lstlisting}
  6086. \end{minipage}
  6087. \end{tabular} \\
  6088. %
  6089. The top-level function definitions need to be updated as well to take
  6090. an extra closure parameter.
  6091. \section{An Example Translation}
  6092. \label{sec:example-lambda}
  6093. Figure~\ref{fig:lexical-functions-example} shows the result of closure
  6094. conversion for the example program demonstrating lexical scoping that
  6095. we discussed at the beginning of this chapter.
  6096. \begin{figure}[h]
  6097. \begin{minipage}{0.8\textwidth}
  6098. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6099. (program
  6100. (define (f [x : Integer]) : (Integer -> Integer)
  6101. (let ([y 4])
  6102. (lambda: ([z : Integer]) : Integer
  6103. (+ x (+ y z)))))
  6104. (let ([g (f 5)])
  6105. (let ([h (f 3)])
  6106. (+ (g 11) (h 15)))))
  6107. \end{lstlisting}
  6108. $\Downarrow$
  6109. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6110. (program (type Integer)
  6111. (define (f (x : Integer)) : (Integer -> Integer)
  6112. (let ((y 4))
  6113. (lambda: ((z : Integer)) : Integer
  6114. (+ x (+ y z)))))
  6115. (let ((g (app (fun-ref f) 5)))
  6116. (let ((h (app (fun-ref f) 3)))
  6117. (+ (app g 11) (app h 15)))))
  6118. \end{lstlisting}
  6119. $\Downarrow$
  6120. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6121. (program (type Integer)
  6122. (define (f (clos.1 : _) (x : Integer)) : (Integer -> Integer)
  6123. (let ((y 4))
  6124. (vector (fun-ref lam.1) x y)))
  6125. (define (lam.1 (clos.2 : _) (z : Integer)) : Integer
  6126. (let ((x (vector-ref clos.2 1)))
  6127. (let ((y (vector-ref clos.2 2)))
  6128. (+ x (+ y z)))))
  6129. (let ((g (let ((t.1 (vector (fun-ref f))))
  6130. (app (vector-ref t.1 0) t.1 5))))
  6131. (let ((h (let ((t.2 (vector (fun-ref f))))
  6132. (app (vector-ref t.2 0) t.2 3))))
  6133. (+ (let ((t.3 g)) (app (vector-ref t.3 0) t.3 11))
  6134. (let ((t.4 h)) (app (vector-ref t.4 0) t.4 15))))))
  6135. \end{lstlisting}
  6136. \end{minipage}
  6137. \caption{Example of closure conversion.}
  6138. \label{fig:lexical-functions-example}
  6139. \end{figure}
  6140. \begin{figure}[p]
  6141. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6142. \node (R4) at (0,2) {\large $R_4$};
  6143. \node (R4-2) at (3,2) {\large $R_4$};
  6144. \node (R4-3) at (6,2) {\large $R_4$};
  6145. \node (F1-1) at (12,0) {\large $F_1$};
  6146. \node (F1-2) at (9,0) {\large $F_1$};
  6147. \node (F1-3) at (6,0) {\large $F_1$};
  6148. \node (F1-4) at (3,0) {\large $F_1$};
  6149. \node (F1-5) at (0,0) {\large $F_1$};
  6150. \node (C3-1) at (6,-2) {\large $C_3$};
  6151. \node (C3-2) at (3,-2) {\large $C_3$};
  6152. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  6153. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  6154. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  6155. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  6156. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  6157. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  6158. \path[->,bend left=15] (R4) edge [above] node
  6159. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  6160. \path[->,bend left=15] (R4-2) edge [above] node
  6161. {\ttfamily\footnotesize uniquify} (R4-3);
  6162. \path[->] (R4-3) edge [right] node
  6163. {\ttfamily\footnotesize reveal-functions} (F1-1);
  6164. \path[->,bend left=15] (F1-1) edge [below] node
  6165. {\ttfamily\footnotesize\color{red} convert-to-clos.} (F1-2);
  6166. \path[->,bend right=15] (F1-2) edge [above] node
  6167. {\ttfamily\footnotesize limit-functions} (F1-3);
  6168. \path[->,bend right=15] (F1-3) edge [above] node
  6169. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  6170. \path[->,bend right=15] (F1-4) edge [above] node
  6171. {\ttfamily\footnotesize remove-complex.} (F1-5);
  6172. \path[->] (F1-5) edge [left] node
  6173. {\ttfamily\footnotesize explicate-control} (C3-1);
  6174. \path[->,bend left=15] (C3-1) edge [below] node
  6175. {\ttfamily\footnotesize uncover-locals} (C3-2);
  6176. \path[->,bend right=15] (C3-2) edge [left] node
  6177. {\ttfamily\footnotesize select-instr.} (x86-2);
  6178. \path[->,bend left=15] (x86-2) edge [left] node
  6179. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6180. \path[->,bend right=15] (x86-2-1) edge [below] node
  6181. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  6182. \path[->,bend right=15] (x86-2-2) edge [left] node
  6183. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6184. \path[->,bend left=15] (x86-3) edge [above] node
  6185. {\ttfamily\footnotesize patch-instr.} (x86-4);
  6186. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  6187. \end{tikzpicture}
  6188. \caption{Diagram of the passes for $R_5$, a language with lexically-scoped
  6189. functions.}
  6190. \label{fig:R5-passes}
  6191. \end{figure}
  6192. Figure~\ref{fig:R5-passes} provides an overview of all the passes needed
  6193. for the compilation of $R_5$.
  6194. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6195. \chapter{Dynamic Typing}
  6196. \label{ch:type-dynamic}
  6197. In this chapter we discuss the compilation of a dynamically typed
  6198. language, named $R_7$, that is a subset of the Racket
  6199. language. (Recall that in the previous chapters we have studied
  6200. subsets of the \emph{Typed} Racket language.) In dynamically typed
  6201. languages, an expression may produce values of differing
  6202. type. Consider the following example with a conditional expression
  6203. that may return a Boolean or an integer depending on the input to the
  6204. program.
  6205. \begin{lstlisting}
  6206. (not (if (eq? (read) 1) #f 0))
  6207. \end{lstlisting}
  6208. Languages that allow expressions to produce different kinds of values
  6209. are called \emph{polymorphic}. There are many kinds of polymorphism,
  6210. such as subtype polymorphism and parametric
  6211. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism are
  6212. talking about here does not have a special name, but it is the usual
  6213. kind that arises in dynamically typed languages.
  6214. Another characteristic of dynamically typed languages is that
  6215. primitive operations, such as \code{not}, are often defined to operate
  6216. on many different types of values. In fact, in Racket, the \code{not}
  6217. operator produces a result for any kind of value: given \code{\#f} it
  6218. returns \code{\#t} and given anything else it returns \code{\#f}.
  6219. Furthermore, even when primitive operations restrict their inputs to
  6220. values of a certain type, this restriction is enforced at runtime
  6221. instead of during compilation. For example, the following vector
  6222. reference results in a run-time contract violation.
  6223. \begin{lstlisting}
  6224. (vector-ref (vector 42) #t)
  6225. \end{lstlisting}
  6226. \begin{figure}[tp]
  6227. \centering
  6228. \fbox{
  6229. \begin{minipage}{0.97\textwidth}
  6230. \[
  6231. \begin{array}{rcl}
  6232. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  6233. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6234. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp) \\
  6235. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  6236. &\mid& \key{\#t} \mid \key{\#f}
  6237. \mid (\key{and}\;\Exp\;\Exp)
  6238. \mid (\key{or}\;\Exp\;\Exp)
  6239. \mid (\key{not}\;\Exp) \\
  6240. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  6241. &\mid& (\key{vector}\;\Exp^{+}) \mid
  6242. (\key{vector-ref}\;\Exp\;\Exp) \\
  6243. &\mid& (\key{vector-set!}\;\Exp\;\Exp\;\Exp) \mid (\key{void}) \\
  6244. &\mid& (\Exp \; \Exp^{*}) \mid (\key{lambda}\; (\Var^{*}) \; \Exp) \\
  6245. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  6246. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  6247. \Def &::=& (\key{define}\; (\Var \; \Var^{*}) \; \Exp) \\
  6248. R_7 &::=& (\key{program} \; \Def^{*}\; \Exp)
  6249. \end{array}
  6250. \]
  6251. \end{minipage}
  6252. }
  6253. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  6254. \label{fig:r7-syntax}
  6255. \end{figure}
  6256. The syntax of $R_7$, our subset of Racket, is defined in
  6257. Figure~\ref{fig:r7-syntax}.
  6258. %
  6259. The definitional interpreter for $R_7$ is given in
  6260. Figure~\ref{fig:interp-R7}.
  6261. \begin{figure}[tbp]
  6262. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6263. (define (get-tagged-type v) (match v [`(tagged ,v1 ,ty) ty]))
  6264. (define (valid-op? op) (member op '(+ - and or not)))
  6265. (define (interp-r7 env)
  6266. (lambda (ast)
  6267. (define recur (interp-r7 env))
  6268. (match ast
  6269. [(? symbol?) (lookup ast env)]
  6270. [(? integer?) `(inject ,ast Integer)]
  6271. [#t `(inject #t Boolean)]
  6272. [#f `(inject #f Boolean)]
  6273. [`(read) `(inject ,(read-fixnum) Integer)]
  6274. [`(lambda (,xs ...) ,body)
  6275. `(inject (lambda ,xs ,body ,env) (,@(map (lambda (x) 'Any) xs) -> Any))]
  6276. [`(define (,f ,xs ...) ,body)
  6277. (mcons f `(lambda ,xs ,body))]
  6278. [`(program ,ds ... ,body)
  6279. (let ([top-level (for/list ([d ds]) ((interp-r7 '()) d))])
  6280. (for/list ([b top-level])
  6281. (set-mcdr! b (match (mcdr b)
  6282. [`(lambda ,xs ,body)
  6283. `(inject (lambda ,xs ,body ,top-level)
  6284. (,@(map (lambda (x) 'Any) xs) -> Any))])))
  6285. ((interp-r7 top-level) body))]
  6286. [`(vector ,(app recur elts) ...)
  6287. (define tys (map get-tagged-type elts))
  6288. `(inject ,(apply vector elts) (Vector ,@tys))]
  6289. [`(vector-set! ,(app recur v1) ,n ,(app recur v2))
  6290. (match v1
  6291. [`(inject ,vec ,ty)
  6292. (vector-set! vec n v2)
  6293. `(inject (void) Void)])]
  6294. [`(vector-ref ,(app recur v) ,n)
  6295. (match v [`(inject ,vec ,ty) (vector-ref vec n)])]
  6296. [`(let ([,x ,(app recur v)]) ,body)
  6297. ((interp-r7 (cons (cons x v) env)) body)]
  6298. [`(,op ,es ...) #:when (valid-op? op)
  6299. (interp-r7-op op (for/list ([e es]) (recur e)))]
  6300. [`(eq? ,(app recur l) ,(app recur r))
  6301. `(inject ,(equal? l r) Boolean)]
  6302. [`(if ,(app recur q) ,t ,f)
  6303. (match q
  6304. [`(inject #f Boolean) (recur f)]
  6305. [else (recur t)])]
  6306. [`(,(app recur f-val) ,(app recur vs) ...)
  6307. (match f-val
  6308. [`(inject (lambda (,xs ...) ,body ,lam-env) ,ty)
  6309. (define new-env (append (map cons xs vs) lam-env))
  6310. ((interp-r7 new-env) body)]
  6311. [else (error "interp-r7, expected function, not" f-val)])])))
  6312. \end{lstlisting}
  6313. \caption{Interpreter for the $R_7$ language. UPDATE ME -Jeremy}
  6314. \label{fig:interp-R7}
  6315. \end{figure}
  6316. Let us consider how we might compile $R_7$ to x86, thinking about the
  6317. first example above. Our bit-level representation of the Boolean
  6318. \code{\#f} is zero and similarly for the integer \code{0}. However,
  6319. \code{(not \#f)} should produce \code{\#t} whereas \code{(not 0)}
  6320. should produce \code{\#f}. Furthermore, the behavior of \code{not}, in
  6321. general, cannot be determined at compile time, but depends on the
  6322. runtime type of its input, as in the example above that depends on the
  6323. result of \code{(read)}.
  6324. The way around this problem is to include information about a value's
  6325. runtime type in the value itself, so that this information can be
  6326. inspected by operators such as \code{not}. In particular, we shall
  6327. steal the 3 right-most bits from our 64-bit values to encode the
  6328. runtime type. We shall use $001$ to identify integers, $100$ for
  6329. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  6330. void value. We shall refer to these 3 bits as the \emph{tag} and we
  6331. define the following auxiliary function.
  6332. \begin{align*}
  6333. \itm{tagof}(\key{Integer}) &= 001 \\
  6334. \itm{tagof}(\key{Boolean}) &= 100 \\
  6335. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  6336. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  6337. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  6338. \itm{tagof}(\key{Void}) &= 101
  6339. \end{align*}
  6340. (We shall say more about the new \key{Vectorof} type shortly.)
  6341. This stealing of 3 bits comes at some
  6342. price: our integers are reduced to ranging from $-2^{60}$ to
  6343. $2^{60}$. The stealing does not adversely affect vectors and
  6344. procedures because those values are addresses, and our addresses are
  6345. 8-byte aligned so the rightmost 3 bits are unused, they are always
  6346. $000$. Thus, we do not lose information by overwriting the rightmost 3
  6347. bits with the tag and we can simply zero-out the tag to recover the
  6348. original address.
  6349. In some sense, these tagged values are a new kind of value. Indeed,
  6350. we can extend our \emph{typed} language with tagged values by adding a
  6351. new type to classify them, called \key{Any}, and with operations for
  6352. creating and using tagged values, yielding the $R_6$ language that we
  6353. define in Section~\ref{sec:r6-lang}. The $R_6$ language provides the
  6354. fundamental support for polymorphism and runtime types that we need to
  6355. support dynamic typing.
  6356. There is an interesting interaction between tagged values and garbage
  6357. collection. A variable of type \code{Any} might refer to a vector and
  6358. therefore it might be a root that needs to be inspected and copied
  6359. during garbage collection. Thus, we need to treat variables of type
  6360. \code{Any} in a similar way to variables of type \code{Vector} for
  6361. purposes of register allocation, which we discuss in
  6362. Section~\ref{sec:register-allocation-r6}. One concern is that, if a
  6363. variable of type \code{Any} is spilled, it must be spilled to the root
  6364. stack. But this means that the garbage collector needs to be able to
  6365. differentiate between (1) plain old pointers to tuples, (2) a tagged
  6366. value that points to a tuple, and (3) a tagged value that is not a
  6367. tuple. We enable this differentiation by choosing not to use the tag
  6368. $000$. Instead, that bit pattern is reserved for identifying plain old
  6369. pointers to tuples. On the other hand, if one of the first three bits
  6370. is set, then we have a tagged value, and inspecting the tag can
  6371. differentiation between vectors ($010$) and the other kinds of values.
  6372. We shall implement our untyped language $R_7$ by compiling it to $R_6$
  6373. (Section~\ref{sec:compile-r7}), but first we describe the how to
  6374. extend our compiler to handle the new features of $R_6$
  6375. (Sections~\ref{sec:shrink-r6}, \ref{sec:select-r6}, and
  6376. \ref{sec:register-allocation-r6}).
  6377. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  6378. \label{sec:r6-lang}
  6379. \begin{figure}[tp]
  6380. \centering
  6381. \fbox{
  6382. \begin{minipage}{0.97\textwidth}
  6383. \[
  6384. \begin{array}{lcl}
  6385. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6386. \mid (\key{Vector}\;\Type^{+}) \mid (\key{Vectorof}\;\Type) \mid \key{Void}} \\
  6387. &\mid& \gray{(\Type^{*} \; \key{->}\; \Type)} \mid \key{Any} \\
  6388. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void} \mid (\key{Vectorof}\;\key{Any}) \mid (\key{Vector}\; \key{Any}^{*}) \\
  6389. &\mid& (\key{Any}^{*} \; \key{->}\; \key{Any})\\
  6390. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  6391. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6392. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  6393. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  6394. &\mid& \gray{\key{\#t} \mid \key{\#f}
  6395. \mid (\key{and}\;\Exp\;\Exp)
  6396. \mid (\key{or}\;\Exp\;\Exp)
  6397. \mid (\key{not}\;\Exp)} \\
  6398. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6399. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  6400. (\key{vector-ref}\;\Exp\;\Int)} \\
  6401. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  6402. &\mid& \gray{(\Exp \; \Exp^{*})
  6403. \mid (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6404. & \mid & (\key{inject}\; \Exp \; \FType) \mid (\key{project}\;\Exp\;\FType) \\
  6405. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  6406. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  6407. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6408. R_6 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  6409. \end{array}
  6410. \]
  6411. \end{minipage}
  6412. }
  6413. \caption{Syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax})
  6414. with \key{Any}.}
  6415. \label{fig:r6-syntax}
  6416. \end{figure}
  6417. The syntax of $R_6$ is defined in Figure~\ref{fig:r6-syntax}. The
  6418. $(\key{inject}\; e\; T)$ form converts the value produced by
  6419. expression $e$ of type $T$ into a tagged value. The
  6420. $(\key{project}\;e\;T)$ form converts the tagged value produced by
  6421. expression $e$ into a value of type $T$ or else halts the program if
  6422. the type tag is equivalent to $T$. We treat
  6423. $(\key{Vectorof}\;\key{Any})$ as equivalent to
  6424. $(\key{Vector}\;\key{Any}\;\ldots)$.
  6425. Note that in both \key{inject} and
  6426. \key{project}, the type $T$ is restricted to the flat types $\FType$,
  6427. which simplifies the implementation and corresponds with what is
  6428. needed for compiling untyped Racket. The type predicates,
  6429. $(\key{boolean?}\,e)$ etc., expect a tagged value and return \key{\#t}
  6430. if the tag corresponds to the predicate, and return \key{\#t}
  6431. otherwise.
  6432. %
  6433. Selections from the type checker for $R_6$ are shown in
  6434. Figure~\ref{fig:typecheck-R6} and the interpreter for $R_6$ is in
  6435. Figure~\ref{fig:interp-R6}.
  6436. \begin{figure}[btp]
  6437. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6438. (define (flat-ty? ty) ...)
  6439. (define (typecheck-R6 env)
  6440. (lambda (e)
  6441. (define recur (typecheck-R6 env))
  6442. (match e
  6443. [`(inject ,e ,ty)
  6444. (unless (flat-ty? ty)
  6445. (error "may only inject a value of flat type, not ~a" ty))
  6446. (define-values (new-e e-ty) (recur e))
  6447. (cond
  6448. [(equal? e-ty ty)
  6449. (values `(inject ,new-e ,ty) 'Any)]
  6450. [else
  6451. (error "inject expected ~a to have type ~a" e ty)])]
  6452. [`(project ,e ,ty)
  6453. (unless (flat-ty? ty)
  6454. (error "may only project to a flat type, not ~a" ty))
  6455. (define-values (new-e e-ty) (recur e))
  6456. (cond
  6457. [(equal? e-ty 'Any)
  6458. (values `(project ,new-e ,ty) ty)]
  6459. [else
  6460. (error "project expected ~a to have type Any" e)])]
  6461. [`(vector-ref ,e ,i)
  6462. (define-values (new-e e-ty) (recur e))
  6463. (match e-ty
  6464. [`(Vector ,ts ...) ...]
  6465. [`(Vectorof ,ty)
  6466. (unless (exact-nonnegative-integer? i)
  6467. (error 'type-check "invalid index ~a" i))
  6468. (values `(vector-ref ,new-e ,i) ty)]
  6469. [else (error "expected a vector in vector-ref, not" e-ty)])]
  6470. ...
  6471. )))
  6472. \end{lstlisting}
  6473. \caption{Type checker for parts of the $R_6$ language.}
  6474. \label{fig:typecheck-R6}
  6475. \end{figure}
  6476. % to do: add rules for vector-ref, etc. for Vectorof
  6477. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  6478. \begin{figure}[btp]
  6479. \begin{lstlisting}
  6480. (define primitives (set 'boolean? ...))
  6481. (define (interp-op op)
  6482. (match op
  6483. ['boolean? (lambda (v)
  6484. (match v
  6485. [`(tagged ,v1 Boolean) #t]
  6486. [else #f]))]
  6487. ...))
  6488. ;; Equivalence of flat types
  6489. (define (tyeq? t1 t2)
  6490. (match `(,t1 ,t2)
  6491. [`((Vectorof Any) (Vector ,t2s ...))
  6492. (for/and ([t2 t2s]) (eq? t2 'Any))]
  6493. [`((Vector ,t1s ...) (Vectorof Any))
  6494. (for/and ([t1 t1s]) (eq? t1 'Any))]
  6495. [else (equal? t1 t2)]))
  6496. (define (interp-R6 env)
  6497. (lambda (ast)
  6498. (match ast
  6499. [`(inject ,e ,t)
  6500. `(tagged ,((interp-R6 env) e) ,t)]
  6501. [`(project ,e ,t2)
  6502. (define v ((interp-R6 env) e))
  6503. (match v
  6504. [`(tagged ,v1 ,t1)
  6505. (cond [(tyeq? t1 t2)
  6506. v1]
  6507. [else
  6508. (error "in project, type mismatch" t1 t2)])]
  6509. [else
  6510. (error "in project, expected tagged value" v)])]
  6511. ...)))
  6512. \end{lstlisting}
  6513. \caption{Interpreter for $R_6$.}
  6514. \label{fig:interp-R6}
  6515. \end{figure}
  6516. %\clearpage
  6517. \section{Shrinking $R_6$}
  6518. \label{sec:shrink-r6}
  6519. In the \code{shrink} pass we recommend compiling \code{project} into
  6520. an explicit \code{if} expression that uses three new operations:
  6521. \code{tag-of-any}, \code{value-of-any}, and \code{exit}. The
  6522. \code{tag-of-any} operation retrieves the type tag from a tagged value
  6523. of type \code{Any}. The \code{value-of-any} retrieves the underlying
  6524. value from a tagged value. Finally, the \code{exit} operation ends the
  6525. execution of the program by invoking the operating system's
  6526. \code{exit} function. So the translation for \code{project} is as
  6527. follows. (We have omitted the \code{has-type} AST nodes to make this
  6528. output more readable.)
  6529. \begin{tabular}{lll}
  6530. \begin{minipage}{0.3\textwidth}
  6531. \begin{lstlisting}
  6532. (project |$e$| |$\Type$|)
  6533. \end{lstlisting}
  6534. \end{minipage}
  6535. &
  6536. $\Rightarrow$
  6537. &
  6538. \begin{minipage}{0.5\textwidth}
  6539. \begin{lstlisting}
  6540. (let ([|$\itm{tmp}$| |$e'$|])
  6541. (if (eq? (tag-of-any |$\itm{tmp}$|) |$\itm{tag}$|)
  6542. (value-of-any |$\itm{tmp}$|)
  6543. (exit)))
  6544. \end{lstlisting}
  6545. \end{minipage}
  6546. \end{tabular} \\
  6547. Similarly, we recommend translating the type predicates
  6548. (\code{boolean?}, etc.) into uses of \code{tag-of-any} and \code{eq?}.
  6549. \section{Instruction Selection for $R_6$}
  6550. \label{sec:select-r6}
  6551. \paragraph{Inject}
  6552. We recommend compiling an \key{inject} as follows if the type is
  6553. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  6554. destination to the left by the number of bits specified its source
  6555. argument (in this case $3$, the length of the tag) and it preserves
  6556. the sign of the integer. We use the \key{orq} instruction to combine
  6557. the tag and the value to form the tagged value. \\
  6558. \begin{tabular}{lll}
  6559. \begin{minipage}{0.4\textwidth}
  6560. \begin{lstlisting}
  6561. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  6562. \end{lstlisting}
  6563. \end{minipage}
  6564. &
  6565. $\Rightarrow$
  6566. &
  6567. \begin{minipage}{0.5\textwidth}
  6568. \begin{lstlisting}
  6569. (movq |$e'$| |\itm{lhs}'|)
  6570. (salq (int 3) |\itm{lhs}'|)
  6571. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  6572. \end{lstlisting}
  6573. \end{minipage}
  6574. \end{tabular} \\
  6575. The instruction selection for vectors and procedures is different
  6576. because their is no need to shift them to the left. The rightmost 3
  6577. bits are already zeros as described above. So we just combine the
  6578. value and the tag using \key{orq}. \\
  6579. \begin{tabular}{lll}
  6580. \begin{minipage}{0.4\textwidth}
  6581. \begin{lstlisting}
  6582. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  6583. \end{lstlisting}
  6584. \end{minipage}
  6585. &
  6586. $\Rightarrow$
  6587. &
  6588. \begin{minipage}{0.5\textwidth}
  6589. \begin{lstlisting}
  6590. (movq |$e'$| |\itm{lhs}'|)
  6591. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  6592. \end{lstlisting}
  6593. \end{minipage}
  6594. \end{tabular}
  6595. \paragraph{Tag of Any}
  6596. Recall that the \code{tag-of-any} operation extracts the type tag from
  6597. a value of type \code{Any}. The type tag is the bottom three bits, so
  6598. we obtain the tag by taking the bitwise-and of the value with $111$
  6599. ($7$ in decimal).
  6600. \begin{tabular}{lll}
  6601. \begin{minipage}{0.4\textwidth}
  6602. \begin{lstlisting}
  6603. (assign |\itm{lhs}| (tag-of-any |$e$|))
  6604. \end{lstlisting}
  6605. \end{minipage}
  6606. &
  6607. $\Rightarrow$
  6608. &
  6609. \begin{minipage}{0.5\textwidth}
  6610. \begin{lstlisting}
  6611. (movq |$e'$| |\itm{lhs}'|)
  6612. (andq (int 7) |\itm{lhs}'|)
  6613. \end{lstlisting}
  6614. \end{minipage}
  6615. \end{tabular}
  6616. \paragraph{Value of Any}
  6617. Like \key{inject}, the instructions for \key{value-of-any} are
  6618. different depending on whether the type $T$ is a pointer (vector or
  6619. procedure) or not (Integer or Boolean). The following shows the
  6620. instruction selection for Integer and Boolean. We produce an untagged
  6621. value by shifting it to the right by 3 bits.
  6622. %
  6623. \\
  6624. \begin{tabular}{lll}
  6625. \begin{minipage}{0.4\textwidth}
  6626. \begin{lstlisting}
  6627. (assign |\itm{lhs}| (project |$e$| |$T$|))
  6628. \end{lstlisting}
  6629. \end{minipage}
  6630. &
  6631. $\Rightarrow$
  6632. &
  6633. \begin{minipage}{0.5\textwidth}
  6634. \begin{lstlisting}
  6635. (movq |$e'$| |\itm{lhs}'|)
  6636. (sarq (int 3) |\itm{lhs}'|)
  6637. \end{lstlisting}
  6638. \end{minipage}
  6639. \end{tabular} \\
  6640. %
  6641. In the case for vectors and procedures, there is no need to
  6642. shift. Instead we just need to zero-out the rightmost 3 bits. We
  6643. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  6644. decimal) and apply \code{bitwise-not} to obtain $\ldots 1000$ which we
  6645. \code{movq} into the destination $\itm{lhs}$. We then generate
  6646. \code{andq} with the tagged value to get the desired result. \\
  6647. %
  6648. \begin{tabular}{lll}
  6649. \begin{minipage}{0.4\textwidth}
  6650. \begin{lstlisting}
  6651. (assign |\itm{lhs}| (project |$e$| |$T$|))
  6652. \end{lstlisting}
  6653. \end{minipage}
  6654. &
  6655. $\Rightarrow$
  6656. &
  6657. \begin{minipage}{0.5\textwidth}
  6658. \begin{lstlisting}
  6659. (movq (int |$\ldots 1000$|) |\itm{lhs}'|)
  6660. (andq |$e'$| |\itm{lhs}'|)
  6661. \end{lstlisting}
  6662. \end{minipage}
  6663. \end{tabular}
  6664. %% \paragraph{Type Predicates} We leave it to the reader to
  6665. %% devise a sequence of instructions to implement the type predicates
  6666. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  6667. \section{Register Allocation for $R_6$}
  6668. \label{sec:register-allocation-r6}
  6669. As mentioned above, a variable of type \code{Any} might refer to a
  6670. vector. Thus, the register allocator for $R_6$ needs to treat variable
  6671. of type \code{Any} in the same way that it treats variables of type
  6672. \code{Vector} for purposes of garbage collection. In particular,
  6673. \begin{itemize}
  6674. \item If a variable of type \code{Any} is live during a function call,
  6675. then it must be spilled. One way to accomplish this is to augment
  6676. the pass \code{build-interference} to mark all variables that are
  6677. live after a \code{callq} as interfering with all the registers.
  6678. \item If a variable of type \code{Any} is spilled, it must be spilled
  6679. to the root stack instead of the normal procedure call stack.
  6680. \end{itemize}
  6681. \section{Compiling $R_7$ to $R_6$}
  6682. \label{sec:compile-r7}
  6683. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  6684. $R_7$ forms into $R_6$. An important invariant of this pass is that
  6685. given a subexpression $e$ of $R_7$, the pass will produce an
  6686. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  6687. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  6688. the Boolean \code{\#t}, which must be injected to produce an
  6689. expression of type \key{Any}.
  6690. %
  6691. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  6692. addition, is representative of compilation for many operations: the
  6693. arguments have type \key{Any} and must be projected to \key{Integer}
  6694. before the addition can be performed.
  6695. The compilation of \key{lambda} (third row of
  6696. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  6697. produce type annotations: we simply use \key{Any}.
  6698. %
  6699. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  6700. has to account for some differences in behavior between $R_7$ and
  6701. $R_6$. The $R_7$ language is more permissive than $R_6$ regarding what
  6702. kind of values can be used in various places. For example, the
  6703. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  6704. the arguments need not be of the same type (but in that case, the
  6705. result will be \code{\#f}).
  6706. \begin{figure}[btp]
  6707. \centering
  6708. \begin{tabular}{|lll|} \hline
  6709. \begin{minipage}{0.25\textwidth}
  6710. \begin{lstlisting}
  6711. #t
  6712. \end{lstlisting}
  6713. \end{minipage}
  6714. &
  6715. $\Rightarrow$
  6716. &
  6717. \begin{minipage}{0.6\textwidth}
  6718. \begin{lstlisting}
  6719. (inject #t Boolean)
  6720. \end{lstlisting}
  6721. \end{minipage}
  6722. \\[2ex]\hline
  6723. \begin{minipage}{0.25\textwidth}
  6724. \begin{lstlisting}
  6725. (+ |$e_1$| |$e_2$|)
  6726. \end{lstlisting}
  6727. \end{minipage}
  6728. &
  6729. $\Rightarrow$
  6730. &
  6731. \begin{minipage}{0.6\textwidth}
  6732. \begin{lstlisting}
  6733. (inject
  6734. (+ (project |$e'_1$| Integer)
  6735. (project |$e'_2$| Integer))
  6736. Integer)
  6737. \end{lstlisting}
  6738. \end{minipage}
  6739. \\[2ex]\hline
  6740. \begin{minipage}{0.25\textwidth}
  6741. \begin{lstlisting}
  6742. (lambda (|$x_1 \ldots$|) |$e$|)
  6743. \end{lstlisting}
  6744. \end{minipage}
  6745. &
  6746. $\Rightarrow$
  6747. &
  6748. \begin{minipage}{0.6\textwidth}
  6749. \begin{lstlisting}
  6750. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  6751. (Any|$\ldots$|Any -> Any))
  6752. \end{lstlisting}
  6753. \end{minipage}
  6754. \\[2ex]\hline
  6755. \begin{minipage}{0.25\textwidth}
  6756. \begin{lstlisting}
  6757. (app |$e_0$| |$e_1 \ldots e_n$|)
  6758. \end{lstlisting}
  6759. \end{minipage}
  6760. &
  6761. $\Rightarrow$
  6762. &
  6763. \begin{minipage}{0.6\textwidth}
  6764. \begin{lstlisting}
  6765. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  6766. |$e'_1 \ldots e'_n$|)
  6767. \end{lstlisting}
  6768. \end{minipage}
  6769. \\[2ex]\hline
  6770. \begin{minipage}{0.25\textwidth}
  6771. \begin{lstlisting}
  6772. (vector-ref |$e_1$| |$e_2$|)
  6773. \end{lstlisting}
  6774. \end{minipage}
  6775. &
  6776. $\Rightarrow$
  6777. &
  6778. \begin{minipage}{0.6\textwidth}
  6779. \begin{lstlisting}
  6780. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  6781. (let ([tmp2 (project |$e'_2$| Integer)])
  6782. (vector-ref tmp1 tmp2)))
  6783. \end{lstlisting}
  6784. \end{minipage}
  6785. \\[2ex]\hline
  6786. \begin{minipage}{0.25\textwidth}
  6787. \begin{lstlisting}
  6788. (if |$e_1$| |$e_2$| |$e_3$|)
  6789. \end{lstlisting}
  6790. \end{minipage}
  6791. &
  6792. $\Rightarrow$
  6793. &
  6794. \begin{minipage}{0.6\textwidth}
  6795. \begin{lstlisting}
  6796. (if (eq? |$e'_1$| (inject #f Boolean))
  6797. |$e'_3$|
  6798. |$e'_2$|)
  6799. \end{lstlisting}
  6800. \end{minipage}
  6801. \\[2ex]\hline
  6802. \begin{minipage}{0.25\textwidth}
  6803. \begin{lstlisting}
  6804. (eq? |$e_1$| |$e_2$|)
  6805. \end{lstlisting}
  6806. \end{minipage}
  6807. &
  6808. $\Rightarrow$
  6809. &
  6810. \begin{minipage}{0.6\textwidth}
  6811. \begin{lstlisting}
  6812. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  6813. \end{lstlisting}
  6814. \end{minipage}
  6815. \\[2ex]\hline
  6816. \end{tabular}
  6817. \caption{Compiling $R_7$ to $R_6$.}
  6818. \label{fig:compile-r7-r6}
  6819. \end{figure}
  6820. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6821. \chapter{Gradual Typing}
  6822. \label{ch:gradual-typing}
  6823. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  6824. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6825. \chapter{Parametric Polymorphism}
  6826. \label{ch:parametric-polymorphism}
  6827. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  6828. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  6829. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6830. \chapter{High-level Optimization}
  6831. \label{ch:high-level-optimization}
  6832. This chapter will present a procedure inlining pass based on the
  6833. algorithm of \citet{Waddell:1997fk}.
  6834. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6835. \chapter{Appendix}
  6836. \section{Interpreters}
  6837. \label{appendix:interp}
  6838. We provide several interpreters in the \key{interp.rkt} file. The
  6839. \key{interp-scheme} function takes an AST in one of the Racket-like
  6840. languages considered in this book ($R_1, R_2, \ldots$) and interprets
  6841. the program, returning the result value. The \key{interp-C} function
  6842. interprets an AST for a program in one of the C-like languages ($C_0,
  6843. C_1, \ldots$), and the \code{interp-x86} function interprets an AST
  6844. for an x86 program.
  6845. \section{Utility Functions}
  6846. \label{appendix:utilities}
  6847. The utility function described in this section can be found in the
  6848. \key{utilities.rkt} file.
  6849. The \key{read-program} function takes a file path and parses that file
  6850. (it must be a Racket program) into an abstract syntax tree (as an
  6851. S-expression) with a \key{program} AST at the top.
  6852. The \key{assert} function displays the error message \key{msg} if the
  6853. Boolean \key{bool} is false.
  6854. \begin{lstlisting}
  6855. (define (assert msg bool) ...)
  6856. \end{lstlisting}
  6857. The \key{lookup} function takes a key and an association list (a list
  6858. of key-value pairs), and returns the first value that is associated
  6859. with the given key, if there is one. If not, an error is triggered.
  6860. The association list may contain both immutable pairs (built with
  6861. \key{cons}) and mutable pairs (built with \key{mcons}).
  6862. The \key{map2} function ...
  6863. %% \subsection{Graphs}
  6864. %% \begin{itemize}
  6865. %% \item The \code{make-graph} function takes a list of vertices
  6866. %% (symbols) and returns a graph.
  6867. %% \item The \code{add-edge} function takes a graph and two vertices and
  6868. %% adds an edge to the graph that connects the two vertices. The graph
  6869. %% is updated in-place. There is no return value for this function.
  6870. %% \item The \code{adjacent} function takes a graph and a vertex and
  6871. %% returns the set of vertices that are adjacent to the given
  6872. %% vertex. The return value is a Racket \code{hash-set} so it can be
  6873. %% used with functions from the \code{racket/set} module.
  6874. %% \item The \code{vertices} function takes a graph and returns the list
  6875. %% of vertices in the graph.
  6876. %% \end{itemize}
  6877. \subsection{Testing}
  6878. The \key{interp-tests} function takes a compiler name (a string), a
  6879. description of the passes, an interpreter for the source language, a
  6880. test family name (a string), and a list of test numbers, and runs the
  6881. compiler passes and the interpreters to check whether the passes
  6882. correct. The description of the passes is a list with one entry per
  6883. pass. An entry is a list with three things: a string giving the name
  6884. of the pass, the function that implements the pass (a translator from
  6885. AST to AST), and a function that implements the interpreter (a
  6886. function from AST to result value) for the language of the output of
  6887. the pass. The interpreters from Appendix~\ref{appendix:interp} make a
  6888. good choice. The \key{interp-tests} function assumes that the
  6889. subdirectory \key{tests} has a collection of Scheme programs whose names
  6890. all start with the family name, followed by an underscore and then the
  6891. test number, ending in \key{.scm}. Also, for each Scheme program there
  6892. is a file with the same number except that it ends with \key{.in} that
  6893. provides the input for the Scheme program.
  6894. \begin{lstlisting}
  6895. (define (interp-tests name passes test-family test-nums) ...)
  6896. \end{lstlisting}
  6897. The compiler-tests function takes a compiler name (a string) a
  6898. description of the passes (as described above for
  6899. \code{interp-tests}), a test family name (a string), and a list of
  6900. test numbers (see the comment for interp-tests), and runs the compiler
  6901. to generate x86 (a \key{.s} file) and then runs gcc to generate
  6902. machine code. It runs the machine code and checks that the output is
  6903. 42.
  6904. \begin{lstlisting}
  6905. (define (compiler-tests name passes test-family test-nums) ...)
  6906. \end{lstlisting}
  6907. The compile-file function takes a description of the compiler passes
  6908. (see the comment for \key{interp-tests}) and returns a function that,
  6909. given a program file name (a string ending in \key{.scm}), applies all
  6910. of the passes and writes the output to a file whose name is the same
  6911. as the program file name but with \key{.scm} replaced with \key{.s}.
  6912. \begin{lstlisting}
  6913. (define (compile-file passes)
  6914. (lambda (prog-file-name) ...))
  6915. \end{lstlisting}
  6916. \section{x86 Instruction Set Quick-Reference}
  6917. \label{sec:x86-quick-reference}
  6918. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  6919. do. We write $A \to B$ to mean that the value of $A$ is written into
  6920. location $B$. Address offsets are given in bytes. The instruction
  6921. arguments $A, B, C$ can be immediate constants (such as $\$4$),
  6922. registers (such as $\%rax$), or memory references (such as
  6923. $-4(\%ebp)$). Most x86 instructions only allow at most one memory
  6924. reference per instruction. Other operands must be immediates or
  6925. registers.
  6926. \begin{table}[tbp]
  6927. \centering
  6928. \begin{tabular}{l|l}
  6929. \textbf{Instruction} & \textbf{Operation} \\ \hline
  6930. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  6931. \texttt{negq} $A$ & $- A \to A$ \\
  6932. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  6933. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  6934. \texttt{callq} *$A$ & Calls the function at the address $A$. \\
  6935. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  6936. \texttt{retq} & Pops the return address and jumps to it \\
  6937. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  6938. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  6939. \texttt{leaq} $A$,$B$ & $A \to B$ ($C$ must be a register) \\
  6940. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register \\
  6941. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  6942. matches the condition code of the instruction, otherwise go to the
  6943. next instructions. The condition codes are \key{e} for ``equal'',
  6944. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  6945. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  6946. \texttt{jl} $L$ & \\
  6947. \texttt{jle} $L$ & \\
  6948. \texttt{jg} $L$ & \\
  6949. \texttt{jge} $L$ & \\
  6950. \texttt{jmp} $L$ & Jump to label $L$ \\
  6951. \texttt{movq} $A$, $B$ & $A \to B$ \\
  6952. \texttt{movzbq} $A$, $B$ &
  6953. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  6954. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  6955. and the extra bytes of $B$ are set to zero.} \\
  6956. & \\
  6957. & \\
  6958. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  6959. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  6960. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  6961. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  6962. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  6963. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  6964. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  6965. description of the condition codes. $A$ must be a single byte register
  6966. (e.g., \texttt{al} or \texttt{cl}).} \\
  6967. \texttt{setl} $A$ & \\
  6968. \texttt{setle} $A$ & \\
  6969. \texttt{setg} $A$ & \\
  6970. \texttt{setge} $A$ &
  6971. \end{tabular}
  6972. \vspace{5pt}
  6973. \caption{Quick-reference for the x86 instructions used in this book.}
  6974. \label{tab:x86-instr}
  6975. \end{table}
  6976. \bibliographystyle{plainnat}
  6977. \bibliography{all}
  6978. \end{document}
  6979. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  6980. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  6981. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  6982. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  6983. %% LocalWords: ast sexp Reynold's reynolds interp cond fx evaluator
  6984. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  6985. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  6986. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  6987. %% LocalWords: allocator gensym alist subdirectory scm rkt tmp lhs
  6988. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  6989. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  6990. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  6991. %% LocalWords: boolean typecheck notq cmpq sete movzbq jmp al xorq
  6992. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  6993. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  6994. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  6995. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  6996. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  6997. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  6998. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  6999. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  7000. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  7001. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  7002. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  7003. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  7004. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  7005. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  7006. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  7007. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  7008. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  7009. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge