book.tex 251 KB

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