book.tex 283 KB

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