book.tex 430 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277
  1. % Why direct style instead of continuation passing style?
  2. %% Student project ideas:
  3. %% * high-level optimizations like procedure inlining, etc.
  4. %% * closure optimization
  5. %% * adding letrec to the language
  6. %% (Thought: in the book and regular course, replace top-level defines
  7. %% with letrec.)
  8. %% * alternative back ends (ARM, LLVM)
  9. %% * alternative calling convention (a la Dybvig)
  10. %% * lazy evaluation
  11. %% * gradual typing
  12. %% * continuations (frames in heap a la SML or segmented stack a la Dybvig)
  13. %% * exceptions
  14. %% * self hosting
  15. %% * I/O
  16. %% * foreign function interface
  17. %% * quasi-quote and unquote
  18. %% * macros (too difficult?)
  19. %% * alternative garbage collector
  20. %% * alternative register allocator
  21. %% * parametric polymorphism
  22. %% * type classes (too difficulty?)
  23. %% * loops (too easy? combine with something else?)
  24. %% * loop optimization (fusion, etc.)
  25. %% * deforestation
  26. %% * records and subtyping
  27. %% * object-oriented features
  28. %% - objects, object types, and structural subtyping (e.g. Abadi & Cardelli)
  29. %% - class-based objects and nominal subtyping (e.g. Featherweight Java)
  30. %% * multi-threading, fork join, futures, implicit parallelism
  31. %% * dataflow analysis, type analysis and specialization
  32. \documentclass[11pt]{book}
  33. \usepackage[T1]{fontenc}
  34. \usepackage[utf8]{inputenc}
  35. \usepackage{lmodern}
  36. \usepackage{hyperref}
  37. \usepackage{graphicx}
  38. \usepackage[english]{babel}
  39. \usepackage{listings}
  40. \usepackage{amsmath}
  41. \usepackage{amsthm}
  42. \usepackage{amssymb}
  43. \usepackage{natbib}
  44. \usepackage{stmaryrd}
  45. \usepackage{xypic}
  46. \usepackage{semantic}
  47. \usepackage{wrapfig}
  48. \usepackage{tcolorbox}
  49. \usepackage{multirow}
  50. \usepackage{color}
  51. \usepackage{upquote}
  52. \usepackage{makeidx}
  53. \makeindex
  54. \definecolor{lightgray}{gray}{1}
  55. \newcommand{\black}[1]{{\color{black} #1}}
  56. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  57. \newcommand{\gray}[1]{{\color{gray} #1}}
  58. %% For pictures
  59. \usepackage{tikz}
  60. \usetikzlibrary{arrows.meta}
  61. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  62. % Computer Modern is already the default. -Jeremy
  63. %\renewcommand{\ttdefault}{cmtt}
  64. \definecolor{comment-red}{rgb}{0.8,0,0}
  65. \if01
  66. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  67. \newcommand{\margincomment}[1]{\marginpar{\color{comment-red}\tiny #1}}
  68. \else
  69. \newcommand{\rn}[1]{}
  70. \newcommand{\margincomment}[1]{}
  71. \fi
  72. \lstset{%
  73. language=Lisp,
  74. basicstyle=\ttfamily\small,
  75. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,while,begin,define,public,override,class},
  76. deletekeywords={read,mapping,vector},
  77. escapechar=|,
  78. columns=flexible,
  79. moredelim=[is][\color{red}]{~}{~},
  80. showstringspaces=false
  81. }
  82. \newtheorem{theorem}{Theorem}
  83. \newtheorem{lemma}[theorem]{Lemma}
  84. \newtheorem{corollary}[theorem]{Corollary}
  85. \newtheorem{proposition}[theorem]{Proposition}
  86. \newtheorem{constraint}[theorem]{Constraint}
  87. \newtheorem{definition}[theorem]{Definition}
  88. \newtheorem{exercise}[theorem]{Exercise}
  89. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  90. % 'dedication' environment: To add a dedication paragraph at the start of book %
  91. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  92. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  93. \newenvironment{dedication}
  94. {
  95. \cleardoublepage
  96. \thispagestyle{empty}
  97. \vspace*{\stretch{1}}
  98. \hfill\begin{minipage}[t]{0.66\textwidth}
  99. \raggedright
  100. }
  101. {
  102. \end{minipage}
  103. \vspace*{\stretch{3}}
  104. \clearpage
  105. }
  106. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  107. % Chapter quote at the start of chapter %
  108. % Source: http://tex.stackexchange.com/a/53380 %
  109. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  110. \makeatletter
  111. \renewcommand{\@chapapp}{}% Not necessary...
  112. \newenvironment{chapquote}[2][2em]
  113. {\setlength{\@tempdima}{#1}%
  114. \def\chapquote@author{#2}%
  115. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  116. \itshape}
  117. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  118. \makeatother
  119. \input{defs}
  120. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  121. \title{\Huge \textbf{Essentials of Compilation} \\
  122. \huge An Incremental Approach}
  123. \author{\textsc{Jeremy G. Siek} \\
  124. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  125. Indiana University \\
  126. \\
  127. with contributions from: \\
  128. Carl Factora \\
  129. Andre Kuhlenschmidt \\
  130. Ryan R. Newton \\
  131. Ryan Scott \\
  132. Cameron Swords \\
  133. Michael M. Vitousek \\
  134. Michael Vollmer
  135. }
  136. \begin{document}
  137. \frontmatter
  138. \maketitle
  139. \begin{dedication}
  140. This book is dedicated to the programming language wonks at Indiana
  141. University.
  142. \end{dedication}
  143. \tableofcontents
  144. \listoffigures
  145. %\listoftables
  146. \mainmatter
  147. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  148. \chapter*{Preface}
  149. The tradition of compiler writing at Indiana University goes back to
  150. research and courses on programming languages by Professor Daniel
  151. Friedman in the 1970's and 1980's. Friedman conducted research on lazy
  152. evaluation~\citep{Friedman:1976aa} in the context of
  153. Lisp~\citep{McCarthy:1960dz} and then studied
  154. continuations~\citep{Felleisen:kx} and
  155. macros~\citep{Kohlbecker:1986dk} in the context of the
  156. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  157. of those courses, Kent Dybvig, went on to build Chez
  158. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  159. compiler for Scheme. After completing his Ph.D. at the University of
  160. North Carolina, he returned to teach at Indiana University.
  161. Throughout the 1990's and 2000's, Professor Dybvig continued
  162. development of Chez Scheme and taught the compiler course.
  163. The compiler course evolved to incorporate novel pedagogical ideas
  164. while also including elements of effective real-world compilers. One
  165. of Friedman's ideas was to split the compiler into many small
  166. ``passes'' so that the code for each pass would be easy to understood
  167. in isolation. (In contrast, most compilers of the time were organized
  168. into only a few monolithic passes for reasons of compile-time
  169. efficiency.) Dybvig, with later help from his students Dipanwita
  170. Sarkar and Andrew Keep, developed infrastructure to support this
  171. approach and evolved the course, first to use smaller micro-passes and
  172. then into even smaller
  173. nano-passes~\citep{Sarkar:2004fk,Keep:2012aa}. I was a student in this
  174. compiler course in the early 2000's as part of his Ph.D. studies at
  175. Indiana University. Needless to say, I enjoyed the course immensely!
  176. During that time, another graduate student named Abdulaziz Ghuloum
  177. observed that the front-to-back organization of the course made it
  178. difficult for students to understand the rationale for the compiler
  179. design. Ghuloum proposed an incremental approach in which the students
  180. build the compiler in stages; they start by implementing a complete
  181. compiler for a very small subset of the input language and in each
  182. subsequent stage they add a language feature and add or modify passes
  183. to handle the new feature~\citep{Ghuloum:2006bh}. In this way, the
  184. students see how the language features motivate aspects of the
  185. compiler design.
  186. After graduating from Indiana University in 2005, I went on to teach
  187. at the University of Colorado. I adapted the nano-pass and incremental
  188. approaches to compiling a subset of the Python
  189. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  190. on the surface but there is a large overlap in the compiler techniques
  191. required for the two languages. Thus, I was able to teach much of the
  192. same content from the Indiana compiler course. I very much enjoyed
  193. teaching the course organized in this way, and even better, many of
  194. the students learned a lot and got excited about compilers.
  195. I returned to teach at Indiana University in 2013. In my absence the
  196. compiler course had switched from the front-to-back organization to a
  197. back-to-front organization. Seeing how well the incremental approach
  198. worked at Colorado, I started porting and adapting the structure of
  199. the Colorado course back into the land of Scheme. In the meantime
  200. Indiana University had moved on from Scheme to Racket, so the course
  201. is now about compiling a subset of Racket (and Typed Racket) to the
  202. x86 assembly language. The compiler is implemented in
  203. Racket~\citep{plt-tr}.
  204. This is the textbook for the incremental version of the compiler
  205. course at Indiana University (Spring 2016 - present) and it is the
  206. first open textbook for an Indiana compiler course. With this book I
  207. hope to make the Indiana compiler course available to people that have
  208. not had the chance to study compilers at Indiana University. Many of
  209. the compiler design decisions in this book are drawn from the
  210. assignment descriptions of \cite{Dybvig:2010aa}. I have captured what
  211. I think are the most important topics from \cite{Dybvig:2010aa} but
  212. have omitted topics that are less interesting conceptually. I have
  213. also made simplifications to reduce complexity. In this way, this
  214. book leans more towards pedagogy than towards the efficiency of the
  215. generated code. Also, the book differs in places where we I the
  216. opportunity to make the topics more fun, such as in relating register
  217. allocation to Sudoku (Chapter~\ref{ch:register-allocation-r1}).
  218. \section*{Prerequisites}
  219. The material in this book is challenging but rewarding. It is meant to
  220. prepare students for a lifelong career in programming languages.
  221. The book uses the Racket language both for the implementation of the
  222. compiler and for the language that is compiled, so a student should be
  223. proficient with Racket (or Scheme) prior to reading this book. There
  224. are many excellent resources for learning Scheme and
  225. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  226. It is helpful but not necessary for the student to have prior exposure
  227. to the x86 assembly language~\citep{Intel:2015aa}, as one might obtain
  228. from a computer systems
  229. course~\citep{Bryant:2010aa}. This book introduces the
  230. parts of x86-64 assembly language that are needed.
  231. %
  232. We follow the System V calling
  233. conventions~\citep{Bryant:2005aa,Matz:2013aa}, which means that the
  234. assembly code that we generate will work properly with our runtime
  235. system (written in C) when it is compiled using the GNU C compiler
  236. (\code{gcc}) on the Linux and MacOS operating systems. (Minor
  237. adjustments are needed for MacOS which we note as they arise.)
  238. %
  239. When running on the Microsoft Windows operating system, the GNU C
  240. compiler follows the Microsoft x64 calling
  241. convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the assembly
  242. code that we generate will \emph{not} work properly with our runtime
  243. system on Windows. One option to consider for using a Windows computer
  244. is to run a virtual machine with Linux as the guest operating system.
  245. %\section*{Structure of book}
  246. % You might want to add short description about each chapter in this book.
  247. %\section*{About the companion website}
  248. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  249. %\begin{itemize}
  250. % \item A link to (freely downlodable) latest version of this document.
  251. % \item Link to download LaTeX source for this document.
  252. % \item Miscellaneous material (e.g. suggested readings etc).
  253. %\end{itemize}
  254. \section*{Acknowledgments}
  255. Many people have contributed to the ideas, techniques, and
  256. organization of this book and have taught courses based on it. We
  257. especially thank John Clements, Bor-Yuh Evan Chang, Kent Dybvig,
  258. Daniel P. Friedman, Ronald Garcia, Abdulaziz Ghuloum, Andrew Keep, Jay
  259. McCarthy, Nate Nystrom, Dipanwita Sarkar, Oscar Waddell, and Michael
  260. Wollowski.
  261. \mbox{}\\
  262. \noindent Jeremy G. Siek \\
  263. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  264. %\noindent Spring 2016
  265. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  266. \chapter{Preliminaries}
  267. \label{ch:trees-recur}
  268. In this chapter we review the basic tools that are needed to implement
  269. a compiler. Programs are typically input by a programmer as text,
  270. i.e., a sequence of characters. The program-as-text representation is
  271. called \emph{concrete syntax}. We use concrete syntax to concisely
  272. write down and talk about programs. Inside the compiler, we use
  273. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  274. that efficiently supports the operations that the compiler needs to
  275. perform.
  276. \index{concrete syntax}
  277. \index{abstract syntax}
  278. \index{abstract syntax tree}
  279. \index{AST}
  280. \index{program}
  281. \index{parse}
  282. %
  283. The translation from concrete syntax to abstract syntax is a process
  284. called \emph{parsing}~\cite{Aho:1986qf}. We do not cover the theory
  285. and implementation of parsing in this book. A parser is provided in
  286. the supporting materials for translating from concrete syntax to
  287. abstract syntax for the languages used in this book.
  288. ASTs can be represented in many different ways inside the compiler,
  289. depending on the programming language used to write the compiler.
  290. %
  291. We use Racket's \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  292. feature to represent ASTs (Section~\ref{sec:ast}). We use grammars to
  293. define the abstract syntax of programming languages (Section~\ref{sec:grammar})
  294. and pattern matching to inspect individual nodes in an AST
  295. (Section~\ref{sec:pattern-matching}). We use recursion to construct
  296. and deconstruct entire ASTs (Section~\ref{sec:recursion}). This
  297. chapter provides an brief introduction to these ideas.
  298. \index{struct}
  299. \section{Abstract Syntax Trees and Racket Structures}
  300. \label{sec:ast}
  301. Compilers use abstract syntax trees to represent programs because
  302. compilers often need to ask questions like: for a given part of a
  303. program, what kind of language feature is it? What are the sub-parts
  304. of this part of the program? Consider the program on the left and its
  305. AST on the right. This program is an addition and it has two
  306. sub-parts, a read operation and a negation. The negation has another
  307. sub-part, the integer constant \code{8}. By using a tree to represent
  308. the program, we can easily follow the links to go from one part of a
  309. program to its sub-parts.
  310. \begin{center}
  311. \begin{minipage}{0.4\textwidth}
  312. \begin{lstlisting}
  313. (+ (read) (- 8))
  314. \end{lstlisting}
  315. \end{minipage}
  316. \begin{minipage}{0.4\textwidth}
  317. \begin{equation}
  318. \begin{tikzpicture}
  319. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  320. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  321. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  322. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  323. \draw[->] (plus) to (read);
  324. \draw[->] (plus) to (minus);
  325. \draw[->] (minus) to (8);
  326. \end{tikzpicture}
  327. \label{eq:arith-prog}
  328. \end{equation}
  329. \end{minipage}
  330. \end{center}
  331. We use the standard terminology for trees to describe ASTs: each
  332. circle above is called a \emph{node}. The arrows connect a node to its
  333. \emph{children} (which are also nodes). The top-most node is the
  334. \emph{root}. Every node except for the root has a \emph{parent} (the
  335. node it is the child of). If a node has no children, it is a
  336. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  337. \index{node}
  338. \index{children}
  339. \index{root}
  340. \index{parent}
  341. \index{leaf}
  342. \index{internal node}
  343. %% Recall that an \emph{symbolic expression} (S-expression) is either
  344. %% \begin{enumerate}
  345. %% \item an atom, or
  346. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  347. %% where $e_1$ and $e_2$ are each an S-expression.
  348. %% \end{enumerate}
  349. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  350. %% null value \code{'()}, etc. We can create an S-expression in Racket
  351. %% simply by writing a backquote (called a quasi-quote in Racket)
  352. %% followed by the textual representation of the S-expression. It is
  353. %% quite common to use S-expressions to represent a list, such as $a, b
  354. %% ,c$ in the following way:
  355. %% \begin{lstlisting}
  356. %% `(a . (b . (c . ())))
  357. %% \end{lstlisting}
  358. %% Each element of the list is in the first slot of a pair, and the
  359. %% second slot is either the rest of the list or the null value, to mark
  360. %% the end of the list. Such lists are so common that Racket provides
  361. %% special notation for them that removes the need for the periods
  362. %% and so many parenthesis:
  363. %% \begin{lstlisting}
  364. %% `(a b c)
  365. %% \end{lstlisting}
  366. %% The following expression creates an S-expression that represents AST
  367. %% \eqref{eq:arith-prog}.
  368. %% \begin{lstlisting}
  369. %% `(+ (read) (- 8))
  370. %% \end{lstlisting}
  371. %% When using S-expressions to represent ASTs, the convention is to
  372. %% represent each AST node as a list and to put the operation symbol at
  373. %% the front of the list. The rest of the list contains the children. So
  374. %% in the above case, the root AST node has operation \code{`+} and its
  375. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  376. %% diagram \eqref{eq:arith-prog}.
  377. %% To build larger S-expressions one often needs to splice together
  378. %% several smaller S-expressions. Racket provides the comma operator to
  379. %% splice an S-expression into a larger one. For example, instead of
  380. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  381. %% we could have first created an S-expression for AST
  382. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  383. %% S-expression.
  384. %% \begin{lstlisting}
  385. %% (define ast1.4 `(- 8))
  386. %% (define ast1.1 `(+ (read) ,ast1.4))
  387. %% \end{lstlisting}
  388. %% In general, the Racket expression that follows the comma (splice)
  389. %% can be any expression that produces an S-expression.
  390. We define a Racket \code{struct} for each kind of node. For this
  391. chapter we require just two kinds of nodes: one for integer constants
  392. and one for primitive operations. The following is the \code{struct}
  393. definition for integer constants.
  394. \begin{lstlisting}
  395. (struct Int (value))
  396. \end{lstlisting}
  397. An integer node includes just one thing: the integer value.
  398. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  399. \begin{lstlisting}
  400. (define eight (Int 8))
  401. \end{lstlisting}
  402. We say that the value created by \code{(Int 8)} is an
  403. \emph{instance} of the \code{Int} structure.
  404. The following is the \code{struct} definition for primitives operations.
  405. \begin{lstlisting}
  406. (struct Prim (op arg*))
  407. \end{lstlisting}
  408. A primitive operation node includes an operator symbol \code{op}
  409. and a list of children \code{arg*}. For example, to create
  410. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  411. \begin{lstlisting}
  412. (define neg-eight (Prim '- (list eight)))
  413. \end{lstlisting}
  414. Primitive operations may have zero or more children. The \code{read}
  415. operator has zero children:
  416. \begin{lstlisting}
  417. (define rd (Prim 'read '()))
  418. \end{lstlisting}
  419. whereas the addition operator has two children:
  420. \begin{lstlisting}
  421. (define ast1.1 (Prim '+ (list rd neg-eight)))
  422. \end{lstlisting}
  423. We have made a design choice regarding the \code{Prim} structure.
  424. Instead of using one structure for many different operations
  425. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  426. structure for each operation, as follows.
  427. \begin{lstlisting}
  428. (struct Read ())
  429. (struct Add (left right))
  430. (struct Neg (value))
  431. \end{lstlisting}
  432. The reason we choose to use just one structure is that in many parts
  433. of the compiler the code for the different primitive operators is the
  434. same, so we might as well just write that code once, which is enabled
  435. by using a single structure.
  436. When compiling a program such as \eqref{eq:arith-prog}, we need to
  437. know that the operation associated with the root node is addition and
  438. we need to be able to access its two children. Racket provides pattern
  439. matching over structures to support these kinds of queries, as we
  440. see in Section~\ref{sec:pattern-matching}.
  441. In this book, we often write down the concrete syntax of a program
  442. even when we really have in mind the AST because the concrete syntax
  443. is more concise. We recommend that, in your mind, you always think of
  444. programs as abstract syntax trees.
  445. \section{Grammars}
  446. \label{sec:grammar}
  447. \index{integer}
  448. \index{literal}
  449. \index{constant}
  450. A programming language can be thought of as a \emph{set} of programs.
  451. The set is typically infinite (one can always create larger and larger
  452. programs), so one cannot simply describe a language by listing all of
  453. the programs in the language. Instead we write down a set of rules, a
  454. \emph{grammar}, for building programs. Grammars are often used to
  455. define the concrete syntax of a language, but they can also be used to
  456. describe the abstract syntax. We write our rules in a variant of
  457. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  458. \index{Backus-Naur Form}\index{BNF}
  459. As an example, we describe a small language, named $R_0$, that consists of
  460. integers and arithmetic operations.
  461. \index{grammar}
  462. The first grammar rule for the abstract syntax of $R_0$ says that an
  463. instance of the \code{Int} structure is an expression:
  464. \begin{equation}
  465. \Exp ::= \INT{\Int} \label{eq:arith-int}
  466. \end{equation}
  467. %
  468. Each rule has a left-hand-side and a right-hand-side. The way to read
  469. a rule is that if you have all the program parts on the
  470. right-hand-side, then you can create an AST node and categorize it
  471. according to the left-hand-side.
  472. %
  473. A name such as $\Exp$ that is
  474. defined by the grammar rules is a \emph{non-terminal}.
  475. \index{non-terminal}
  476. %
  477. The name $\Int$ is a also a non-terminal, but instead of defining it
  478. with a grammar rule, we define it with the following explanation. We
  479. make the simplifying design decision that all of the languages in this
  480. book only handle machine-representable integers. On most modern
  481. machines this corresponds to integers represented with 64-bits, i.e.,
  482. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  483. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  484. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  485. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  486. that the sequence of decimals represent an integer in range $-2^{62}$
  487. to $2^{62}-1$.
  488. The second grammar rule is the \texttt{read} operation that receives
  489. an input integer from the user of the program.
  490. \begin{equation}
  491. \Exp ::= \READ{} \label{eq:arith-read}
  492. \end{equation}
  493. The third rule says that, given an $\Exp$ node, you can build another
  494. $\Exp$ node by negating it.
  495. \begin{equation}
  496. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  497. \end{equation}
  498. Symbols in typewriter font such as \key{-} and \key{read} are
  499. \emph{terminal} symbols and must literally appear in the program for
  500. the rule to be applicable.
  501. \index{terminal}
  502. We can apply the rules to build ASTs in the $R_0$
  503. language. For example, by rule \eqref{eq:arith-int}, \texttt{(Int 8)} is an
  504. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  505. an $\Exp$.
  506. \begin{center}
  507. \begin{minipage}{0.4\textwidth}
  508. \begin{lstlisting}
  509. (Prim '- (list (Int 8)))
  510. \end{lstlisting}
  511. \end{minipage}
  512. \begin{minipage}{0.25\textwidth}
  513. \begin{equation}
  514. \begin{tikzpicture}
  515. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  516. \node[draw, circle] (8) at (0, -1.2) {$8$};
  517. \draw[->] (minus) to (8);
  518. \end{tikzpicture}
  519. \label{eq:arith-neg8}
  520. \end{equation}
  521. \end{minipage}
  522. \end{center}
  523. The next grammar rule defines addition expressions:
  524. \begin{equation}
  525. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  526. \end{equation}
  527. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  528. $R_0$. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  529. \eqref{eq:arith-read} and we have already shown that \code{(Prim '-
  530. (list (Int 8)))} is an $\Exp$, so we apply rule \eqref{eq:arith-add}
  531. to show that
  532. \begin{lstlisting}
  533. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  534. \end{lstlisting}
  535. is an $\Exp$ in the $R_0$ language.
  536. If you have an AST for which the above rules do not apply, then the
  537. AST is not in $R_0$. For example, the program \code{(- (read) (+ 8))}
  538. is not in $R_0$ because there are no rules for \code{+} with only one
  539. argument, nor for \key{-} with two arguments. Whenever we define a
  540. language with a grammar, the language only includes those programs
  541. that are justified by the rules.
  542. The last grammar rule for $R_0$ states that there is a \code{Program}
  543. node to mark the top of the whole program:
  544. \[
  545. R_0 ::= \PROGRAM{\code{'()}}{\Exp}
  546. \]
  547. The \code{Program} structure is defined as follows
  548. \begin{lstlisting}
  549. (struct Program (info body))
  550. \end{lstlisting}
  551. where \code{body} is an expression. In later chapters, the \code{info}
  552. part will be used to store auxiliary information but for now it is
  553. just the empty list.
  554. It is common to have many grammar rules with the same left-hand side
  555. but different right-hand sides, such as the rules for $\Exp$ in the
  556. grammar of $R_0$. As a short-hand, a vertical bar can be used to
  557. combine several right-hand-sides into a single rule.
  558. We collect all of the grammar rules for the abstract syntax of $R_0$
  559. in Figure~\ref{fig:r0-syntax}. The concrete syntax for $R_0$ is
  560. defined in Figure~\ref{fig:r0-concrete-syntax}.
  561. The \code{read-program} function provided in \code{utilities.rkt} of
  562. the support materials reads a program in from a file (the sequence of
  563. characters in the concrete syntax of Racket) and parses it into an
  564. abstract syntax tree. See the description of \code{read-program} in
  565. Appendix~\ref{appendix:utilities} for more details.
  566. \begin{figure}[tp]
  567. \fbox{
  568. \begin{minipage}{0.96\textwidth}
  569. \[
  570. \begin{array}{rcl}
  571. \begin{array}{rcl}
  572. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)\\
  573. R_0 &::=& \Exp
  574. \end{array}
  575. \end{array}
  576. \]
  577. \end{minipage}
  578. }
  579. \caption{The concrete syntax of $R_0$.}
  580. \label{fig:r0-concrete-syntax}
  581. \end{figure}
  582. \begin{figure}[tp]
  583. \fbox{
  584. \begin{minipage}{0.96\textwidth}
  585. \[
  586. \begin{array}{rcl}
  587. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  588. &\mid& \ADD{\Exp}{\Exp} \\
  589. R_0 &::=& \PROGRAM{\code{'()}}{\Exp}
  590. \end{array}
  591. \]
  592. \end{minipage}
  593. }
  594. \caption{The abstract syntax of $R_0$.}
  595. \label{fig:r0-syntax}
  596. \end{figure}
  597. \section{Pattern Matching}
  598. \label{sec:pattern-matching}
  599. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  600. the parts of an AST node. Racket provides the \texttt{match} form to
  601. access the parts of a structure. Consider the following example and
  602. the output on the right. \index{match} \index{pattern matching}
  603. \begin{center}
  604. \begin{minipage}{0.5\textwidth}
  605. \begin{lstlisting}
  606. (match ast1.1
  607. [(Prim op (list child1 child2))
  608. (print op)])
  609. \end{lstlisting}
  610. \end{minipage}
  611. \vrule
  612. \begin{minipage}{0.25\textwidth}
  613. \begin{lstlisting}
  614. '+
  615. \end{lstlisting}
  616. \end{minipage}
  617. \end{center}
  618. In the above example, the \texttt{match} form takes the AST
  619. \eqref{eq:arith-prog} and binds its parts to the three pattern
  620. variables \texttt{op}, \texttt{child1}, and \texttt{child2}. In
  621. general, a match clause consists of a \emph{pattern} and a
  622. \emph{body}.
  623. \index{pattern}
  624. Patterns are recursively defined to be either a pattern
  625. variable, a structure name followed by a pattern for each of the
  626. structure's arguments, or an S-expression (symbols, lists, etc.).
  627. (See Chapter 12 of The Racket
  628. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  629. and Chapter 9 of The Racket
  630. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  631. for a complete description of \code{match}.)
  632. %
  633. The body of a match clause may contain arbitrary Racket code. The
  634. pattern variables can be used in the scope of the body.
  635. A \code{match} form may contain several clauses, as in the following
  636. function \code{leaf?} that recognizes when an $R_0$ node is
  637. a leaf. The \code{match} proceeds through the clauses in order,
  638. checking whether the pattern can match the input AST. The
  639. body of the first clause that matches is executed. The output of
  640. \code{leaf?} for several ASTs is shown on the right.
  641. \begin{center}
  642. \begin{minipage}{0.6\textwidth}
  643. \begin{lstlisting}
  644. (define (leaf? arith)
  645. (match arith
  646. [(Int n) #t]
  647. [(Prim 'read '()) #t]
  648. [(Prim '- (list c1)) #f]
  649. [(Prim '+ (list c1 c2)) #f]))
  650. (leaf? (Prim 'read '()))
  651. (leaf? (Prim '- (list (Int 8))))
  652. (leaf? (Int 8))
  653. \end{lstlisting}
  654. \end{minipage}
  655. \vrule
  656. \begin{minipage}{0.25\textwidth}
  657. \begin{lstlisting}
  658. #t
  659. #f
  660. #t
  661. \end{lstlisting}
  662. \end{minipage}
  663. \end{center}
  664. When writing a \code{match}, we refer to the grammar definition to
  665. identify which non-terminal we are expecting to match against, then we
  666. make sure that 1) we have one clause for each alternative of that
  667. non-terminal and 2) that the pattern in each clause corresponds to the
  668. corresponding right-hand side of a grammar rule. For the \code{match}
  669. in the \code{leaf?} function, we refer to the grammar for $R_0$ in
  670. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  671. alternatives, so the \code{match} has 4 clauses. The pattern in each
  672. clause corresponds to the right-hand side of a grammar rule. For
  673. example, the pattern \code{(Prim '+ (list c1 c2))} corresponds to the
  674. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  675. patterns, replace non-terminals such as $\Exp$ with pattern variables
  676. of your choice (e.g. \code{c1} and \code{c2}).
  677. \section{Recursion}
  678. \label{sec:recursion}
  679. \index{recursive function}
  680. Programs are inherently recursive. For example, an $R_0$ expression is
  681. often made of smaller expressions. Thus, the natural way to process an
  682. entire program is with a recursive function. As a first example of
  683. such a recursive function, we define \texttt{exp?} below, which takes
  684. an arbitrary value and determines whether or not it is an $R_0$
  685. expression.
  686. %
  687. When a recursive function is defined using a sequence of match clauses
  688. that correspond to a grammar, and the body of each clause makes a
  689. recursive call on each child node, then we say the function is defined
  690. by \emph{structural recursion}\footnote{This principle of structuring
  691. code according to the data definition is advocated in the book
  692. \emph{How to Design Programs}
  693. \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}. Below we also
  694. define a second function, named \code{R0?}, that determines whether a
  695. value is an $R_0$ program. In general we can expect to write one
  696. recursive function to handle each non-terminal in a grammar.
  697. \index{structural recursion}
  698. %
  699. \begin{center}
  700. \begin{minipage}{0.7\textwidth}
  701. \begin{lstlisting}
  702. (define (exp? ast)
  703. (match ast
  704. [(Int n) #t]
  705. [(Prim 'read '()) #t]
  706. [(Prim '- (list e)) (exp? e)]
  707. [(Prim '+ (list e1 e2))
  708. (and (exp? e1) (exp? e2))]
  709. [else #f]))
  710. (define (R0? ast)
  711. (match ast
  712. [(Program '() e) (exp? e)]
  713. [else #f]))
  714. (R0? (Program '() ast1.1)
  715. (R0? (Program '()
  716. (Prim '- (list (Prim 'read '())
  717. (Prim '+ (list (Num 8)))))))
  718. \end{lstlisting}
  719. \end{minipage}
  720. \vrule
  721. \begin{minipage}{0.25\textwidth}
  722. \begin{lstlisting}
  723. #t
  724. #f
  725. \end{lstlisting}
  726. \end{minipage}
  727. \end{center}
  728. You may be tempted to merge the two functions into one, like this:
  729. \begin{center}
  730. \begin{minipage}{0.5\textwidth}
  731. \begin{lstlisting}
  732. (define (R0? ast)
  733. (match ast
  734. [(Int n) #t]
  735. [(Prim 'read '()) #t]
  736. [(Prim '- (list e)) (R0? e)]
  737. [(Prim '+ (list e1 e2)) (and (R0? e1) (R0? e2))]
  738. [(Program '() e) (R0? e)]
  739. [else #f]))
  740. \end{lstlisting}
  741. \end{minipage}
  742. \end{center}
  743. %
  744. Sometimes such a trick will save a few lines of code, especially when
  745. it comes to the \code{Program} wrapper. Yet this style is generally
  746. \emph{not} recommended because it can get you into trouble.
  747. %
  748. For example, the above function is subtly wrong:
  749. \lstinline{(R0? (Program '() (Program '() (Int 3))))}
  750. will return true, when it should return false.
  751. %% NOTE FIXME - must check for consistency on this issue throughout.
  752. \section{Interpreters}
  753. \label{sec:interp-R0}
  754. \index{interpreter}
  755. The meaning, or semantics, of a program is typically defined in the
  756. specification of the language. For example, the Scheme language is
  757. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  758. defined in its reference manual~\citep{plt-tr}. In this book we use an
  759. interpreter to define the meaning of each language that we consider,
  760. following Reynolds' advice~\citep{reynolds72:_def_interp}. An
  761. interpreter that is designated (by some people) as the definition of a
  762. language is called a \emph{definitional interpreter}.
  763. \index{definitional interpreter}
  764. We warm up by creating a definitional interpreter for the $R_0$ language, which
  765. serves as a second example of structural recursion. The
  766. \texttt{interp-R0} function is defined in
  767. Figure~\ref{fig:interp-R0}. The body of the function is a match on the
  768. input program followed by a call to the \lstinline{interp-exp} helper
  769. function, which in turn has one match clause per grammar rule for
  770. $R_0$ expressions.
  771. \begin{figure}[tp]
  772. \begin{lstlisting}
  773. (define (interp-exp e)
  774. (match e
  775. [(Int n) n]
  776. [(Prim 'read '())
  777. (define r (read))
  778. (cond [(fixnum? r) r]
  779. [else (error 'interp-R0 "expected an integer" r)])]
  780. [(Prim '- (list e))
  781. (define v (interp-exp e))
  782. (fx- 0 v)]
  783. [(Prim '+ (list e1 e2))
  784. (define v1 (interp-exp e1))
  785. (define v2 (interp-exp e2))
  786. (fx+ v1 v2)]
  787. ))
  788. (define (interp-R0 p)
  789. (match p
  790. [(Program '() e) (interp-exp e)]
  791. ))
  792. \end{lstlisting}
  793. \caption{Interpreter for the $R_0$ language.}
  794. \label{fig:interp-R0}
  795. \end{figure}
  796. Let us consider the result of interpreting a few $R_0$ programs. The
  797. following program adds two integers.
  798. \begin{lstlisting}
  799. (+ 10 32)
  800. \end{lstlisting}
  801. The result is \key{42}. We wrote the above program in concrete syntax,
  802. whereas the parsed abstract syntax is:
  803. \begin{lstlisting}
  804. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  805. \end{lstlisting}
  806. The next example demonstrates that expressions may be nested within
  807. each other, in this case nesting several additions and negations.
  808. \begin{lstlisting}
  809. (+ 10 (- (+ 12 20)))
  810. \end{lstlisting}
  811. What is the result of the above program?
  812. As mentioned previously, the $R_0$ language does not support
  813. arbitrarily-large integers, but only $63$-bit integers, so we
  814. interpret the arithmetic operations of $R_0$ using fixnum arithmetic
  815. in Racket.
  816. Suppose
  817. \[
  818. n = 999999999999999999
  819. \]
  820. which indeed fits in $63$-bits. What happens when we run the
  821. following program in our interpreter?
  822. \begin{lstlisting}
  823. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  824. \end{lstlisting}
  825. It produces an error:
  826. \begin{lstlisting}
  827. fx+: result is not a fixnum
  828. \end{lstlisting}
  829. We establish the convention that if running the definitional
  830. interpreter on a program produces an error, then the meaning of that
  831. program is \emph{unspecified}. That means a compiler for the language
  832. is under no obligations regarding that program; it may or may not
  833. produce an executable, and if it does, that executable can do
  834. anything. This convention applies to the languages defined in this
  835. book, as a way to simplify the student's task of implementing them,
  836. but this convention is not applicable to all programming languages.
  837. \index{unspecified behavior}
  838. Moving on to the last feature of the $R_0$ language, the \key{read}
  839. operation prompts the user of the program for an integer. Recall that
  840. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  841. \code{8}. So if we run
  842. \begin{lstlisting}
  843. (interp-R0 (Program '() ast1.1))
  844. \end{lstlisting}
  845. and if the input is \code{50}, then we get the answer to life, the
  846. universe, and everything: \code{42}!\footnote{\emph{The Hitchhiker's
  847. Guide to the Galaxy} by Douglas Adams.}
  848. We include the \key{read} operation in $R_0$ so a clever student
  849. cannot implement a compiler for $R_0$ that simply runs the interpreter
  850. during compilation to obtain the output and then generates the trivial
  851. code to produce the output. (Yes, a clever student did this in the
  852. first instance of this course.)
  853. The job of a compiler is to translate a program in one language into a
  854. program in another language so that the output program behaves the
  855. same way as the input program does according to its definitional
  856. interpreter. This idea is depicted in the following diagram. Suppose
  857. we have two languages, $\mathcal{L}_1$ and $\mathcal{L}_2$, and an
  858. interpreter for each language. Suppose that the compiler translates
  859. program $P_1$ in language $\mathcal{L}_1$ into program $P_2$ in
  860. language $\mathcal{L}_2$. Then interpreting $P_1$ and $P_2$ on their
  861. respective interpreters with input $i$ should yield the same output
  862. $o$.
  863. \begin{equation} \label{eq:compile-correct}
  864. \begin{tikzpicture}[baseline=(current bounding box.center)]
  865. \node (p1) at (0, 0) {$P_1$};
  866. \node (p2) at (3, 0) {$P_2$};
  867. \node (o) at (3, -2.5) {$o$};
  868. \path[->] (p1) edge [above] node {compile} (p2);
  869. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  870. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  871. \end{tikzpicture}
  872. \end{equation}
  873. In the next section we see our first example of a compiler.
  874. \section{Example Compiler: a Partial Evaluator}
  875. \label{sec:partial-evaluation}
  876. In this section we consider a compiler that translates $R_0$ programs
  877. into $R_0$ programs that may be more efficient, that is, this compiler
  878. is an optimizer. This optimizer eagerly computes the parts of the
  879. program that do not depend on any inputs, a process known as
  880. \emph{partial evaluation}~\cite{Jones:1993uq}.
  881. \index{partial evaluation}
  882. For example, given the following program
  883. \begin{lstlisting}
  884. (+ (read) (- (+ 5 3)))
  885. \end{lstlisting}
  886. our compiler will translate it into the program
  887. \begin{lstlisting}
  888. (+ (read) -8)
  889. \end{lstlisting}
  890. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  891. evaluator for the $R_0$ language. The output of the partial evaluator
  892. is an $R_0$ program. In Figure~\ref{fig:pe-arith}, the structural
  893. recursion over $\Exp$ is captured in the \code{pe-exp} function
  894. whereas the code for partially evaluating the negation and addition
  895. operations is factored into two separate helper functions:
  896. \code{pe-neg} and \code{pe-add}. The input to these helper
  897. functions is the output of partially evaluating the children.
  898. \begin{figure}[tp]
  899. \begin{lstlisting}
  900. (define (pe-neg r)
  901. (match r
  902. [(Int n) (Int (fx- 0 n))]
  903. [else (Prim '- (list r))]))
  904. (define (pe-add r1 r2)
  905. (match* (r1 r2)
  906. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  907. [(_ _) (Prim '+ (list r1 r2))]))
  908. (define (pe-exp e)
  909. (match e
  910. [(Int n) (Int n)]
  911. [(Prim 'read '()) (Prim 'read '())]
  912. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  913. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]
  914. ))
  915. (define (pe-R0 p)
  916. (match p
  917. [(Program '() e) (Program '() (pe-exp e))]
  918. ))
  919. \end{lstlisting}
  920. \caption{A partial evaluator for $R_0$ expressions.}
  921. \label{fig:pe-arith}
  922. \end{figure}
  923. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  924. arguments are integers and if they are, perform the appropriate
  925. arithmetic. Otherwise, they create an AST node for the operation
  926. (either negation or addition).
  927. To gain some confidence that the partial evaluator is correct, we can
  928. test whether it produces programs that get the same result as the
  929. input programs. That is, we can test whether it satisfies Diagram
  930. \eqref{eq:compile-correct}. The following code runs the partial
  931. evaluator on several examples and tests the output program. The
  932. \texttt{parse-program} and \texttt{assert} functions are defined in
  933. Appendix~\ref{appendix:utilities}.\\
  934. \begin{minipage}{1.0\textwidth}
  935. \begin{lstlisting}
  936. (define (test-pe p)
  937. (assert "testing pe-R0"
  938. (equal? (interp-R0 p) (interp-R0 (pe-R0 p)))))
  939. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  940. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  941. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  942. \end{lstlisting}
  943. \end{minipage}
  944. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  945. \chapter{Integers and Variables}
  946. \label{ch:int-exp}
  947. This chapter is about compiling the subset of Racket that includes
  948. integer arithmetic and local variable binding, which we name $R_1$, to
  949. x86-64 assembly code~\citep{Intel:2015aa}. Henceforth we refer
  950. to x86-64 simply as x86. The chapter begins with a description of the
  951. $R_1$ language (Section~\ref{sec:s0}) followed by a description of x86
  952. (Section~\ref{sec:x86}). The x86 assembly language is large, so we
  953. discuss only what is needed for compiling $R_1$. We introduce more of
  954. x86 in later chapters. Once we have introduced $R_1$ and x86, we
  955. reflect on their differences and come up with a plan to break down the
  956. translation from $R_1$ to x86 into a handful of steps
  957. (Section~\ref{sec:plan-s0-x86}). The rest of the sections in this
  958. chapter give detailed hints regarding each step
  959. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  960. to give enough hints that the well-prepared reader, together with a
  961. few friends, can implement a compiler from $R_1$ to x86 in a couple
  962. weeks while at the same time leaving room for some fun and creativity.
  963. To give the reader a feeling for the scale of this first compiler, the
  964. instructor solution for the $R_1$ compiler is less than 500 lines of
  965. code.
  966. \section{The $R_1$ Language}
  967. \label{sec:s0}
  968. \index{variable}
  969. The $R_1$ language extends the $R_0$ language with variable
  970. definitions. The concrete syntax of the $R_1$ language is defined by
  971. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  972. syntax is defined in Figure~\ref{fig:r1-syntax}. The non-terminal
  973. \Var{} may be any Racket identifier. As in $R_0$, \key{read} is a
  974. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  975. operator. Similar to $R_0$, the abstract syntax of $R_1$ includes the
  976. \key{Program} struct to mark the top of the program.
  977. %% The $\itm{info}$
  978. %% field of the \key{Program} structure contains an \emph{association
  979. %% list} (a list of key-value pairs) that is used to communicate
  980. %% auxiliary data from one compiler pass the next.
  981. Despite the simplicity of the $R_1$ language, it is rich enough to
  982. exhibit several compilation techniques.
  983. \begin{figure}[tp]
  984. \centering
  985. \fbox{
  986. \begin{minipage}{0.96\textwidth}
  987. \[
  988. \begin{array}{rcl}
  989. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp}\\
  990. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  991. R_1 &::=& \Exp
  992. \end{array}
  993. \]
  994. \end{minipage}
  995. }
  996. \caption{The concrete syntax of $R_1$.}
  997. \label{fig:r1-concrete-syntax}
  998. \end{figure}
  999. \begin{figure}[tp]
  1000. \centering
  1001. \fbox{
  1002. \begin{minipage}{0.96\textwidth}
  1003. \[
  1004. \begin{array}{rcl}
  1005. \Exp &::=& \INT{\Int} \mid \READ{} \\
  1006. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  1007. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  1008. R_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1009. \end{array}
  1010. \]
  1011. \end{minipage}
  1012. }
  1013. \caption{The abstract syntax of $R_1$.}
  1014. \label{fig:r1-syntax}
  1015. \end{figure}
  1016. Let us dive further into the syntax and semantics of the $R_1$
  1017. language. The \key{Let} feature defines a variable for use within its
  1018. body and initializes the variable with the value of an expression.
  1019. The abstract syntax for \key{Let} is defined in Figure~\ref{fig:r1-syntax}.
  1020. The concrete syntax for \key{Let} is
  1021. \begin{lstlisting}
  1022. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1023. \end{lstlisting}
  1024. For example, the following program initializes \code{x} to $32$ and then
  1025. evaluates the body \code{(+ 10 x)}, producing $42$.
  1026. \begin{lstlisting}
  1027. (let ([x (+ 12 20)]) (+ 10 x))
  1028. \end{lstlisting}
  1029. When there are multiple \key{let}'s for the same variable, the closest
  1030. enclosing \key{let} is used. That is, variable definitions overshadow
  1031. prior definitions. Consider the following program with two \key{let}'s
  1032. that define variables named \code{x}. Can you figure out the result?
  1033. \begin{lstlisting}
  1034. (let ([x 32]) (+ (let ([x 10]) x) x))
  1035. \end{lstlisting}
  1036. For the purposes of depicting which variable uses correspond to which
  1037. definitions, the following shows the \code{x}'s annotated with
  1038. subscripts to distinguish them. Double check that your answer for the
  1039. above is the same as your answer for this annotated version of the
  1040. program.
  1041. \begin{lstlisting}
  1042. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1043. \end{lstlisting}
  1044. The initializing expression is always evaluated before the body of the
  1045. \key{let}, so in the following, the \key{read} for \code{x} is
  1046. performed before the \key{read} for \code{y}. Given the input
  1047. $52$ then $10$, the following produces $42$ (not $-42$).
  1048. \begin{lstlisting}
  1049. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1050. \end{lstlisting}
  1051. \subsection{Extensible Interpreters via Method Overriding}
  1052. To prepare for discussing the interpreter for $R_1$, we need to
  1053. explain why we choose to implement the interpreter using
  1054. object-oriented programming, that is, as a collection of methods
  1055. inside of a class. Throughout this book we define many interpreters,
  1056. one for each of the languages that we study. Because each language
  1057. builds on the prior one, there is a lot of commonality between their
  1058. interpreters. We want to write down those common parts just once
  1059. instead of many times. A naive approach would be to have, for example,
  1060. the interpreter for $R_2$ handle all of the new features in that
  1061. language and then have a default case that dispatches to the
  1062. interpreter for $R_1$. The follow code sketches this idea.
  1063. \begin{center}
  1064. \begin{minipage}{0.45\textwidth}
  1065. \begin{lstlisting}
  1066. (define (interp-R1 e)
  1067. (match e
  1068. [(Prim '- (list e))
  1069. (define v (interp-R1 e))
  1070. (fx- 0 v)]
  1071. ...
  1072. ))
  1073. \end{lstlisting}
  1074. \end{minipage}
  1075. \begin{minipage}{0.45\textwidth}
  1076. \begin{lstlisting}
  1077. (define (interp-R2 e)
  1078. (match e
  1079. [(If cnd thn els)
  1080. (define b (interp-R2 cnd))
  1081. (match b
  1082. [#t (interp-R2 thn)]
  1083. [#f (interp-R2 els)])]
  1084. ...
  1085. [else (interp-R1 e)]
  1086. ))
  1087. \end{lstlisting}
  1088. \end{minipage}
  1089. \end{center}
  1090. The problem with this approach is that it does not handle situations
  1091. in which an $R_2$ feature, like \code{If}, is nested inside an $R_1$
  1092. feature, like the \code{-} operator, as in the following program.
  1093. \begin{lstlisting}
  1094. (Prim '- (list (If (Bool #t) (Int 42) (Int 0))))
  1095. \end{lstlisting}
  1096. If we invoke \code{interp-R2} on this program, it dispatches to
  1097. \code{interp-R1} to handle the \code{-} operator, but then it
  1098. recurisvely calls \code{interp-R1} again on the argument of \code{-},
  1099. which is an \code{If}. But there is no case for \code{If} in
  1100. \code{interp-R1}, so we get an error!
  1101. To make our intepreters extensible we need something called \emph{open
  1102. recursion}\index{open recursion}. That is, a recursive call should
  1103. always invoke the ``top'' interpreter, even if the recursive call is
  1104. made from interpreters that are lower down. Object-oriented languages
  1105. provide open recursion in the form of method overriding\index{method
  1106. overriding}. The follow code sketches this idea for interpreting
  1107. $R_1$ and $R_2$ using the
  1108. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1109. \index{class} feature of Racket. We define one class for each
  1110. language and place a method for interpreting expressions inside each
  1111. class. The class for $R_2$ inherits from the class for $R_1$ and the
  1112. method \code{interp-exp} for $R_2$ overrides the \code{interp-exp} for
  1113. $R_1$. Note that the default case in \code{interp-exp} for $R_2$ uses
  1114. \code{super} to invoke \code{interp-exp}, and because $R_2$ inherits
  1115. from $R_1$, that dispatches to the \code{interp-exp} for $R_1$.
  1116. \begin{center}
  1117. \begin{minipage}{0.45\textwidth}
  1118. \begin{lstlisting}
  1119. (define interp-R1-class
  1120. (class object%
  1121. (define/public (interp-exp e)
  1122. (match e
  1123. [(Prim '- (list e))
  1124. (define v (interp-exp e))
  1125. (fx- 0 v)]
  1126. ...
  1127. ))
  1128. ...
  1129. ))
  1130. \end{lstlisting}
  1131. \end{minipage}
  1132. \begin{minipage}{0.45\textwidth}
  1133. \begin{lstlisting}
  1134. (define interp-R2-class
  1135. (class interp-R1-class
  1136. (define/override (interp-exp e)
  1137. (match e
  1138. [(If cnd thn els)
  1139. (define b (interp-exp cnd))
  1140. (match b
  1141. [#t (interp-exp thn)]
  1142. [#f (interp-exp els)])]
  1143. ...
  1144. [else (super interp-exp e)]
  1145. ))
  1146. ...
  1147. ))
  1148. \end{lstlisting}
  1149. \end{minipage}
  1150. \end{center}
  1151. Getting back to the troublesome example, repeated here:
  1152. \begin{lstlisting}
  1153. (define e0 (Prim '- (list (If (Bool #t) (Int 42) (Int 0)))))
  1154. \end{lstlisting}
  1155. We can invoke the \code{interp-exp} method for $R_2$ on this
  1156. expression by creating an object of the $R_2$ class and sending it the
  1157. \code{interp-exp} method with the argument \code{e0}.
  1158. \begin{lstlisting}
  1159. (send (new interp-R2-class) interp-exp e0)
  1160. \end{lstlisting}
  1161. This will again hit the default case and dispatch to the
  1162. \code{interp-exp} method for $R_1$, which will handle the \code{-}
  1163. operator. But then for the recursive method call, it will dispatch
  1164. back to \code{interp-exp} for $R_2$, where the \code{If} will be
  1165. correctly handled. Thus, method overriding gives us the open recursion
  1166. that we need to implement our interpreters in an extensible way.
  1167. \newpage
  1168. \subsection{Definitional Interpreter for $R_1$}
  1169. \begin{wrapfigure}[24]{r}[1.0in]{0.6\textwidth}
  1170. \small
  1171. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1172. An \emph{association list} (alist) is a list of key-value pairs.
  1173. For example, we can map people to their ages with an alist.
  1174. \index{alist}\index{association list}
  1175. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1176. (define ages
  1177. '((jane . 25) (sam . 24) (kate . 45)))
  1178. \end{lstlisting}
  1179. The \emph{dictionary} interface is for mapping keys to values.
  1180. Every alist implements this interface. \index{dictionary} The package
  1181. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1182. provides many functions for working with dictionaries. Here
  1183. are a few of them:
  1184. \begin{description}
  1185. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1186. returns the value associated with the given $\itm{key}$.
  1187. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1188. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1189. but otherwise is the same as $\itm{dict}$.
  1190. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1191. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1192. of keys and values in $\itm{dict}$. For example, the following
  1193. creates a new alist in which the ages are incremented.
  1194. \end{description}
  1195. \vspace{-10pt}
  1196. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1197. (for/list ([(k v) (in-dict ages)])
  1198. (cons k (add1 v)))
  1199. \end{lstlisting}
  1200. \end{tcolorbox}
  1201. \end{wrapfigure}
  1202. Now that we have explained why we use classes and methods to implement
  1203. interpreters, we turn to the discussion of the actual interpreter for
  1204. $R_1$. Figure~\ref{fig:interp-R1} shows the definitional interpreter
  1205. for the $R_1$ language. It is similar to the interpreter for $R_0$ but
  1206. it adds two new \key{match} clauses for variables and for \key{let}.
  1207. For \key{let}, we need a way to communicate the value of a variable to
  1208. all the uses of a variable. To accomplish this, we maintain a mapping
  1209. from variables to values. Throughout the compiler we often need to map
  1210. variables to information about them. We refer to these mappings as
  1211. \emph{environments}\index{environment}
  1212. \footnote{Another common term for environment in the compiler
  1213. literature is \emph{symbol table}\index{symbol table}.}.
  1214. For simplicity, we use an
  1215. association list (alist) to represent the environment. The sidebar to
  1216. the right gives a brief introduction to alists and the
  1217. \code{racket/dict} package. The \code{interp-R1} function takes the
  1218. current environment, \code{env}, as an extra parameter. When the
  1219. interpreter encounters a variable, it finds the corresponding value
  1220. using the \code{dict-ref} function. When the interpreter encounters a
  1221. \key{Let}, it evaluates the initializing expression, extends the
  1222. environment with the result value bound to the variable, using
  1223. \code{dict-set}, then evaluates the body of the \key{Let}.
  1224. \begin{figure}[tp]
  1225. \begin{lstlisting}
  1226. (define interp-R1-class
  1227. (class object%
  1228. (super-new)
  1229. (define/public ((interp-exp env) e)
  1230. (match e
  1231. [(Int n) n]
  1232. [(Prim 'read '())
  1233. (define r (read))
  1234. (cond [(fixnum? r) r]
  1235. [else (error 'interp-exp "expected an integer" r)])]
  1236. [(Prim '- (list e))
  1237. (define v ((interp-exp env) e))
  1238. (fx- 0 v)]
  1239. [(Prim '+ (list e1 e2))
  1240. (define v1 ((interp-exp env) e1))
  1241. (define v2 ((interp-exp env) e2))
  1242. (fx+ v1 v2)]
  1243. [(Var x) (dict-ref env x)]
  1244. [(Let x e body)
  1245. (define new-env (dict-set env x ((interp-exp env) e)))
  1246. ((interp-exp new-env) body)]
  1247. ))
  1248. (define/public (interp-program p)
  1249. (match p
  1250. [(Program '() e) ((interp-exp '()) e)]
  1251. ))
  1252. ))
  1253. (define (interp-R1 p)
  1254. (send (new interp-R1-class) interp-program p))
  1255. \end{lstlisting}
  1256. \caption{Interpreter for the $R_1$ language.}
  1257. \label{fig:interp-R1}
  1258. \end{figure}
  1259. The goal for this chapter is to implement a compiler that translates
  1260. any program $P_1$ written in the $R_1$ language into an x86 assembly
  1261. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1262. computer as the $P_1$ program interpreted by \code{interp-R1}. That
  1263. is, they both output the same integer $n$. We depict this correctness
  1264. criteria in the following diagram.
  1265. \[
  1266. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1267. \node (p1) at (0, 0) {$P_1$};
  1268. \node (p2) at (4, 0) {$P_2$};
  1269. \node (o) at (4, -2) {$n$};
  1270. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1271. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  1272. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  1273. \end{tikzpicture}
  1274. \]
  1275. In the next section we introduce enough of the x86 assembly
  1276. language to compile $R_1$.
  1277. \section{The x86$_0$ Assembly Language}
  1278. \label{sec:x86}
  1279. \index{x86}
  1280. Figure~\ref{fig:x86-0-concrete} defines the concrete syntax for the subset of
  1281. the x86 assembly language needed for this chapter, which we call x86$_0$.
  1282. %
  1283. An x86 program begins with a \code{main} label followed by a sequence
  1284. of instructions. In the grammar, ellipses such as $\ldots$ are used to
  1285. indicate a sequence of items, e.g., $\Instr \ldots$ is a sequence of
  1286. instructions.\index{instruction}
  1287. %
  1288. An x86 program is stored in the computer's memory and the computer has
  1289. a \emph{program counter} (PC)\index{program counter}\index{PC}
  1290. that points to the address of the next
  1291. instruction to be executed. For most instructions, once the
  1292. instruction is executed, the program counter is incremented to point
  1293. to the immediately following instruction in memory. Most x86
  1294. instructions take two operands, where each operand is either an
  1295. integer constant (called \emph{immediate value}\index{immediate value}),
  1296. a \emph{register}\index{register}, or a memory location.
  1297. A register is a special kind of variable. Each
  1298. one holds a 64-bit value; there are 16 registers in the computer and
  1299. their names are given in Figure~\ref{fig:x86-0-concrete}. The computer's memory
  1300. as a mapping of 64-bit addresses to 64-bit values%
  1301. \footnote{This simple story suffices for describing how sequential
  1302. programs access memory but is not sufficient for multi-threaded
  1303. programs. However, multi-threaded execution is beyond the scope of
  1304. this book.}.
  1305. %
  1306. We use the AT\&T syntax expected by the GNU assembler, which comes
  1307. with the \key{gcc} compiler that we use for compiling assembly code to
  1308. machine code.
  1309. %
  1310. Appendix~\ref{sec:x86-quick-reference} is a quick-reference for all of
  1311. the x86 instructions used in this book.
  1312. % to do: finish treatment of imulq
  1313. % it's needed for vector's in R6/R7
  1314. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1315. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1316. && \key{r8} \mid \key{r9} \mid \key{r10}
  1317. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1318. \mid \key{r14} \mid \key{r15}}
  1319. \begin{figure}[tp]
  1320. \fbox{
  1321. \begin{minipage}{0.96\textwidth}
  1322. \[
  1323. \begin{array}{lcl}
  1324. \Reg &::=& \allregisters{} \\
  1325. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1326. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1327. \key{subq} \; \Arg\key{,} \Arg \mid
  1328. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1329. && \key{callq} \; \mathit{label} \mid
  1330. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} \\
  1331. && \itm{label}\key{:}\; \Instr \\
  1332. x86_0 &::= & \key{.globl main}\\
  1333. & & \key{main:} \; \Instr\ldots
  1334. \end{array}
  1335. \]
  1336. \end{minipage}
  1337. }
  1338. \caption{The syntax of the x86$_0$ assembly language (AT\&T syntax).}
  1339. \label{fig:x86-0-concrete}
  1340. \end{figure}
  1341. An immediate value is written using the notation \key{\$}$n$ where $n$
  1342. is an integer.
  1343. %
  1344. A register is written with a \key{\%} followed by the register name,
  1345. such as \key{\%rax}.
  1346. %
  1347. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1348. which obtains the address stored in register $r$ and then adds $n$
  1349. bytes to the address. The resulting address is used to either load or
  1350. store to memory depending on whether it occurs as a source or
  1351. destination argument of an instruction.
  1352. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1353. source $s$ and destination $d$, applies the arithmetic operation, then
  1354. writes the result back to the destination $d$.
  1355. %
  1356. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1357. stores the result in $d$.
  1358. %
  1359. The $\key{callq}\,\itm{label}$ instruction executes the procedure
  1360. specified by the label and $\key{retq}$ returns from a procedure to
  1361. its caller. The abstract syntax for \code{callq} includes an extra
  1362. integer field that represents the arity (number of parameters) of the
  1363. function being called.
  1364. %
  1365. We discuss procedure calls in more detail later in this
  1366. chapter and in Chapter~\ref{ch:functions}. The
  1367. $\key{jmp}\,\itm{label}$ instruction updates the program counter to
  1368. the address of the instruction after the specified label.
  1369. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  1370. to \code{(+ 10 32)}. The \key{globl} directive says that the
  1371. \key{main} procedure is externally visible, which is necessary so
  1372. that the operating system can call it. The label \key{main:}
  1373. indicates the beginning of the \key{main} procedure which is where
  1374. the operating system starts executing this program. The instruction
  1375. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  1376. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  1377. $10$ in \key{rax} and puts the result, $42$, back into
  1378. \key{rax}.
  1379. %
  1380. The last instruction, \key{retq}, finishes the \key{main} function by
  1381. returning the integer in \key{rax} to the operating system. The
  1382. operating system interprets this integer as the program's exit
  1383. code. By convention, an exit code of 0 indicates that a program
  1384. completed successfully, and all other exit codes indicate various
  1385. errors. Nevertheless, we return the result of the program as the exit
  1386. code.
  1387. %\begin{wrapfigure}{r}{2.25in}
  1388. \begin{figure}[tbp]
  1389. \begin{lstlisting}
  1390. .globl main
  1391. main:
  1392. movq $10, %rax
  1393. addq $32, %rax
  1394. retq
  1395. \end{lstlisting}
  1396. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1397. \label{fig:p0-x86}
  1398. %\end{wrapfigure}
  1399. \end{figure}
  1400. Unfortunately, x86 varies in a couple ways depending on what operating
  1401. system it is assembled in. The code examples shown here are correct on
  1402. Linux and most Unix-like platforms, but when assembled on Mac OS X,
  1403. labels like \key{main} must be prefixed with an underscore, as in
  1404. \key{\_main}.
  1405. We exhibit the use of memory for storing intermediate results in the
  1406. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1407. equivalent to \code{(+ 52 (- 10))}. This program uses a region of
  1408. memory called the \emph{procedure call stack} (or \emph{stack} for
  1409. short). \index{stack}\index{procedure call stack} The stack consists
  1410. of a separate \emph{frame}\index{frame} for each procedure call. The
  1411. memory layout for an individual frame is shown in
  1412. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1413. \emph{stack pointer}\index{stack pointer} and points to the item at
  1414. the top of the stack. The stack grows downward in memory, so we
  1415. increase the size of the stack by subtracting from the stack pointer.
  1416. In the context of a procedure call, the \emph{return
  1417. address}\index{return address} is the instruction after the call
  1418. instruction on the caller side. The function call instruction,
  1419. \code{callq}, pushes the return address onto the stack. The register
  1420. \key{rbp} is the \emph{base pointer}\index{base pointer} and is used
  1421. to access variables associated with the current procedure call. The
  1422. base pointer of the caller is pushed onto the stack after the return
  1423. address. We number the variables from $1$ to $n$. Variable $1$ is
  1424. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  1425. $-16\key{(\%rbp)}$, etc.
  1426. \begin{figure}[tbp]
  1427. \begin{lstlisting}
  1428. start:
  1429. movq $10, -8(%rbp)
  1430. negq -8(%rbp)
  1431. movq -8(%rbp), %rax
  1432. addq $52, %rax
  1433. jmp conclusion
  1434. .globl main
  1435. main:
  1436. pushq %rbp
  1437. movq %rsp, %rbp
  1438. subq $16, %rsp
  1439. jmp start
  1440. conclusion:
  1441. addq $16, %rsp
  1442. popq %rbp
  1443. retq
  1444. \end{lstlisting}
  1445. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1446. \label{fig:p1-x86}
  1447. \end{figure}
  1448. \begin{figure}[tbp]
  1449. \centering
  1450. \begin{tabular}{|r|l|} \hline
  1451. Position & Contents \\ \hline
  1452. 8(\key{\%rbp}) & return address \\
  1453. 0(\key{\%rbp}) & old \key{rbp} \\
  1454. -8(\key{\%rbp}) & variable $1$ \\
  1455. -16(\key{\%rbp}) & variable $2$ \\
  1456. \ldots & \ldots \\
  1457. 0(\key{\%rsp}) & variable $n$\\ \hline
  1458. \end{tabular}
  1459. \caption{Memory layout of a frame.}
  1460. \label{fig:frame}
  1461. \end{figure}
  1462. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  1463. control is transferred from the operating system to the \code{main}
  1464. function. The operating system issues a \code{callq main} instruction
  1465. which pushes its return address on the stack and then jumps to
  1466. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  1467. by 16 bytes prior to the execution of any \code{callq} instruction, so
  1468. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  1469. alignment (because the \code{callq} pushed the return address). The
  1470. first three instructions are the typical \emph{prelude}\index{prelude}
  1471. for a procedure. The instruction \code{pushq \%rbp} saves the base
  1472. pointer for the caller onto the stack and subtracts $8$ from the stack
  1473. pointer. At this point the stack pointer is back to being 16-byte
  1474. aligned. The second instruction \code{movq \%rsp, \%rbp} changes the
  1475. base pointer so that it points the location of the old base
  1476. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  1477. pointer down to make enough room for storing variables. This program
  1478. needs one variable ($8$ bytes) but we round up to 16 bytes to maintain
  1479. the 16-byte alignment of the \code{rsp}. With the \code{rsp} aligned,
  1480. we are ready to make calls to other functions. The last instruction of
  1481. the prelude is \code{jmp start}, which transfers control to the
  1482. instructions that were generated from the Racket expression \code{(+
  1483. 10 32)}.
  1484. The four instructions under the label \code{start} carry out the work
  1485. of computing \code{(+ 52 (- 10)))}.
  1486. %
  1487. The first instruction \code{movq \$10, -8(\%rbp)} stores $10$ in
  1488. variable $1$.
  1489. %
  1490. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  1491. %
  1492. The following instruction moves the $-10$ from variable $1$ into the
  1493. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  1494. the value in \code{rax}, updating its contents to $42$.
  1495. The three instructions under the label \code{conclusion} are the
  1496. typical \emph{conclusion}\index{conclusion} of a procedure. The first
  1497. two instructions are necessary to get the state of the machine back to
  1498. where it was at the beginning of the procedure. The instruction
  1499. \key{addq \$16, \%rsp} moves the stack pointer back to point at the
  1500. old base pointer. The amount added here needs to match the amount that
  1501. was subtracted in the prelude of the procedure. Then \key{popq \%rbp}
  1502. returns the old base pointer to \key{rbp} and adds $8$ to the stack
  1503. pointer. The last instruction, \key{retq}, jumps back to the
  1504. procedure that called this one and adds 8 to the stack pointer, which
  1505. returns the stack pointer to where it was prior to the procedure call.
  1506. The compiler needs a convenient representation for manipulating x86
  1507. programs, so we define an abstract syntax for x86 in
  1508. Figure~\ref{fig:x86-0-ast}. We refer to this language as x86$_0$ with
  1509. a subscript $0$ because later we introduce extended versions of this
  1510. assembly language. The main difference compared to the concrete syntax
  1511. of x86 (Figure~\ref{fig:x86-0-concrete}) is that it does not allow
  1512. labeled instructions to appear anywhere, but instead organizes
  1513. instructions into a group called a
  1514. \emph{block}\index{block}\index{basic block} and associates a label
  1515. with every block, which is why the \key{CFG} struct (for control-flow
  1516. graph) includes an alist mapping labels to blocks. The reason for this
  1517. organization becomes apparent in Chapter~\ref{ch:bool-types} when we
  1518. introduce conditional branching. The \code{Block} structure includes
  1519. an $\itm{info}$ field that is not needed for this chapter, but will
  1520. become useful in Chapter~\ref{ch:register-allocation-r1}. For now,
  1521. the $\itm{info}$ field should just contain an empty list. Also,
  1522. regarding the abstract syntax for \code{callq}, the \code{Callq}
  1523. struct includes an integer for representing the arity of the function,
  1524. i.e., the number of arguments, which is helpful to know during
  1525. register allocation (Chapter~\ref{ch:register-allocation-r1}).
  1526. \begin{figure}[tp]
  1527. \fbox{
  1528. \begin{minipage}{0.96\textwidth}
  1529. \small
  1530. \[
  1531. \begin{array}{lcl}
  1532. \Reg &::=& \allregisters{} \\
  1533. \Arg &::=& \IMM{\Int} \mid \REG{\Reg}
  1534. \mid \DEREF{\Reg}{\Int} \\
  1535. \Instr &::=& \BININSTR{\code{'addq}}{\Arg}{\Arg}
  1536. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} \\
  1537. &\mid& \BININSTR{\code{'movq}}{\Arg}{\Arg}
  1538. \mid \UNIINSTR{\code{'negq}}{\Arg}\\
  1539. &\mid& \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  1540. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  1541. \Block &::= & \BLOCK{\itm{info}}{\Instr\ldots} \\
  1542. x86_0 &::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}}
  1543. \end{array}
  1544. \]
  1545. \end{minipage}
  1546. }
  1547. \caption{The abstract syntax of x86$_0$ assembly.}
  1548. \label{fig:x86-0-ast}
  1549. \end{figure}
  1550. \section{Planning the trip to x86 via the $C_0$ language}
  1551. \label{sec:plan-s0-x86}
  1552. To compile one language to another it helps to focus on the
  1553. differences between the two languages because the compiler will need
  1554. to bridge those differences. What are the differences between $R_1$
  1555. and x86 assembly? Here are some of the most important ones:
  1556. \begin{enumerate}
  1557. \item[(a)] x86 arithmetic instructions typically have two arguments
  1558. and update the second argument in place. In contrast, $R_1$
  1559. arithmetic operations take two arguments and produce a new value.
  1560. An x86 instruction may have at most one memory-accessing argument.
  1561. Furthermore, some instructions place special restrictions on their
  1562. arguments.
  1563. \item[(b)] An argument of an $R_1$ operator can be any expression,
  1564. whereas x86 instructions restrict their arguments to be integers
  1565. constants, registers, and memory locations.
  1566. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1567. sequence of instructions and jumps to labeled positions, whereas in
  1568. $R_1$ the order of evaluation is a left-to-right depth-first
  1569. traversal of the abstract syntax tree.
  1570. \item[(d)] An $R_1$ program can have any number of variables whereas
  1571. x86 has 16 registers and the procedure calls stack.
  1572. \item[(e)] Variables in $R_1$ can overshadow other variables with the
  1573. same name. The registers and memory locations of x86 all have unique
  1574. names or addresses.
  1575. \end{enumerate}
  1576. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1577. the problem into several steps, dealing with the above differences one
  1578. at a time. Each of these steps is called a \emph{pass} of the
  1579. compiler.\index{pass}\index{compiler pass}
  1580. %
  1581. This terminology comes from each step traverses (i.e. passes over) the
  1582. AST of the program.
  1583. %
  1584. We begin by sketching how we might implement each pass, and give them
  1585. names. We then figure out an ordering of the passes and the
  1586. input/output language for each pass. The very first pass has $R_1$ as
  1587. its input language and the last pass has x86 as its output
  1588. language. In between we can choose whichever language is most
  1589. convenient for expressing the output of each pass, whether that be
  1590. $R_1$, x86, or new \emph{intermediate languages} of our own design.
  1591. Finally, to implement each pass we write one recursive function per
  1592. non-terminal in the grammar of the input language of the pass.
  1593. \index{intermediate language}
  1594. \begin{description}
  1595. \item[Pass \key{select-instructions}] To handle the difference between
  1596. $R_1$ operations and x86 instructions we convert each $R_1$
  1597. operation to a short sequence of instructions that accomplishes the
  1598. same task.
  1599. \item[Pass \key{remove-complex-opera*}] To ensure that each
  1600. subexpression (i.e. operator and operand, and hence the name
  1601. \key{opera*}) is an \emph{atomic} expression (a variable or
  1602. integer), we introduce temporary variables to hold the results
  1603. of subexpressions.\index{atomic expression}
  1604. \item[Pass \key{explicate-control}] To make the execution order of the
  1605. program explicit, we convert from the abstract syntax tree
  1606. representation into a control-flow graph in which each node
  1607. contains a sequence of statements and the edges between nodes say
  1608. where to go at the end of the sequence.
  1609. \item[Pass \key{assign-homes}] To handle the difference between the
  1610. variables in $R_1$ versus the registers and stack locations in x86,
  1611. we map each variable to a register or stack location.
  1612. \item[Pass \key{uniquify}] This pass deals with the shadowing of variables
  1613. by renaming every variable to a unique name, so that shadowing no
  1614. longer occurs.
  1615. \end{description}
  1616. The next question is: in what order should we apply these passes? This
  1617. question can be challenging because it is difficult to know ahead of
  1618. time which orders will be better (easier to implement, produce more
  1619. efficient code, etc.) so oftentimes trial-and-error is
  1620. involved. Nevertheless, we can try to plan ahead and make educated
  1621. choices regarding the ordering.
  1622. Let us consider the ordering of \key{uniquify} and
  1623. \key{remove-complex-opera*}. The assignment of subexpressions to
  1624. temporary variables involves introducing new variables and moving
  1625. subexpressions, which might change the shadowing of variables and
  1626. inadvertently change the behavior of the program. But if we apply
  1627. \key{uniquify} first, this will not be an issue. Of course, this means
  1628. that in \key{remove-complex-opera*}, we need to ensure that the
  1629. temporary variables that it creates are unique.
  1630. What should be the ordering of \key{explicate-control} with respect to
  1631. \key{uniquify}? The \key{uniquify} pass should come first because
  1632. \key{explicate-control} changes all the \key{let}-bound variables to
  1633. become local variables whose scope is the entire program, which would
  1634. confuse variables with the same name.
  1635. %
  1636. Likewise, we place \key{explicate-control} after
  1637. \key{remove-complex-opera*} because \key{explicate-control} removes
  1638. the \key{let} form, but it is convenient to use \key{let} in the
  1639. output of \key{remove-complex-opera*}.
  1640. %
  1641. Regarding \key{assign-homes}, it is helpful to place
  1642. \key{explicate-control} first because \key{explicate-control} changes
  1643. \key{let}-bound variables into program-scope variables. This means
  1644. that the \key{assign-homes} pass can read off the variables from the
  1645. $\itm{info}$ of the \key{Program} AST node instead of traversing the
  1646. entire program in search of \key{let}-bound variables.
  1647. Last, we need to decide on the ordering of \key{select-instructions}
  1648. and \key{assign-homes}. These two passes are intertwined, creating a
  1649. Gordian Knot. To do a good job of assigning homes, it is helpful to
  1650. have already determined which instructions will be used, because x86
  1651. instructions have restrictions about which of their arguments can be
  1652. registers versus stack locations. One might want to give preferential
  1653. treatment to variables that occur in register-argument positions. On
  1654. the other hand, it may turn out to be impossible to make sure that all
  1655. such variables are assigned to registers, and then one must redo the
  1656. selection of instructions. Some compilers handle this problem by
  1657. iteratively repeating these two passes until a good solution is found.
  1658. We use a simpler approach in which \key{select-instructions}
  1659. comes first, followed by the \key{assign-homes}, then a third
  1660. pass named \key{patch-instructions} that uses a reserved register to
  1661. patch-up outstanding problems regarding instructions with too many
  1662. memory accesses. The disadvantage of this approach is some programs
  1663. may not execute as efficiently as they would if we used the iterative
  1664. approach and used all of the registers for variables.
  1665. \begin{figure}[tbp]
  1666. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1667. \node (R1) at (0,2) {\large $R_1$};
  1668. \node (R1-2) at (3,2) {\large $R_1$};
  1669. \node (R1-3) at (6,2) {\large $R_1^{\dagger}$};
  1670. %\node (C0-1) at (6,0) {\large $C_0$};
  1671. \node (C0-2) at (3,0) {\large $C_0$};
  1672. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_0$};
  1673. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_0$};
  1674. \node (x86-4) at (9,-2) {\large $\text{x86}_0$};
  1675. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}_0$};
  1676. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1677. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  1678. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-2);
  1679. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1680. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1681. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1682. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1683. \end{tikzpicture}
  1684. \caption{Overview of the passes for compiling $R_1$. }
  1685. \label{fig:R1-passes}
  1686. \end{figure}
  1687. Figure~\ref{fig:R1-passes} presents the ordering of the compiler
  1688. passes in the form of a graph. Each pass is an edge and the
  1689. input/output language of each pass is a node in the graph. The output
  1690. of \key{uniquify} and \key{remove-complex-opera*} are programs that
  1691. are still in the $R_1$ language, but the output of the pass
  1692. \key{explicate-control} is in a different language $C_0$ that is
  1693. designed to make the order of evaluation explicit in its syntax, which
  1694. we introduce in the next section. The \key{select-instruction} pass
  1695. translates from $C_0$ to a variant of x86. The \key{assign-homes} and
  1696. \key{patch-instructions} passes input and output variants of x86
  1697. assembly. The last pass in Figure~\ref{fig:R1-passes} is
  1698. \key{print-x86}, which converts from the abstract syntax of
  1699. $\text{x86}_0$ to the concrete syntax of x86.
  1700. In the next sections we discuss the $C_0$ language and the
  1701. $\text{x86}^{*}_0$ and $\text{x86}^{\dagger}_0$ dialects of x86. The
  1702. remainder of this chapter gives hints regarding the implementation of
  1703. each of the compiler passes in Figure~\ref{fig:R1-passes}.
  1704. \subsection{The $C_0$ Intermediate Language}
  1705. The output of \key{explicate-control} is similar to the $C$
  1706. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1707. categories for expressions and statements, so we name it $C_0$. The
  1708. concrete syntax for $C_0$ is defined in
  1709. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for $C_0$
  1710. is defined in Figure~\ref{fig:c0-syntax}.
  1711. %
  1712. The $C_0$ language supports the same operators as $R_1$ but the
  1713. arguments of operators are restricted to atomic expressions (variables
  1714. and integers), thanks to the \key{remove-complex-opera*} pass. Instead
  1715. of \key{Let} expressions, $C_0$ has assignment statements which can be
  1716. executed in sequence using the \key{Seq} form. A sequence of
  1717. statements always ends with \key{Return}, a guarantee that is baked
  1718. into the grammar rules for the \itm{tail} non-terminal. The naming of
  1719. this non-terminal comes from the term \emph{tail position}\index{tail position},
  1720. which refers to an expression that is the last one to execute within a
  1721. function. (An expression in tail position may contain subexpressions,
  1722. and those may or may not be in tail position depending on the kind of
  1723. expression.)
  1724. A $C_0$ program consists of a control-flow graph (represented as an
  1725. alist mapping labels to tails). This is more general than
  1726. necessary for the present chapter, as we do not yet need to introduce
  1727. \key{goto} for jumping to labels, but it saves us from having to
  1728. change the syntax of the program construct in
  1729. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1730. \key{start}, and the whole program is its tail.
  1731. %
  1732. The $\itm{info}$ field of the \key{Program} form, after the
  1733. \key{explicate-control} pass, contains a mapping from the symbol
  1734. \key{locals} to a list of variables, that is, a list of all the
  1735. variables used in the program. At the start of the program, these
  1736. variables are uninitialized; they become initialized on their first
  1737. assignment.
  1738. \begin{figure}[tbp]
  1739. \fbox{
  1740. \begin{minipage}{0.96\textwidth}
  1741. \[
  1742. \begin{array}{lcl}
  1743. \Atm &::=& \Int \mid \Var \\
  1744. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  1745. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  1746. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  1747. C_0 & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  1748. \end{array}
  1749. \]
  1750. \end{minipage}
  1751. }
  1752. \caption{The concrete syntax of the $C_0$ intermediate language.}
  1753. \label{fig:c0-concrete-syntax}
  1754. \end{figure}
  1755. \begin{figure}[tbp]
  1756. \fbox{
  1757. \begin{minipage}{0.96\textwidth}
  1758. \[
  1759. \begin{array}{lcl}
  1760. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1761. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1762. &\mid& \ADD{\Atm}{\Atm}\\
  1763. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  1764. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1765. C_0 & ::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}\ldots}}
  1766. \end{array}
  1767. \]
  1768. \end{minipage}
  1769. }
  1770. \caption{The abstract syntax of the $C_0$ intermediate language.}
  1771. \label{fig:c0-syntax}
  1772. \end{figure}
  1773. \subsection{The dialects of x86}
  1774. The x86$^{*}_0$ language, pronounced ``pseudo x86'', is the output of
  1775. the pass \key{select-instructions}. It extends x86$_0$ with an
  1776. unbounded number of program-scope variables and has looser rules
  1777. regarding instruction arguments. The x86$^{\dagger}$ language, the
  1778. output of \key{print-x86}, is the concrete syntax for x86.
  1779. \section{Uniquify Variables}
  1780. \label{sec:uniquify-s0}
  1781. The \code{uniquify} pass compiles arbitrary $R_1$ programs into $R_1$
  1782. programs in which every \key{let} uses a unique variable name. For
  1783. example, the \code{uniquify} pass should translate the program on the
  1784. left into the program on the right. \\
  1785. \begin{tabular}{lll}
  1786. \begin{minipage}{0.4\textwidth}
  1787. \begin{lstlisting}
  1788. (let ([x 32])
  1789. (+ (let ([x 10]) x) x))
  1790. \end{lstlisting}
  1791. \end{minipage}
  1792. &
  1793. $\Rightarrow$
  1794. &
  1795. \begin{minipage}{0.4\textwidth}
  1796. \begin{lstlisting}
  1797. (let ([x.1 32])
  1798. (+ (let ([x.2 10]) x.2) x.1))
  1799. \end{lstlisting}
  1800. \end{minipage}
  1801. \end{tabular} \\
  1802. %
  1803. The following is another example translation, this time of a program
  1804. with a \key{let} nested inside the initializing expression of another
  1805. \key{let}.\\
  1806. \begin{tabular}{lll}
  1807. \begin{minipage}{0.4\textwidth}
  1808. \begin{lstlisting}
  1809. (let ([x (let ([x 4])
  1810. (+ x 1))])
  1811. (+ x 2))
  1812. \end{lstlisting}
  1813. \end{minipage}
  1814. &
  1815. $\Rightarrow$
  1816. &
  1817. \begin{minipage}{0.4\textwidth}
  1818. \begin{lstlisting}
  1819. (let ([x.2 (let ([x.1 4])
  1820. (+ x.1 1))])
  1821. (+ x.2 2))
  1822. \end{lstlisting}
  1823. \end{minipage}
  1824. \end{tabular}
  1825. We recommend implementing \code{uniquify} by creating a function named
  1826. \code{uniquify-exp} that is structurally recursive function and mostly
  1827. just copies the input program. However, when encountering a \key{let},
  1828. it should generate a unique name for the variable (the Racket function
  1829. \code{gensym} is handy for this) and associate the old name with the
  1830. new unique name in an alist. The \code{uniquify-exp}
  1831. function will need to access this alist when it gets to a
  1832. variable reference, so we add another parameter to \code{uniquify-exp}
  1833. for the alist.
  1834. The skeleton of the \code{uniquify-exp} function is shown in
  1835. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1836. convenient to partially apply it to a symbol table and then apply it
  1837. to different expressions, as in the last clause for primitive
  1838. operations in Figure~\ref{fig:uniquify-s0}. The \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  1839. form is useful for applying a function to each element of a list to produce
  1840. a new list.
  1841. \index{for/list}
  1842. \begin{exercise}
  1843. \normalfont % I don't like the italics for exercises. -Jeremy
  1844. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1845. implement the clauses for variables and for the \key{let} form.
  1846. \end{exercise}
  1847. \begin{figure}[tbp]
  1848. \begin{lstlisting}
  1849. (define (uniquify-exp symtab)
  1850. (lambda (e)
  1851. (match e
  1852. [(Var x) ___]
  1853. [(Int n) (Int n)]
  1854. [(Let x e body) ___]
  1855. [(Prim op es)
  1856. (Prim op (for/list ([e es]) ((uniquify-exp symtab) e)))]
  1857. )))
  1858. (define (uniquify p)
  1859. (match p
  1860. [(Program '() e)
  1861. (Program '() ((uniquify-exp '()) e))]
  1862. )))
  1863. \end{lstlisting}
  1864. \caption{Skeleton for the \key{uniquify} pass.}
  1865. \label{fig:uniquify-s0}
  1866. \end{figure}
  1867. \begin{exercise}
  1868. \normalfont % I don't like the italics for exercises. -Jeremy
  1869. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1870. and checking whether the output programs produce the same result as
  1871. the input programs. The $R_1$ programs should be designed to test the
  1872. most interesting parts of the \key{uniquify} pass, that is, the
  1873. programs should include \key{let} forms, variables, and variables that
  1874. overshadow each other. The five programs should be in a subdirectory
  1875. named \key{tests} and they should have the same file name except for a
  1876. different integer at the end of the name, followed by the ending
  1877. \key{.rkt}. Use the \key{interp-tests} function
  1878. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1879. your \key{uniquify} pass on the example programs. See the
  1880. \key{run-tests.rkt} script in the support code for an example of how
  1881. to use \key{interp-tests}. The support code is in a \code{github}
  1882. repository at the following URL:
  1883. \begin{center}\footnotesize
  1884. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  1885. \end{center}
  1886. \end{exercise}
  1887. \section{Remove Complex Operands}
  1888. \label{sec:remove-complex-opera-R1}
  1889. The \code{remove-complex-opera*} pass compiles $R_1$ programs into
  1890. $R_1$ programs in which the arguments of operations are atomic
  1891. expressions. Put another way, this pass removes complex
  1892. operands\index{complex operand}, such as the expression \code{(- 10)}
  1893. in the program below. This is accomplished by introducing a new
  1894. \key{let}-bound variable, binding the complex operand to the new
  1895. variable, and then using the new variable in place of the complex
  1896. operand, as shown in the output of \code{remove-complex-opera*} on the
  1897. right.\\
  1898. \begin{tabular}{lll}
  1899. \begin{minipage}{0.4\textwidth}
  1900. % s0_19.rkt
  1901. \begin{lstlisting}
  1902. (+ 52 (- 10))
  1903. \end{lstlisting}
  1904. \end{minipage}
  1905. &
  1906. $\Rightarrow$
  1907. &
  1908. \begin{minipage}{0.4\textwidth}
  1909. \begin{lstlisting}
  1910. (let ([tmp.1 (- 10)])
  1911. (+ 52 tmp.1))
  1912. \end{lstlisting}
  1913. \end{minipage}
  1914. \end{tabular}
  1915. \begin{figure}[tp]
  1916. \centering
  1917. \fbox{
  1918. \begin{minipage}{0.96\textwidth}
  1919. \[
  1920. \begin{array}{rcl}
  1921. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1922. \Exp &::=& \Atm \mid \READ{} \\
  1923. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  1924. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  1925. R^{\dagger}_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1926. \end{array}
  1927. \]
  1928. \end{minipage}
  1929. }
  1930. \caption{$R_1^{\dagger}$ is $R_1$ in administrative normal form (ANF).}
  1931. \label{fig:r1-anf-syntax}
  1932. \end{figure}
  1933. Figure~\ref{fig:r1-anf-syntax} presents the grammar for the output of
  1934. this pass, language $R_1^{\dagger}$. The main difference is that
  1935. operator arguments are required to be atomic expressions. In the
  1936. literature, this is called \emph{administrative normal form}, or ANF
  1937. for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  1938. \index{administrative normal form}
  1939. \index{ANF}
  1940. We recommend implementing this pass with two mutually recursive
  1941. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1942. \code{rco-atom} to subexpressions that are required to be atomic and
  1943. to apply \code{rco-exp} to subexpressions that can be atomic or
  1944. complex (see Figure~\ref{fig:r1-anf-syntax}). Both functions take an
  1945. $R_1$ expression as input. The \code{rco-exp} function returns an
  1946. expression. The \code{rco-atom} function returns two things: an
  1947. atomic expression and alist mapping temporary variables to complex
  1948. subexpressions. You can return multiple things from a function using
  1949. Racket's \key{values} form and you can receive multiple things from a
  1950. function call using the \key{define-values} form. If you are not
  1951. familiar with these features, review the Racket documentation. Also,
  1952. the \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  1953. form is useful for applying a function to each
  1954. element of a list, in the case where the function returns multiple
  1955. values.
  1956. \index{for/lists}
  1957. The following shows the output of \code{rco-atom} on the expression
  1958. \code{(- 10)} (using concrete syntax to be concise).
  1959. \begin{tabular}{lll}
  1960. \begin{minipage}{0.4\textwidth}
  1961. \begin{lstlisting}
  1962. (- 10)
  1963. \end{lstlisting}
  1964. \end{minipage}
  1965. &
  1966. $\Rightarrow$
  1967. &
  1968. \begin{minipage}{0.4\textwidth}
  1969. \begin{lstlisting}
  1970. tmp.1
  1971. ((tmp.1 . (- 10)))
  1972. \end{lstlisting}
  1973. \end{minipage}
  1974. \end{tabular}
  1975. Take special care of programs such as the next one that \key{let}-bind
  1976. variables with integers or other variables. You should leave them
  1977. unchanged, as shown in to the program on the right \\
  1978. \begin{tabular}{lll}
  1979. \begin{minipage}{0.4\textwidth}
  1980. % s0_20.rkt
  1981. \begin{lstlisting}
  1982. (let ([a 42])
  1983. (let ([b a])
  1984. b))
  1985. \end{lstlisting}
  1986. \end{minipage}
  1987. &
  1988. $\Rightarrow$
  1989. &
  1990. \begin{minipage}{0.4\textwidth}
  1991. \begin{lstlisting}
  1992. (let ([a 42])
  1993. (let ([b a])
  1994. b))
  1995. \end{lstlisting}
  1996. \end{minipage}
  1997. \end{tabular} \\
  1998. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  1999. produce the following output.\\
  2000. \begin{minipage}{0.4\textwidth}
  2001. \begin{lstlisting}
  2002. (let ([tmp.1 42])
  2003. (let ([a tmp.1])
  2004. (let ([tmp.2 a])
  2005. (let ([b tmp.2])
  2006. b))))
  2007. \end{lstlisting}
  2008. \end{minipage}
  2009. \begin{exercise}
  2010. \normalfont Implement the \code{remove-complex-opera*} pass.
  2011. Test the new pass on all of the example programs that you created to test the
  2012. \key{uniquify} pass and create three new example programs that are
  2013. designed to exercise the interesting code in the
  2014. \code{remove-complex-opera*} pass. Use the \key{interp-tests} function
  2015. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2016. your passes on the example programs.
  2017. \end{exercise}
  2018. \section{Explicate Control}
  2019. \label{sec:explicate-control-r1}
  2020. The \code{explicate-control} pass compiles $R_1$ programs into $C_0$
  2021. programs that make the order of execution explicit in their
  2022. syntax. For now this amounts to flattening \key{let} constructs into a
  2023. sequence of assignment statements. For example, consider the following
  2024. $R_1$ program.\\
  2025. % s0_11.rkt
  2026. \begin{minipage}{0.96\textwidth}
  2027. \begin{lstlisting}
  2028. (let ([y (let ([x 20])
  2029. (+ x (let ([x 22]) x)))])
  2030. y)
  2031. \end{lstlisting}
  2032. \end{minipage}\\
  2033. %
  2034. The output of the previous pass and of \code{explicate-control} is
  2035. shown below. Recall that the right-hand-side of a \key{let} executes
  2036. before its body, so the order of evaluation for this program is to
  2037. assign \code{20} to \code{x.1}, assign \code{22} to \code{x.2}, assign
  2038. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  2039. output of \code{explicate-control} makes this ordering explicit.\\
  2040. \begin{tabular}{lll}
  2041. \begin{minipage}{0.4\textwidth}
  2042. \begin{lstlisting}
  2043. (let ([y (let ([x.1 20])
  2044. (let ([x.2 22])
  2045. (+ x.1 x.2)))])
  2046. y)
  2047. \end{lstlisting}
  2048. \end{minipage}
  2049. &
  2050. $\Rightarrow$
  2051. &
  2052. \begin{minipage}{0.4\textwidth}
  2053. \begin{lstlisting}
  2054. start:
  2055. x.1 = 20;
  2056. x.2 = 22;
  2057. y = (+ x.1 x.2);
  2058. return y;
  2059. \end{lstlisting}
  2060. \end{minipage}
  2061. \end{tabular}
  2062. We recommend implementing \code{explicate-control} using two mutually
  2063. recursive functions: \code{explicate-tail} and
  2064. \code{explicate-assign}. The first function should be applied to
  2065. expressions in tail position whereas the second should be applied to
  2066. expressions that occur on the right-hand-side of a \key{let}.
  2067. %
  2068. The \code{explicate-tail} function takes an $R_1$ expression as input
  2069. and produces a $C_0$ $\Tail$ (see Figure~\ref{fig:c0-syntax}).
  2070. %
  2071. The \code{explicate-assign} function takes an $R_1$ expression, the
  2072. variable that it is to be assigned to, and $C_0$ code (a $\Tail$) that
  2073. should come after the assignment (e.g., the code generated for the
  2074. body of the \key{let}) and returns a $\Tail$. The
  2075. \code{explicate-assign} function is in accumulator-passing style in
  2076. that its third parameter is some $C_0$ code that it adds to and
  2077. returns. The reader might be tempted to instead organize
  2078. \code{explicate-assign} in a more direct fashion, without the third
  2079. parameter and perhaps using \code{append} to combine statements. We
  2080. warn against that alternative because the accumulator-passing style is
  2081. key to how we generate high-quality code for conditional expressions
  2082. in Chapter~\ref{ch:bool-types}.
  2083. The top-level \code{explicate-control} function should invoke
  2084. \code{explicate-tail} on the body of the \key{Program} AST node.
  2085. \section{Select Instructions}
  2086. \label{sec:select-r1}
  2087. \index{instruction selection}
  2088. In the \code{select-instructions} pass we begin the work of
  2089. translating from $C_0$ to $\text{x86}^{*}_0$. The target language of
  2090. this pass is a variant of x86 that still uses variables, so we add an
  2091. AST node of the form $\VAR{\itm{var}}$ to the $\text{x86}_0$ abstract
  2092. syntax of Figure~\ref{fig:x86-0-ast}. We recommend implementing the
  2093. \code{select-instructions} in terms of three auxiliary functions, one
  2094. for each of the non-terminals of $C_0$: $\Atm$, $\Stmt$, and $\Tail$.
  2095. The cases for $\Atm$ are straightforward, variables stay
  2096. the same and integer constants are changed to immediates:
  2097. $\INT{n}$ changes to $\IMM{n}$.
  2098. Next we consider the cases for $\Stmt$, starting with arithmetic
  2099. operations. For example, in $C_0$ an addition operation can take the
  2100. form below, to the left of the $\Rightarrow$. To translate to x86, we
  2101. need to use the \key{addq} instruction which does an in-place
  2102. update. So we must first move \code{10} to \code{x}. \\
  2103. \begin{tabular}{lll}
  2104. \begin{minipage}{0.4\textwidth}
  2105. \begin{lstlisting}
  2106. x = (+ 10 32);
  2107. \end{lstlisting}
  2108. \end{minipage}
  2109. &
  2110. $\Rightarrow$
  2111. &
  2112. \begin{minipage}{0.4\textwidth}
  2113. \begin{lstlisting}
  2114. movq $10, x
  2115. addq $32, x
  2116. \end{lstlisting}
  2117. \end{minipage}
  2118. \end{tabular} \\
  2119. %
  2120. There are cases that require special care to avoid generating
  2121. needlessly complicated code. If one of the arguments of the addition
  2122. is the same as the left-hand side of the assignment, then there is no
  2123. need for the extra move instruction. For example, the following
  2124. assignment statement can be translated into a single \key{addq}
  2125. instruction.\\
  2126. \begin{tabular}{lll}
  2127. \begin{minipage}{0.4\textwidth}
  2128. \begin{lstlisting}
  2129. x = (+ 10 x);
  2130. \end{lstlisting}
  2131. \end{minipage}
  2132. &
  2133. $\Rightarrow$
  2134. &
  2135. \begin{minipage}{0.4\textwidth}
  2136. \begin{lstlisting}
  2137. addq $10, x
  2138. \end{lstlisting}
  2139. \end{minipage}
  2140. \end{tabular} \\
  2141. The \key{read} operation does not have a direct counterpart in x86
  2142. assembly, so we have instead implemented this functionality in the C
  2143. language~\citep{Kernighan:1988nx}, with the function \code{read\_int}
  2144. in the file \code{runtime.c}. In general, we refer to all of the
  2145. functionality in this file as the \emph{runtime system}\index{runtime system},
  2146. or simply the \emph{runtime} for short. When compiling your generated x86
  2147. assembly code, you need to compile \code{runtime.c} to \code{runtime.o} (an
  2148. ``object file'', using \code{gcc} option \code{-c}) and link it into
  2149. the executable. For our purposes of code generation, all you need to
  2150. do is translate an assignment of \key{read} into some variable
  2151. $\itm{lhs}$ (for left-hand side) into a call to the \code{read\_int}
  2152. function followed by a move from \code{rax} to the left-hand side.
  2153. The move from \code{rax} is needed because the return value from
  2154. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  2155. \begin{tabular}{lll}
  2156. \begin{minipage}{0.3\textwidth}
  2157. \begin{lstlisting}
  2158. |$\itm{var}$| = (read);
  2159. \end{lstlisting}
  2160. \end{minipage}
  2161. &
  2162. $\Rightarrow$
  2163. &
  2164. \begin{minipage}{0.3\textwidth}
  2165. \begin{lstlisting}
  2166. callq read_int
  2167. movq %rax, |$\itm{var}$|
  2168. \end{lstlisting}
  2169. \end{minipage}
  2170. \end{tabular} \\
  2171. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  2172. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  2173. assignment to the \key{rax} register followed by a jump to the
  2174. conclusion of the program (so the conclusion needs to be labeled).
  2175. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  2176. recursively and append the resulting instructions.
  2177. \begin{exercise}
  2178. \normalfont
  2179. Implement the \key{select-instructions} pass and test it on all of the
  2180. example programs that you created for the previous passes and create
  2181. three new example programs that are designed to exercise all of the
  2182. interesting code in this pass. Use the \key{interp-tests} function
  2183. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2184. your passes on the example programs.
  2185. \end{exercise}
  2186. \section{Assign Homes}
  2187. \label{sec:assign-r1}
  2188. The \key{assign-homes} pass compiles $\text{x86}^{*}_0$ programs to
  2189. $\text{x86}^{*}_0$ programs that no longer use program variables.
  2190. Thus, the \key{assign-homes} pass is responsible for placing all of
  2191. the program variables in registers or on the stack. For runtime
  2192. efficiency, it is better to place variables in registers, but as there
  2193. are only 16 registers, some programs must necessarily resort to
  2194. placing some variables on the stack. In this chapter we focus on the
  2195. mechanics of placing variables on the stack. We study an algorithm for
  2196. placing variables in registers in
  2197. Chapter~\ref{ch:register-allocation-r1}.
  2198. Consider again the following $R_1$ program.
  2199. % s0_20.rkt
  2200. \begin{lstlisting}
  2201. (let ([a 42])
  2202. (let ([b a])
  2203. b))
  2204. \end{lstlisting}
  2205. For reference, we repeat the output of \code{select-instructions} on
  2206. the left and show the output of \code{assign-homes} on the right.
  2207. %
  2208. %% Recall that \key{explicate-control} associated the list of
  2209. %% variables with the \code{locals} symbol in the program's $\itm{info}$
  2210. %% field, so \code{assign-homes} has convenient access to the them.
  2211. %
  2212. In this example, we assign variable \code{a} to stack location
  2213. \code{-8(\%rbp)} and variable \code{b} to location
  2214. \code{-16(\%rbp)}.\\
  2215. \begin{tabular}{l}
  2216. \begin{minipage}{0.4\textwidth}
  2217. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2218. locals-types:
  2219. a : 'Integer, b : 'Integer
  2220. start:
  2221. movq $42, a
  2222. movq a, b
  2223. movq b, %rax
  2224. jmp conclusion
  2225. \end{lstlisting}
  2226. \end{minipage}
  2227. {$\Rightarrow$}
  2228. \begin{minipage}{0.4\textwidth}
  2229. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2230. stack-space: 16
  2231. start:
  2232. movq $42, -8(%rbp)
  2233. movq -8(%rbp), -16(%rbp)
  2234. movq -16(%rbp), %rax
  2235. jmp conclusion
  2236. \end{lstlisting}
  2237. \end{minipage}
  2238. \end{tabular} \\
  2239. In the output of \code{select-instructions}, there is a entry for
  2240. \code{locals-types} in the $\itm{info}$ of the \code{Program} node,
  2241. which is needed here so that we have the list of variables that should
  2242. be assigned to homes. The support code computes the
  2243. \code{locals-types} entry. In particular, \code{type-check-C0}
  2244. installs it in the $\itm{info}$ field of the \code{Program} node.
  2245. When using \code{interp-tests} or \code{compiler-tests} (see Appendix,
  2246. Section~\ref{appendix:utilities}), specify \code{type-check-C0} as the
  2247. type checker to use after \code{explicate-control}.
  2248. In the process of assigning variables to stack locations, it is
  2249. convenient for you to compute and store the size of the frame (in
  2250. bytes) in the $\itm{info}$ field of the \key{Program} node, with the
  2251. key \code{stack-space}, which is needed later to generate the
  2252. conclusion of the \code{main} procedure. The x86-64 standard requires
  2253. the frame size to be a multiple of 16 bytes. \index{frame}
  2254. \begin{exercise}
  2255. \normalfont Implement the \key{assign-homes} pass and test it on all
  2256. of the example programs that you created for the previous passes pass.
  2257. We recommend that \key{assign-homes} take an extra parameter that is a
  2258. mapping of variable names to homes (stack locations for now). Use the
  2259. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  2260. \key{utilities.rkt} to test your passes on the example programs.
  2261. \end{exercise}
  2262. \section{Patch Instructions}
  2263. \label{sec:patch-s0}
  2264. The \code{patch-instructions} pass compiles $\text{x86}^{*}_0$
  2265. programs to $\text{x86}_0$ programs by making sure that each
  2266. instruction adheres to the restrictions of the x86 assembly language.
  2267. In particular, at most one argument of an instruction may be a memory
  2268. reference.
  2269. We return to the following running example.
  2270. % s0_20.rkt
  2271. \begin{lstlisting}
  2272. (let ([a 42])
  2273. (let ([b a])
  2274. b))
  2275. \end{lstlisting}
  2276. After the \key{assign-homes} pass, the above program has been translated to
  2277. the following. \\
  2278. \begin{minipage}{0.5\textwidth}
  2279. \begin{lstlisting}
  2280. stack-space: 16
  2281. start:
  2282. movq $42, -8(%rbp)
  2283. movq -8(%rbp), -16(%rbp)
  2284. movq -16(%rbp), %rax
  2285. jmp conclusion
  2286. \end{lstlisting}
  2287. \end{minipage}\\
  2288. The second \key{movq} instruction is problematic because both
  2289. arguments are stack locations. We suggest fixing this problem by
  2290. moving from the source location to the register \key{rax} and then
  2291. from \key{rax} to the destination location, as follows.
  2292. \begin{lstlisting}
  2293. movq -8(%rbp), %rax
  2294. movq %rax, -16(%rbp)
  2295. \end{lstlisting}
  2296. \begin{exercise}
  2297. \normalfont
  2298. Implement the \key{patch-instructions} pass and test it on all of the
  2299. example programs that you created for the previous passes and create
  2300. three new example programs that are designed to exercise all of the
  2301. interesting code in this pass. Use the \key{interp-tests} function
  2302. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2303. your passes on the example programs.
  2304. \end{exercise}
  2305. \section{Print x86}
  2306. \label{sec:print-x86}
  2307. The last step of the compiler from $R_1$ to x86 is to convert the
  2308. $\text{x86}_0$ AST (defined in Figure~\ref{fig:x86-0-ast}) to the
  2309. string representation (defined in Figure~\ref{fig:x86-0-concrete}). The Racket
  2310. \key{format} and \key{string-append} functions are useful in this
  2311. regard. The main work that this step needs to perform is to create the
  2312. \key{main} function and the standard instructions for its prelude and
  2313. conclusion, as shown in Figure~\ref{fig:p1-x86} of
  2314. Section~\ref{sec:x86}. You need to know the number of stack-allocated
  2315. variables, so we suggest computing it in the \key{assign-homes} pass
  2316. (Section~\ref{sec:assign-r1}) and storing it in the $\itm{info}$ field
  2317. of the \key{program} node.
  2318. %% Your compiled code should print the result of the program's execution
  2319. %% by using the \code{print\_int} function provided in
  2320. %% \code{runtime.c}. If your compiler has been implemented correctly so
  2321. %% far, this final result should be stored in the \key{rax} register.
  2322. %% We'll talk more about how to perform function calls with arguments in
  2323. %% general later on, but for now, place the following after the compiled
  2324. %% code for the $R_1$ program but before the conclusion:
  2325. %% \begin{lstlisting}
  2326. %% movq %rax, %rdi
  2327. %% callq print_int
  2328. %% \end{lstlisting}
  2329. %% These lines move the value in \key{rax} into the \key{rdi} register, which
  2330. %% stores the first argument to be passed into \key{print\_int}.
  2331. If you want your program to run on Mac OS X, your code needs to
  2332. determine whether or not it is running on a Mac, and prefix
  2333. underscores to labels like \key{main}. You can determine the platform
  2334. with the Racket call \code{(system-type 'os)}, which returns
  2335. \code{'macosx}, \code{'unix}, or \code{'windows}.
  2336. %% In addition to
  2337. %% placing underscores on \key{main}, you need to put them in front of
  2338. %% \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  2339. %% \_print\_int}).
  2340. \begin{exercise}
  2341. \normalfont Implement the \key{print-x86} pass and test it on all of
  2342. the example programs that you created for the previous passes. Use the
  2343. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  2344. \key{utilities.rkt} to test your complete compiler on the example
  2345. programs. See the \key{run-tests.rkt} script in the student support
  2346. code for an example of how to use \key{compiler-tests}. Also, remember
  2347. to compile the provided \key{runtime.c} file to \key{runtime.o} using
  2348. \key{gcc}.
  2349. \end{exercise}
  2350. \section{Challenge: Partial Evaluator for $R_1$}
  2351. \label{sec:pe-R1}
  2352. \index{partial evaluation}
  2353. This section describes optional challenge exercises that involve
  2354. adapting and improving the partial evaluator for $R_0$ that was
  2355. introduced in Section~\ref{sec:partial-evaluation}.
  2356. \begin{exercise}\label{ex:pe-R1}
  2357. \normalfont
  2358. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2359. (Figure~\ref{fig:pe-arith}) so that it applies to $R_1$ programs
  2360. instead of $R_0$ programs. Recall that $R_1$ adds \key{let} binding
  2361. and variables to the $R_0$ language, so you will need to add cases for
  2362. them in the \code{pe-exp} function. Also, note that the \key{program}
  2363. form changes slightly to include an $\itm{info}$ field. Once
  2364. complete, add the partial evaluation pass to the front of your
  2365. compiler and make sure that your compiler still passes all of the
  2366. tests.
  2367. \end{exercise}
  2368. The next exercise builds on Exercise~\ref{ex:pe-R1}.
  2369. \begin{exercise}
  2370. \normalfont
  2371. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2372. \code{pe-add} auxiliary functions with functions that know more about
  2373. arithmetic. For example, your partial evaluator should translate
  2374. \begin{lstlisting}
  2375. (+ 1 (+ (read) 1))
  2376. \end{lstlisting}
  2377. into
  2378. \begin{lstlisting}
  2379. (+ 2 (read))
  2380. \end{lstlisting}
  2381. To accomplish this, the \code{pe-exp} function should produce output
  2382. in the form of the $\itm{residual}$ non-terminal of the following
  2383. grammar.
  2384. \[
  2385. \begin{array}{lcl}
  2386. \itm{inert} &::=& \Var \mid (\key{read}) \mid (\key{-} \;(\key{read}))
  2387. \mid (\key{+} \; \itm{inert} \; \itm{inert})\\
  2388. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \itm{inert}) \mid \itm{inert}
  2389. \end{array}
  2390. \]
  2391. The \code{pe-add} and \code{pe-neg} functions may therefore assume
  2392. that their inputs are $\itm{residual}$ expressions and they should
  2393. return $\itm{residual}$ expressions. Once the improvements are
  2394. complete, make sure that your compiler still passes all of the tests.
  2395. After all, fast code is useless if it produces incorrect results!
  2396. \end{exercise}
  2397. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2398. \chapter{Register Allocation}
  2399. \label{ch:register-allocation-r1}
  2400. \index{register allocation}
  2401. In Chapter~\ref{ch:int-exp} we placed all variables on the stack to
  2402. make our life easier. However, we can improve the performance of the
  2403. generated code if we instead place some variables into registers. The
  2404. CPU can access a register in a single cycle, whereas accessing the
  2405. stack takes many cycles if the relevant data is in cache or many more
  2406. to access main memory if the data is not in cache.
  2407. Figure~\ref{fig:reg-eg} shows a program with four variables that
  2408. serves as a running example. We show the source program and also the
  2409. output of instruction selection. At that point the program is almost
  2410. x86 assembly but not quite; it still contains variables instead of
  2411. stack locations or registers.
  2412. \begin{figure}
  2413. \begin{minipage}{0.45\textwidth}
  2414. Example $R_1$ program:
  2415. % s0_28.rkt
  2416. \begin{lstlisting}
  2417. (let ([v 1])
  2418. (let ([w 42])
  2419. (let ([x (+ v 7)])
  2420. (let ([y x])
  2421. (let ([z (+ x w)])
  2422. (+ z (- y)))))))
  2423. \end{lstlisting}
  2424. \end{minipage}
  2425. \begin{minipage}{0.45\textwidth}
  2426. After instruction selection:
  2427. \begin{lstlisting}
  2428. locals-types:
  2429. x : Integer, y : Integer,
  2430. z : Integer, t : Integer,
  2431. v : Integer, w : Integer
  2432. start:
  2433. movq $1, v
  2434. movq $42, w
  2435. movq v, x
  2436. addq $7, x
  2437. movq x, y
  2438. movq x, z
  2439. addq w, z
  2440. movq y, t
  2441. negq t
  2442. movq z, %rax
  2443. addq t, %rax
  2444. jmp conclusion
  2445. \end{lstlisting}
  2446. \end{minipage}
  2447. \caption{A running example program for register allocation.}
  2448. \label{fig:reg-eg}
  2449. \end{figure}
  2450. The goal of register allocation is to fit as many variables into
  2451. registers as possible. A program sometimes has more variables than
  2452. registers, so we cannot always map each variable to a different
  2453. register. Fortunately, it is common for different variables to be
  2454. needed during different periods of time during program execution, and
  2455. in such cases several variables can be mapped to the same register.
  2456. Consider variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}.
  2457. After the variable \code{x} is moved to \code{z} it is no longer
  2458. needed. Variable \code{y}, on the other hand, is used only after this
  2459. point, so \code{x} and \code{y} could share the same register. The
  2460. topic of Section~\ref{sec:liveness-analysis-r1} is how to compute
  2461. where a variable is needed. Once we have that information, we compute
  2462. which variables are needed at the same time, i.e., which ones
  2463. \emph{interfere} with each other, and represent this relation as an
  2464. undirected graph whose vertices are variables and edges indicate when
  2465. two variables interfere (Section~\ref{sec:build-interference}). We
  2466. then model register allocation as a graph coloring problem, which we
  2467. discuss in Section~\ref{sec:graph-coloring}.
  2468. If we run out of registers despite these efforts, we place the
  2469. remaining variables on the stack, similar to what we did in
  2470. Chapter~\ref{ch:int-exp}. It is common to use the verb \emph{spill}
  2471. for assigning a variable to a stack location. The decision to spill a
  2472. variable is handled as part of the graph coloring process described in
  2473. Section~\ref{sec:graph-coloring}.
  2474. We make the simplifying assumption that each variable is assigned to
  2475. one location (a register or stack address). A more sophisticated
  2476. approach is to assign a variable to one or more locations in different
  2477. regions of the program. For example, if a variable is used many times
  2478. in short sequence and then only used again after many other
  2479. instructions, it could be more efficient to assign the variable to a
  2480. register during the initial sequence and then move it to the stack for
  2481. the rest of its lifetime. We refer the interested reader to
  2482. \citet{Cooper:1998ly} and \citet{Cooper:2011aa} for more information
  2483. about that approach.
  2484. % discuss prioritizing variables based on how much they are used.
  2485. \section{Registers and Calling Conventions}
  2486. \label{sec:calling-conventions}
  2487. \index{calling conventions}
  2488. As we perform register allocation, we need to be aware of the
  2489. \emph{calling conventions} \index{calling conventions} that govern how
  2490. functions calls are performed in x86. Function calls require
  2491. coordination between the caller and the callee, which is often
  2492. assembly code written by different programmers or generated by
  2493. different compilers. Here we follow the System V calling conventions
  2494. that are used by the \code{gcc} compiler on Linux and
  2495. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  2496. %
  2497. Even though $R_1$ does not include programmer-defined functions, our
  2498. generated code will 1) include a \code{main} function that the
  2499. operating system will call to initiate execution, and 2) make calls to
  2500. the \code{read\_int} function in our runtime system.
  2501. The calling conventions include rules about how functions share the
  2502. use of registers. In particular, the caller is responsible for freeing
  2503. up some registers prior to the function call for use by the callee.
  2504. These are called the \emph{caller-saved registers}
  2505. \index{caller-saved registers}
  2506. and they are
  2507. \begin{lstlisting}
  2508. rax rcx rdx rsi rdi r8 r9 r10 r11
  2509. \end{lstlisting}
  2510. On the other hand, the callee is responsible for preserving the values
  2511. of the \emph{callee-saved registers}, \index{callee-saved registers}
  2512. which are
  2513. \begin{lstlisting}
  2514. rsp rbp rbx r12 r13 r14 r15
  2515. \end{lstlisting}
  2516. We can think about this caller/callee convention from two points of
  2517. view, the caller view and the callee view:
  2518. \begin{itemize}
  2519. \item The caller should assume that all the caller-saved registers get
  2520. overwritten with arbitrary values by the callee. On the other hand,
  2521. the caller can safely assume that all the callee-saved registers
  2522. contain the same values after the call that they did before the
  2523. call.
  2524. \item The callee can freely use any of the caller-saved registers.
  2525. However, if the callee wants to use a callee-saved register, the
  2526. callee must arrange to put the original value back in the register
  2527. prior to returning to the caller, which is usually accomplished by
  2528. saving the value to the stack in the prelude of the function and
  2529. restoring the value in the conclusion of the function.
  2530. \end{itemize}
  2531. In x86, registers are also used for passing arguments to a function
  2532. and for the return value. In particular, the first six arguments of a
  2533. function are passed in the following six registers, in the order
  2534. given.
  2535. \begin{lstlisting}
  2536. rdi rsi rdx rcx r8 r9
  2537. \end{lstlisting}
  2538. If there are more than six arguments, then the convention is to use
  2539. space on the frame of the caller for the rest of the
  2540. arguments. However, in Chapter~\ref{ch:functions} we arrange to never
  2541. need more than six arguments. For now, the only function we care about
  2542. is \code{read\_int} and it takes zero argument.
  2543. %
  2544. The register \code{rax} is for the return value of a function.
  2545. The next question is how these calling conventions impact register
  2546. allocation. Consider the $R_1$ program in
  2547. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  2548. example from the caller point of view and then from the callee point
  2549. of view.
  2550. The program makes two calls to the \code{read} function. Also, the
  2551. variable \code{x} is in-use during the second call to \code{read}, so
  2552. we need to make sure that the value in \code{x} does not get
  2553. accidentally wiped out by the call to \code{read}. One obvious
  2554. approach is to save all the values in caller-saved registers to the
  2555. stack prior to each function call, and restore them after each
  2556. call. That way, if the register allocator chooses to assign \code{x}
  2557. to a caller-saved register, its value will be preserved across the
  2558. call to \code{read}. However, the disadvantage of this approach is
  2559. that saving and restoring to the stack is relatively slow. If \code{x}
  2560. is not used many times, it may be better to assign \code{x} to a stack
  2561. location in the first place. Or better yet, if we can arrange for
  2562. \code{x} to be placed in a callee-saved register, then it won't need
  2563. to be saved and restored during function calls.
  2564. The approach that we recommend for variables that are in-use during a
  2565. function call is to either assign them to callee-saved registers or to
  2566. spill them to the stack. On the other hand, for variables that are not
  2567. in-use during a function call, we try the following alternatives in
  2568. order 1) look for an available caller-saved register (to leave room
  2569. for other variables in the callee-saved register), 2) look for a
  2570. callee-saved register, and 3) spill the variable to the stack.
  2571. It is straightforward to implement this approach in a graph coloring
  2572. register allocator. First, we know which variables are in-use during
  2573. every function call because we compute that information for every
  2574. instruction (Section~\ref{sec:liveness-analysis-r1}). Second, when we
  2575. build the interference graph (Section~\ref{sec:build-interference}),
  2576. we can place an edge between each of these variables and the
  2577. caller-saved registers in the interference graph. This will prevent
  2578. the graph coloring algorithm from assigning those variables to
  2579. caller-saved registers.
  2580. Returning to the example in
  2581. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  2582. generated x86 code on the right-hand side, focusing on the
  2583. \code{start} block. Notice that variable \code{x} is assigned to
  2584. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  2585. place during the second call to \code{read\_int}. Next, notice that
  2586. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  2587. because there are no function calls in the remainder of the block.
  2588. Next we analyze the example from the callee point of view, focusing on
  2589. the prelude and conclusion of the \code{main} function. As usual the
  2590. prelude begins with saving the \code{rbp} register to the stack and
  2591. setting the \code{rbp} to the current stack pointer. We now know why
  2592. it is necessary to save the \code{rbp}: it is a callee-saved register.
  2593. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  2594. is also a callee-saved register and 2) \code{rbx} is assigned to a
  2595. variable (\code{x}). There are several more callee-saved register that
  2596. are not saved in the prelude because they were not assigned to
  2597. variables. The prelude subtracts 8 bytes from the \code{rsp} to make
  2598. it 16-byte aligned and then jumps to the \code{start} block. Shifting
  2599. attention to the \code{conclusion}, we see that \code{rbx} is restored
  2600. from the stack with a \code{popq} instruction.
  2601. \index{prelude}\index{conclusion}
  2602. \begin{figure}[tp]
  2603. \begin{minipage}{0.45\textwidth}
  2604. Example $R_1$ program:
  2605. %s0_14.rkt
  2606. \begin{lstlisting}
  2607. (let ([x (read)])
  2608. (let ([y (read)])
  2609. (+ (+ x y) 42)))
  2610. \end{lstlisting}
  2611. \end{minipage}
  2612. \begin{minipage}{0.45\textwidth}
  2613. Generated x86 assembly:
  2614. \begin{lstlisting}
  2615. start:
  2616. callq read_int
  2617. movq %rax, %rbx
  2618. callq read_int
  2619. movq %rax, %rcx
  2620. addq %rcx, %rbx
  2621. movq %rbx, %rax
  2622. addq $42, %rax
  2623. jmp _conclusion
  2624. .globl main
  2625. main:
  2626. pushq %rbp
  2627. movq %rsp, %rbp
  2628. pushq %rbx
  2629. subq $8, %rsp
  2630. jmp start
  2631. conclusion:
  2632. addq $8, %rsp
  2633. popq %rbx
  2634. popq %rbp
  2635. retq
  2636. \end{lstlisting}
  2637. \end{minipage}
  2638. \caption{An example with function calls.}
  2639. \label{fig:example-calling-conventions}
  2640. \end{figure}
  2641. \section{Liveness Analysis}
  2642. \label{sec:liveness-analysis-r1}
  2643. \index{liveness analysis}
  2644. A variable or register is \emph{live} at a program point if its
  2645. current value is used at some later point in the program. We
  2646. refer to variables and registers collectively as \emph{locations}.
  2647. %
  2648. Consider the following code fragment in which there are two writes to
  2649. \code{b}. Are \code{a} and \code{b} both live at the same time?
  2650. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2651. movq $5, a
  2652. movq $30, b
  2653. movq a, c
  2654. movq $10, b
  2655. addq b, c
  2656. \end{lstlisting}
  2657. The answer is no because the integer \code{30} written to \code{b} on
  2658. line 2 is never used. The variable \code{b} is read on line 5 and
  2659. there is an intervening write to \code{b} on line 4, so the read on
  2660. line 5 receives the value written on line 4, not line 2.
  2661. \begin{wrapfigure}[19]{l}[1.0in]{0.6\textwidth}
  2662. \small
  2663. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  2664. A \emph{set} is an unordered collection of elements without duplicates.
  2665. \index{set}
  2666. \begin{description}
  2667. \item[$\LP\code{set}\,v\,\ldots\RP$] constructs a set containing the specified elements.
  2668. \item[$\LP\code{set-union}\,set_1\,set_2\RP$] returns the union of the two sets.
  2669. \item[$\LP\code{set-subtract}\,set_1\,set_2\RP$] returns the difference of the two sets.
  2670. \item[$\LP\code{set-member?}\,set\,v\RP$] is element $v$ in $set$?
  2671. \item[$\LP\code{set-count}\,set\RP$] how many unique elements are in $set$?
  2672. \item[$\LP\code{set->list}\,set\RP$] converts the set to a list.
  2673. \end{description}
  2674. \end{tcolorbox}
  2675. \end{wrapfigure}
  2676. The live locations can be computed by traversing the instruction
  2677. sequence back to front (i.e., backwards in execution order). Let
  2678. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2679. $L_{\mathsf{after}}(k)$ for the set of live locations after
  2680. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2681. locations before instruction $I_k$. The live locations after an
  2682. instruction are always the same as the live locations before the next
  2683. instruction. \index{live-after} \index{live-before}
  2684. \begin{equation} \label{eq:live-after-before-next}
  2685. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2686. \end{equation}
  2687. To start things off, there are no live locations after the last
  2688. instruction\footnote{Technically, the \code{rax} register is live
  2689. but we do not use it for register allocation.}, so
  2690. \begin{equation}\label{eq:live-last-empty}
  2691. L_{\mathsf{after}}(n) = \emptyset
  2692. \end{equation}
  2693. We then apply the following rule repeatedly, traversing the
  2694. instruction sequence back to front.
  2695. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2696. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2697. \end{equation}
  2698. where $W(k)$ are the locations written to by instruction $I_k$ and
  2699. $R(k)$ are the locations read by instruction $I_k$.
  2700. There is a special case for \code{jmp} instructions. The locations
  2701. that are live before a \code{jmp} should be the locations that are
  2702. live before the instruction that follows the target label. So we
  2703. recommend maintaining an alist, perhaps called \code{label->live},
  2704. that maps each label to a set of such locations. Recall that for now,
  2705. the only \code{jmp} in a pseudo-x86 program is the one at the end, to
  2706. the \code{conclusion}. (For example, see Figure~\ref{fig:reg-eg}.) So
  2707. the alist should map \code{conclusion} to the set
  2708. $\{\ttm{rax},\ttm{rsp}\}$.
  2709. Let us walk through the above example, applying these formulas
  2710. starting with the instruction on line 5. We collect the answers in the
  2711. below listing. The $L_{\mathsf{after}}$ for the \code{addq b, c}
  2712. instruction is $\emptyset$ because it is the last instruction
  2713. (formula~\ref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  2714. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  2715. variables \code{b} and \code{c}
  2716. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  2717. \[
  2718. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  2719. \]
  2720. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2721. the live-before set from line 5 to be the live-after set for this
  2722. instruction (formula~\ref{eq:live-after-before-next}).
  2723. \[
  2724. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  2725. \]
  2726. This move instruction writes to \code{b} and does not read from any
  2727. variables, so we have the following live-before set
  2728. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2729. \[
  2730. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  2731. \]
  2732. The live-before for instruction \code{movq a, c}
  2733. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  2734. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2735. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  2736. variable that is not live and does not read from a variable.
  2737. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2738. because it writes to variable \code{a}.
  2739. \begin{center}
  2740. \begin{minipage}{0.45\textwidth}
  2741. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2742. movq $5, a
  2743. movq $30, b
  2744. movq a, c
  2745. movq $10, b
  2746. addq b, c
  2747. \end{lstlisting}
  2748. \end{minipage}
  2749. \vrule\hspace{10pt}
  2750. \begin{minipage}{0.45\textwidth}
  2751. \begin{align*}
  2752. L_{\mathsf{before}}(1)= \emptyset,
  2753. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  2754. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  2755. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  2756. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  2757. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  2758. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  2759. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  2760. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  2761. L_{\mathsf{after}}(5)= \emptyset
  2762. \end{align*}
  2763. \end{minipage}
  2764. \end{center}
  2765. Figure~\ref{fig:live-eg} shows the results of liveness analysis for
  2766. the running example program, with the live-before and live-after sets
  2767. shown between each instruction to make the figure easy to read.
  2768. \begin{figure}[tp]
  2769. \hspace{20pt}
  2770. \begin{minipage}{0.45\textwidth}
  2771. \begin{lstlisting}
  2772. |$\{\ttm{rsp}\}$|
  2773. movq $1, v
  2774. |$\{\ttm{v},\ttm{rsp}\}$|
  2775. movq $42, w
  2776. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  2777. movq v, x
  2778. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  2779. addq $7, x
  2780. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  2781. movq x, y
  2782. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  2783. movq x, z
  2784. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  2785. addq w, z
  2786. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  2787. movq y, t
  2788. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  2789. negq t
  2790. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  2791. movq z, %rax
  2792. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  2793. addq t, %rax
  2794. |$\{\ttm{rax},\ttm{rsp}\}$|
  2795. jmp conclusion
  2796. \end{lstlisting}
  2797. \end{minipage}
  2798. \caption{The running example annotated with live-after sets.}
  2799. \label{fig:live-eg}
  2800. \end{figure}
  2801. \begin{exercise}\normalfont
  2802. Implement the compiler pass named \code{uncover-live} that computes
  2803. the live-after sets. We recommend storing the live-after sets (a list
  2804. of a set of variables) in the $\itm{info}$ field of the \code{Block}
  2805. structure.
  2806. %
  2807. We recommend organizing your code to use a helper function that takes
  2808. a list of instructions and an initial live-after set (typically empty)
  2809. and returns the list of live-after sets.
  2810. %
  2811. We recommend creating helper functions to 1) compute the set of
  2812. locations that appear in an argument (of an instruction), 2) compute
  2813. the locations read by an instruction which corresponds to the $R$
  2814. function discussed above, and 3) the locations written by an
  2815. instruction which corresponds to $W$. The \code{callq} instruction
  2816. should include all of the caller-saved registers in its write-set $W$
  2817. because the calling convention says that those registers may be
  2818. written to during the function call. Likewise, the \code{callq}
  2819. instruction should include the appropriate number of argument passing
  2820. registers in its read-set $R$, depending on the arity of the function
  2821. being called. (This is why the abstract syntax for \code{callq}
  2822. includes the arity.)
  2823. \end{exercise}
  2824. \section{Building the Interference Graph}
  2825. \label{sec:build-interference}
  2826. \begin{wrapfigure}[27]{r}[1.0in]{0.6\textwidth}
  2827. \small
  2828. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  2829. A \emph{graph} is a collection of vertices and edges where each
  2830. edge connects two vertices. A graph is \emph{directed} if each
  2831. edge points from a source to a target. Otherwise the graph is
  2832. \emph{undirected}.
  2833. \index{graph}\index{directed graph}\index{undirected graph}
  2834. \begin{description}
  2835. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  2836. directed graph from a list of edges. Each edge is a list
  2837. containing the source and target vertex.
  2838. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  2839. undirected graph from a list of edges. Each edge is represented by
  2840. a list containing two vertices.
  2841. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  2842. inserts a vertex into the graph.
  2843. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  2844. inserts an edge between the two vertices into the graph.
  2845. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  2846. returns a sequence of all the neighbors of the given vertex.
  2847. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  2848. returns a sequence of all the vertices in the graph.
  2849. \end{description}
  2850. \end{tcolorbox}
  2851. \end{wrapfigure}
  2852. Based on the liveness analysis, we know where each location is used
  2853. (read from). However, during register allocation, we need to answer
  2854. questions of the specific form: are locations $u$ and $v$ live at the
  2855. same time? (And therefore cannot be assigned to the same register.)
  2856. To make this question easier to answer, we create an explicit data
  2857. structure, an \emph{interference graph}\index{interference graph}. An
  2858. interference graph is an undirected graph that has an edge between two
  2859. locations if they are live at the same time, that is, if they
  2860. interfere with each other.
  2861. The most obvious way to compute the interference graph is to look at
  2862. the set of live location between each statement in the program and add
  2863. an edge to the graph for every pair of variables in the same set.
  2864. This approach is less than ideal for two reasons. First, it can be
  2865. expensive because it takes $O(n^2)$ time to look at every pair in a
  2866. set of $n$ live locations. Second, there is a special case in which
  2867. two locations that are live at the same time do not actually interfere
  2868. with each other: when they both contain the same value because we have
  2869. assigned one to the other.
  2870. A better way to compute the interference graph is to focus on the
  2871. writes~\cite{Appel:2003fk}. We do not want the writes performed by an
  2872. instruction to overwrite something in a live location. So for each
  2873. instruction, we create an edge between the locations being written to
  2874. and all the other live locations. (Except that one should not create
  2875. self edges.) Recall that for a \key{callq} instruction, we consider
  2876. all of the caller-saved registers as being written to, so an edge will
  2877. be added between every live variable and every caller-saved
  2878. register. For \key{movq}, we deal with the above-mentioned special
  2879. case by not adding an edge between a live variable $v$ and destination
  2880. $d$ if $v$ matches the source of the move. So we have the following
  2881. two rules.
  2882. \begin{enumerate}
  2883. \item If instruction $I_k$ is a move such as \key{movq} $s$\key{,}
  2884. $d$, then add the edge $(d,v)$ for every $v \in
  2885. L_{\mathsf{after}}(k)$ unless $v = d$ or $v = s$.
  2886. \item For any other instruction $I_k$, for every $d \in W(k)$
  2887. add an edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  2888. %% \item If instruction $I_k$ is an arithmetic instruction such as
  2889. %% \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2890. %% L_{\mathsf{after}}(k)$ unless $v = d$.
  2891. %% \item If instruction $I_k$ is of the form \key{callq}
  2892. %% $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2893. %% register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2894. \end{enumerate}
  2895. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  2896. the above rules to each instruction. We highlight a few of the
  2897. instructions and then refer the reader to
  2898. Figure~\ref{fig:interference-results} for all the interference
  2899. results. The first instruction is \lstinline{movq $1, v}, so rule 3
  2900. applies, and the live-after set is $\{\ttm{v}\}$. We do not add any
  2901. interference edges because the one live variable \code{v} is also the
  2902. destination of this instruction.
  2903. %
  2904. For the second instruction, \lstinline{movq $42, w}, so rule 3 applies
  2905. again, and the live-after set is $\{\ttm{v},\ttm{w}\}$. So the target
  2906. $\ttm{w}$ of \key{movq} interferes with $\ttm{v}$.
  2907. %
  2908. Next we skip forward to the instruction \lstinline{movq x, y}.
  2909. \begin{figure}[tbp]
  2910. \begin{quote}
  2911. \begin{tabular}{ll}
  2912. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  2913. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  2914. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  2915. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  2916. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  2917. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  2918. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  2919. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  2920. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  2921. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  2922. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  2923. \lstinline!jmp conclusion!& no interference.
  2924. \end{tabular}
  2925. \end{quote}
  2926. \caption{Interference results for the running example.}
  2927. \label{fig:interference-results}
  2928. \end{figure}
  2929. The resulting interference graph is shown in
  2930. Figure~\ref{fig:interfere}.
  2931. \begin{figure}[tbp]
  2932. \large
  2933. \[
  2934. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2935. \node (rax) at (0,0) {$\ttm{rax}$};
  2936. \node (rsp) at (9,2) {$\ttm{rsp}$};
  2937. \node (t1) at (0,2) {$\ttm{t}$};
  2938. \node (z) at (3,2) {$\ttm{z}$};
  2939. \node (x) at (6,2) {$\ttm{x}$};
  2940. \node (y) at (3,0) {$\ttm{y}$};
  2941. \node (w) at (6,0) {$\ttm{w}$};
  2942. \node (v) at (9,0) {$\ttm{v}$};
  2943. \draw (t1) to (rax);
  2944. \draw (t1) to (z);
  2945. \draw (z) to (y);
  2946. \draw (z) to (w);
  2947. \draw (x) to (w);
  2948. \draw (y) to (w);
  2949. \draw (v) to (w);
  2950. \draw (v) to (rsp);
  2951. \draw (w) to (rsp);
  2952. \draw (x) to (rsp);
  2953. \draw (y) to (rsp);
  2954. \path[-.,bend left=15] (z) edge node {} (rsp);
  2955. \path[-.,bend left=10] (t1) edge node {} (rsp);
  2956. \draw (rax) to (rsp);
  2957. \end{tikzpicture}
  2958. \]
  2959. \caption{The interference graph of the example program.}
  2960. \label{fig:interfere}
  2961. \end{figure}
  2962. %% Our next concern is to choose a data structure for representing the
  2963. %% interference graph. There are many choices for how to represent a
  2964. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2965. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2966. %% data structure is to study the algorithm that uses the data structure,
  2967. %% determine what operations need to be performed, and then choose the
  2968. %% data structure that provide the most efficient implementations of
  2969. %% those operations. Often times the choice of data structure can have an
  2970. %% effect on the time complexity of the algorithm, as it does here. If
  2971. %% you skim the next section, you will see that the register allocation
  2972. %% algorithm needs to ask the graph for all of its vertices and, given a
  2973. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2974. %% correct choice of graph representation is that of an adjacency
  2975. %% list. There are helper functions in \code{utilities.rkt} for
  2976. %% representing graphs using the adjacency list representation:
  2977. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2978. %% (Appendix~\ref{appendix:utilities}).
  2979. %% %
  2980. %% \margincomment{\footnotesize To do: change to use the
  2981. %% Racket graph library. \\ --Jeremy}
  2982. %% %
  2983. %% In particular, those functions use a hash table to map each vertex to
  2984. %% the set of adjacent vertices, and the sets are represented using
  2985. %% Racket's \key{set}, which is also a hash table.
  2986. \begin{exercise}\normalfont
  2987. Implement the compiler pass named \code{build-interference} according
  2988. to the algorithm suggested above. We recommend using the \code{graph}
  2989. package to create and inspect the interference graph. The output
  2990. graph of this pass should be stored in the $\itm{info}$ field of the
  2991. program, under the key \code{conflicts}.
  2992. \end{exercise}
  2993. \section{Graph Coloring via Sudoku}
  2994. \label{sec:graph-coloring}
  2995. \index{graph coloring}
  2996. \index{Sudoku}
  2997. \index{color}
  2998. We come to the main event, mapping variables to registers (or to stack
  2999. locations in the event that we run out of registers). We need to make
  3000. sure that two variables do not get mapped to the same register if the
  3001. two variables interfere with each other. Thinking about the
  3002. interference graph, this means that adjacent vertices must be mapped
  3003. to different registers. If we think of registers as colors, the
  3004. register allocation problem becomes the widely-studied graph coloring
  3005. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  3006. The reader may be more familiar with the graph coloring problem than he
  3007. or she realizes; the popular game of Sudoku is an instance of the
  3008. graph coloring problem. The following describes how to build a graph
  3009. out of an initial Sudoku board.
  3010. \begin{itemize}
  3011. \item There is one vertex in the graph for each Sudoku square.
  3012. \item There is an edge between two vertices if the corresponding squares
  3013. are in the same row, in the same column, or if the squares are in
  3014. the same $3\times 3$ region.
  3015. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  3016. \item Based on the initial assignment of numbers to squares in the
  3017. Sudoku board, assign the corresponding colors to the corresponding
  3018. vertices in the graph.
  3019. \end{itemize}
  3020. If you can color the remaining vertices in the graph with the nine
  3021. colors, then you have also solved the corresponding game of Sudoku.
  3022. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  3023. the corresponding graph with colored vertices. We map the Sudoku
  3024. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  3025. sampling of the vertices (the colored ones) because showing edges for
  3026. all of the vertices would make the graph unreadable.
  3027. \begin{figure}[tbp]
  3028. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  3029. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  3030. \caption{A Sudoku game board and the corresponding colored graph.}
  3031. \label{fig:sudoku-graph}
  3032. \end{figure}
  3033. Given that Sudoku is an instance of graph coloring, one can use Sudoku
  3034. strategies to come up with an algorithm for allocating registers. For
  3035. example, one of the basic techniques for Sudoku is called Pencil
  3036. Marks. The idea is to use a process of elimination to determine what
  3037. numbers no longer make sense for a square and write down those
  3038. numbers in the square (writing very small). For example, if the number
  3039. $1$ is assigned to a square, then by process of elimination, you can
  3040. write the pencil mark $1$ in all the squares in the same row, column,
  3041. and region. Many Sudoku computer games provide automatic support for
  3042. Pencil Marks.
  3043. %
  3044. The Pencil Marks technique corresponds to the notion of
  3045. \emph{saturation}\index{saturation} due to \cite{Brelaz:1979eu}.
  3046. The saturation of a
  3047. vertex, in Sudoku terms, is the set of numbers that are no longer
  3048. available. In graph terminology, we have the following definition:
  3049. \begin{equation*}
  3050. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  3051. \text{ and } \mathrm{color}(v) = c \}
  3052. \end{equation*}
  3053. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  3054. edge with $u$.
  3055. Using the Pencil Marks technique leads to a simple strategy for
  3056. filling in numbers: if there is a square with only one possible number
  3057. left, then choose that number! But what if there are no squares with
  3058. only one possibility left? One brute-force approach is to try them
  3059. all: choose the first and if it ultimately leads to a solution,
  3060. great. If not, backtrack and choose the next possibility. One good
  3061. thing about Pencil Marks is that it reduces the degree of branching in
  3062. the search tree. Nevertheless, backtracking can be horribly time
  3063. consuming. One way to reduce the amount of backtracking is to use the
  3064. most-constrained-first heuristic. That is, when choosing a square,
  3065. always choose one with the fewest possibilities left (the vertex with
  3066. the highest saturation). The idea is that choosing highly constrained
  3067. squares earlier rather than later is better because later on there may
  3068. not be any possibilities left for those squares.
  3069. However, register allocation is easier than Sudoku because the
  3070. register allocator can map variables to stack locations when the
  3071. registers run out. Thus, it makes sense to drop backtracking in favor
  3072. of greedy search, that is, make the best choice at the time and keep
  3073. going. We still wish to minimize the number of colors needed, so
  3074. keeping the most-constrained-first heuristic is a good idea.
  3075. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  3076. algorithm for register allocation based on saturation and the
  3077. most-constrained-first heuristic. It is roughly equivalent to the
  3078. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  3079. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just as in
  3080. Sudoku, the algorithm represents colors with integers. The integers
  3081. $0$ through $k-1$ correspond to the $k$ registers that we use for
  3082. register allocation. The integers $k$ and larger correspond to stack
  3083. locations. The registers that are not used for register allocation,
  3084. such as \code{rax}, are assigned to negative integers. In particular,
  3085. we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  3086. One might wonder why we include registers at all in the liveness
  3087. analysis and interference graph, for example, we never allocate a
  3088. variable to \code{rax} and \code{rsp}, so it would be harmless to
  3089. leave them out. As we see in Chapter~\ref{ch:tuples}, when we begin
  3090. to use register for passing arguments to functions, it will be
  3091. necessary for those registers to appear in the interference graph
  3092. because those registers will also be assigned to variables, and we
  3093. don't want those two uses to encroach on each other. Regarding
  3094. registers such as \code{rax} and \code{rsp} that are not used for
  3095. variables, we could omit them from the interference graph but that
  3096. would require adding special cases to our algorithm, which would
  3097. complicate the logic for little gain.
  3098. \begin{figure}[btp]
  3099. \centering
  3100. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  3101. Algorithm: DSATUR
  3102. Input: a graph |$G$|
  3103. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  3104. |$W \gets \mathrm{vertices}(G)$|
  3105. while |$W \neq \emptyset$| do
  3106. pick a vertex |$u$| from |$W$| with the highest saturation,
  3107. breaking ties randomly
  3108. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  3109. |$\mathrm{color}[u] \gets c$|
  3110. |$W \gets W - \{u\}$|
  3111. \end{lstlisting}
  3112. \caption{The saturation-based greedy graph coloring algorithm.}
  3113. \label{fig:satur-algo}
  3114. \end{figure}
  3115. With the DSATUR algorithm in hand, let us return to the running
  3116. example and consider how to color the interference graph in
  3117. Figure~\ref{fig:interfere}.
  3118. %
  3119. We color the vertices for registers with their own color. For example,
  3120. \code{rax} is assigned the color $-1$ and \code{rsp} is assigned $-2$.
  3121. The vertices for variables are not yet colored, so they annotated with
  3122. a dash. We then update the saturation for vertices that are adjacent
  3123. to a register. For example, the saturation for \code{t} is $\{-1,-2\}$
  3124. because it interferes with both \code{rax} and \code{rsp}.
  3125. \[
  3126. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3127. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  3128. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  3129. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  3130. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  3131. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3132. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3133. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3134. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3135. \draw (t1) to (rax);
  3136. \draw (t1) to (z);
  3137. \draw (z) to (y);
  3138. \draw (z) to (w);
  3139. \draw (x) to (w);
  3140. \draw (y) to (w);
  3141. \draw (v) to (w);
  3142. \draw (v) to (rsp);
  3143. \draw (w) to (rsp);
  3144. \draw (x) to (rsp);
  3145. \draw (y) to (rsp);
  3146. \path[-.,bend left=15] (z) edge node {} (rsp);
  3147. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3148. \draw (rax) to (rsp);
  3149. \end{tikzpicture}
  3150. \]
  3151. The algorithm says to select a maximally saturated vertex. So we pick
  3152. $\ttm{t}$ and color it with the first available integer, which is
  3153. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  3154. and \ttm{rsp} because they interfere with $\ttm{t}$.
  3155. \[
  3156. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3157. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3158. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  3159. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  3160. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  3161. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3162. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3163. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3164. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3165. \draw (t1) to (rax);
  3166. \draw (t1) to (z);
  3167. \draw (z) to (y);
  3168. \draw (z) to (w);
  3169. \draw (x) to (w);
  3170. \draw (y) to (w);
  3171. \draw (v) to (w);
  3172. \draw (v) to (rsp);
  3173. \draw (w) to (rsp);
  3174. \draw (x) to (rsp);
  3175. \draw (y) to (rsp);
  3176. \path[-.,bend left=15] (z) edge node {} (rsp);
  3177. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3178. \draw (rax) to (rsp);
  3179. \end{tikzpicture}
  3180. \]
  3181. We repeat the process, selecting another maximally saturated
  3182. vertex, which is \code{z}, and color it with the first available
  3183. number, which is $1$. We add $1$ to the saturation for the
  3184. neighboring vertices \code{t}, \code{y}, \code{w}, and \code{rsp}.
  3185. \[
  3186. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3187. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3188. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3189. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3190. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3191. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3192. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3193. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3194. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3195. \draw (t1) to (rax);
  3196. \draw (t1) to (z);
  3197. \draw (z) to (y);
  3198. \draw (z) to (w);
  3199. \draw (x) to (w);
  3200. \draw (y) to (w);
  3201. \draw (v) to (w);
  3202. \draw (v) to (rsp);
  3203. \draw (w) to (rsp);
  3204. \draw (x) to (rsp);
  3205. \draw (y) to (rsp);
  3206. \path[-.,bend left=15] (z) edge node {} (rsp);
  3207. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3208. \draw (rax) to (rsp);
  3209. \end{tikzpicture}
  3210. \]
  3211. The most saturated vertices are now \code{w} and \code{y}. We color
  3212. \code{w} with the first available color, which is $0$.
  3213. \[
  3214. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3215. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3216. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3217. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3218. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3219. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3220. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  3221. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  3222. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  3223. \draw (t1) to (rax);
  3224. \draw (t1) to (z);
  3225. \draw (z) to (y);
  3226. \draw (z) to (w);
  3227. \draw (x) to (w);
  3228. \draw (y) to (w);
  3229. \draw (v) to (w);
  3230. \draw (v) to (rsp);
  3231. \draw (w) to (rsp);
  3232. \draw (x) to (rsp);
  3233. \draw (y) to (rsp);
  3234. \path[-.,bend left=15] (z) edge node {} (rsp);
  3235. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3236. \draw (rax) to (rsp);
  3237. \end{tikzpicture}
  3238. \]
  3239. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  3240. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  3241. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  3242. and \code{z}, whose colors are $0$ and $1$ respectively.
  3243. \[
  3244. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3245. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3246. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3247. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3248. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3249. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3250. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3251. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3252. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  3253. \draw (t1) to (rax);
  3254. \draw (t1) to (z);
  3255. \draw (z) to (y);
  3256. \draw (z) to (w);
  3257. \draw (x) to (w);
  3258. \draw (y) to (w);
  3259. \draw (v) to (w);
  3260. \draw (v) to (rsp);
  3261. \draw (w) to (rsp);
  3262. \draw (x) to (rsp);
  3263. \draw (y) to (rsp);
  3264. \path[-.,bend left=15] (z) edge node {} (rsp);
  3265. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3266. \draw (rax) to (rsp);
  3267. \end{tikzpicture}
  3268. \]
  3269. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  3270. \[
  3271. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3272. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3273. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3274. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3275. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3276. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3277. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3278. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3279. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3280. \draw (t1) to (rax);
  3281. \draw (t1) to (z);
  3282. \draw (z) to (y);
  3283. \draw (z) to (w);
  3284. \draw (x) to (w);
  3285. \draw (y) to (w);
  3286. \draw (v) to (w);
  3287. \draw (v) to (rsp);
  3288. \draw (w) to (rsp);
  3289. \draw (x) to (rsp);
  3290. \draw (y) to (rsp);
  3291. \path[-.,bend left=15] (z) edge node {} (rsp);
  3292. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3293. \draw (rax) to (rsp);
  3294. \end{tikzpicture}
  3295. \]
  3296. In the last step of the algorithm, we color \code{x} with $1$.
  3297. \[
  3298. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3299. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3300. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3301. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3302. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3303. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  3304. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3305. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3306. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3307. \draw (t1) to (rax);
  3308. \draw (t1) to (z);
  3309. \draw (z) to (y);
  3310. \draw (z) to (w);
  3311. \draw (x) to (w);
  3312. \draw (y) to (w);
  3313. \draw (v) to (w);
  3314. \draw (v) to (rsp);
  3315. \draw (w) to (rsp);
  3316. \draw (x) to (rsp);
  3317. \draw (y) to (rsp);
  3318. \path[-.,bend left=15] (z) edge node {} (rsp);
  3319. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3320. \draw (rax) to (rsp);
  3321. \end{tikzpicture}
  3322. \]
  3323. With the coloring complete, we finalize the assignment of variables to
  3324. registers and stack locations. Recall that if we have $k$ registers to
  3325. use for allocation, we map the first $k$ colors to registers and the
  3326. rest to stack locations. Suppose for the moment that we have just one
  3327. register to use for register allocation, \key{rcx}. Then the following
  3328. maps of colors to registers and stack allocations.
  3329. \[
  3330. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  3331. \]
  3332. Putting this mapping together with the above coloring of the
  3333. variables, we arrive at the following assignment.
  3334. \begin{gather*}
  3335. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  3336. \ttm{w} \mapsto \key{\%rcx}, \,
  3337. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  3338. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  3339. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  3340. \ttm{t} \mapsto \key{\%rcx} \}
  3341. \end{gather*}
  3342. Applying this assignment to our running example, on the left, yields
  3343. the program on the right.
  3344. % why frame size of 32? -JGS
  3345. \begin{center}
  3346. \begin{minipage}{0.3\textwidth}
  3347. \begin{lstlisting}
  3348. movq $1, v
  3349. movq $42, w
  3350. movq v, x
  3351. addq $7, x
  3352. movq x, y
  3353. movq x, z
  3354. addq w, z
  3355. movq y, t
  3356. negq t
  3357. movq z, %rax
  3358. addq t, %rax
  3359. jmp conclusion
  3360. \end{lstlisting}
  3361. \end{minipage}
  3362. $\Rightarrow\qquad$
  3363. \begin{minipage}{0.45\textwidth}
  3364. \begin{lstlisting}
  3365. movq $1, %rcx
  3366. movq $42, %rcx
  3367. movq %rcx, -8(%rbp)
  3368. addq $7, -8(%rbp)
  3369. movq -8(%rbp), -16(%rbp)
  3370. movq -8(%rbp), -8(%rbp)
  3371. addq %rcx, -8(%rbp)
  3372. movq -16(%rbp), %rcx
  3373. negq %rcx
  3374. movq -8(%rbp), %rax
  3375. addq %rcx, %rax
  3376. jmp conclusion
  3377. \end{lstlisting}
  3378. \end{minipage}
  3379. \end{center}
  3380. The resulting program is almost an x86 program. The remaining step is
  3381. the patch instructions pass. In this example, the trivial move of
  3382. \code{-8(\%rbp)} to itself is deleted and the addition of
  3383. \code{-8(\%rbp)} to \key{-16(\%rbp)} is fixed by going through
  3384. \code{rax} as follows.
  3385. \begin{lstlisting}
  3386. movq -8(%rbp), %rax
  3387. addq %rax, -16(%rbp)
  3388. \end{lstlisting}
  3389. We recommend creating a helper function named \code{color-graph} that
  3390. takes an interference graph and a list of all the variables in the
  3391. program. This function should return a mapping of variables to their
  3392. colors (represented as natural numbers). By creating this helper
  3393. function, you will be able to reuse it in Chapter~\ref{ch:functions}
  3394. when you add support for functions. To prioritize the processing of
  3395. highly saturated nodes inside your \code{color-graph} function, we
  3396. recommend using the priority queue data structure (see the side bar on
  3397. the right). Note that you will also need to maintain a mapping from
  3398. variables to their ``handles'' in the priority queue so that you can
  3399. notify the priority queue when their saturation changes.
  3400. \begin{wrapfigure}[23]{r}[1.0in]{0.6\textwidth}
  3401. \small
  3402. \begin{tcolorbox}[title=Priority Queue]
  3403. A \emph{priority queue} is a collection of items in which the
  3404. removal of items is governed by priority. In a ``min'' queue,
  3405. lower priority items are removed first. An implementation is in
  3406. \code{priority\_queue.rkt} of the support code. \index{priority
  3407. queue} \index{minimum priority queue}
  3408. \begin{description}
  3409. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  3410. priority queue that uses the $\itm{cmp}$ predicate to determine
  3411. whether its first argument has lower or equal priority to its
  3412. second argument.
  3413. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  3414. items in the queue.
  3415. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  3416. the item into the queue and returns a handle for the item in the
  3417. queue.
  3418. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  3419. the lowest priority.
  3420. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  3421. notifies the queue that the priority has decreased for the item
  3422. associated with the given handle.
  3423. \end{description}
  3424. \end{tcolorbox}
  3425. \end{wrapfigure}
  3426. Once you have obtained the coloring from \code{color-graph}, you can
  3427. assign the variables to registers or stack locations and then reuse
  3428. code from the \code{assign-homes} pass from
  3429. Section~\ref{sec:assign-r1} to replace the variables with their
  3430. assigned location.
  3431. \begin{exercise}\normalfont
  3432. Implement the compiler pass \code{allocate-registers}, which should
  3433. come after the \code{build-interference} pass. The three new passes
  3434. described in this chapter replace the \code{assign-homes} pass of
  3435. Section~\ref{sec:assign-r1}.
  3436. %
  3437. Test your updated compiler by creating new example programs that
  3438. exercise all of the register allocation algorithm, such as forcing
  3439. variables to be spilled to the stack.
  3440. \end{exercise}
  3441. \section{Print x86}
  3442. \label{sec:print-x86-reg-alloc}
  3443. \index{calling conventions}
  3444. \index{prelude}\index{conclusion}
  3445. Recall that the \code{print-x86} pass generates the prelude and
  3446. conclusion instructions for the \code{main} function.
  3447. %
  3448. The prelude saved the values in \code{rbp} and \code{rsp} and the
  3449. conclusion returned those values to \code{rbp} and \code{rsp}. The
  3450. reason for this is that our \code{main} function must adhere to the
  3451. x86 calling conventions that we described in
  3452. Section~\ref{sec:calling-conventions}. Furthermore, if your register
  3453. allocator assigned variables to other callee-saved registers
  3454. (e.g. \code{rbx}, \code{r12}, etc.), then those variables must also be
  3455. saved to the stack in the prelude and restored in the conclusion. The
  3456. simplest approach is to save and restore all of the callee-saved
  3457. registers. The more efficient approach is to keep track of which
  3458. callee-saved registers were used and only save and restore
  3459. them. Either way, make sure to take this use of stack space into
  3460. account when you are calculating the size of the frame and adjusting
  3461. the \code{rsp} in the prelude. Also, don't forget that the size of the
  3462. frame needs to be a multiple of 16 bytes!
  3463. An overview of all of the passes involved in register allocation is
  3464. shown in Figure~\ref{fig:reg-alloc-passes}.
  3465. \begin{figure}[tbp]
  3466. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3467. \node (R1) at (0,2) {\large $R_1$};
  3468. \node (R1-2) at (3,2) {\large $R_1$};
  3469. \node (R1-3) at (6,2) {\large $R_1$};
  3470. \node (C0-1) at (3,0) {\large $C_0$};
  3471. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  3472. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  3473. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  3474. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}$};
  3475. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  3476. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  3477. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  3478. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  3479. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  3480. \path[->,bend right=15] (C0-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  3481. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  3482. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  3483. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  3484. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  3485. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  3486. \end{tikzpicture}
  3487. \caption{Diagram of the passes for $R_1$ with register allocation.}
  3488. \label{fig:reg-alloc-passes}
  3489. \end{figure}
  3490. \section{Challenge: Move Biasing}
  3491. \label{sec:move-biasing}
  3492. \index{move biasing}
  3493. This section describes an optional enhancement to register allocation
  3494. for those students who are looking for an extra challenge or who have
  3495. a deeper interest in register allocation.
  3496. We return to the running example, but we remove the supposition that
  3497. we only have one register to use. So we have the following mapping of
  3498. color numbers to registers.
  3499. \[
  3500. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx} \}
  3501. \]
  3502. Using the same assignment of variables to color numbers that was
  3503. produced by the register allocator described in the last section, we
  3504. get the following program.
  3505. \begin{minipage}{0.3\textwidth}
  3506. \begin{lstlisting}
  3507. movq $1, v
  3508. movq $42, w
  3509. movq v, x
  3510. addq $7, x
  3511. movq x, y
  3512. movq x, z
  3513. addq w, z
  3514. movq y, t
  3515. negq t
  3516. movq z, %rax
  3517. addq t, %rax
  3518. jmp conclusion
  3519. \end{lstlisting}
  3520. \end{minipage}
  3521. $\Rightarrow\qquad$
  3522. \begin{minipage}{0.45\textwidth}
  3523. \begin{lstlisting}
  3524. movq $1, %rcx
  3525. movq $42, $rbx
  3526. movq %rcx, %rcx
  3527. addq $7, %rcx
  3528. movq %rcx, %rdx
  3529. movq %rcx, %rcx
  3530. addq %rbx, %rcx
  3531. movq %rdx, %rbx
  3532. negq %rbx
  3533. movq %rcx, %rax
  3534. addq %rbx, %rax
  3535. jmp conclusion
  3536. \end{lstlisting}
  3537. \end{minipage}
  3538. In the above output code there are two \key{movq} instructions that
  3539. can be removed because their source and target are the same. However,
  3540. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  3541. register, we could instead remove three \key{movq} instructions. We
  3542. can accomplish this by taking into account which variables appear in
  3543. \key{movq} instructions with which other variables.
  3544. We say that two variables $p$ and $q$ are \emph{move
  3545. related}\index{move related} if they participate together in a
  3546. \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  3547. \key{movq} $q$\key{,} $p$. When the register allocator chooses a color
  3548. for a variable, it should prefer a color that has already been used
  3549. for a move-related variable (assuming that they do not interfere). Of
  3550. course, this preference should not override the preference for
  3551. registers over stack locations. This preference should be used as a
  3552. tie breaker when choosing between registers or when choosing between
  3553. stack locations.
  3554. We recommend representing the move relationships in a graph, similar
  3555. to how we represented interference. The following is the \emph{move
  3556. graph} for our running example.
  3557. \[
  3558. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3559. \node (rax) at (0,0) {$\ttm{rax}$};
  3560. \node (rsp) at (9,2) {$\ttm{rsp}$};
  3561. \node (t) at (0,2) {$\ttm{t}$};
  3562. \node (z) at (3,2) {$\ttm{z}$};
  3563. \node (x) at (6,2) {$\ttm{x}$};
  3564. \node (y) at (3,0) {$\ttm{y}$};
  3565. \node (w) at (6,0) {$\ttm{w}$};
  3566. \node (v) at (9,0) {$\ttm{v}$};
  3567. \draw (v) to (x);
  3568. \draw (x) to (y);
  3569. \draw (x) to (z);
  3570. \draw (y) to (t);
  3571. \end{tikzpicture}
  3572. \]
  3573. Now we replay the graph coloring, pausing to see the coloring of
  3574. \code{y}. Recall the following configuration. The most saturated vertices
  3575. were \code{w} and \code{y}.
  3576. \[
  3577. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3578. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3579. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3580. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3581. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3582. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3583. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3584. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3585. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  3586. \draw (t1) to (rax);
  3587. \draw (t1) to (z);
  3588. \draw (z) to (y);
  3589. \draw (z) to (w);
  3590. \draw (x) to (w);
  3591. \draw (y) to (w);
  3592. \draw (v) to (w);
  3593. \draw (v) to (rsp);
  3594. \draw (w) to (rsp);
  3595. \draw (x) to (rsp);
  3596. \draw (y) to (rsp);
  3597. \path[-.,bend left=15] (z) edge node {} (rsp);
  3598. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3599. \draw (rax) to (rsp);
  3600. \end{tikzpicture}
  3601. \]
  3602. %
  3603. Last time we chose to color \code{w} with $0$. But this time we see
  3604. that \code{w} is not move related to any vertex, but \code{y} is move
  3605. related to \code{t}. So we choose to color \code{y} the same color as
  3606. \code{t}, $0$.
  3607. \[
  3608. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3609. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3610. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3611. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3612. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3613. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3614. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  3615. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  3616. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  3617. \draw (t1) to (rax);
  3618. \draw (t1) to (z);
  3619. \draw (z) to (y);
  3620. \draw (z) to (w);
  3621. \draw (x) to (w);
  3622. \draw (y) to (w);
  3623. \draw (v) to (w);
  3624. \draw (v) to (rsp);
  3625. \draw (w) to (rsp);
  3626. \draw (x) to (rsp);
  3627. \draw (y) to (rsp);
  3628. \path[-.,bend left=15] (z) edge node {} (rsp);
  3629. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3630. \draw (rax) to (rsp);
  3631. \end{tikzpicture}
  3632. \]
  3633. Now \code{w} is the most saturated, so we color it $2$.
  3634. \[
  3635. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3636. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3637. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3638. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3639. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3640. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  3641. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  3642. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  3643. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  3644. \draw (t1) to (rax);
  3645. \draw (t1) to (z);
  3646. \draw (z) to (y);
  3647. \draw (z) to (w);
  3648. \draw (x) to (w);
  3649. \draw (y) to (w);
  3650. \draw (v) to (w);
  3651. \draw (v) to (rsp);
  3652. \draw (w) to (rsp);
  3653. \draw (x) to (rsp);
  3654. \draw (y) to (rsp);
  3655. \path[-.,bend left=15] (z) edge node {} (rsp);
  3656. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3657. \draw (rax) to (rsp);
  3658. \end{tikzpicture}
  3659. \]
  3660. At this point, vertices \code{x} and \code{v} are most saturated, but
  3661. \code{x} is move related to \code{y} and \code{z}, so we color
  3662. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  3663. \[
  3664. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3665. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3666. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3667. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3668. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3669. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  3670. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  3671. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  3672. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  3673. \draw (t1) to (rax);
  3674. \draw (t) to (z);
  3675. \draw (z) to (y);
  3676. \draw (z) to (w);
  3677. \draw (x) to (w);
  3678. \draw (y) to (w);
  3679. \draw (v) to (w);
  3680. \draw (v) to (rsp);
  3681. \draw (w) to (rsp);
  3682. \draw (x) to (rsp);
  3683. \draw (y) to (rsp);
  3684. \path[-.,bend left=15] (z) edge node {} (rsp);
  3685. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3686. \draw (rax) to (rsp);
  3687. \end{tikzpicture}
  3688. \]
  3689. So we have the following assignment of variables to registers.
  3690. \begin{gather*}
  3691. \{ \ttm{v} \mapsto \key{\%rbx}, \,
  3692. \ttm{w} \mapsto \key{\%rdx}, \,
  3693. \ttm{x} \mapsto \key{\%rbx}, \,
  3694. \ttm{y} \mapsto \key{\%rbx}, \,
  3695. \ttm{z} \mapsto \key{\%rcx}, \,
  3696. \ttm{t} \mapsto \key{\%rbx} \}
  3697. \end{gather*}
  3698. We apply this register assignment to the running example, on the left,
  3699. to obtain the code in the middle. The \code{patch-instructions} then
  3700. removes the three trivial moves from \key{rbx} to \key{rbx} to obtain
  3701. the code on the right.
  3702. \begin{minipage}{0.25\textwidth}
  3703. \begin{lstlisting}
  3704. movq $1, v
  3705. movq $42, w
  3706. movq v, x
  3707. addq $7, x
  3708. movq x, y
  3709. movq x, z
  3710. addq w, z
  3711. movq y, t
  3712. negq t
  3713. movq z, %rax
  3714. addq t, %rax
  3715. jmp conclusion
  3716. \end{lstlisting}
  3717. \end{minipage}
  3718. $\Rightarrow\qquad$
  3719. \begin{minipage}{0.25\textwidth}
  3720. \begin{lstlisting}
  3721. movq $1, %rbx
  3722. movq $42, %rdx
  3723. movq %rbx, %rbx
  3724. addq $7, %rbx
  3725. movq %rbx, %rbx
  3726. movq %rbx, %rcx
  3727. addq %rdx, %rcx
  3728. movq %rbx, %rbx
  3729. negq %rbx
  3730. movq %rcx, %rax
  3731. addq %rbx, %rax
  3732. jmp conclusion
  3733. \end{lstlisting}
  3734. \end{minipage}
  3735. $\Rightarrow\qquad$
  3736. \begin{minipage}{0.25\textwidth}
  3737. \begin{lstlisting}
  3738. movq $1, %rbx
  3739. movq $42, %rdx
  3740. addq $7, %rbx
  3741. movq %rbx, %rcx
  3742. addq %rdx, %rcx
  3743. negq %rbx
  3744. movq %rcx, %rax
  3745. addq %rbx, %rax
  3746. jmp conclusion
  3747. \end{lstlisting}
  3748. \end{minipage}
  3749. \begin{exercise}\normalfont
  3750. Change your implementation of \code{allocate-registers} to take move
  3751. biasing into account. Make sure that your compiler still passes all of
  3752. the previous tests. Create two new tests that include at least one
  3753. opportunity for move biasing and visually inspect the output x86
  3754. programs to make sure that your move biasing is working properly.
  3755. \end{exercise}
  3756. \margincomment{\footnotesize To do: another neat challenge would be to do
  3757. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3758. \section{Output of the Running Example}
  3759. \label{sec:reg-alloc-output}
  3760. \index{prelude}\index{conclusion}
  3761. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  3762. the running example (Figure~\ref{fig:reg-eg}) with register allocation
  3763. and move biasing. To demonstrate both the use of registers and the
  3764. stack, we have limited the register allocator to use just two
  3765. registers: \code{rbx} and \code{rcx}. In the prelude of the
  3766. \code{main} function, we push \code{rbx} onto the stack because it is
  3767. a callee-saved register and it was assigned to variable by the
  3768. register allocator. We subtract \code{8} from the \code{rsp} at the
  3769. end of the prelude to reserve space for the one spilled variable.
  3770. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  3771. Moving on the the \code{start} block, we see how the registers were
  3772. allocated. Variables \code{v}, \code{x}, and \code{y} were assigned to
  3773. \code{rbx} and variable \code{z} was assigned to \code{rcx}. Variable
  3774. \code{w} was spilled to the stack location \code{-16(\%rbp)}. Recall
  3775. that the prelude saved the callee-save register \code{rbx} onto the
  3776. stack. The spilled variables must be placed lower on the stack than
  3777. the saved callee-save registers, so in this case \code{w} is placed at
  3778. \code{-16(\%rbp)}.
  3779. In the \code{conclusion}, we undo the work that was done in the
  3780. prelude. We move the stack pointer up by \code{8} bytes (the room for
  3781. spilled variables), then we pop the old values of \code{rbx} and
  3782. \code{rbp} (callee-saved registers), and finish with \code{retq} to
  3783. return control to the operating system.
  3784. \begin{figure}[tbp]
  3785. % s0_28.rkt
  3786. % (use-minimal-set-of-registers! #t)
  3787. % and only rbx rcx
  3788. % tmp 0 rbx
  3789. % z 1 rcx
  3790. % y 0 rbx
  3791. % w 2 16(%rbp)
  3792. % v 0 rbx
  3793. % x 0 rbx
  3794. \begin{lstlisting}
  3795. start:
  3796. movq $1, %rbx
  3797. movq $42, -16(%rbp)
  3798. addq $7, %rbx
  3799. movq %rbx, %rcx
  3800. addq -16(%rbp), %rcx
  3801. negq %rbx
  3802. movq %rcx, %rax
  3803. addq %rbx, %rax
  3804. jmp conclusion
  3805. .globl main
  3806. main:
  3807. pushq %rbp
  3808. movq %rsp, %rbp
  3809. pushq %rbx
  3810. subq $8, %rsp
  3811. jmp start
  3812. conclusion:
  3813. addq $8, %rsp
  3814. popq %rbx
  3815. popq %rbp
  3816. retq
  3817. \end{lstlisting}
  3818. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  3819. \label{fig:running-example-x86}
  3820. \end{figure}
  3821. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3822. \chapter{Booleans and Control Flow}
  3823. \label{ch:bool-types}
  3824. \index{Boolean}
  3825. \index{control flow}
  3826. \index{conditional expression}
  3827. The $R_0$ and $R_1$ languages only have a single kind of value, the
  3828. integers. In this chapter we add a second kind of value, the Booleans,
  3829. to create the $R_2$ language. The Boolean values \emph{true} and
  3830. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  3831. Racket. The $R_2$ language includes several operations that involve
  3832. Booleans (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the
  3833. conditional \key{if} expression. With the addition of \key{if}
  3834. expressions, programs can have non-trivial control flow which which
  3835. significantly impacts the \code{explicate-control} and the liveness
  3836. analysis for register allocation. Also, because we now have two kinds
  3837. of values, we need to handle programs that apply an operation to the
  3838. wrong kind of value, such as \code{(not 1)}.
  3839. There are two language design options for such situations. One option
  3840. is to signal an error and the other is to provide a wider
  3841. interpretation of the operation. The Racket language uses a mixture of
  3842. these two options, depending on the operation and the kind of
  3843. value. For example, the result of \code{(not 1)} in Racket is
  3844. \code{\#f} because Racket treats non-zero integers as if they were
  3845. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  3846. error in Racket stating that \code{car} expects a pair.
  3847. The Typed Racket language makes similar design choices as Racket,
  3848. except much of the error detection happens at compile time instead of
  3849. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  3850. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  3851. reports a compile-time error because Typed Racket expects the type of
  3852. the argument to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  3853. For the $R_2$ language we choose to be more like Typed Racket in that
  3854. we perform type checking during compilation. In
  3855. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  3856. is, how to compile a dynamically typed language like Racket. The
  3857. $R_2$ language is a subset of Typed Racket but by no means includes
  3858. all of Typed Racket. For many operations we take a narrower
  3859. interpretation than Typed Racket, for example, rejecting \code{(not 1)}.
  3860. This chapter is organized as follows. We begin by defining the syntax
  3861. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  3862. then introduce the idea of type checking and build a type checker for
  3863. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  3864. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  3865. Section~\ref{sec:c1}. The remaining sections of this chapter discuss
  3866. how our compiler passes need to change to accommodate Booleans and
  3867. conditional control flow.
  3868. \section{The $R_2$ Language}
  3869. \label{sec:r2-lang}
  3870. The concrete syntax of the $R_2$ language is defined in
  3871. Figure~\ref{fig:r2-concrete-syntax} and the abstract syntax is defined
  3872. in Figure~\ref{fig:r2-syntax}. The $R_2$ language includes all of
  3873. $R_1$ (shown in gray), the Boolean literals \code{\#t} and \code{\#f},
  3874. and the conditional \code{if} expression. Also, we expand the
  3875. operators to include
  3876. \begin{enumerate}
  3877. \item subtraction on integers,
  3878. \item the logical operators \key{and}, \key{or} and \key{not},
  3879. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  3880. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  3881. comparing integers.
  3882. \end{enumerate}
  3883. We reorganize the abstract syntax for the primitive operations in
  3884. Figure~\ref{fig:r2-syntax}, using only one grammar rule for all of
  3885. them. This means that the grammar no longer checks whether the arity
  3886. of an operators matches the number of arguments. That responsibility
  3887. is moved to the type checker for $R_2$, which we introduce in
  3888. Section~\ref{sec:type-check-r2}.
  3889. \begin{figure}[tp]
  3890. \centering
  3891. \fbox{
  3892. \begin{minipage}{0.96\textwidth}
  3893. \[
  3894. \begin{array}{lcl}
  3895. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3896. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3897. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} } \mid \CSUB{\Exp}{\Exp} \\
  3898. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} } \\
  3899. &\mid& \itm{bool}
  3900. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  3901. \mid (\key{not}\;\Exp) \\
  3902. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} \\
  3903. R_2 &::=& \Exp
  3904. \end{array}
  3905. \]
  3906. \end{minipage}
  3907. }
  3908. \caption{The concrete syntax of $R_2$, extending $R_1$
  3909. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  3910. \label{fig:r2-concrete-syntax}
  3911. \end{figure}
  3912. \begin{figure}[tp]
  3913. \centering
  3914. \fbox{
  3915. \begin{minipage}{0.96\textwidth}
  3916. \[
  3917. \begin{array}{lcl}
  3918. \itm{bool} &::=& \code{\#t} \mid \code{\#f} \\
  3919. \itm{cmp} &::= & \code{eq?} \mid \code{<} \mid \code{<=} \mid \code{>} \mid \code{>=} \\
  3920. \itm{op} &::= & \itm{cmp} \mid \code{read} \mid \code{+} \mid \code{-}
  3921. \mid \code{and} \mid \code{or} \mid \code{not} \\
  3922. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  3923. &\mid& \PRIM{\itm{op}}{\Exp\ldots}\\
  3924. &\mid& \BOOL{\itm{bool}} \mid \IF{\Exp}{\Exp}{\Exp} \\
  3925. R_2 &::=& \PROGRAM{\code{'()}}{\Exp}
  3926. \end{array}
  3927. \]
  3928. \end{minipage}
  3929. }
  3930. \caption{The abstract syntax of $R_2$.}
  3931. \label{fig:r2-syntax}
  3932. \end{figure}
  3933. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$,
  3934. inheriting from the interpreter for $R_1$
  3935. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  3936. evaluate to the corresponding Boolean values. The conditional
  3937. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  3938. the Boolean expression \itm{cnd} and then either evaluates \itm{thn}
  3939. or \itm{els} depending on whether \itm{cnd} produced \code{\#t} or
  3940. \code{\#f}. The logical operations \code{not} and \code{and} behave as
  3941. you might expect, but note that the \code{and} operation is
  3942. short-circuiting. That is, given the expression
  3943. $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not evaluated if
  3944. $e_1$ evaluates to \code{\#f}.
  3945. With the increase in the number of primitive operations, the
  3946. interpreter code for them could become repetitive without some
  3947. care. We factor out the different parts of the code for primitive
  3948. operations into the \code{interp-op} method shown in in
  3949. Figure~\ref{fig:interp-op-R2}. The match clause for \code{Prim} makes
  3950. the recursive calls to interpret the arguments and then passes the
  3951. resulting values to \code{interp-op}. We do not use \code{interp-op}
  3952. for the \code{and} operation because of its short-circuiting behavior.
  3953. \begin{figure}[tbp]
  3954. \begin{lstlisting}
  3955. (define interp-R2-class
  3956. (class interp-R1-class
  3957. (super-new)
  3958. (define/public (interp-op op) ...)
  3959. (define/override ((interp-exp env) e)
  3960. (define recur (interp-exp env))
  3961. (match e
  3962. [(Bool b) b]
  3963. [(If cnd thn els)
  3964. (define b (recur cnd))
  3965. (match b
  3966. [#t (recur thn)]
  3967. [#f (recur els)])]
  3968. [(Prim 'and (list e1 e2))
  3969. (define v1 (recur e1))
  3970. (match v1
  3971. [#t (match (recur e2) [#t #t] [#f #f])]
  3972. [#f #f])]
  3973. [(Prim op args)
  3974. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  3975. [else ((super interp-exp env) e)]
  3976. ))
  3977. ))
  3978. (define (interp-R2 p)
  3979. (send (new interp-R2-class) interp-program p))
  3980. \end{lstlisting}
  3981. \caption{Interpreter for the $R_2$ language. (See
  3982. Figure~\ref{fig:interp-op-R2} for \code{interp-op}.)}
  3983. \label{fig:interp-R2}
  3984. \end{figure}
  3985. \begin{figure}[tbp]
  3986. \begin{lstlisting}
  3987. (define/public (interp-op op)
  3988. (match op
  3989. ['+ fx+]
  3990. ['- fx-]
  3991. ['read read-fixnum]
  3992. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  3993. ['or (lambda (v1 v2)
  3994. (cond [(and (boolean? v1) (boolean? v2))
  3995. (or v1 v2)]))]
  3996. ['eq? (lambda (v1 v2)
  3997. (cond [(or (and (fixnum? v1) (fixnum? v2))
  3998. (and (boolean? v1) (boolean? v2))
  3999. (and (vector? v1) (vector? v2)))
  4000. (eq? v1 v2)]))]
  4001. ['< (lambda (v1 v2)
  4002. (cond [(and (fixnum? v1) (fixnum? v2))
  4003. (< v1 v2)]))]
  4004. ['<= (lambda (v1 v2)
  4005. (cond [(and (fixnum? v1) (fixnum? v2))
  4006. (<= v1 v2)]))]
  4007. ['> (lambda (v1 v2)
  4008. (cond [(and (fixnum? v1) (fixnum? v2))
  4009. (> v1 v2)]))]
  4010. ['>= (lambda (v1 v2)
  4011. (cond [(and (fixnum? v1) (fixnum? v2))
  4012. (>= v1 v2)]))]
  4013. [else (error 'interp-op "unknown operator")]
  4014. ))
  4015. \end{lstlisting}
  4016. \caption{Interpreter for the primitive operators in the $R_2$ language.}
  4017. \label{fig:interp-op-R2}
  4018. \end{figure}
  4019. \section{Type Checking $R_2$ Programs}
  4020. \label{sec:type-check-r2}
  4021. \index{type checking}
  4022. \index{semantic analysis}
  4023. It is helpful to think about type checking in two complementary
  4024. ways. A type checker predicts the type of value that will be produced
  4025. by each expression in the program. For $R_2$, we have just two types,
  4026. \key{Integer} and \key{Boolean}. So a type checker should predict that
  4027. \begin{lstlisting}
  4028. (+ 10 (- (+ 12 20)))
  4029. \end{lstlisting}
  4030. produces an \key{Integer} while
  4031. \begin{lstlisting}
  4032. (and (not #f) #t)
  4033. \end{lstlisting}
  4034. produces a \key{Boolean}.
  4035. Another way to think about type checking is that it enforces a set of
  4036. rules about which operators can be applied to which kinds of
  4037. values. For example, our type checker for $R_2$ will signal an error
  4038. for the below expression because, as we have seen above, the
  4039. expression \code{(+ 10 ...)} has type \key{Integer} but the type
  4040. checker enforces the rule that the argument of \code{not} must be a
  4041. \key{Boolean}.
  4042. \begin{lstlisting}
  4043. (not (+ 10 (- (+ 12 20))))
  4044. \end{lstlisting}
  4045. We implement type checking using classes and method overriding for the
  4046. same reason that we use them to implement the interpreters. We
  4047. separate the type checker for the $R_1$ fragment into its own class,
  4048. shown in Figure~\ref{fig:type-check-R1}. The type checker for $R_2$ is
  4049. shown in Figure~\ref{fig:type-check-R2}; inherits from the one for
  4050. $R_1$. The code for these type checkers are in the files
  4051. \code{type-check-R1.rkt} and \code{type-check-R2.rkt} of the support
  4052. code.
  4053. %
  4054. Each type checker is a structurally recursive function over the AST.
  4055. Given an input expression \code{e}, the type checker either signals an
  4056. error or returns an expression and its type (\key{Integer} or
  4057. \key{Boolean}). There are situations in which we want to change or
  4058. update the expression.
  4059. %
  4060. The type of an integer literal is \code{Integer} and
  4061. the type of a Boolean literal is \code{Boolean}. To handle variables,
  4062. the type checker uses the environment \code{env} to map variables to
  4063. types. Consider the clause for \key{let}. We type check the
  4064. initializing expression to obtain its type \key{T} and then associate
  4065. type \code{T} with the variable \code{x} in the environment used to
  4066. type check the body of the \key{let}. Thus, when the type checker
  4067. encounters a use of variable \code{x}, it can find its type in the
  4068. environment.
  4069. \begin{figure}[tbp]
  4070. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4071. (define type-check-R1-class
  4072. (class object%
  4073. (super-new)
  4074. (define/public (operator-types)
  4075. '((+ . ((Integer Integer) . Integer))
  4076. (- . ((Integer) . Integer))
  4077. (read . (() . Integer))))
  4078. (define/public (type-equal? t1 t2) (equal? t1 t2))
  4079. (define/public (check-type-equal? t1 t2 e)
  4080. (unless (type-equal? t1 t2)
  4081. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  4082. (define/public (type-check-op op arg-types e)
  4083. (match (dict-ref (operator-types) op)
  4084. [`(,param-types . ,return-type)
  4085. (for ([at arg-types] [pt param-types])
  4086. (check-type-equal? at pt e))
  4087. return-type]
  4088. [else (error 'type-check-op "unrecognized ~a" op)]))
  4089. (define/public (type-check-exp env)
  4090. (lambda (e)
  4091. (debug 'type-check-exp "R1" e)
  4092. (match e
  4093. [(Var x) (values (Var x) (dict-ref env x))]
  4094. [(Int n) (values (Int n) 'Integer)]
  4095. [(Let x e body)
  4096. (define-values (e^ Te) ((type-check-exp env) e))
  4097. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  4098. (values (Let x e^ b) Tb)]
  4099. [(Prim op es)
  4100. (define-values (new-es ts)
  4101. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  4102. (values (Prim op new-es) (type-check-op op ts e))]
  4103. [else (error 'type-check-exp "couldn't match" e)])))
  4104. (define/public (type-check-program e)
  4105. (match e
  4106. [(Program info body)
  4107. (define-values (body^ Tb) ((type-check-exp '()) body))
  4108. (check-type-equal? Tb 'Integer body)
  4109. (Program info body^)]
  4110. [else (error 'type-check-R1 "couldn't match ~a" e)]))
  4111. ))
  4112. (define (type-check-R1 p)
  4113. (send (new type-check-R1-class) type-check-program p))
  4114. \end{lstlisting}
  4115. \caption{Type checker for the $R_1$ fragment of $R_2$.}
  4116. \label{fig:type-check-R1}
  4117. \end{figure}
  4118. \begin{figure}[tbp]
  4119. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4120. (define type-check-R2-class
  4121. (class type-check-R1-class
  4122. (super-new)
  4123. (inherit check-type-equal?)
  4124. (define/override (operator-types)
  4125. (append '((- . ((Integer Integer) . Integer))
  4126. (and . ((Boolean Boolean) . Boolean))
  4127. (or . ((Boolean Boolean) . Boolean))
  4128. (< . ((Integer Integer) . Boolean))
  4129. (<= . ((Integer Integer) . Boolean))
  4130. (> . ((Integer Integer) . Boolean))
  4131. (>= . ((Integer Integer) . Boolean))
  4132. (not . ((Boolean) . Boolean))
  4133. )
  4134. (super operator-types)))
  4135. (define/override (type-check-exp env)
  4136. (lambda (e)
  4137. (match e
  4138. [(Bool b) (values (Bool b) 'Boolean)]
  4139. [(If cnd thn els)
  4140. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  4141. (define-values (thn^ Tt) ((type-check-exp env) thn))
  4142. (define-values (els^ Te) ((type-check-exp env) els))
  4143. (check-type-equal? Tc 'Boolean e)
  4144. (check-type-equal? Tt Te e)
  4145. (values (If cnd^ thn^ els^) Te)]
  4146. [(Prim 'eq? (list e1 e2))
  4147. (define-values (e1^ T1) ((type-check-exp env) e1))
  4148. (define-values (e2^ T2) ((type-check-exp env) e2))
  4149. (check-type-equal? T1 T2 e)
  4150. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  4151. [else ((super type-check-exp env) e)])))
  4152. ))
  4153. (define (type-check-R2 p)
  4154. (send (new type-check-R2-class) type-check-program p))
  4155. \end{lstlisting}
  4156. \caption{Type checker for the $R_2$ language.}
  4157. \label{fig:type-check-R2}
  4158. \end{figure}
  4159. Three auxiliary methods are used in the type checker. The method
  4160. \code{operator-types} defines a dictionary that maps the operator
  4161. names to their parameter and return types. The \code{type-equal?}
  4162. method determines whether two types are equal, which for now simply
  4163. dispatches to \code{equal?} (deep equality). The \code{type-check-op}
  4164. method looks up the operator in the \code{operator-types} dictionary
  4165. and then checks whether the argument types are equal to the parameter
  4166. types. The result is the return type of the operator.
  4167. \begin{exercise}\normalfont
  4168. Create 10 new example programs in $R_2$. Half of the example programs
  4169. should have a type error. For those programs, to signal that a type
  4170. error is expected, create an empty file with the same base name but
  4171. with file extension \code{.tyerr}. For example, if the test
  4172. \code{r2\_14.rkt} is expected to error, then create an empty file
  4173. named \code{r2\_14.tyerr}. The other half of the example programs
  4174. should not have type errors. Note that if the type checker does not
  4175. signal an error for a program, then interpreting that program should
  4176. not encounter an error.
  4177. \end{exercise}
  4178. \section{Shrink the $R_2$ Language}
  4179. \label{sec:shrink-r2}
  4180. The $R_2$ language includes several operators that are easily
  4181. expressible in terms of other operators. For example, subtraction is
  4182. expressible in terms of addition and negation.
  4183. \[
  4184. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  4185. \]
  4186. Several of the comparison operations are expressible in terms of
  4187. less-than and logical negation.
  4188. \[
  4189. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  4190. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  4191. \]
  4192. The \key{let} is needed in the above translation to ensure that
  4193. expression $e_1$ is evaluated before $e_2$.
  4194. By performing these translations near the front-end of the compiler,
  4195. the later passes of the compiler do not need to deal with these
  4196. constructs, making those passes shorter. On the other hand, sometimes
  4197. these translations make it more difficult to generate the most
  4198. efficient code with respect to the number of instructions. However,
  4199. these differences typically do not affect the number of accesses to
  4200. memory, which is the primary factor that determines execution time on
  4201. modern computer architectures.
  4202. \begin{exercise}\normalfont
  4203. Implement the pass \code{shrink} that removes subtraction,
  4204. \key{and}, \key{or}, \key{<=}, \key{>}, and \key{>=} from the language
  4205. by translating them to other constructs in $R_2$. Create tests to
  4206. make sure that the behavior of all of these constructs stays the
  4207. same after translation.
  4208. \end{exercise}
  4209. \section{The x86$_1$ Language}
  4210. \label{sec:x86-1}
  4211. \index{x86}
  4212. To implement the new logical operations, the comparison operations,
  4213. and the \key{if} expression, we need to delve further into the x86
  4214. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} define
  4215. the concrete and abstract syntax for a larger subset of x86 that
  4216. includes instructions for logical operations, comparisons, and
  4217. conditional jumps.
  4218. One small challenge is that x86 does not provide an instruction that
  4219. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  4220. However, the \code{xorq} instruction can be used to encode \code{not}.
  4221. The \key{xorq} instruction takes two arguments, performs a pairwise
  4222. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  4223. and writes the results into its second argument. Recall the truth
  4224. table for exclusive-or:
  4225. \begin{center}
  4226. \begin{tabular}{l|cc}
  4227. & 0 & 1 \\ \hline
  4228. 0 & 0 & 1 \\
  4229. 1 & 1 & 0
  4230. \end{tabular}
  4231. \end{center}
  4232. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  4233. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  4234. for the bit $1$, the result is the opposite of the second bit. Thus,
  4235. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  4236. the first argument:
  4237. \[
  4238. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  4239. \qquad\Rightarrow\qquad
  4240. \begin{array}{l}
  4241. \key{movq}~ \Arg\key{,} \Var\\
  4242. \key{xorq}~ \key{\$1,} \Var
  4243. \end{array}
  4244. \]
  4245. \begin{figure}[tp]
  4246. \fbox{
  4247. \begin{minipage}{0.96\textwidth}
  4248. \[
  4249. \begin{array}{lcl}
  4250. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  4251. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4252. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} } \mid \key{\%}\itm{bytereg}\\
  4253. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4254. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \mid
  4255. \key{subq} \; \Arg\key{,} \Arg \mid
  4256. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid } \\
  4257. && \gray{ \key{callq} \; \itm{label} \mid
  4258. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} } \\
  4259. && \gray{ \itm{label}\key{:}\; \Instr }
  4260. \mid \key{xorq}~\Arg\key{,}~\Arg
  4261. \mid \key{cmpq}~\Arg\key{,}~\Arg \mid \\
  4262. && \key{set}cc~\Arg
  4263. \mid \key{movzbq}~\Arg\key{,}~\Arg
  4264. \mid \key{j}cc~\itm{label}
  4265. \\
  4266. x86_1 &::= & \gray{ \key{.globl main} }\\
  4267. & & \gray{ \key{main:} \; \Instr\ldots }
  4268. \end{array}
  4269. \]
  4270. \end{minipage}
  4271. }
  4272. \caption{The concrete syntax of x86$_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-concrete}).}
  4273. \label{fig:x86-1-concrete}
  4274. \end{figure}
  4275. \begin{figure}[tp]
  4276. \fbox{
  4277. \begin{minipage}{0.96\textwidth}
  4278. \small
  4279. \[
  4280. \begin{array}{lcl}
  4281. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  4282. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4283. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}}
  4284. \mid \BYTEREG{\itm{bytereg}} \\
  4285. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4286. \Instr &::=& \gray{ \BININSTR{\code{'addq}}{\Arg}{\Arg}
  4287. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} } \\
  4288. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  4289. \mid \UNIINSTR{\code{'negq}}{\Arg} } \\
  4290. &\mid& \gray{ \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  4291. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  4292. &\mid& \BININSTR{\code{'xorq}}{\Arg}{\Arg}
  4293. \mid \BININSTR{\code{'cmpq}}{\Arg}{\Arg}\\
  4294. &\mid& \BININSTR{\code{'set}}{\itm{cc}}{\Arg}
  4295. \mid \BININSTR{\code{'movzbq}}{\Arg}{\Arg}\\
  4296. &\mid& \JMPIF{\itm{cc}}{\itm{label}} \\
  4297. \Block &::= & \gray{\BLOCK{\itm{info}}{\Instr\ldots}} \\
  4298. x86_1 &::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}}}
  4299. \end{array}
  4300. \]
  4301. \end{minipage}
  4302. }
  4303. \caption{The abstract syntax of x86$_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-ast}).}
  4304. \label{fig:x86-1}
  4305. \end{figure}
  4306. Next we consider the x86 instructions that are relevant for compiling
  4307. the comparison operations. The \key{cmpq} instruction compares its two
  4308. arguments to determine whether one argument is less than, equal, or
  4309. greater than the other argument. The \key{cmpq} instruction is unusual
  4310. regarding the order of its arguments and where the result is
  4311. placed. The argument order is backwards: if you want to test whether
  4312. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  4313. \key{cmpq} is placed in the special EFLAGS register. This register
  4314. cannot be accessed directly but it can be queried by a number of
  4315. instructions, including the \key{set} instruction. The \key{set}
  4316. instruction puts a \key{1} or \key{0} into its destination depending
  4317. on whether the comparison came out according to the condition code
  4318. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  4319. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  4320. The \key{set} instruction has an annoying quirk in that its
  4321. destination argument must be single byte register, such as \code{al}
  4322. (L for lower bits) or \code{ah} (H for higher bits), which are part of
  4323. the \code{rax} register. Thankfully, the \key{movzbq} instruction can
  4324. then be used to move from a single byte register to a normal 64-bit
  4325. register.
  4326. The x86 instruction for conditional jump are relevant to the
  4327. compilation of \key{if} expressions. The \key{JmpIf} instruction
  4328. updates the program counter to point to the instruction after the
  4329. indicated label depending on whether the result in the EFLAGS register
  4330. matches the condition code \itm{cc}, otherwise the \key{JmpIf}
  4331. instruction falls through to the next instruction. The abstract
  4332. syntax for \key{JmpIf} differs from the concrete syntax for x86 in
  4333. that it separates the instruction name from the condition code. For
  4334. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  4335. the \key{JmpIf} instruction relies on the EFLAGS register, it is
  4336. common for the \key{JmpIf} to be immediately preceded by a \key{cmpq}
  4337. instruction to set the EFLAGS register.
  4338. \section{The $C_1$ Intermediate Language}
  4339. \label{sec:c1}
  4340. As with $R_1$, we compile $R_2$ to a C-like intermediate language, but
  4341. we need to grow that intermediate language to handle the new features
  4342. in $R_2$: Booleans and conditional expressions.
  4343. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of
  4344. $C_1$ and Figure~\ref{fig:c1-syntax} defines the abstract syntax. In
  4345. particular, we add logical and comparison operators to the $\Exp$
  4346. non-terminal and the literals \key{\#t} and \key{\#f} to the $\Arg$
  4347. non-terminal. Regarding control flow, $C_1$ differs considerably from
  4348. $R_2$. Instead of \key{if} expressions, $C_1$ has \key{goto} and
  4349. conditional \key{goto} in the grammar for $\Tail$. This means that a
  4350. sequence of statements may now end with a \code{goto} or a conditional
  4351. \code{goto}. The conditional \code{goto} jumps to one of two labels
  4352. depending on the outcome of the comparison. In
  4353. Section~\ref{sec:explicate-control-r2} we discuss how to translate
  4354. from $R_2$ to $C_1$, bridging this gap between \key{if} expressions
  4355. and \key{goto}'s.
  4356. \begin{figure}[tbp]
  4357. \fbox{
  4358. \begin{minipage}{0.96\textwidth}
  4359. \small
  4360. \[
  4361. \begin{array}{lcl}
  4362. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  4363. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  4364. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  4365. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  4366. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  4367. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  4368. \mid \key{goto}~\itm{label}\key{;}\\
  4369. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  4370. C_1 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  4371. \end{array}
  4372. \]
  4373. \end{minipage}
  4374. }
  4375. \caption{The concrete syntax of the $C_1$ intermediate language.}
  4376. \label{fig:c1-concrete-syntax}
  4377. \end{figure}
  4378. \begin{figure}[tp]
  4379. \fbox{
  4380. \begin{minipage}{0.96\textwidth}
  4381. \small
  4382. \[
  4383. \begin{array}{lcl}
  4384. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  4385. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  4386. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  4387. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4388. &\mid& \UNIOP{\key{'not}}{\Atm}
  4389. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  4390. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  4391. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  4392. \mid \GOTO{\itm{label}} \\
  4393. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  4394. C_1 & ::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}\ldots}}}
  4395. \end{array}
  4396. \]
  4397. \end{minipage}
  4398. }
  4399. \caption{The abstract syntax of $C_1$, an extension of $C_0$
  4400. (Figure~\ref{fig:c0-syntax}).}
  4401. \label{fig:c1-syntax}
  4402. \end{figure}
  4403. \clearpage
  4404. \section{Remove Complex Operands}
  4405. \label{sec:remove-complex-opera-R2}
  4406. Add cases for \code{Bool} and \code{If} to the \code{rco-exp} and
  4407. \code{rco-atom} functions according to the definition of the output
  4408. language for this pass, $R_2^{\dagger}$, the administrative normal
  4409. form of $R_2$, which is defined in Figure~\ref{fig:r2-anf-syntax}. The
  4410. \code{Bool} form is an atomic expressions but \code{If} is not. All
  4411. three sub-expressions of an \code{If} are allowed to be complex
  4412. expressions in the output of \code{remove-complex-opera*}, but the
  4413. operands of \code{not} and the comparisons must be atoms. Regarding
  4414. the \code{If} form, it is particularly important to \textbf{not}
  4415. replace its condition with a temporary variable because that would
  4416. interfere with the generation of high-quality output in the
  4417. \code{explicate-control} pass.
  4418. \begin{figure}[tp]
  4419. \centering
  4420. \fbox{
  4421. \begin{minipage}{0.96\textwidth}
  4422. \[
  4423. \begin{array}{rcl}
  4424. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} } \mid \BOOL{\itm{bool}}\\
  4425. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  4426. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4427. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  4428. &\mid& \UNIOP{\key{'not}}{\Atm} \\
  4429. &\mid& \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4430. R^{\dagger}_2 &::=& \PROGRAM{\code{'()}}{\Exp}
  4431. \end{array}
  4432. \]
  4433. \end{minipage}
  4434. }
  4435. \caption{$R_2^{\dagger}$ is $R_2$ in administrative normal form (ANF).}
  4436. \label{fig:r2-anf-syntax}
  4437. \end{figure}
  4438. \section{Explicate Control}
  4439. \label{sec:explicate-control-r2}
  4440. Recall that the purpose of \code{explicate-control} is to make the
  4441. order of evaluation explicit in the syntax of the program. With the
  4442. addition of \key{if} in $R_2$ this get more interesting.
  4443. As a motivating example, consider the following program that has an
  4444. \key{if} expression nested in the predicate of another \key{if}.
  4445. % s1_41.rkt
  4446. \begin{center}
  4447. \begin{minipage}{0.96\textwidth}
  4448. \begin{lstlisting}
  4449. (let ([x (read)])
  4450. (let ([y (read)])
  4451. (if (if (< x 1) (eq? x 0) (eq? x 2))
  4452. (+ y 2)
  4453. (+ y 10))))
  4454. \end{lstlisting}
  4455. \end{minipage}
  4456. \end{center}
  4457. %
  4458. The naive way to compile \key{if} and the comparison would be to
  4459. handle each of them in isolation, regardless of their context. Each
  4460. comparison would be translated into a \key{cmpq} instruction followed
  4461. by a couple instructions to move the result from the EFLAGS register
  4462. into a general purpose register or stack location. Each \key{if} would
  4463. be translated into the combination of a \key{cmpq} and a conditional
  4464. jump. The generated code for the inner \key{if} in the above example
  4465. would be as follows.
  4466. \begin{center}
  4467. \begin{minipage}{0.96\textwidth}
  4468. \begin{lstlisting}
  4469. ...
  4470. cmpq $1, x ;; (< x 1)
  4471. setl %al
  4472. movzbq %al, tmp
  4473. cmpq $1, tmp ;; (if (< x 1) ...)
  4474. je then_branch_1
  4475. jmp else_branch_1
  4476. ...
  4477. \end{lstlisting}
  4478. \end{minipage}
  4479. \end{center}
  4480. However, if we take context into account we can do better and reduce
  4481. the use of \key{cmpq} and EFLAG-accessing instructions.
  4482. One idea is to try and reorganize the code at the level of $R_2$,
  4483. pushing the outer \key{if} inside the inner one. This would yield the
  4484. following code.
  4485. \begin{center}
  4486. \begin{minipage}{0.96\textwidth}
  4487. \begin{lstlisting}
  4488. (let ([x (read)])
  4489. (let ([y (read)])
  4490. (if (< x 1)
  4491. (if (eq? x 0)
  4492. (+ y 2)
  4493. (+ y 10))
  4494. (if (eq? x 2)
  4495. (+ y 2)
  4496. (+ y 10)))))
  4497. \end{lstlisting}
  4498. \end{minipage}
  4499. \end{center}
  4500. Unfortunately, this approach duplicates the two branches, and a
  4501. compiler must never duplicate code!
  4502. We need a way to perform the above transformation, but without
  4503. duplicating code. That is, we need a way for different parts of a
  4504. program to refer to the same piece of code, that is, to \emph{share}
  4505. code. At the level of x86 assembly this is straightforward because we
  4506. can label the code for each of the branches and insert jumps in all
  4507. the places that need to execute the branches. At the higher level of
  4508. our intermediate languages, we need to move away from abstract syntax
  4509. \emph{trees} and instead use \emph{graphs}. In particular, we use a
  4510. standard program representation called a \emph{control flow graph}
  4511. (CFG), due to Frances Elizabeth \citet{Allen:1970uq}.
  4512. \index{control-flow graph} Each vertex is a labeled sequence of code,
  4513. called a \emph{basic block}, and each edge represents a jump to
  4514. another block. The \key{Program} construct of $C_0$ and $C_1$ contains
  4515. a control flow graph represented as an alist mapping labels to basic
  4516. blocks. Each basic block is represented by the $\Tail$ non-terminal.
  4517. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  4518. \code{remove-complex-opera*} pass and then the
  4519. \code{explicate-control} pass on the example program. We walk through
  4520. the output program and then discuss the algorithm.
  4521. %
  4522. Following the order of evaluation in the output of
  4523. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  4524. and then the less-than-comparison to \code{1} in the predicate of the
  4525. inner \key{if}. In the output of \code{explicate-control}, in the
  4526. block labeled \code{start}, this becomes two assignment statements
  4527. followed by a conditional \key{goto} to label \code{block40} or
  4528. \code{block41}. The blocks associated with those labels contain the
  4529. translations of the code \code{(eq? x 0)} and \code{(eq? x 2)},
  4530. respectively. Regarding the block labeled with \code{block40}, we
  4531. start with the comparison to \code{0} and then have a conditional
  4532. goto, either to label \code{block38} or label \code{block39}, which
  4533. are the two branches of the outer \key{if}, i.e., \code{(+ y 2)} and
  4534. \code{(+ y 10)}. The story for the block labeled \code{block41} is
  4535. similar.
  4536. \begin{figure}[tbp]
  4537. \begin{tabular}{lll}
  4538. \begin{minipage}{0.4\textwidth}
  4539. % s1_41.rkt
  4540. \begin{lstlisting}
  4541. (let ([x (read)])
  4542. (let ([y (read)])
  4543. (if (if (< x 1)
  4544. (eq? x 0)
  4545. (eq? x 2))
  4546. (+ y 2)
  4547. (+ y 10))))
  4548. \end{lstlisting}
  4549. \hspace{40pt}$\Downarrow$
  4550. \begin{lstlisting}
  4551. (let ([x (read)])
  4552. (let ([y (read)])
  4553. (if (if (< x 1)
  4554. (eq? x 0)
  4555. (eq? x 2))
  4556. (+ y 2)
  4557. (+ y 10))))
  4558. \end{lstlisting}
  4559. \end{minipage}
  4560. &
  4561. $\Rightarrow$
  4562. &
  4563. \begin{minipage}{0.55\textwidth}
  4564. \begin{lstlisting}
  4565. start:
  4566. x = (read);
  4567. y = (read);
  4568. if (< x 1)
  4569. goto block40;
  4570. else
  4571. goto block41;
  4572. block40:
  4573. if (eq? x 0)
  4574. goto block38;
  4575. else
  4576. goto block39;
  4577. block41:
  4578. if (eq? x 2)
  4579. goto block38;
  4580. else
  4581. goto block39;
  4582. block38:
  4583. return (+ y 2);
  4584. block39:
  4585. return (+ y 10);
  4586. \end{lstlisting}
  4587. \end{minipage}
  4588. \end{tabular}
  4589. \caption{Translation from $R_2$ to $C_1$
  4590. via the \code{explicate-control}.}
  4591. \label{fig:explicate-control-s1-38}
  4592. \end{figure}
  4593. %% The nice thing about the output of \code{explicate-control} is that
  4594. %% there are no unnecessary comparisons and every comparison is part of a
  4595. %% conditional jump.
  4596. %% The down-side of this output is that it includes
  4597. %% trivial blocks, such as the blocks labeled \code{block92} through
  4598. %% \code{block95}, that only jump to another block. We discuss a solution
  4599. %% to this problem in Section~\ref{sec:opt-jumps}.
  4600. Recall that in Section~\ref{sec:explicate-control-r1} we implement
  4601. \code{explicate-control} for $R_1$ using two mutually recursive
  4602. functions, \code{explicate-tail} and \code{explicate-assign}. The
  4603. former function translates expressions in tail position whereas the
  4604. later function translates expressions on the right-hand-side of a
  4605. \key{let}. With the addition of \key{if} expression in $R_2$ we have a
  4606. new kind of context to deal with: the predicate position of the
  4607. \key{if}. We need another function, \code{explicate-pred}, that takes
  4608. an $R_2$ expression and two blocks for the then-branch and
  4609. else-branch. The output of \code{explicate-pred} is a block.
  4610. %
  4611. %% Note that the three explicate functions need to construct a
  4612. %% control-flow graph, which we recommend they do via updates to a global
  4613. %% variable.
  4614. %
  4615. In the following paragraphs we discuss specific cases in the
  4616. \code{explicate-pred} function as well as the additions to the
  4617. \code{explicate-tail} and \code{explicate-assign} functions.
  4618. The function \code{explicate-pred} will need a case for every
  4619. expression that can have type \code{Boolean}. We detail a few cases
  4620. here and leave the rest for the reader. The input to this function is
  4621. an expression and two blocks, $B_1$ and $B_2$, for the two branches of
  4622. the enclosing \key{if}, though some care will be needed regarding how
  4623. we represent the blocks. Suppose the expression is the Boolean
  4624. \code{\#t}. Then we can perform a kind of partial evaluation
  4625. \index{partial evaluation} and translate it to the ``then'' branch
  4626. $B_1$. Likewise, we translate \code{\#f} to the ``else`` branch $B_2$.
  4627. \[
  4628. \key{\#t} \quad\Rightarrow\quad B_1,
  4629. \qquad\qquad\qquad
  4630. \key{\#f} \quad\Rightarrow\quad B_2
  4631. \]
  4632. These two cases demonstrate that we sometimes discard one of the
  4633. blocks that are input to \code{explicate-pred}. We will need to
  4634. arrange for the blocks that we actually use to appear in the resulting
  4635. control-flow graph, but not the discarded blocks.
  4636. The case for \key{if} in \code{explicate-pred} is particularly
  4637. illuminating as it deals with the challenges that we discussed above
  4638. regarding the example of the nested \key{if} expressions. The
  4639. ``then'' and ``else'' branches of the current \key{if} inherit their
  4640. context from the current one, that is, predicate context. So we
  4641. recursively apply \code{explicate-pred} to the ``then'' and ``else''
  4642. branches. For both of those recursive calls, we shall pass the blocks
  4643. $B_1$ and $B_2$. Thus, $B_1$ may get used twice, once inside each
  4644. recursive call, and likewise for $B_2$. As discussed above, to avoid
  4645. duplicating code, we need to add these blocks to the control-flow
  4646. graph so that we can instead refer to them by name and execute them
  4647. with a \key{goto}. However, as we saw in the cases above for \key{\#t}
  4648. and \key{\#f}, the blocks $B_1$ or $B_2$ may not get used at all and
  4649. we don't want to prematurely add them to the control-flow graph if
  4650. they end up being discarded.
  4651. The solution to this conundrum is to use \emph{lazy evaluation} to
  4652. delay adding the blocks to the control-flow graph until the points
  4653. where we know they will be used~\citep{Friedman:1976aa}.\index{lazy
  4654. evaluation} Racket provides support for lazy evaluation with the
  4655. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  4656. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  4657. \index{delay} creates a \emph{promise}\index{promise} in which the
  4658. evaluation of the expressions is postponed. When \key{(force}
  4659. $p$\key{)}\index{force} is applied to a promise $p$ for the first
  4660. time, the expressions $e_1 \ldots e_n$ are evaluated and the result of
  4661. $e_n$ is cached in the promise and returned. If \code{force} is
  4662. applied again to the same promise, then the cached result is returned.
  4663. We use lazy evaluation for the input and output blocks of the
  4664. functions \code{explicate-pred} and \code{explicate-assign} and for
  4665. the output block of \code{explicate-tail}. So instead of taking and
  4666. returning blocks, they take and return promised blocks. Furthermore,
  4667. when we come to a situation in which we a block might be used more
  4668. than once, as in the case for \code{if} above, we transform the
  4669. promise into a new promise that will add the block to the control-flow
  4670. graph and return a \code{goto}. The following auxiliary function
  4671. accomplishes this task. It begins with \code{delay} to create a
  4672. promise. When forced, this promise will force the input block. If that
  4673. block is already a \code{goto} (because it was already added to the
  4674. control-flow graph), then we return that \code{goto}. Otherwise we add
  4675. the block to the control-flow graph with another auxiliary function
  4676. named \code{add-node} that returns the new label, and then return the
  4677. \code{goto}.
  4678. \begin{lstlisting}
  4679. (define (block->goto block)
  4680. (delay
  4681. (define b (force block))
  4682. (match b
  4683. [(Goto label) (Goto label)]
  4684. [else (Goto (add-node b))]
  4685. )))
  4686. \end{lstlisting}
  4687. Getting back to the case for \code{if} in \code{explicate-pred}, we
  4688. make the recursive calls to \code{explicate-pred} on the ``then'' and
  4689. ``else'' branches with the arguments \code{(block->goto} $B_1$\code{)}
  4690. and \code{(block->goto} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  4691. results from the two recursive calls. We complete the case for
  4692. \code{if} by recursively apply \code{explicate-pred} to the condition
  4693. of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  4694. the result $B_5$.
  4695. \[
  4696. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  4697. \quad\Rightarrow\quad
  4698. B_5
  4699. \]
  4700. Next, consider the case for a less-than comparison in
  4701. \code{explicate-pred}. We translate it to an \code{if} statement,
  4702. whose two branches are required to be \code{goto}'s. So we apply
  4703. \code{block->goto} to $B_1$ and $B_2$ to obtain two promised goto's,
  4704. which we can \code{force} to obtain the two actual goto's $G_1$ and
  4705. $G_2$. The translation of the less-than comparison is as follows.
  4706. \[
  4707. (\key{<}~e_1~e_2) \quad\Rightarrow\quad
  4708. \begin{array}{l}
  4709. \key{if}~(\key{<}~e_1~e_2) \; G_1\\
  4710. \key{else} \; G_2
  4711. \end{array}
  4712. \]
  4713. The \code{explicate-tail} function needs to be updated to use lazy
  4714. evaluation and it needs an additional case for \key{if}. Each of the
  4715. cases that return an AST node need use \code{delay} to instead return
  4716. a promise of an AST node. Recall that \code{explicate-tail} has an
  4717. accumulator parameter that is a block, which now becomes a promise of
  4718. a block, which we refer to as $B_0$.
  4719. In the case for \code{if} in \code{explicate-tail}, the two branches
  4720. inherit the current context, so they are in tail position. Thus, the
  4721. recursive calls on the ``then'' and ``else'' branch should be calls to
  4722. \code{explicate-tail}.
  4723. %
  4724. We need to pass $B_0$ as the accumulator argument for both of these
  4725. recursive calls, but we need to be careful not to duplicate $B_0$.
  4726. Thus, we first apply \code{block->goto} to $B_0$ so that it gets added
  4727. to the control-flow graph and obtain a promised goto $G_0$.
  4728. %
  4729. Let $B_1$ be the result of \code{explicate-tail} on the ``then''
  4730. branch and $G_0$ and let $B_2$ be the result of \code{explicate-tail}
  4731. on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  4732. \code{explicate-pred} to the condition of the \key{if}, $B_1$, and
  4733. $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  4734. \[
  4735. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  4736. \]
  4737. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  4738. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  4739. %% should not be confused with the labels for the blocks that appear in
  4740. %% the generated code. We initially construct unlabeled blocks; we only
  4741. %% attach labels to blocks when we add them to the control-flow graph, as
  4742. %% we see in the next case.
  4743. Next consider the case for \key{if} in the \code{explicate-assign}
  4744. function. The context of the \key{if} is an assignment to some
  4745. variable $x$ and then the control continues to some promised block
  4746. $B_1$. The code that we generate for both the ``then'' and ``else''
  4747. branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  4748. apply \code{block->goto} to it and obtain a promised goto $G_1$. The
  4749. branches of the \key{if} inherit the current context, so they are in
  4750. assignment positions. Let $B_2$ be the result of applying
  4751. \code{explicate-assign} to the ``then'' branch, variable $x$, and
  4752. $G_1$. Let $B_3$ be the result of applying \code{explicate-assign} to
  4753. the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  4754. the result of applying \code{explicate-pred} to the predicate
  4755. $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  4756. translates to the promise $B_4$.
  4757. \[
  4758. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  4759. \]
  4760. This completes the description of \code{explicate-control} for $R_2$.
  4761. The way in which the \code{shrink} pass transforms logical operations
  4762. such as \code{and} and \code{or} can impact the quality of code
  4763. generated by \code{explicate-control}. For example, consider the
  4764. following program.
  4765. % s1_21.rkt
  4766. \begin{lstlisting}
  4767. (if (and (eq? (read) 0) (eq? (read) 1))
  4768. 0
  4769. 42)
  4770. \end{lstlisting}
  4771. The \code{and} operation should transform into something that the
  4772. \code{explicate-pred} function can still analyze and descend through to
  4773. reach the underlying \code{eq?} conditions. Ideally, your
  4774. \code{explicate-control} pass should generate code similar to the
  4775. following for the above program.
  4776. \begin{center}
  4777. \begin{lstlisting}
  4778. start:
  4779. tmp1 = (read);
  4780. if (eq? tmp1 0)
  4781. goto block40;
  4782. else
  4783. goto block39;
  4784. block40:
  4785. tmp2 = (read);
  4786. if (eq? tmp2 1)
  4787. goto block38;
  4788. else
  4789. goto block39;
  4790. block38:
  4791. return 0;
  4792. block39:
  4793. return 42;
  4794. \end{lstlisting}
  4795. \end{center}
  4796. \begin{exercise}\normalfont
  4797. Implement the pass \code{explicate-control} by adding the cases for
  4798. \key{if} to the functions for tail and assignment contexts, and
  4799. implement \code{explicate-pred} for predicate contexts. Create test
  4800. cases that exercise all of the new cases in the code for this pass.
  4801. \end{exercise}
  4802. \section{Select Instructions}
  4803. \label{sec:select-r2}
  4804. \index{instruction selection}
  4805. Recall that the \code{select-instructions} pass lowers from our
  4806. $C$-like intermediate representation to the pseudo-x86 language, which
  4807. is suitable for conducting register allocation. The pass is
  4808. implemented using three auxiliary functions, one for each of the
  4809. non-terminals $\Atm$, $\Stmt$, and $\Tail$.
  4810. For $\Atm$, we have new cases for the Booleans. We take the usual
  4811. approach of encoding them as integers, with true as 1 and false as 0.
  4812. \[
  4813. \key{\#t} \Rightarrow \key{1}
  4814. \qquad
  4815. \key{\#f} \Rightarrow \key{0}
  4816. \]
  4817. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  4818. be implemented in terms of \code{xorq} as we discussed at the
  4819. beginning of this section. Given an assignment
  4820. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  4821. if the left-hand side $\itm{var}$ is
  4822. the same as $\Atm$, then just the \code{xorq} suffices.
  4823. \[
  4824. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  4825. \quad\Rightarrow\quad
  4826. \key{xorq}~\key{\$}1\key{,}~\Var
  4827. \]
  4828. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  4829. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  4830. x86. Then we have
  4831. \[
  4832. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  4833. \quad\Rightarrow\quad
  4834. \begin{array}{l}
  4835. \key{movq}~\Arg\key{,}~\Var\\
  4836. \key{xorq}~\key{\$}1\key{,}~\Var
  4837. \end{array}
  4838. \]
  4839. Next consider the cases for \code{eq?} and less-than comparison.
  4840. Translating these operations to x86 is slightly involved due to the
  4841. unusual nature of the \key{cmpq} instruction discussed above. We
  4842. recommend translating an assignment from \code{eq?} into the following
  4843. sequence of three instructions. \\
  4844. \begin{tabular}{lll}
  4845. \begin{minipage}{0.4\textwidth}
  4846. \begin{lstlisting}
  4847. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  4848. \end{lstlisting}
  4849. \end{minipage}
  4850. &
  4851. $\Rightarrow$
  4852. &
  4853. \begin{minipage}{0.4\textwidth}
  4854. \begin{lstlisting}
  4855. cmpq |$\Arg_2$|, |$\Arg_1$|
  4856. sete %al
  4857. movzbq %al, |$\Var$|
  4858. \end{lstlisting}
  4859. \end{minipage}
  4860. \end{tabular} \\
  4861. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  4862. and conditional \key{goto}. Both are straightforward to handle. A
  4863. \key{goto} becomes a jump instruction.
  4864. \[
  4865. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  4866. \]
  4867. A conditional \key{goto} becomes a compare instruction followed
  4868. by a conditional jump (for ``then'') and the fall-through is
  4869. to a regular jump (for ``else'').\\
  4870. \begin{tabular}{lll}
  4871. \begin{minipage}{0.4\textwidth}
  4872. \begin{lstlisting}
  4873. if (eq? |$\Atm_1$| |$\Atm_2$|)
  4874. goto |$\ell_1$|;
  4875. else
  4876. goto |$\ell_2$|;
  4877. \end{lstlisting}
  4878. \end{minipage}
  4879. &
  4880. $\Rightarrow$
  4881. &
  4882. \begin{minipage}{0.4\textwidth}
  4883. \begin{lstlisting}
  4884. cmpq |$\Arg_2$|, |$\Arg_1$|
  4885. je |$\ell_1$|
  4886. jmp |$\ell_2$|
  4887. \end{lstlisting}
  4888. \end{minipage}
  4889. \end{tabular} \\
  4890. \begin{exercise}\normalfont
  4891. Expand your \code{select-instructions} pass to handle the new features
  4892. of the $R_2$ language. Test the pass on all the examples you have
  4893. created and make sure that you have some test programs that use the
  4894. \code{eq?} and \code{<} operators, creating some if necessary. Test
  4895. the output using the \code{interp-x86} interpreter
  4896. (Appendix~\ref{appendix:interp}).
  4897. \end{exercise}
  4898. \section{Register Allocation}
  4899. \label{sec:register-allocation-r2}
  4900. \index{register allocation}
  4901. The changes required for $R_2$ affect liveness analysis, building the
  4902. interference graph, and assigning homes, but the graph coloring
  4903. algorithm itself does not change.
  4904. \subsection{Liveness Analysis}
  4905. \label{sec:liveness-analysis-r2}
  4906. \index{liveness analysis}
  4907. Recall that for $R_1$ we implemented liveness analysis for a single
  4908. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  4909. addition of \key{if} expressions to $R_2$, \code{explicate-control}
  4910. produces many basic blocks arranged in a control-flow graph. We
  4911. recommend that you create a new auxiliary function named
  4912. \code{uncover-live-CFG} that applies liveness analysis to a
  4913. control-flow graph.
  4914. The first question we need to consider is: what order should we
  4915. process the basic blocks in the control-flow graph? To perform
  4916. liveness analysis on a basic block, we need to know its live-after
  4917. set. If a basic block has no successor blocks (i.e. no out-edges in
  4918. the control flow graph), then it has an empty live-after set and we
  4919. can immediately apply liveness analysis to it. If a basic block has
  4920. some successors, then we need to complete liveness analysis on those
  4921. blocks first. Thankfully, the control flow graph does not contain any
  4922. cycles because $R_2$ does not include loops. (In
  4923. Chapter~\ref{ch:loop} we add loops and study how to handle cycles in
  4924. the control-flow graph.)
  4925. %
  4926. Returning to the question of what order should we process the basic
  4927. blocks, the answer is reverse topological order. We recommend using
  4928. the \code{tsort} (topological sort) and \code{transpose} functions of
  4929. the Racket \code{graph} package to obtain this ordering.
  4930. \index{topological order}
  4931. \index{topological sort}
  4932. The next question is how to analyze the jump instructions. In
  4933. Section~\ref{sec:liveness-analysis-r1} we recommended that you
  4934. maintain an alist named \code{label->live} that maps each label to the
  4935. set of live locations at the beginning of the associated block. Now
  4936. that we have many basic blocks, the alist needs to be extended as we
  4937. process the blocks. In particular, after performing liveness analysis
  4938. on a block, we can take the live-before set for its first instruction
  4939. and associate that with the block's label in the alist.
  4940. %
  4941. As discussed in Section~\ref{sec:liveness-analysis-r1}, the
  4942. live-before set for a $\JMP{\itm{label}}$ instruction is given by the
  4943. mapping for $\itm{label}$ in \code{label->live}.
  4944. Now for $x86_1$ we also have the conditional jump
  4945. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. This one is
  4946. particularly interesting because during compilation we do not know, in
  4947. general, which way a conditional jump will go, so we do not know
  4948. whether to use the live-before set for the following instruction or
  4949. the live-before set for $\itm{label}$. The solution to this challenge
  4950. is based on the observation that there is no harm to the correctness
  4951. of the compiler if we classify more locations as live than the ones
  4952. that are truly live during a particular execution of the
  4953. instruction. Thus, we can take the union of the live-before sets from
  4954. the following instruction and from the mapping fro $\itm{label}$ in
  4955. \code{label->live}.
  4956. The helper functions for computing the variables in an instruction's
  4957. argument and for computing the variables read-from ($R$) or written-to
  4958. ($W$) by an instruction need to be updated to handle the new kinds of
  4959. arguments and instructions in x86$_1$.
  4960. \subsection{Build Interference}
  4961. \label{sec:build-interference-r2}
  4962. Many of the new instructions in x86$_1$ can be handled in the same way
  4963. as the instructions in x86$_0$. Thus, if your code was already quite
  4964. general, it will not need to be changed to handle the new
  4965. instructions. If you code is not general enough, I recommend that you
  4966. change your code to be more general. For example, you can factor out
  4967. the computing of the the read and write sets for each kind of
  4968. instruction into two auxiliary functions.
  4969. Note that the \key{movzbq} instruction requires some special care,
  4970. just like the \key{movq} instruction. See rule number 3 in
  4971. Section~\ref{sec:build-interference}.
  4972. %% \subsection{Assign Homes}
  4973. %% \label{sec:assign-homes-r2}
  4974. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  4975. %% to be updated to handle the \key{if} statement, simply by recursively
  4976. %% processing the child nodes. Hopefully your code already handles the
  4977. %% other new instructions, but if not, you can generalize your code.
  4978. \begin{exercise}\normalfont
  4979. Update the \code{register-allocation} pass so that it works for $R_2$
  4980. and test your compiler using your previously created programs on the
  4981. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4982. \end{exercise}
  4983. \section{Patch Instructions}
  4984. The second argument of the \key{cmpq} instruction must not be an
  4985. immediate value (such as an integer). So if you are comparing two
  4986. immediates, we recommend inserting a \key{movq} instruction to put the
  4987. second argument in \key{rax}. Also, recall that instructions may have
  4988. at most one memory reference.
  4989. %
  4990. The second argument of the \key{movzbq} must be a register.
  4991. %
  4992. There are no special restrictions on the x86 instructions \key{JmpIf}
  4993. and \key{Jmp}.
  4994. \begin{exercise}\normalfont
  4995. Update \code{patch-instructions} to handle the new x86 instructions.
  4996. Test your compiler using your previously created programs on the
  4997. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4998. \end{exercise}
  4999. \begin{figure}[tbp]
  5000. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5001. \node (R2) at (0,2) {\large $R_2$};
  5002. \node (R2-2) at (3,2) {\large $R_2$};
  5003. \node (R2-3) at (6,2) {\large $R_2$};
  5004. \node (R2-4) at (9,2) {\large $R_2$};
  5005. \node (R2-5) at (12,2) {\large $R_2$};
  5006. \node (C1-1) at (3,0) {\large $C_1$};
  5007. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_1$};
  5008. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_1$};
  5009. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}_1$};
  5010. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}_1$};
  5011. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}_1$};
  5012. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}_1$};
  5013. \path[->,bend left=15] (R2) edge [above] node {\ttfamily\footnotesize\color{red} type-check} (R2-2);
  5014. \path[->,bend left=15] (R2-2) edge [above] node {\ttfamily\footnotesize\color{red} shrink} (R2-3);
  5015. \path[->,bend left=15] (R2-3) edge [above] node {\ttfamily\footnotesize uniquify} (R2-4);
  5016. \path[->,bend left=15] (R2-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R2-5);
  5017. \path[->,bend left=15] (R2-5) edge [left] node {\ttfamily\footnotesize\color{red} explicate-control} (C1-1);
  5018. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize\color{red} select-instructions} (x86-2);
  5019. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  5020. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  5021. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  5022. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  5023. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86 } (x86-5);
  5024. \end{tikzpicture}
  5025. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  5026. \label{fig:R2-passes}
  5027. \end{figure}
  5028. Figure~\ref{fig:R2-passes} lists all the passes needed for the
  5029. compilation of $R_2$.
  5030. \section{An Example Translation}
  5031. Figure~\ref{fig:if-example-x86} shows a simple example program in
  5032. $R_2$ translated to x86, showing the results of
  5033. \code{explicate-control}, \code{select-instructions}, and the final
  5034. x86 assembly code.
  5035. \begin{figure}[tbp]
  5036. \begin{tabular}{lll}
  5037. \begin{minipage}{0.5\textwidth}
  5038. % s1_20.rkt
  5039. \begin{lstlisting}
  5040. (if (eq? (read) 1) 42 0)
  5041. \end{lstlisting}
  5042. $\Downarrow$
  5043. \begin{lstlisting}
  5044. start:
  5045. tmp7951 = (read);
  5046. if (eq? tmp7951 1) then
  5047. goto block7952;
  5048. else
  5049. goto block7953;
  5050. block7952:
  5051. return 42;
  5052. block7953:
  5053. return 0;
  5054. \end{lstlisting}
  5055. $\Downarrow$
  5056. \begin{lstlisting}
  5057. start:
  5058. callq read_int
  5059. movq %rax, tmp7951
  5060. cmpq $1, tmp7951
  5061. je block7952
  5062. jmp block7953
  5063. block7953:
  5064. movq $0, %rax
  5065. jmp conclusion
  5066. block7952:
  5067. movq $42, %rax
  5068. jmp conclusion
  5069. \end{lstlisting}
  5070. \end{minipage}
  5071. &
  5072. $\Rightarrow\qquad$
  5073. \begin{minipage}{0.4\textwidth}
  5074. \begin{lstlisting}
  5075. start:
  5076. callq read_int
  5077. movq %rax, %rcx
  5078. cmpq $1, %rcx
  5079. je block7952
  5080. jmp block7953
  5081. block7953:
  5082. movq $0, %rax
  5083. jmp conclusion
  5084. block7952:
  5085. movq $42, %rax
  5086. jmp conclusion
  5087. .globl main
  5088. main:
  5089. pushq %rbp
  5090. movq %rsp, %rbp
  5091. pushq %r13
  5092. pushq %r12
  5093. pushq %rbx
  5094. pushq %r14
  5095. subq $0, %rsp
  5096. jmp start
  5097. conclusion:
  5098. addq $0, %rsp
  5099. popq %r14
  5100. popq %rbx
  5101. popq %r12
  5102. popq %r13
  5103. popq %rbp
  5104. retq
  5105. \end{lstlisting}
  5106. \end{minipage}
  5107. \end{tabular}
  5108. \caption{Example compilation of an \key{if} expression to x86.}
  5109. \label{fig:if-example-x86}
  5110. \end{figure}
  5111. \section{Challenge: Remove Jumps}
  5112. \label{sec:opt-jumps}
  5113. %% Recall that in the example output of \code{explicate-control} in
  5114. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  5115. %% \code{block60} are trivial blocks, they do nothing but jump to another
  5116. %% block. The first goal of this challenge assignment is to remove those
  5117. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  5118. %% \code{explicate-control} on the left and shows the result of bypassing
  5119. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  5120. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  5121. %% \code{block55}. The optimized code on the right of
  5122. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  5123. %% \code{then} branch jumping directly to \code{block55}. The story is
  5124. %% similar for the \code{else} branch, as well as for the two branches in
  5125. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  5126. %% have been optimized in this way, there are no longer any jumps to
  5127. %% blocks \code{block57} through \code{block60}, so they can be removed.
  5128. %% \begin{figure}[tbp]
  5129. %% \begin{tabular}{lll}
  5130. %% \begin{minipage}{0.4\textwidth}
  5131. %% \begin{lstlisting}
  5132. %% block62:
  5133. %% tmp54 = (read);
  5134. %% if (eq? tmp54 2) then
  5135. %% goto block59;
  5136. %% else
  5137. %% goto block60;
  5138. %% block61:
  5139. %% tmp53 = (read);
  5140. %% if (eq? tmp53 0) then
  5141. %% goto block57;
  5142. %% else
  5143. %% goto block58;
  5144. %% block60:
  5145. %% goto block56;
  5146. %% block59:
  5147. %% goto block55;
  5148. %% block58:
  5149. %% goto block56;
  5150. %% block57:
  5151. %% goto block55;
  5152. %% block56:
  5153. %% return (+ 700 77);
  5154. %% block55:
  5155. %% return (+ 10 32);
  5156. %% start:
  5157. %% tmp52 = (read);
  5158. %% if (eq? tmp52 1) then
  5159. %% goto block61;
  5160. %% else
  5161. %% goto block62;
  5162. %% \end{lstlisting}
  5163. %% \end{minipage}
  5164. %% &
  5165. %% $\Rightarrow$
  5166. %% &
  5167. %% \begin{minipage}{0.55\textwidth}
  5168. %% \begin{lstlisting}
  5169. %% block62:
  5170. %% tmp54 = (read);
  5171. %% if (eq? tmp54 2) then
  5172. %% goto block55;
  5173. %% else
  5174. %% goto block56;
  5175. %% block61:
  5176. %% tmp53 = (read);
  5177. %% if (eq? tmp53 0) then
  5178. %% goto block55;
  5179. %% else
  5180. %% goto block56;
  5181. %% block56:
  5182. %% return (+ 700 77);
  5183. %% block55:
  5184. %% return (+ 10 32);
  5185. %% start:
  5186. %% tmp52 = (read);
  5187. %% if (eq? tmp52 1) then
  5188. %% goto block61;
  5189. %% else
  5190. %% goto block62;
  5191. %% \end{lstlisting}
  5192. %% \end{minipage}
  5193. %% \end{tabular}
  5194. %% \caption{Optimize jumps by removing trivial blocks.}
  5195. %% \label{fig:optimize-jumps}
  5196. %% \end{figure}
  5197. %% The name of this pass is \code{optimize-jumps}. We recommend
  5198. %% implementing this pass in two phases. The first phrase builds a hash
  5199. %% table that maps labels to possibly improved labels. The second phase
  5200. %% changes the target of each \code{goto} to use the improved label. If
  5201. %% the label is for a trivial block, then the hash table should map the
  5202. %% label to the first non-trivial block that can be reached from this
  5203. %% label by jumping through trivial blocks. If the label is for a
  5204. %% non-trivial block, then the hash table should map the label to itself;
  5205. %% we do not want to change jumps to non-trivial blocks.
  5206. %% The first phase can be accomplished by constructing an empty hash
  5207. %% table, call it \code{short-cut}, and then iterating over the control
  5208. %% flow graph. Each time you encouter a block that is just a \code{goto},
  5209. %% then update the hash table, mapping the block's source to the target
  5210. %% of the \code{goto}. Also, the hash table may already have mapped some
  5211. %% labels to the block's source, to you must iterate through the hash
  5212. %% table and update all of those so that they instead map to the target
  5213. %% of the \code{goto}.
  5214. %% For the second phase, we recommend iterating through the $\Tail$ of
  5215. %% each block in the program, updating the target of every \code{goto}
  5216. %% according to the mapping in \code{short-cut}.
  5217. %% \begin{exercise}\normalfont
  5218. %% Implement the \code{optimize-jumps} pass as a transformation from
  5219. %% $C_1$ to $C_1$, coming after the \code{explicate-control} pass.
  5220. %% Check that \code{optimize-jumps} removes trivial blocks in a few
  5221. %% example programs. Then check that your compiler still passes all of
  5222. %% your tests.
  5223. %% \end{exercise}
  5224. There is an opportunity for optimizing jumps that is apparent in the
  5225. example of Figure~\ref{fig:if-example-x86}. The \code{start} block end
  5226. with a jump to \code{block7953} and there are no other jumps to
  5227. \code{block7953} in the rest of the program. In this situation we can
  5228. avoid the runtime overhead of this jump by merging \code{block7953}
  5229. into the preceding block, in this case the \code{start} block.
  5230. Figure~\ref{fig:remove-jumps} shows the output of
  5231. \code{select-instructions} on the left and the result of this
  5232. optimization on the right.
  5233. \begin{figure}[tbp]
  5234. \begin{tabular}{lll}
  5235. \begin{minipage}{0.5\textwidth}
  5236. % s1_20.rkt
  5237. \begin{lstlisting}
  5238. start:
  5239. callq read_int
  5240. movq %rax, tmp7951
  5241. cmpq $1, tmp7951
  5242. je block7952
  5243. jmp block7953
  5244. block7953:
  5245. movq $0, %rax
  5246. jmp conclusion
  5247. block7952:
  5248. movq $42, %rax
  5249. jmp conclusion
  5250. \end{lstlisting}
  5251. \end{minipage}
  5252. &
  5253. $\Rightarrow\qquad$
  5254. \begin{minipage}{0.4\textwidth}
  5255. \begin{lstlisting}
  5256. start:
  5257. callq read_int
  5258. movq %rax, tmp7951
  5259. cmpq $1, tmp7951
  5260. je block7952
  5261. movq $0, %rax
  5262. jmp conclusion
  5263. block7952:
  5264. movq $42, %rax
  5265. jmp conclusion
  5266. \end{lstlisting}
  5267. \end{minipage}
  5268. \end{tabular}
  5269. \caption{Merging basic blocks by removing unnecessary jumps.}
  5270. \label{fig:remove-jumps}
  5271. \end{figure}
  5272. \begin{exercise}\normalfont
  5273. Implement a pass named \code{remove-jumps} that merges basic blocks
  5274. into their preceding basic block, when there is only one preceding
  5275. block. The pass should translate from pseudo $x86_1$ to pseudo
  5276. $x86_1$ and it should come immediately after
  5277. \code{select-instructions}. Check that \code{remove-jumps}
  5278. accomplishes the goal of merging basic blocks on several test
  5279. programs and check that your compiler passes all of your tests.
  5280. \end{exercise}
  5281. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5282. \chapter{Tuples and Garbage Collection}
  5283. \label{ch:tuples}
  5284. \index{tuple}
  5285. \index{vector}
  5286. \margincomment{\scriptsize To do: challenge assignments: mark-and-sweep,
  5287. add simple structures. \\ --Jeremy}
  5288. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  5289. things to discuss in this chapter. \\ --Jeremy}
  5290. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  5291. all the IR grammars are spelled out! \\ --Jeremy}
  5292. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  5293. but keep type annotations on vector creation and local variables, function
  5294. parameters, etc. \\ --Jeremy}
  5295. \margincomment{\scriptsize Be more explicit about how to deal with
  5296. the root stack. \\ --Jeremy}
  5297. In this chapter we study the implementation of mutable tuples (called
  5298. ``vectors'' in Racket). This language feature is the first to use the
  5299. computer's \emph{heap}\index{heap} because the lifetime of a Racket tuple is
  5300. indefinite, that is, a tuple lives forever from the programmer's
  5301. viewpoint. Of course, from an implementer's viewpoint, it is important
  5302. to reclaim the space associated with a tuple when it is no longer
  5303. needed, which is why we also study \emph{garbage collection}
  5304. \emph{garbage collection}
  5305. techniques in this chapter.
  5306. Section~\ref{sec:r3} introduces the $R_3$ language including its
  5307. interpreter and type checker. The $R_3$ language extends the $R_2$
  5308. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  5309. \code{void} value. The reason for including the later is that the
  5310. \code{vector-set!} operation returns a value of type
  5311. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  5312. called the \code{Unit} type in the programming languages
  5313. literature. Racket's \code{Void} type is inhabited by a single value
  5314. \code{void} which corresponds to \code{unit} or \code{()} in the
  5315. literature~\citep{Pierce:2002hj}.}.
  5316. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  5317. copying live objects back and forth between two halves of the
  5318. heap. The garbage collector requires coordination with the compiler so
  5319. that it can see all of the \emph{root} pointers, that is, pointers in
  5320. registers or on the procedure call stack.
  5321. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  5322. discuss all the necessary changes and additions to the compiler
  5323. passes, including a new compiler pass named \code{expose-allocation}.
  5324. \section{The $R_3$ Language}
  5325. \label{sec:r3}
  5326. Figure~\ref{fig:r3-concrete-syntax} defines the concrete syntax for
  5327. $R_3$ and Figure~\ref{fig:r3-syntax} defines the abstract syntax. The
  5328. $R_3$ language includes three new forms: \code{vector} for creating a
  5329. tuple, \code{vector-ref} for reading an element of a tuple, and
  5330. \code{vector-set!} for writing to an element of a tuple. The program
  5331. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  5332. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  5333. the 3-tuple, demonstrating that tuples are first-class values. The
  5334. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  5335. of the \key{if} is taken. The element at index $0$ of \code{t} is
  5336. \code{40}, to which we add \code{2}, the element at index $0$ of the
  5337. 1-tuple. So the result of the program is \code{42}.
  5338. \begin{figure}[tbp]
  5339. \centering
  5340. \fbox{
  5341. \begin{minipage}{0.96\textwidth}
  5342. \[
  5343. \begin{array}{lcl}
  5344. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  5345. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}\\
  5346. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  5347. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  5348. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5349. \mid (\key{and}\;\Exp\;\Exp)
  5350. \mid (\key{or}\;\Exp\;\Exp)
  5351. \mid (\key{not}\;\Exp) } \\
  5352. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  5353. \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  5354. &\mid& (\key{vector}\;\Exp\ldots)
  5355. \mid (\key{vector-ref}\;\Exp\;\Int) \\
  5356. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)
  5357. \mid (\key{vector-length}\;\Exp) \\
  5358. &\mid& (\key{void}) \mid (\key{has-type}~\Exp~\Type)\\
  5359. R_3 &::=& \Exp
  5360. \end{array}
  5361. \]
  5362. \end{minipage}
  5363. }
  5364. \caption{The concrete syntax of $R_3$, extending $R_2$
  5365. (Figure~\ref{fig:r2-concrete-syntax}).}
  5366. \label{fig:r3-concrete-syntax}
  5367. \end{figure}
  5368. \begin{figure}[tbp]
  5369. \begin{lstlisting}
  5370. (let ([t (vector 40 #t (vector 2))])
  5371. (if (vector-ref t 1)
  5372. (+ (vector-ref t 0)
  5373. (vector-ref (vector-ref t 2) 0))
  5374. 44))
  5375. \end{lstlisting}
  5376. \caption{Example program that creates tuples and reads from them.}
  5377. \label{fig:vector-eg}
  5378. \end{figure}
  5379. \begin{figure}[tp]
  5380. \centering
  5381. \fbox{
  5382. \begin{minipage}{0.96\textwidth}
  5383. \[
  5384. \begin{array}{lcl}
  5385. \itm{op} &::=& \ldots
  5386. \mid \code{vector} \mid \code{vector-ref} \mid \code{vector-set!}
  5387. \mid \code{vector-length} \\
  5388. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  5389. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots}
  5390. \mid \BOOL{\itm{bool}}
  5391. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  5392. &\mid& \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP \\
  5393. R_3 &::=& \PROGRAM{\key{'()}}{\Exp}
  5394. \end{array}
  5395. \]
  5396. \end{minipage}
  5397. }
  5398. \caption{The abstract syntax of $R_3$.}
  5399. \label{fig:r3-syntax}
  5400. \end{figure}
  5401. \index{allocate}
  5402. \index{heap allocate}
  5403. Tuples are our first encounter with heap-allocated data, which raises
  5404. several interesting issues. First, variable binding performs a
  5405. shallow-copy when dealing with tuples, which means that different
  5406. variables can refer to the same tuple, that is, different variables
  5407. can be \emph{aliases} for the same entity. Consider the following
  5408. example in which both \code{t1} and \code{t2} refer to the same tuple.
  5409. Thus, the mutation through \code{t2} is visible when referencing the
  5410. tuple from \code{t1}, so the result of this program is \code{42}.
  5411. \index{alias}\index{mutation}
  5412. \begin{center}
  5413. \begin{minipage}{0.96\textwidth}
  5414. \begin{lstlisting}
  5415. (let ([t1 (vector 3 7)])
  5416. (let ([t2 t1])
  5417. (let ([_ (vector-set! t2 0 42)])
  5418. (vector-ref t1 0))))
  5419. \end{lstlisting}
  5420. \end{minipage}
  5421. \end{center}
  5422. The next issue concerns the lifetime of tuples. Of course, they are
  5423. created by the \code{vector} form, but when does their lifetime end?
  5424. Notice that $R_3$ does not include an operation for deleting
  5425. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  5426. of static scoping. For example, the following program returns
  5427. \code{42} even though the variable \code{w} goes out of scope prior to
  5428. the \code{vector-ref} that reads from the vector it was bound to.
  5429. \begin{center}
  5430. \begin{minipage}{0.96\textwidth}
  5431. \begin{lstlisting}
  5432. (let ([v (vector (vector 44))])
  5433. (let ([x (let ([w (vector 42)])
  5434. (let ([_ (vector-set! v 0 w)])
  5435. 0))])
  5436. (+ x (vector-ref (vector-ref v 0) 0))))
  5437. \end{lstlisting}
  5438. \end{minipage}
  5439. \end{center}
  5440. From the perspective of programmer-observable behavior, tuples live
  5441. forever. Of course, if they really lived forever, then many programs
  5442. would run out of memory.\footnote{The $R_3$ language does not have
  5443. looping or recursive functions, so it is nigh impossible to write a
  5444. program in $R_3$ that will run out of memory. However, we add
  5445. recursive functions in the next Chapter!} A Racket implementation
  5446. must therefore perform automatic garbage collection.
  5447. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  5448. $R_3$ language. We define the \code{vector}, \code{vector-length},
  5449. \code{vector-ref}, and \code{vector-set!} operations for $R_3$ in
  5450. terms of the corresponding operations in Racket. One subtle point is
  5451. that the \code{vector-set!} operation returns the \code{\#<void>}
  5452. value. The \code{\#<void>} value can be passed around just like other
  5453. values inside an $R_3$ program and a \code{\#<void>} value can be
  5454. compared for equality with another \code{\#<void>} value. However,
  5455. there are no other operations specific to the the \code{\#<void>}
  5456. value in $R_3$. In contrast, Racket defines the \code{void?} predicate
  5457. that returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  5458. otherwise.
  5459. \begin{figure}[tbp]
  5460. \begin{lstlisting}
  5461. (define interp-R3-class
  5462. (class interp-R2-class
  5463. (super-new)
  5464. (define/override (interp-op op)
  5465. (match op
  5466. ['eq? (lambda (v1 v2)
  5467. (cond [(or (and (fixnum? v1) (fixnum? v2))
  5468. (and (boolean? v1) (boolean? v2))
  5469. (and (vector? v1) (vector? v2))
  5470. (and (void? v1) (void? v2)))
  5471. (eq? v1 v2)]))]
  5472. ['vector vector]
  5473. ['vector-length vector-length]
  5474. ['vector-ref vector-ref]
  5475. ['vector-set! vector-set!]
  5476. [else (super interp-op op)]
  5477. ))
  5478. (define/override ((interp-exp env) e)
  5479. (define recur (interp-exp env))
  5480. (match e
  5481. [(HasType e t) (recur e)]
  5482. [(Void) (void)]
  5483. [else ((super interp-exp env) e)]
  5484. ))
  5485. ))
  5486. (define (interp-R3 p)
  5487. (send (new interp-R3-class) interp-program p))
  5488. \end{lstlisting}
  5489. \caption{Interpreter for the $R_3$ language.}
  5490. \label{fig:interp-R3}
  5491. \end{figure}
  5492. Figure~\ref{fig:type-check-R3} shows the type checker for $R_3$, which
  5493. deserves some explanation. When allocating a vector, we need to know
  5494. which elements of the vector are pointers (i.e. are also vectors). We
  5495. can obtain this information during type checking. The type checker in
  5496. Figure~\ref{fig:type-check-R3} not only computes the type of an
  5497. expression, it also wraps every \key{vector} creation with the form
  5498. $(\key{HasType}~e~T)$, where $T$ is the vector's type.
  5499. %
  5500. To create the s-expression for the \code{Vector} type in
  5501. Figure~\ref{fig:type-check-R3}, we use the
  5502. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  5503. operator} \code{,@} to insert the list \code{t*} without its usual
  5504. start and end parentheses. \index{unquote-slicing}
  5505. \begin{figure}[tp]
  5506. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5507. (define type-check-R3-class
  5508. (class type-check-R2-class
  5509. (super-new)
  5510. (inherit check-type-equal?)
  5511. (define/override (type-check-exp env)
  5512. (lambda (e)
  5513. (define recur (type-check-exp env))
  5514. (match e
  5515. [(Void) (values (Void) 'Void)]
  5516. [(Prim 'vector es)
  5517. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  5518. (define t `(Vector ,@t*))
  5519. (values (HasType (Prim 'vector e*) t) t)]
  5520. [(Prim 'vector-ref (list e1 (Int i)))
  5521. (define-values (e1^ t) (recur e1))
  5522. (match t
  5523. [`(Vector ,ts ...)
  5524. (unless (and (0 . <= . i) (i . < . (length ts)))
  5525. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  5526. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  5527. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  5528. [(Prim 'vector-set! (list e1 (Int i) arg) )
  5529. (define-values (e-vec t-vec) (recur e1))
  5530. (define-values (e-arg^ t-arg) (recur arg))
  5531. (match t-vec
  5532. [`(Vector ,ts ...)
  5533. (unless (and (0 . <= . i) (i . < . (length ts)))
  5534. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  5535. (check-type-equal? (list-ref ts i) t-arg e)
  5536. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  5537. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  5538. [(Prim 'vector-length (list e))
  5539. (define-values (e^ t) (recur e))
  5540. (match t
  5541. [`(Vector ,ts ...)
  5542. (values (Prim 'vector-length (list e^)) 'Integer)]
  5543. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  5544. [(Prim 'eq? (list arg1 arg2))
  5545. (define-values (e1 t1) (recur arg1))
  5546. (define-values (e2 t2) (recur arg2))
  5547. (match* (t1 t2)
  5548. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  5549. [(other wise) (check-type-equal? t1 t2 e)])
  5550. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  5551. [(HasType (Prim 'vector es) t)
  5552. ((type-check-exp env) (Prim 'vector es))]
  5553. [(HasType e1 t)
  5554. (define-values (e1^ t^) (recur e1))
  5555. (check-type-equal? t t^ e)
  5556. (values (HasType e1^ t) t)]
  5557. [else ((super type-check-exp env) e)]
  5558. )))
  5559. ))
  5560. (define (type-check-R3 p)
  5561. (send (new type-check-R3-class) type-check-program p))
  5562. \end{lstlisting}
  5563. \caption{Type checker for the $R_3$ language.}
  5564. \label{fig:type-check-R3}
  5565. \end{figure}
  5566. \section{Garbage Collection}
  5567. \label{sec:GC}
  5568. Here we study a relatively simple algorithm for garbage collection
  5569. that is the basis of state-of-the-art garbage
  5570. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  5571. particular, we describe a two-space copying
  5572. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  5573. perform the
  5574. copy~\citep{Cheney:1970aa}.
  5575. \index{copying collector}
  5576. \index{two-space copying collector}
  5577. Figure~\ref{fig:copying-collector} gives a
  5578. coarse-grained depiction of what happens in a two-space collector,
  5579. showing two time steps, prior to garbage collection (on the top) and
  5580. after garbage collection (on the bottom). In a two-space collector,
  5581. the heap is divided into two parts named the FromSpace and the
  5582. ToSpace. Initially, all allocations go to the FromSpace until there is
  5583. not enough room for the next allocation request. At that point, the
  5584. garbage collector goes to work to make more room.
  5585. \index{ToSpace}
  5586. \index{FromSpace}
  5587. The garbage collector must be careful not to reclaim tuples that will
  5588. be used by the program in the future. Of course, it is impossible in
  5589. general to predict what a program will do, but we can over approximate
  5590. the will-be-used tuples by preserving all tuples that could be
  5591. accessed by \emph{any} program given the current computer state. A
  5592. program could access any tuple whose address is in a register or on
  5593. the procedure call stack. These addresses are called the \emph{root
  5594. set}\index{root set}. In addition, a program could access any tuple that is
  5595. transitively reachable from the root set. Thus, it is safe for the
  5596. garbage collector to reclaim the tuples that are not reachable in this
  5597. way.
  5598. So the goal of the garbage collector is twofold:
  5599. \begin{enumerate}
  5600. \item preserve all tuple that are reachable from the root set via a
  5601. path of pointers, that is, the \emph{live} tuples, and
  5602. \item reclaim the memory of everything else, that is, the
  5603. \emph{garbage}.
  5604. \end{enumerate}
  5605. A copying collector accomplishes this by copying all of the live
  5606. objects from the FromSpace into the ToSpace and then performs a slight
  5607. of hand, treating the ToSpace as the new FromSpace and the old
  5608. FromSpace as the new ToSpace. In the example of
  5609. Figure~\ref{fig:copying-collector}, there are three pointers in the
  5610. root set, one in a register and two on the stack. All of the live
  5611. objects have been copied to the ToSpace (the right-hand side of
  5612. Figure~\ref{fig:copying-collector}) in a way that preserves the
  5613. pointer relationships. For example, the pointer in the register still
  5614. points to a 2-tuple whose first element is a 3-tuple and whose second
  5615. element is a 2-tuple. There are four tuples that are not reachable
  5616. from the root set and therefore do not get copied into the ToSpace.
  5617. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  5618. created by a well-typed program in $R_3$ because it contains a
  5619. cycle. However, creating cycles will be possible once we get to $R_6$.
  5620. We design the garbage collector to deal with cycles to begin with so
  5621. we will not need to revisit this issue.
  5622. \begin{figure}[tbp]
  5623. \centering
  5624. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  5625. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  5626. \caption{A copying collector in action.}
  5627. \label{fig:copying-collector}
  5628. \end{figure}
  5629. There are many alternatives to copying collectors (and their bigger
  5630. siblings, the generational collectors) when its comes to garbage
  5631. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  5632. reference counting~\citep{Collins:1960aa}. The strengths of copying
  5633. collectors are that allocation is fast (just a comparison and pointer
  5634. increment), there is no fragmentation, cyclic garbage is collected,
  5635. and the time complexity of collection only depends on the amount of
  5636. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  5637. main disadvantages of a two-space copying collector is that it uses a
  5638. lot of space and takes a long time to perform the copy, though these
  5639. problems are ameliorated in generational collectors. Racket and
  5640. Scheme programs tend to allocate many small objects and generate a lot
  5641. of garbage, so copying and generational collectors are a good fit.
  5642. Garbage collection is an active research topic, especially concurrent
  5643. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  5644. developing new techniques and revisiting old
  5645. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  5646. meet every year at the International Symposium on Memory Management to
  5647. present these findings.
  5648. \subsection{Graph Copying via Cheney's Algorithm}
  5649. \label{sec:cheney}
  5650. \index{Cheney's algorithm}
  5651. Let us take a closer look at the copying of the live objects. The
  5652. allocated objects and pointers can be viewed as a graph and we need to
  5653. copy the part of the graph that is reachable from the root set. To
  5654. make sure we copy all of the reachable vertices in the graph, we need
  5655. an exhaustive graph traversal algorithm, such as depth-first search or
  5656. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  5657. such algorithms take into account the possibility of cycles by marking
  5658. which vertices have already been visited, so as to ensure termination
  5659. of the algorithm. These search algorithms also use a data structure
  5660. such as a stack or queue as a to-do list to keep track of the vertices
  5661. that need to be visited. We use breadth-first search and a trick
  5662. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  5663. and copying tuples into the ToSpace.
  5664. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  5665. copy progresses. The queue is represented by a chunk of contiguous
  5666. memory at the beginning of the ToSpace, using two pointers to track
  5667. the front and the back of the queue. The algorithm starts by copying
  5668. all tuples that are immediately reachable from the root set into the
  5669. ToSpace to form the initial queue. When we copy a tuple, we mark the
  5670. old tuple to indicate that it has been visited. We discuss how this
  5671. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  5672. pointers inside the copied tuples in the queue still point back to the
  5673. FromSpace. Once the initial queue has been created, the algorithm
  5674. enters a loop in which it repeatedly processes the tuple at the front
  5675. of the queue and pops it off the queue. To process a tuple, the
  5676. algorithm copies all the tuple that are directly reachable from it to
  5677. the ToSpace, placing them at the back of the queue. The algorithm then
  5678. updates the pointers in the popped tuple so they point to the newly
  5679. copied tuples.
  5680. \begin{figure}[tbp]
  5681. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  5682. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  5683. \label{fig:cheney}
  5684. \end{figure}
  5685. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  5686. tuple whose second element is $42$ to the back of the queue. The other
  5687. pointer goes to a tuple that has already been copied, so we do not
  5688. need to copy it again, but we do need to update the pointer to the new
  5689. location. This can be accomplished by storing a \emph{forwarding
  5690. pointer} to the new location in the old tuple, back when we initially
  5691. copied the tuple into the ToSpace. This completes one step of the
  5692. algorithm. The algorithm continues in this way until the front of the
  5693. queue is empty, that is, until the front catches up with the back.
  5694. \subsection{Data Representation}
  5695. \label{sec:data-rep-gc}
  5696. The garbage collector places some requirements on the data
  5697. representations used by our compiler. First, the garbage collector
  5698. needs to distinguish between pointers and other kinds of data. There
  5699. are several ways to accomplish this.
  5700. \begin{enumerate}
  5701. \item Attached a tag to each object that identifies what type of
  5702. object it is~\citep{McCarthy:1960dz}.
  5703. \item Store different types of objects in different
  5704. regions~\citep{Steele:1977ab}.
  5705. \item Use type information from the program to either generate
  5706. type-specific code for collecting or to generate tables that can
  5707. guide the
  5708. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  5709. \end{enumerate}
  5710. Dynamically typed languages, such as Lisp, need to tag objects
  5711. anyways, so option 1 is a natural choice for those languages.
  5712. However, $R_3$ is a statically typed language, so it would be
  5713. unfortunate to require tags on every object, especially small and
  5714. pervasive objects like integers and Booleans. Option 3 is the
  5715. best-performing choice for statically typed languages, but comes with
  5716. a relatively high implementation complexity. To keep this chapter
  5717. within a 2-week time budget, we recommend a combination of options 1
  5718. and 2, using separate strategies for the stack and the heap.
  5719. Regarding the stack, we recommend using a separate stack for pointers,
  5720. which we call a \emph{root stack}\index{root stack} (a.k.a. ``shadow
  5721. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  5722. is, when a local variable needs to be spilled and is of type
  5723. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  5724. stack instead of the normal procedure call stack. Furthermore, we
  5725. always spill vector-typed variables if they are live during a call to
  5726. the collector, thereby ensuring that no pointers are in registers
  5727. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  5728. example from Figure~\ref{fig:copying-collector} and contrasts it with
  5729. the data layout using a root stack. The root stack contains the two
  5730. pointers from the regular stack and also the pointer in the second
  5731. register.
  5732. \begin{figure}[tbp]
  5733. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  5734. \caption{Maintaining a root stack to facilitate garbage collection.}
  5735. \label{fig:shadow-stack}
  5736. \end{figure}
  5737. The problem of distinguishing between pointers and other kinds of data
  5738. also arises inside of each tuple on the heap. We solve this problem by
  5739. attaching a tag, an extra 64-bits, to each
  5740. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  5741. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  5742. that we have drawn the bits in a big-endian way, from right-to-left,
  5743. with bit location 0 (the least significant bit) on the far right,
  5744. which corresponds to the direction of the x86 shifting instructions
  5745. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  5746. is dedicated to specifying which elements of the tuple are pointers,
  5747. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  5748. indicates there is a pointer and a 0 bit indicates some other kind of
  5749. data. The pointer mask starts at bit location 7. We have limited
  5750. tuples to a maximum size of 50 elements, so we just need 50 bits for
  5751. the pointer mask. The tag also contains two other pieces of
  5752. information. The length of the tuple (number of elements) is stored in
  5753. bits location 1 through 6. Finally, the bit at location 0 indicates
  5754. whether the tuple has yet to be copied to the ToSpace. If the bit has
  5755. value 1, then this tuple has not yet been copied. If the bit has
  5756. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  5757. of a pointer are always zero anyways because our tuples are 8-byte
  5758. aligned.)
  5759. \begin{figure}[tbp]
  5760. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  5761. \caption{Representation of tuples in the heap.}
  5762. \label{fig:tuple-rep}
  5763. \end{figure}
  5764. \subsection{Implementation of the Garbage Collector}
  5765. \label{sec:organize-gz}
  5766. \index{prelude}
  5767. An implementation of the copying collector is provided in the
  5768. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  5769. interface to the garbage collector that is used by the compiler. The
  5770. \code{initialize} function creates the FromSpace, ToSpace, and root
  5771. stack and should be called in the prelude of the \code{main}
  5772. function. The arguments of \code{initialize} are the root stack size
  5773. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  5774. good choice for both. The \code{initialize} function puts the address
  5775. of the beginning of the FromSpace into the global variable
  5776. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  5777. the address that is 1-past the last element of the FromSpace. (We use
  5778. half-open intervals to represent chunks of
  5779. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  5780. points to the first element of the root stack.
  5781. As long as there is room left in the FromSpace, your generated code
  5782. can allocate tuples simply by moving the \code{free\_ptr} forward.
  5783. %
  5784. The amount of room left in FromSpace is the difference between the
  5785. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  5786. function should be called when there is not enough room left in the
  5787. FromSpace for the next allocation. The \code{collect} function takes
  5788. a pointer to the current top of the root stack (one past the last item
  5789. that was pushed) and the number of bytes that need to be
  5790. allocated. The \code{collect} function performs the copying collection
  5791. and leaves the heap in a state such that the next allocation will
  5792. succeed.
  5793. \begin{figure}[tbp]
  5794. \begin{lstlisting}
  5795. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  5796. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  5797. int64_t* free_ptr;
  5798. int64_t* fromspace_begin;
  5799. int64_t* fromspace_end;
  5800. int64_t** rootstack_begin;
  5801. \end{lstlisting}
  5802. \caption{The compiler's interface to the garbage collector.}
  5803. \label{fig:gc-header}
  5804. \end{figure}
  5805. %% \begin{exercise}
  5806. %% In the file \code{runtime.c} you will find the implementation of
  5807. %% \code{initialize} and a partial implementation of \code{collect}.
  5808. %% The \code{collect} function calls another function, \code{cheney},
  5809. %% to perform the actual copy, and that function is left to the reader
  5810. %% to implement. The following is the prototype for \code{cheney}.
  5811. %% \begin{lstlisting}
  5812. %% static void cheney(int64_t** rootstack_ptr);
  5813. %% \end{lstlisting}
  5814. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  5815. %% rootstack (which is an array of pointers). The \code{cheney} function
  5816. %% also communicates with \code{collect} through the global
  5817. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  5818. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  5819. %% the ToSpace:
  5820. %% \begin{lstlisting}
  5821. %% static int64_t* tospace_begin;
  5822. %% static int64_t* tospace_end;
  5823. %% \end{lstlisting}
  5824. %% The job of the \code{cheney} function is to copy all the live
  5825. %% objects (reachable from the root stack) into the ToSpace, update
  5826. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  5827. %% update the root stack so that it points to the objects in the
  5828. %% ToSpace, and finally to swap the global pointers for the FromSpace
  5829. %% and ToSpace.
  5830. %% \end{exercise}
  5831. %% \section{Compiler Passes}
  5832. %% \label{sec:code-generation-gc}
  5833. The introduction of garbage collection has a non-trivial impact on our
  5834. compiler passes. We introduce a new compiler pass named
  5835. \code{expose-allocation}. We make
  5836. significant changes to \code{select-instructions},
  5837. \code{build-interference}, \code{allocate-registers}, and
  5838. \code{print-x86} and make minor changes in several more passes. The
  5839. following program will serve as our running example. It creates two
  5840. tuples, one nested inside the other. Both tuples have length one. The
  5841. program accesses the element in the inner tuple tuple via two vector
  5842. references.
  5843. % tests/s2_17.rkt
  5844. \begin{lstlisting}
  5845. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  5846. \end{lstlisting}
  5847. \section{Shrink}
  5848. \label{sec:shrink-R3}
  5849. Recall that the \code{shrink} pass translates the primitives operators
  5850. into a smaller set of primitives. Because this pass comes after type
  5851. checking, but before the passes that require the type information in
  5852. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  5853. to wrap \code{HasType} around each AST node that it generates.
  5854. \section{Expose Allocation}
  5855. \label{sec:expose-allocation}
  5856. The pass \code{expose-allocation} lowers the \code{vector} creation
  5857. form into a conditional call to the collector followed by the
  5858. allocation. We choose to place the \code{expose-allocation} pass
  5859. before \code{remove-complex-opera*} because the code generated by
  5860. \code{expose-allocation} contains complex operands. We also place
  5861. \code{expose-allocation} before \code{explicate-control} because
  5862. \code{expose-allocation} introduces new variables using \code{let},
  5863. but \code{let} is gone after \code{explicate-control}.
  5864. The output of \code{expose-allocation} is a language $R'_3$ that
  5865. extends $R_3$ with the three new forms that we use in the translation
  5866. of the \code{vector} form.
  5867. \[
  5868. \begin{array}{lcl}
  5869. \Exp &::=& \cdots
  5870. \mid (\key{collect} \,\itm{int})
  5871. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  5872. \mid (\key{global-value} \,\itm{name})
  5873. \end{array}
  5874. \]
  5875. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  5876. $n$ bytes. It will become a call to the \code{collect} function in
  5877. \code{runtime.c} in \code{select-instructions}. The
  5878. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  5879. \index{allocate}
  5880. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  5881. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  5882. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  5883. a global variable, such as \code{free\_ptr}.
  5884. In the following, we show the transformation for the \code{vector}
  5885. form into 1) a sequence of let-bindings for the initializing
  5886. expressions, 2) a conditional call to \code{collect}, 3) a call to
  5887. \code{allocate}, and 4) the initialization of the vector. In the
  5888. following, \itm{len} refers to the length of the vector and
  5889. \itm{bytes} is how many total bytes need to be allocated for the
  5890. vector, which is 8 for the tag plus \itm{len} times 8.
  5891. \begin{lstlisting}
  5892. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  5893. |$\Longrightarrow$|
  5894. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  5895. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  5896. (global-value fromspace_end))
  5897. (void)
  5898. (collect |\itm{bytes}|))])
  5899. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  5900. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  5901. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  5902. |$v$|) ... )))) ...)
  5903. \end{lstlisting}
  5904. In the above, we suppressed all of the \code{has-type} forms in the
  5905. output for the sake of readability. The placement of the initializing
  5906. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  5907. sequence of \code{vector-set!} is important, as those expressions may
  5908. trigger garbage collection and we cannot have an allocated but
  5909. uninitialized tuple on the heap during a collection.
  5910. Figure~\ref{fig:expose-alloc-output} shows the output of the
  5911. \code{expose-allocation} pass on our running example.
  5912. \begin{figure}[tbp]
  5913. % tests/s2_17.rkt
  5914. \begin{lstlisting}
  5915. (vector-ref
  5916. (vector-ref
  5917. (let ([vecinit7976
  5918. (let ([vecinit7972 42])
  5919. (let ([collectret7974
  5920. (if (< (+ (global-value free_ptr) 16)
  5921. (global-value fromspace_end))
  5922. (void)
  5923. (collect 16)
  5924. )])
  5925. (let ([alloc7971 (allocate 1 (Vector Integer))])
  5926. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  5927. alloc7971)
  5928. )
  5929. )
  5930. )
  5931. ])
  5932. (let ([collectret7978
  5933. (if (< (+ (global-value free_ptr) 16)
  5934. (global-value fromspace_end))
  5935. (void)
  5936. (collect 16)
  5937. )])
  5938. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  5939. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  5940. alloc7975)
  5941. )
  5942. )
  5943. )
  5944. 0)
  5945. 0)
  5946. \end{lstlisting}
  5947. \caption{Output of the \code{expose-allocation} pass, minus
  5948. all of the \code{has-type} forms.}
  5949. \label{fig:expose-alloc-output}
  5950. \end{figure}
  5951. \section{Remove Complex Operands}
  5952. \label{sec:remove-complex-opera-R3}
  5953. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  5954. should all be treated as complex operands.
  5955. %% A new case for
  5956. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  5957. %% handled carefully to prevent the \code{Prim} node from being separated
  5958. %% from its enclosing \code{HasType}.
  5959. Figure~\ref{fig:r3-anf-syntax}
  5960. shows the grammar for the output language $R_3^{\dagger}$ of this
  5961. pass, which is $R_3$ in administrative normal form.
  5962. \begin{figure}[tp]
  5963. \centering
  5964. \fbox{
  5965. \begin{minipage}{0.96\textwidth}
  5966. \small
  5967. \[
  5968. \begin{array}{rcl}
  5969. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }
  5970. \mid \VOID{} \\
  5971. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  5972. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  5973. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  5974. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  5975. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  5976. &\mid& \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  5977. \mid \LP\key{GlobalValue}~\Var\RP\\
  5978. % &\mid& \LP\key{HasType}~\Exp~\Type\RP \\
  5979. R^{\dagger}_3 &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  5980. \end{array}
  5981. \]
  5982. \end{minipage}
  5983. }
  5984. \caption{$R_3^{\dagger}$ is $R_3$ in administrative normal form (ANF).}
  5985. \label{fig:r3-anf-syntax}
  5986. \end{figure}
  5987. \section{Explicate Control and the $C_2$ language}
  5988. \label{sec:explicate-control-r3}
  5989. \begin{figure}[tbp]
  5990. \fbox{
  5991. \begin{minipage}{0.96\textwidth}
  5992. \small
  5993. \[
  5994. \begin{array}{lcl}
  5995. \Atm &::=& \gray{ \Int \mid \Var \mid \itm{bool} } \\
  5996. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5997. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  5998. &\mid& \gray{ \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP } \\
  5999. &\mid& \LP \key{allocate}~\Int~\Type \RP \\
  6000. &\mid& (\key{vector-ref}\;\Atm\;\Int) \mid (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  6001. &\mid& \LP \key{global-value}~\Var \RP \mid \LP \key{void} \RP \\
  6002. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \mid \LP\key{collect}~\Int \RP\\
  6003. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  6004. \mid \gray{ \key{goto}~\itm{label}\key{;} }\\
  6005. &\mid& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  6006. C_2 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  6007. \end{array}
  6008. \]
  6009. \end{minipage}
  6010. }
  6011. \caption{The concrete syntax of the $C_2$ intermediate language.}
  6012. \label{fig:c2-concrete-syntax}
  6013. \end{figure}
  6014. \begin{figure}[tp]
  6015. \fbox{
  6016. \begin{minipage}{0.96\textwidth}
  6017. \small
  6018. \[
  6019. \begin{array}{lcl}
  6020. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  6021. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  6022. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  6023. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  6024. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  6025. &\mid& (\key{Allocate} \,\itm{int}\,\itm{type}) \\
  6026. &\mid& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  6027. &\mid& (\key{Prim}~\key{'vector-set!}\,(\key{list}\,\Atm\,\INT{\Int}\,\Atm))\\
  6028. &\mid& (\key{GlobalValue} \,\Var) \mid (\key{Void})\\
  6029. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  6030. \mid (\key{Collect} \,\itm{int}) \\
  6031. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  6032. \mid \GOTO{\itm{label}} } \\
  6033. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  6034. C_2 & ::= & \gray{ \PROGRAM{\itm{info}}{\CFG{(\itm{label}\,\key{.}\,\Tail)\ldots}} }
  6035. \end{array}
  6036. \]
  6037. \end{minipage}
  6038. }
  6039. \caption{The abstract syntax of $C_2$, extending $C_1$
  6040. (Figure~\ref{fig:c1-syntax}).}
  6041. \label{fig:c2-syntax}
  6042. \end{figure}
  6043. The output of \code{explicate-control} is a program in the
  6044. intermediate language $C_2$, whose concrete syntax is defined in
  6045. Figure~\ref{fig:c2-concrete-syntax} and whose abstract syntax is
  6046. defined in Figure~\ref{fig:c2-syntax}. The new forms of $C_2$ include
  6047. the \key{allocate}, \key{vector-ref}, and \key{vector-set!}, and
  6048. \key{global-value} expressions and the \code{collect} statement. The
  6049. \code{explicate-control} pass can treat these new forms much like the
  6050. other expression forms that we've already encoutered.
  6051. \section{Select Instructions and the x86$_2$ Language}
  6052. \label{sec:select-instructions-gc}
  6053. \index{instruction selection}
  6054. %% void (rep as zero)
  6055. %% allocate
  6056. %% collect (callq collect)
  6057. %% vector-ref
  6058. %% vector-set!
  6059. %% global (postpone)
  6060. In this pass we generate x86 code for most of the new operations that
  6061. were needed to compile tuples, including \code{Allocate},
  6062. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  6063. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  6064. the later has a different concrete syntax (see
  6065. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  6066. \index{x86}
  6067. The \code{vector-ref} and \code{vector-set!} forms translate into
  6068. \code{movq} instructions. (The plus one in the offset is to get past
  6069. the tag at the beginning of the tuple representation.)
  6070. \begin{lstlisting}
  6071. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  6072. |$\Longrightarrow$|
  6073. movq |$\itm{vec}'$|, %r11
  6074. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  6075. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  6076. |$\Longrightarrow$|
  6077. movq |$\itm{vec}'$|, %r11
  6078. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  6079. movq $0, |$\itm{lhs'}$|
  6080. \end{lstlisting}
  6081. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  6082. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  6083. register \code{r11} ensures that offset expression
  6084. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  6085. removing \code{r11} from consideration by the register allocating.
  6086. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  6087. \code{rax}. Then the generated code for \code{vector-set!} would be
  6088. \begin{lstlisting}
  6089. movq |$\itm{vec}'$|, %rax
  6090. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  6091. movq $0, |$\itm{lhs}'$|
  6092. \end{lstlisting}
  6093. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  6094. \code{patch-instructions} would insert a move through \code{rax}
  6095. as follows.
  6096. \begin{lstlisting}
  6097. movq |$\itm{vec}'$|, %rax
  6098. movq |$\itm{arg}'$|, %rax
  6099. movq %rax, |$8(n+1)$|(%rax)
  6100. movq $0, |$\itm{lhs}'$|
  6101. \end{lstlisting}
  6102. But the above sequence of instructions does not work because we're
  6103. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  6104. $\itm{arg}'$) at the same time!
  6105. We compile the \code{allocate} form to operations on the
  6106. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  6107. is the next free address in the FromSpace, so we copy it into
  6108. \code{r11} and then move it forward by enough space for the tuple
  6109. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  6110. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  6111. initialize the \itm{tag} and finally copy the address in \code{r11} to
  6112. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  6113. tag is organized. We recommend using the Racket operations
  6114. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  6115. during compilation. The type annotation in the \code{vector} form is
  6116. used to determine the pointer mask region of the tag.
  6117. \begin{lstlisting}
  6118. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  6119. |$\Longrightarrow$|
  6120. movq free_ptr(%rip), %r11
  6121. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  6122. movq $|$\itm{tag}$|, 0(%r11)
  6123. movq %r11, |$\itm{lhs}'$|
  6124. \end{lstlisting}
  6125. The \code{collect} form is compiled to a call to the \code{collect}
  6126. function in the runtime. The arguments to \code{collect} are 1) the
  6127. top of the root stack and 2) the number of bytes that need to be
  6128. allocated. We use another dedicated register, \code{r15}, to
  6129. store the pointer to the top of the root stack. So \code{r15} is not
  6130. available for use by the register allocator.
  6131. \begin{lstlisting}
  6132. (collect |$\itm{bytes}$|)
  6133. |$\Longrightarrow$|
  6134. movq %r15, %rdi
  6135. movq $|\itm{bytes}|, %rsi
  6136. callq collect
  6137. \end{lstlisting}
  6138. \begin{figure}[tp]
  6139. \fbox{
  6140. \begin{minipage}{0.96\textwidth}
  6141. \[
  6142. \begin{array}{lcl}
  6143. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)} \\
  6144. x86_1 &::= & \gray{ \key{.globl main} }\\
  6145. & & \gray{ \key{main:} \; \Instr\ldots }
  6146. \end{array}
  6147. \]
  6148. \end{minipage}
  6149. }
  6150. \caption{The concrete syntax of x86$_2$ (extends x86$_1$ of Figure~\ref{fig:x86-1-concrete}).}
  6151. \label{fig:x86-2-concrete}
  6152. \end{figure}
  6153. \begin{figure}[tp]
  6154. \fbox{
  6155. \begin{minipage}{0.96\textwidth}
  6156. \small
  6157. \[
  6158. \begin{array}{lcl}
  6159. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  6160. \mid \BYTEREG{\Reg}} \\
  6161. &\mid& (\key{Global}~\Var) \\
  6162. x86_2 &::= & \gray{ \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}} }
  6163. \end{array}
  6164. \]
  6165. \end{minipage}
  6166. }
  6167. \caption{The abstract syntax of x86$_2$ (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  6168. \label{fig:x86-2}
  6169. \end{figure}
  6170. The concrete and abstract syntax of the $x86_2$ language is defined in
  6171. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It differs from
  6172. x86$_1$ just in the addition of the form for global variables.
  6173. %
  6174. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  6175. \code{select-instructions} pass on the running example.
  6176. \begin{figure}[tbp]
  6177. \centering
  6178. % tests/s2_17.rkt
  6179. \begin{minipage}[t]{0.5\textwidth}
  6180. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6181. block35:
  6182. movq free_ptr(%rip), alloc9024
  6183. addq $16, free_ptr(%rip)
  6184. movq alloc9024, %r11
  6185. movq $131, 0(%r11)
  6186. movq alloc9024, %r11
  6187. movq vecinit9025, 8(%r11)
  6188. movq $0, initret9026
  6189. movq alloc9024, %r11
  6190. movq 8(%r11), tmp9034
  6191. movq tmp9034, %r11
  6192. movq 8(%r11), %rax
  6193. jmp conclusion
  6194. block36:
  6195. movq $0, collectret9027
  6196. jmp block35
  6197. block38:
  6198. movq free_ptr(%rip), alloc9020
  6199. addq $16, free_ptr(%rip)
  6200. movq alloc9020, %r11
  6201. movq $3, 0(%r11)
  6202. movq alloc9020, %r11
  6203. movq vecinit9021, 8(%r11)
  6204. movq $0, initret9022
  6205. movq alloc9020, vecinit9025
  6206. movq free_ptr(%rip), tmp9031
  6207. movq tmp9031, tmp9032
  6208. addq $16, tmp9032
  6209. movq fromspace_end(%rip), tmp9033
  6210. cmpq tmp9033, tmp9032
  6211. jl block36
  6212. jmp block37
  6213. block37:
  6214. movq %r15, %rdi
  6215. movq $16, %rsi
  6216. callq 'collect
  6217. jmp block35
  6218. block39:
  6219. movq $0, collectret9023
  6220. jmp block38
  6221. \end{lstlisting}
  6222. \end{minipage}
  6223. \begin{minipage}[t]{0.45\textwidth}
  6224. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6225. start:
  6226. movq $42, vecinit9021
  6227. movq free_ptr(%rip), tmp9028
  6228. movq tmp9028, tmp9029
  6229. addq $16, tmp9029
  6230. movq fromspace_end(%rip), tmp9030
  6231. cmpq tmp9030, tmp9029
  6232. jl block39
  6233. jmp block40
  6234. block40:
  6235. movq %r15, %rdi
  6236. movq $16, %rsi
  6237. callq 'collect
  6238. jmp block38
  6239. \end{lstlisting}
  6240. \end{minipage}
  6241. \caption{Output of the \code{select-instructions} pass.}
  6242. \label{fig:select-instr-output-gc}
  6243. \end{figure}
  6244. \clearpage
  6245. \section{Register Allocation}
  6246. \label{sec:reg-alloc-gc}
  6247. \index{register allocation}
  6248. As discussed earlier in this chapter, the garbage collector needs to
  6249. access all the pointers in the root set, that is, all variables that
  6250. are vectors. It will be the responsibility of the register allocator
  6251. to make sure that:
  6252. \begin{enumerate}
  6253. \item the root stack is used for spilling vector-typed variables, and
  6254. \item if a vector-typed variable is live during a call to the
  6255. collector, it must be spilled to ensure it is visible to the
  6256. collector.
  6257. \end{enumerate}
  6258. The later responsibility can be handled during construction of the
  6259. interference graph, by adding interference edges between the call-live
  6260. vector-typed variables and all the callee-saved registers. (They
  6261. already interfere with the caller-saved registers.) The type
  6262. information for variables is in the \code{Program} form, so we
  6263. recommend adding another parameter to the \code{build-interference}
  6264. function to communicate this alist.
  6265. The spilling of vector-typed variables to the root stack can be
  6266. handled after graph coloring, when choosing how to assign the colors
  6267. (integers) to registers and stack locations. The \code{Program} output
  6268. of this pass changes to also record the number of spills to the root
  6269. stack.
  6270. % build-interference
  6271. %
  6272. % callq
  6273. % extra parameter for var->type assoc. list
  6274. % update 'program' and 'if'
  6275. % allocate-registers
  6276. % allocate spilled vectors to the rootstack
  6277. % don't change color-graph
  6278. \section{Print x86}
  6279. \label{sec:print-x86-gc}
  6280. \index{prelude}\index{conclusion}
  6281. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  6282. \code{print-x86} pass on the running example. In the prelude and
  6283. conclusion of the \code{main} function, we treat the root stack very
  6284. much like the regular stack in that we move the root stack pointer
  6285. (\code{r15}) to make room for the spills to the root stack, except
  6286. that the root stack grows up instead of down. For the running
  6287. example, there was just one spill so we increment \code{r15} by 8
  6288. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  6289. One issue that deserves special care is that there may be a call to
  6290. \code{collect} prior to the initializing assignments for all the
  6291. variables in the root stack. We do not want the garbage collector to
  6292. accidentally think that some uninitialized variable is a pointer that
  6293. needs to be followed. Thus, we zero-out all locations on the root
  6294. stack in the prelude of \code{main}. In
  6295. Figure~\ref{fig:print-x86-output-gc}, the instruction
  6296. %
  6297. \lstinline{movq $0, (%r15)}
  6298. %
  6299. accomplishes this task. The garbage collector tests each root to see
  6300. if it is null prior to dereferencing it.
  6301. \begin{figure}[htbp]
  6302. \begin{minipage}[t]{0.5\textwidth}
  6303. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6304. block35:
  6305. movq free_ptr(%rip), %rcx
  6306. addq $16, free_ptr(%rip)
  6307. movq %rcx, %r11
  6308. movq $131, 0(%r11)
  6309. movq %rcx, %r11
  6310. movq -8(%r15), %rax
  6311. movq %rax, 8(%r11)
  6312. movq $0, %rdx
  6313. movq %rcx, %r11
  6314. movq 8(%r11), %rcx
  6315. movq %rcx, %r11
  6316. movq 8(%r11), %rax
  6317. jmp conclusion
  6318. block36:
  6319. movq $0, %rcx
  6320. jmp block35
  6321. block38:
  6322. movq free_ptr(%rip), %rcx
  6323. addq $16, free_ptr(%rip)
  6324. movq %rcx, %r11
  6325. movq $3, 0(%r11)
  6326. movq %rcx, %r11
  6327. movq %rbx, 8(%r11)
  6328. movq $0, %rdx
  6329. movq %rcx, -8(%r15)
  6330. movq free_ptr(%rip), %rcx
  6331. addq $16, %rcx
  6332. movq fromspace_end(%rip), %rdx
  6333. cmpq %rdx, %rcx
  6334. jl block36
  6335. movq %r15, %rdi
  6336. movq $16, %rsi
  6337. callq collect
  6338. jmp block35
  6339. block39:
  6340. movq $0, %rcx
  6341. jmp block38
  6342. \end{lstlisting}
  6343. \end{minipage}
  6344. \begin{minipage}[t]{0.45\textwidth}
  6345. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6346. start:
  6347. movq $42, %rbx
  6348. movq free_ptr(%rip), %rdx
  6349. addq $16, %rdx
  6350. movq fromspace_end(%rip), %rcx
  6351. cmpq %rcx, %rdx
  6352. jl block39
  6353. movq %r15, %rdi
  6354. movq $16, %rsi
  6355. callq collect
  6356. jmp block38
  6357. .globl main
  6358. main:
  6359. pushq %rbp
  6360. movq %rsp, %rbp
  6361. pushq %r13
  6362. pushq %r12
  6363. pushq %rbx
  6364. pushq %r14
  6365. subq $0, %rsp
  6366. movq $16384, %rdi
  6367. movq $16384, %rsi
  6368. callq initialize
  6369. movq rootstack_begin(%rip), %r15
  6370. movq $0, (%r15)
  6371. addq $8, %r15
  6372. jmp start
  6373. conclusion:
  6374. subq $8, %r15
  6375. addq $0, %rsp
  6376. popq %r14
  6377. popq %rbx
  6378. popq %r12
  6379. popq %r13
  6380. popq %rbp
  6381. retq
  6382. \end{lstlisting}
  6383. \end{minipage}
  6384. \caption{Output of the \code{print-x86} pass.}
  6385. \label{fig:print-x86-output-gc}
  6386. \end{figure}
  6387. \begin{figure}[p]
  6388. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6389. \node (R3) at (0,2) {\large $R_3$};
  6390. \node (R3-2) at (3,2) {\large $R_3$};
  6391. \node (R3-3) at (6,2) {\large $R_3$};
  6392. \node (R3-4) at (9,2) {\large $R_3$};
  6393. \node (R3-5) at (12,2) {\large $R'_3$};
  6394. \node (C2-4) at (3,0) {\large $C_2$};
  6395. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_2$};
  6396. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_2$};
  6397. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}_2$};
  6398. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}_2$};
  6399. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}_2$};
  6400. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}_2$};
  6401. %\path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize\color{red} type-check} (R3-2);
  6402. \path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize shrink} (R3-2);
  6403. \path[->,bend left=15] (R3-2) edge [above] node {\ttfamily\footnotesize uniquify} (R3-3);
  6404. \path[->,bend left=15] (R3-3) edge [above] node {\ttfamily\footnotesize\color{red} expose-alloc.} (R3-4);
  6405. \path[->,bend left=15] (R3-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R3-5);
  6406. \path[->,bend left=20] (R3-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-4);
  6407. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  6408. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6409. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  6410. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  6411. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  6412. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  6413. \end{tikzpicture}
  6414. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  6415. \label{fig:R3-passes}
  6416. \end{figure}
  6417. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  6418. for the compilation of $R_3$.
  6419. \section{Challenge: Simple Structures}
  6420. \label{sec:simple-structures}
  6421. \index{struct}
  6422. \index{structure}
  6423. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  6424. $R^s_3$, which extends $R^3$ with support for simple structures.
  6425. Recall that a \code{struct} in Typed Racket is a user-defined data
  6426. type that contains named fields and that is heap allocated, similar to
  6427. a vector. The following is an example of a structure definition, in
  6428. this case the definition of a \code{point} type.
  6429. \begin{lstlisting}
  6430. (struct point ([x : Integer] [y : Integer]) #:mutable)
  6431. \end{lstlisting}
  6432. \begin{figure}[tbp]
  6433. \centering
  6434. \fbox{
  6435. \begin{minipage}{0.96\textwidth}
  6436. \[
  6437. \begin{array}{lcl}
  6438. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6439. \mid (\key{Vector}\;\Type \ldots) \mid \key{Void} } \mid \Var \\
  6440. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6441. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  6442. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  6443. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6444. \mid (\key{and}\;\Exp\;\Exp)
  6445. \mid (\key{or}\;\Exp\;\Exp)
  6446. \mid (\key{not}\;\Exp) } \\
  6447. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  6448. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  6449. &\mid& \gray{ (\key{vector}\;\Exp \ldots)
  6450. \mid (\key{vector-ref}\;\Exp\;\Int) } \\
  6451. &\mid& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  6452. &\mid& \gray{ (\key{void}) } \mid (\Var\;\Exp \ldots)\\
  6453. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  6454. R_3 &::=& \Def \ldots \; \Exp
  6455. \end{array}
  6456. \]
  6457. \end{minipage}
  6458. }
  6459. \caption{The concrete syntax of $R^s_3$, extending $R_3$
  6460. (Figure~\ref{fig:r3-concrete-syntax}).}
  6461. \label{fig:r3s-concrete-syntax}
  6462. \end{figure}
  6463. An instance of a structure is created using function call syntax, with
  6464. the name of the structure in the function position:
  6465. \begin{lstlisting}
  6466. (point 7 12)
  6467. \end{lstlisting}
  6468. Function-call syntax is also used to read the value in a field of a
  6469. structure. The function name is formed by the structure name, a dash,
  6470. and the field name. The following example uses \code{point-x} and
  6471. \code{point-y} to access the \code{x} and \code{y} fields of two point
  6472. instances.
  6473. \begin{center}
  6474. \begin{lstlisting}
  6475. (let ([pt1 (point 7 12)])
  6476. (let ([pt2 (point 4 3)])
  6477. (+ (- (point-x pt1) (point-x pt2))
  6478. (- (point-y pt1) (point-y pt2)))))
  6479. \end{lstlisting}
  6480. \end{center}
  6481. Similarly, to write to a field of a structure, use its set function,
  6482. whose name starts with \code{set-}, followed by the structure name,
  6483. then a dash, then the field name, and concluded with an exclamation
  6484. mark. The following example uses \code{set-point-x!} to change the
  6485. \code{x} field from \code{7} to \code{42}.
  6486. \begin{center}
  6487. \begin{lstlisting}
  6488. (let ([pt (point 7 12)])
  6489. (let ([_ (set-point-x! pt 42)])
  6490. (point-x pt)))
  6491. \end{lstlisting}
  6492. \end{center}
  6493. \begin{exercise}\normalfont
  6494. Extend your compiler with support for simple structures, compiling
  6495. $R^s_3$ to x86 assembly code. Create five new test cases that use
  6496. structures and test your compiler.
  6497. \end{exercise}
  6498. \section{Challenge: Generational Collection}
  6499. The copying collector described in Section~\ref{sec:GC} can incur
  6500. significant runtime overhead because the call to \code{collect} takes
  6501. time proportional to all of the live data. One way to reduce this
  6502. overhead is to reduce how much data is inspected in each call to
  6503. \code{collect}. In particular, researchers have observed that recently
  6504. allocated data is more likely to become garbage then data that has
  6505. survived one or more previous calls to \code{collect}. This insight
  6506. motivated the creation of \emph{generational garbage collectors}
  6507. \index{generational garbage collector} that
  6508. 1) segregates data according to its age into two or more generations,
  6509. 2) allocates less space for younger generations, so collecting them is
  6510. faster, and more space for the older generations, and 3) performs
  6511. collection on the younger generations more frequently then for older
  6512. generations~\citep{Wilson:1992fk}.
  6513. For this challenge assignment, the goal is to adapt the copying
  6514. collector implemented in \code{runtime.c} to use two generations, one
  6515. for young data and one for old data. Each generation consists of a
  6516. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  6517. \code{collect} function to use the two generations.
  6518. \begin{enumerate}
  6519. \item Copy the young generation's FromSpace to its ToSpace then switch
  6520. the role of the ToSpace and FromSpace
  6521. \item If there is enough space for the requested number of bytes in
  6522. the young FromSpace, then return from \code{collect}.
  6523. \item If there is not enough space in the young FromSpace for the
  6524. requested bytes, then move the data from the young generation to the
  6525. old one with the following steps:
  6526. \begin{enumerate}
  6527. \item If there is enough room in the old FromSpace, copy the young
  6528. FromSpace to the old FromSpace and then return.
  6529. \item If there is not enough room in the old FromSpace, then collect
  6530. the old generation by copying the old FromSpace to the old ToSpace
  6531. and swap the roles of the old FromSpace and ToSpace.
  6532. \item If there is enough room now, copy the young FromSpace to the
  6533. old FromSpace and return. Otherwise, allocate a larger FromSpace
  6534. and ToSpace for the old generation. Copy the young FromSpace and
  6535. the old FromSpace into the larger FromSpace for the old
  6536. generation and then return.
  6537. \end{enumerate}
  6538. \end{enumerate}
  6539. We recommend that you generalize the \code{cheney} function so that it
  6540. can be used for all the copies mentioned above: between the young
  6541. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  6542. between the young FromSpace and old FromSpace. This can be
  6543. accomplished by adding parameters to \code{cheney} that replace its
  6544. use of the global variables \code{fromspace\_begin},
  6545. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  6546. Note that the collection of the young generation does not traverse the
  6547. old generation. This introduces a potential problem: there may be
  6548. young data that is only reachable through pointers in the old
  6549. generation. If these pointers are not taken into account, the
  6550. collector could throw away young data that is live! One solution,
  6551. called \emph{pointer recording}, is to maintain a set of all the
  6552. pointers from the old generation into the new generation and consider
  6553. this set as part of the root set. To maintain this set, the compiler
  6554. must insert extra instructions around every \code{vector-set!}. If the
  6555. vector being modified is in the old generation, and if the value being
  6556. written is a pointer into the new generation, than that pointer must
  6557. be added to the set. Also, if the value being overwritten was a
  6558. pointer into the new generation, then that pointer should be removed
  6559. from the set.
  6560. \begin{exercise}\normalfont
  6561. Adapt the \code{collect} function in \code{runtime.c} to implement
  6562. generational garbage collection, as outlined in this section.
  6563. Update the code generation for \code{vector-set!} to implement
  6564. pointer recording. Make sure that your new compiler and runtime
  6565. passes your test suite.
  6566. \end{exercise}
  6567. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6568. \chapter{Functions}
  6569. \label{ch:functions}
  6570. \index{function}
  6571. This chapter studies the compilation of functions similar to those
  6572. found in the C language. This corresponds to a subset of Typed Racket
  6573. in which only top-level function definitions are allowed. This kind of
  6574. function is an important stepping stone to implementing
  6575. lexically-scoped functions, that is, \key{lambda} abstractions, which
  6576. is the topic of Chapter~\ref{ch:lambdas}.
  6577. \section{The $R_4$ Language}
  6578. The concrete and abstract syntax for function definitions and function
  6579. application is shown in Figures~\ref{fig:r4-concrete-syntax} and
  6580. \ref{fig:r4-syntax}, where we define the $R_4$ language. Programs in
  6581. $R_4$ begin with zero or more function definitions. The function
  6582. names from these definitions are in-scope for the entire program,
  6583. including all other function definitions (so the ordering of function
  6584. definitions does not matter). The concrete syntax for function
  6585. application\index{function application} is $(\Exp \; \Exp \ldots)$
  6586. where the first expression must
  6587. evaluate to a function and the rest are the arguments.
  6588. The abstract syntax for function application is
  6589. $\APPLY{\Exp}{\Exp\ldots}$.
  6590. %% The syntax for function application does not include an explicit
  6591. %% keyword, which is error prone when using \code{match}. To alleviate
  6592. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  6593. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  6594. Functions are first-class in the sense that a function pointer
  6595. \index{function pointer} is data and can be stored in memory or passed
  6596. as a parameter to another function. Thus, we introduce a function
  6597. type, written
  6598. \begin{lstlisting}
  6599. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  6600. \end{lstlisting}
  6601. for a function whose $n$ parameters have the types $\Type_1$ through
  6602. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  6603. these functions (with respect to Racket functions) is that they are
  6604. not lexically scoped. That is, the only external entities that can be
  6605. referenced from inside a function body are other globally-defined
  6606. functions. The syntax of $R_4$ prevents functions from being nested
  6607. inside each other.
  6608. \begin{figure}[tp]
  6609. \centering
  6610. \fbox{
  6611. \begin{minipage}{0.96\textwidth}
  6612. \small
  6613. \[
  6614. \begin{array}{lcl}
  6615. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  6616. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void} } \mid (\Type \ldots \; \key{->}\; \Type) \\
  6617. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6618. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  6619. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  6620. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6621. \mid (\key{and}\;\Exp\;\Exp)
  6622. \mid (\key{or}\;\Exp\;\Exp)
  6623. \mid (\key{not}\;\Exp)} \\
  6624. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  6625. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  6626. (\key{vector-ref}\;\Exp\;\Int)} \\
  6627. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  6628. \mid \LP\key{has-type}~\Exp~\Type\RP } \\
  6629. &\mid& \LP\Exp \; \Exp \ldots\RP \\
  6630. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  6631. R_4 &::=& \Def \ldots \; \Exp
  6632. \end{array}
  6633. \]
  6634. \end{minipage}
  6635. }
  6636. \caption{The concrete syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-concrete-syntax}).}
  6637. \label{fig:r4-concrete-syntax}
  6638. \end{figure}
  6639. \begin{figure}[tp]
  6640. \centering
  6641. \fbox{
  6642. \begin{minipage}{0.96\textwidth}
  6643. \small
  6644. \[
  6645. \begin{array}{lcl}
  6646. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6647. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  6648. &\mid& \gray{ \BOOL{\itm{bool}}
  6649. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6650. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP }
  6651. \mid \APPLY{\Exp}{\Exp\ldots}\\
  6652. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}\\
  6653. R_4 &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  6654. \end{array}
  6655. \]
  6656. \end{minipage}
  6657. }
  6658. \caption{The abstract syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-syntax}).}
  6659. \label{fig:r4-syntax}
  6660. \end{figure}
  6661. The program in Figure~\ref{fig:r4-function-example} is a
  6662. representative example of defining and using functions in $R_4$. We
  6663. define a function \code{map-vec} that applies some other function
  6664. \code{f} to both elements of a vector and returns a new
  6665. vector containing the results. We also define a function \code{add1}.
  6666. The program applies
  6667. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  6668. \code{(vector 1 42)}, from which we return the \code{42}.
  6669. \begin{figure}[tbp]
  6670. \begin{lstlisting}
  6671. (define (map-vec [f : (Integer -> Integer)]
  6672. [v : (Vector Integer Integer)])
  6673. : (Vector Integer Integer)
  6674. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  6675. (define (add1 [x : Integer]) : Integer
  6676. (+ x 1))
  6677. (vector-ref (map-vec add1 (vector 0 41)) 1)
  6678. \end{lstlisting}
  6679. \caption{Example of using functions in $R_4$.}
  6680. \label{fig:r4-function-example}
  6681. \end{figure}
  6682. The definitional interpreter for $R_4$ is in
  6683. Figure~\ref{fig:interp-R4}. The case for the \code{ProgramDefsExp} form is
  6684. responsible for setting up the mutual recursion between the top-level
  6685. function definitions. We use the classic back-patching \index{back-patching}
  6686. approach that uses mutable variables and makes two passes over the function
  6687. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  6688. top-level environment using a mutable cons cell for each function
  6689. definition. Note that the \code{lambda} value for each function is
  6690. incomplete; it does not yet include the environment. Once the
  6691. top-level environment is constructed, we then iterate over it and
  6692. update the \code{lambda} values to use the top-level environment.
  6693. \begin{figure}[tp]
  6694. \begin{lstlisting}
  6695. (define interp-R4-class
  6696. (class interp-R3-class
  6697. (super-new)
  6698. (define/override ((interp-exp env) e)
  6699. (define recur (interp-exp env))
  6700. (match e
  6701. [(Var x) (unbox (dict-ref env x))]
  6702. [(Let x e body)
  6703. (define new-env (dict-set env x (box (recur e))))
  6704. ((interp-exp new-env) body)]
  6705. [(Apply fun args)
  6706. (define fun-val (recur fun))
  6707. (define arg-vals (for/list ([e args]) (recur e)))
  6708. (match fun-val
  6709. [`(function (,xs ...) ,body ,fun-env)
  6710. (define params-args (for/list ([x xs] [arg arg-vals])
  6711. (cons x (box arg))))
  6712. (define new-env (append params-args fun-env))
  6713. ((interp-exp new-env) body)]
  6714. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  6715. [else ((super interp-exp env) e)]
  6716. ))
  6717. (define/public (interp-def d)
  6718. (match d
  6719. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  6720. (cons f (box `(function ,xs ,body ())))]))
  6721. (define/override (interp-program p)
  6722. (match p
  6723. [(ProgramDefsExp info ds body)
  6724. (let ([top-level (for/list ([d ds]) (interp-def d))])
  6725. (for/list ([f (in-dict-values top-level)])
  6726. (set-box! f (match (unbox f)
  6727. [`(function ,xs ,body ())
  6728. `(function ,xs ,body ,top-level)])))
  6729. ((interp-exp top-level) body))]))
  6730. ))
  6731. (define (interp-R4 p)
  6732. (send (new interp-R4-class) interp-program p))
  6733. \end{lstlisting}
  6734. \caption{Interpreter for the $R_4$ language.}
  6735. \label{fig:interp-R4}
  6736. \end{figure}
  6737. \margincomment{TODO: explain type checker}
  6738. The type checker for $R_4$ is is in Figure~\ref{fig:type-check-R4}.
  6739. \begin{figure}[tp]
  6740. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6741. (define type-check-R4-class
  6742. (class type-check-R3-class
  6743. (super-new)
  6744. (inherit check-type-equal?)
  6745. (define/public (type-check-apply env e es)
  6746. (define-values (e^ ty) ((type-check-exp env) e))
  6747. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  6748. ((type-check-exp env) e)))
  6749. (match ty
  6750. [`(,ty^* ... -> ,rt)
  6751. (for ([arg-ty ty*] [param-ty ty^*])
  6752. (check-type-equal? arg-ty param-ty (Apply e es)))
  6753. (values e^ e* rt)]))
  6754. (define/override (type-check-exp env)
  6755. (lambda (e)
  6756. (match e
  6757. [(FunRef f)
  6758. (values (FunRef f) (dict-ref env f))]
  6759. [(Apply e es)
  6760. (define-values (e^ es^ rt) (type-check-apply env e es))
  6761. (values (Apply e^ es^) rt)]
  6762. [(Call e es)
  6763. (define-values (e^ es^ rt) (type-check-apply env e es))
  6764. (values (Call e^ es^) rt)]
  6765. [else ((super type-check-exp env) e)])))
  6766. (define/public (type-check-def env)
  6767. (lambda (e)
  6768. (match e
  6769. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  6770. (define new-env (append (map cons xs ps) env))
  6771. (define-values (body^ ty^) ((type-check-exp new-env) body))
  6772. (check-type-equal? ty^ rt body)
  6773. (Def f p:t* rt info body^)])))
  6774. (define/public (fun-def-type d)
  6775. (match d
  6776. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  6777. (define/override (type-check-program e)
  6778. (match e
  6779. [(ProgramDefsExp info ds body)
  6780. (define new-env (for/list ([d ds])
  6781. (cons (Def-name d) (fun-def-type d))))
  6782. (define ds^ (for/list ([d ds]) ((type-check-def new-env) d)))
  6783. (define-values (body^ ty) ((type-check-exp new-env) body))
  6784. (check-type-equal? ty 'Integer body)
  6785. (ProgramDefsExp info ds^ body^)]))))
  6786. (define (type-check-R4 p)
  6787. (send (new type-check-R4-class) type-check-program p))
  6788. \end{lstlisting}
  6789. \caption{Type checker for the $R_4$ language.}
  6790. \label{fig:type-check-R4}
  6791. \end{figure}
  6792. \section{Functions in x86}
  6793. \label{sec:fun-x86}
  6794. \margincomment{\tiny Make sure callee-saved registers are discussed
  6795. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  6796. \margincomment{\tiny Talk about the return address on the
  6797. stack and what callq and retq does.\\ --Jeremy }
  6798. The x86 architecture provides a few features to support the
  6799. implementation of functions. We have already seen that x86 provides
  6800. labels so that one can refer to the location of an instruction, as is
  6801. needed for jump instructions. Labels can also be used to mark the
  6802. beginning of the instructions for a function. Going further, we can
  6803. obtain the address of a label by using the \key{leaq} instruction and
  6804. PC-relative addressing. For example, the following puts the
  6805. address of the \code{add1} label into the \code{rbx} register.
  6806. \begin{lstlisting}
  6807. leaq add1(%rip), %rbx
  6808. \end{lstlisting}
  6809. The instruction pointer register \key{rip} (aka. the program counter
  6810. \index{program counter}) always points to the next instruction to be
  6811. executed. When combined with an label, as in \code{add1(\%rip)}, the
  6812. linker computes the distance $d$ between the address of \code{add1}
  6813. and where the \code{rip} would be at that moment and then changes
  6814. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  6815. the address of \code{add1}.
  6816. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  6817. jump to a function whose location is given by a label. To support
  6818. function calls in this chapter we instead will be jumping to a
  6819. function whose location is given by an address in a register, that is,
  6820. we need to make an \emph{indirect function call}. The x86 syntax for
  6821. this is a \code{callq} instruction but with an asterisk before the
  6822. register name.\index{indirect function call}
  6823. \begin{lstlisting}
  6824. callq *%rbx
  6825. \end{lstlisting}
  6826. \subsection{Calling Conventions}
  6827. \index{calling conventions}
  6828. The \code{callq} instruction provides partial support for implementing
  6829. functions: it pushes the return address on the stack and it jumps to
  6830. the target. However, \code{callq} does not handle
  6831. \begin{enumerate}
  6832. \item parameter passing,
  6833. \item pushing frames on the procedure call stack and popping them off,
  6834. or
  6835. \item determining how registers are shared by different functions.
  6836. \end{enumerate}
  6837. Regarding (1) parameter passing, recall that the following six
  6838. registers are used to pass arguments to a function, in this order.
  6839. \begin{lstlisting}
  6840. rdi rsi rdx rcx r8 r9
  6841. \end{lstlisting}
  6842. If there are
  6843. more than six arguments, then the convention is to use space on the
  6844. frame of the caller for the rest of the arguments. However, to ease
  6845. the implementation of efficient tail calls
  6846. (Section~\ref{sec:tail-call}), we arrange to never need more than six
  6847. arguments.
  6848. %
  6849. Also recall that the register \code{rax} is for the return value of
  6850. the function.
  6851. \index{prelude}\index{conclusion}
  6852. Regarding (2) frames \index{frame} and the procedure call stack,
  6853. \index{procedure call stack} recall from Section~\ref{sec:x86} that
  6854. the stack grows down, with each function call using a chunk of space
  6855. called a frame. The caller sets the stack pointer, register
  6856. \code{rsp}, to the last data item in its frame. The callee must not
  6857. change anything in the caller's frame, that is, anything that is at or
  6858. above the stack pointer. The callee is free to use locations that are
  6859. below the stack pointer.
  6860. Recall that we are storing variables of vector type on the root stack.
  6861. So the prelude needs to move the root stack pointer \code{r15} up and
  6862. the conclusion needs to move the root stack pointer back down. Also,
  6863. the prelude must initialize to \code{0} this frame's slots in the root
  6864. stack to signal to the garbage collector that those slots do not yet
  6865. contain a pointer to a vector. Otherwise the garbage collector will
  6866. interpret the garbage bits in those slots as memory addresses and try
  6867. to traverse them, causing serious mayhem!
  6868. Regarding (3) the sharing of registers between different functions,
  6869. recall from Section~\ref{sec:calling-conventions} that the registers
  6870. are divided into two groups, the caller-saved registers and the
  6871. callee-saved registers. The caller should assume that all the
  6872. caller-saved registers get overwritten with arbitrary values by the
  6873. callee. That is why we recommend in
  6874. Section~\ref{sec:calling-conventions} that variables that are live
  6875. during a function call should not be assigned to caller-saved
  6876. registers.
  6877. On the flip side, if the callee wants to use a callee-saved register,
  6878. the callee must save the contents of those registers on their stack
  6879. frame and then put them back prior to returning to the caller. That
  6880. is why we recommended in Section~\ref{sec:calling-conventions} that if
  6881. the register allocator assigns a variable to a callee-saved register,
  6882. then the prelude of the \code{main} function must save that register
  6883. to the stack and the conclusion of \code{main} must restore it. This
  6884. recommendation now generalizes to all functions.
  6885. Also recall that the base pointer, register \code{rbp}, is used as a
  6886. point-of-reference within a frame, so that each local variable can be
  6887. accessed at a fixed offset from the base pointer
  6888. (Section~\ref{sec:x86}).
  6889. %
  6890. Figure~\ref{fig:call-frames} shows the general layout of the caller
  6891. and callee frames.
  6892. \begin{figure}[tbp]
  6893. \centering
  6894. \begin{tabular}{r|r|l|l} \hline
  6895. Caller View & Callee View & Contents & Frame \\ \hline
  6896. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  6897. 0(\key{\%rbp}) & & old \key{rbp} \\
  6898. -8(\key{\%rbp}) & & callee-saved $1$ \\
  6899. \ldots & & \ldots \\
  6900. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  6901. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  6902. \ldots & & \ldots \\
  6903. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  6904. %% & & \\
  6905. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  6906. %% & \ldots & \ldots \\
  6907. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  6908. \hline
  6909. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  6910. & 0(\key{\%rbp}) & old \key{rbp} \\
  6911. & -8(\key{\%rbp}) & callee-saved $1$ \\
  6912. & \ldots & \ldots \\
  6913. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  6914. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  6915. & \ldots & \ldots \\
  6916. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  6917. \end{tabular}
  6918. \caption{Memory layout of caller and callee frames.}
  6919. \label{fig:call-frames}
  6920. \end{figure}
  6921. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  6922. %% local variables and for storing the values of callee-saved registers
  6923. %% (we shall refer to all of these collectively as ``locals''), and that
  6924. %% at the beginning of a function we move the stack pointer \code{rsp}
  6925. %% down to make room for them.
  6926. %% We recommend storing the local variables
  6927. %% first and then the callee-saved registers, so that the local variables
  6928. %% can be accessed using \code{rbp} the same as before the addition of
  6929. %% functions.
  6930. %% To make additional room for passing arguments, we shall
  6931. %% move the stack pointer even further down. We count how many stack
  6932. %% arguments are needed for each function call that occurs inside the
  6933. %% body of the function and find their maximum. Adding this number to the
  6934. %% number of locals gives us how much the \code{rsp} should be moved at
  6935. %% the beginning of the function. In preparation for a function call, we
  6936. %% offset from \code{rsp} to set up the stack arguments. We put the first
  6937. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  6938. %% so on.
  6939. %% Upon calling the function, the stack arguments are retrieved by the
  6940. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  6941. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  6942. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  6943. %% the layout of the caller and callee frames. Notice how important it is
  6944. %% that we correctly compute the maximum number of arguments needed for
  6945. %% function calls; if that number is too small then the arguments and
  6946. %% local variables will smash into each other!
  6947. \subsection{Efficient Tail Calls}
  6948. \label{sec:tail-call}
  6949. In general, the amount of stack space used by a program is determined
  6950. by the longest chain of nested function calls. That is, if function
  6951. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  6952. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  6953. $n$ can grow quite large in the case of recursive or mutually
  6954. recursive functions. However, in some cases we can arrange to use only
  6955. constant space, i.e. $O(1)$, instead of $O(n)$.
  6956. If a function call is the last action in a function body, then that
  6957. call is said to be a \emph{tail call}\index{tail call}.
  6958. For example, in the following
  6959. program, the recursive call to \code{tail-sum} is a tail call.
  6960. \begin{center}
  6961. \begin{lstlisting}
  6962. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  6963. (if (eq? n 0)
  6964. r
  6965. (tail-sum (- n 1) (+ n r))))
  6966. (+ (tail-sum 5 0) 27)
  6967. \end{lstlisting}
  6968. \end{center}
  6969. At a tail call, the frame of the caller is no longer needed, so we
  6970. can pop the caller's frame before making the tail call. With this
  6971. approach, a recursive function that only makes tail calls will only
  6972. use $O(1)$ stack space. Functional languages like Racket typically
  6973. rely heavily on recursive functions, so they typically guarantee that
  6974. all tail calls will be optimized in this way.
  6975. \index{frame}
  6976. However, some care is needed with regards to argument passing in tail
  6977. calls. As mentioned above, for arguments beyond the sixth, the
  6978. convention is to use space in the caller's frame for passing
  6979. arguments. But for a tail call we pop the caller's frame and can no
  6980. longer use it. Another alternative is to use space in the callee's
  6981. frame for passing arguments. However, this option is also problematic
  6982. because the caller and callee's frame overlap in memory. As we begin
  6983. to copy the arguments from their sources in the caller's frame, the
  6984. target locations in the callee's frame might overlap with the sources
  6985. for later arguments! We solve this problem by not using the stack for
  6986. passing more than six arguments but instead using the heap, as we
  6987. describe in the Section~\ref{sec:limit-functions-r4}.
  6988. As mentioned above, for a tail call we pop the caller's frame prior to
  6989. making the tail call. The instructions for popping a frame are the
  6990. instructions that we usually place in the conclusion of a
  6991. function. Thus, we also need to place such code immediately before
  6992. each tail call. These instructions include restoring the callee-saved
  6993. registers, so it is good that the argument passing registers are all
  6994. caller-saved registers.
  6995. One last note regarding which instruction to use to make the tail
  6996. call. When the callee is finished, it should not return to the current
  6997. function, but it should return to the function that called the current
  6998. one. Thus, the return address that is already on the stack is the
  6999. right one, and we should not use \key{callq} to make the tail call, as
  7000. that would unnecessarily overwrite the return address. Instead we can
  7001. simply use the \key{jmp} instruction. Like the indirect function call,
  7002. we write an \emph{indirect jump}\index{indirect jump} with a register
  7003. prefixed with an asterisk. We recommend using \code{rax} to hold the
  7004. jump target because the preceding conclusion overwrites just about
  7005. everything else.
  7006. \begin{lstlisting}
  7007. jmp *%rax
  7008. \end{lstlisting}
  7009. \section{Shrink $R_4$}
  7010. \label{sec:shrink-r4}
  7011. The \code{shrink} pass performs a minor modification to ease the
  7012. later passes. This pass introduces an explicit \code{main} function
  7013. and changes the top \code{ProgramDefsExp} form to
  7014. \code{ProgramDefs} as follows.
  7015. \begin{lstlisting}
  7016. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  7017. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  7018. \end{lstlisting}
  7019. where $\itm{mainDef}$ is
  7020. \begin{lstlisting}
  7021. (Def 'main '() 'Integer '() |$\Exp'$|)
  7022. \end{lstlisting}
  7023. \section{Reveal Functions and the $F_1$ language}
  7024. \label{sec:reveal-functions-r4}
  7025. The syntax of $R_4$ is inconvenient for purposes of compilation in one
  7026. respect: it conflates the use of function names and local
  7027. variables. This is a problem because we need to compile the use of a
  7028. function name differently than the use of a local variable; we need to
  7029. use \code{leaq} to convert the function name (a label in x86) to an
  7030. address in a register. Thus, it is a good idea to create a new pass
  7031. that changes function references from just a symbol $f$ to
  7032. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  7033. output language, $F_1$, is defined in Figure~\ref{fig:f1-syntax}.
  7034. The concrete syntax for a function reference is $\CFUNREF{f}$.
  7035. \begin{figure}[tp]
  7036. \centering
  7037. \fbox{
  7038. \begin{minipage}{0.96\textwidth}
  7039. \[
  7040. \begin{array}{lcl}
  7041. \Exp &::=& \ldots \mid \FUNREF{\Var}\\
  7042. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7043. F_1 &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  7044. \end{array}
  7045. \]
  7046. \end{minipage}
  7047. }
  7048. \caption{The abstract syntax $F_1$, an extension of $R_4$
  7049. (Figure~\ref{fig:r4-syntax}).}
  7050. \label{fig:f1-syntax}
  7051. \end{figure}
  7052. %% Distinguishing between calls in tail position and non-tail position
  7053. %% requires the pass to have some notion of context. We recommend using
  7054. %% two mutually recursive functions, one for processing expressions in
  7055. %% tail position and another for the rest.
  7056. Placing this pass after \code{uniquify} will make sure that there are
  7057. no local variables and functions that share the same name. On the
  7058. other hand, \code{reveal-functions} needs to come before the
  7059. \code{explicate-control} pass because that pass helps us compile
  7060. \code{FunRef} forms into assignment statements.
  7061. \section{Limit Functions}
  7062. \label{sec:limit-functions-r4}
  7063. Recall that we wish to limit the number of function parameters to six
  7064. so that we do not need to use the stack for argument passing, which
  7065. makes it easier to implement efficient tail calls. However, because
  7066. the input language $R_4$ supports arbitrary numbers of function
  7067. arguments, we have some work to do!
  7068. This pass transforms functions and function calls that involve more
  7069. than six arguments to pass the first five arguments as usual, but it
  7070. packs the rest of the arguments into a vector and passes it as the
  7071. sixth argument.
  7072. Each function definition with too many parameters is transformed as
  7073. follows.
  7074. \begin{lstlisting}
  7075. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  7076. |$\Rightarrow$|
  7077. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  7078. \end{lstlisting}
  7079. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  7080. the occurrences of the later parameters with vector references.
  7081. \begin{lstlisting}
  7082. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  7083. \end{lstlisting}
  7084. For function calls with too many arguments, the \code{limit-functions}
  7085. pass transforms them in the following way.
  7086. \begin{tabular}{lll}
  7087. \begin{minipage}{0.2\textwidth}
  7088. \begin{lstlisting}
  7089. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  7090. \end{lstlisting}
  7091. \end{minipage}
  7092. &
  7093. $\Rightarrow$
  7094. &
  7095. \begin{minipage}{0.4\textwidth}
  7096. \begin{lstlisting}
  7097. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  7098. \end{lstlisting}
  7099. \end{minipage}
  7100. \end{tabular}
  7101. \section{Remove Complex Operands}
  7102. \label{sec:rco-r4}
  7103. The primary decisions to make for this pass is whether to classify
  7104. \code{FunRef} and \code{Apply} as either atomic or complex
  7105. expressions. Recall that a simple expression will eventually end up as
  7106. just an immediate argument of an x86 instruction. Function
  7107. application will be translated to a sequence of instructions, so
  7108. \code{Apply} must be classified as complex expression.
  7109. On the other hand, the arguments of \code{Apply} should be
  7110. atomic expressions.
  7111. %
  7112. Regarding \code{FunRef}, as discussed above, the function label needs
  7113. to be converted to an address using the \code{leaq} instruction. Thus,
  7114. even though \code{FunRef} seems rather simple, it needs to be
  7115. classified as a complex expression so that we generate an assignment
  7116. statement with a left-hand side that can serve as the target of the
  7117. \code{leaq}. Figure~\ref{fig:r4-anf-syntax} defines the
  7118. output language $R_4^{\dagger}$ of this pass.
  7119. \begin{figure}[tp]
  7120. \centering
  7121. \fbox{
  7122. \begin{minipage}{0.96\textwidth}
  7123. \small
  7124. \[
  7125. \begin{array}{rcl}
  7126. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  7127. \mid \VOID{} } \\
  7128. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  7129. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  7130. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  7131. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  7132. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  7133. &\mid& \gray{ \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  7134. \mid \LP\key{GlobalValue}~\Var\RP }\\
  7135. &\mid& \FUNREF{\Var} \mid \APPLY{\Atm}{\Atm\ldots}\\
  7136. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7137. R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  7138. \end{array}
  7139. \]
  7140. \end{minipage}
  7141. }
  7142. \caption{$R_4^{\dagger}$ is $R_4$ in administrative normal form (ANF).}
  7143. \label{fig:r4-anf-syntax}
  7144. \end{figure}
  7145. \section{Explicate Control and the $C_3$ language}
  7146. \label{sec:explicate-control-r4}
  7147. Figures~\ref{fig:c3-concrete-syntax} and \ref{fig:c3-syntax} define
  7148. the concrete and abstract syntax for $C_3$, the output of
  7149. \key{explicate-control}. The auxiliary functions for assignment and
  7150. tail contexts should be updated with cases for \code{Apply} and
  7151. \code{FunRef} and the function for predicate context should be updated
  7152. for \code{Apply} but not \code{FunRef}. (A \code{FunRef} can't be a
  7153. Boolean.) In assignment and predicate contexts, \code{Apply} becomes
  7154. \code{Call}, whereas in tail position \code{Apply} becomes
  7155. \code{TailCall}. We recommend defining a new auxiliary function for
  7156. processing function definitions. This code is similar to the case for
  7157. \code{Program} in $R_3$. The top-level \code{explicate-control}
  7158. function that handles the \code{ProgramDefs} form of $R_4$ can then
  7159. apply this new function to all the function definitions.
  7160. \begin{figure}[tp]
  7161. \fbox{
  7162. \begin{minipage}{0.96\textwidth}
  7163. \small
  7164. \[
  7165. \begin{array}{lcl}
  7166. \Atm &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  7167. \\
  7168. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  7169. \Exp &::= & \gray{ \Atm \mid \LP\key{read}\RP \mid \LP\key{-}\;\Atm\RP \mid \LP\key{+} \; \Atm\;\Atm\RP
  7170. \mid \LP\key{not}\;\Atm\RP \mid \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  7171. &\mid& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  7172. \mid \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  7173. &\mid& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \mid \LP\key{global-value} \,\itm{name}\RP \mid \LP\key{void}\RP } \\
  7174. &\mid& \LP\key{fun-ref}~\itm{label}\RP \mid \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  7175. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  7176. \mid \LP\key{collect} \,\itm{int}\RP }\\
  7177. \Tail &::= & \gray{\RETURN{\Exp} \mid \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  7178. &\mid& \gray{\LP\key{goto}\,\itm{label}\RP
  7179. \mid \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  7180. &\mid& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  7181. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  7182. C_3 & ::= & \Def\ldots
  7183. \end{array}
  7184. \]
  7185. \end{minipage}
  7186. }
  7187. \caption{The $C_3$ language, extending $C_2$ (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  7188. \label{fig:c3-concrete-syntax}
  7189. \end{figure}
  7190. \begin{figure}[tp]
  7191. \fbox{
  7192. \begin{minipage}{0.96\textwidth}
  7193. \small
  7194. \[
  7195. \begin{array}{lcl}
  7196. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  7197. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  7198. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  7199. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  7200. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  7201. &\mid& \gray{ \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP } \\
  7202. &\mid& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  7203. &\mid& \gray{ \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP }\\
  7204. &\mid& \gray{ \LP\key{GlobalValue} \,\Var\RP \mid \LP\key{Void}\RP }\\
  7205. &\mid& \FUNREF{\itm{label}} \mid \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  7206. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  7207. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  7208. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  7209. \mid \GOTO{\itm{label}} } \\
  7210. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  7211. &\mid& \TAILCALL{\Atm}{\Atm\ldots} \\
  7212. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  7213. C_3 & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  7214. \end{array}
  7215. \]
  7216. \end{minipage}
  7217. }
  7218. \caption{The abstract syntax of $C_3$, extending $C_2$ (Figure~\ref{fig:c2-syntax}).}
  7219. \label{fig:c3-syntax}
  7220. \end{figure}
  7221. \section{Select Instructions and the x86$_3$ Language}
  7222. \label{sec:select-r4}
  7223. \index{instruction selection}
  7224. The output of select instructions is a program in the x86$_3$
  7225. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  7226. \index{x86}
  7227. \begin{figure}[tp]
  7228. \fbox{
  7229. \begin{minipage}{0.96\textwidth}
  7230. \small
  7231. \[
  7232. \begin{array}{lcl}
  7233. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)}
  7234. \mid \LP\key{fun-ref}\; \itm{label}\RP\\
  7235. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  7236. \Instr &::=& \ldots
  7237. \mid \key{callq}\;\key{*}\Arg \mid \key{tailjmp}\;\Arg
  7238. \mid \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  7239. \Block &::= & \Instr\ldots \\
  7240. \Def &::= & \LP\key{define} \; \LP\itm{label}\RP \;\LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\RP\\
  7241. x86_3 &::= & \Def\ldots
  7242. \end{array}
  7243. \]
  7244. \end{minipage}
  7245. }
  7246. \caption{The concrete syntax of x86$_3$ (extends x86$_2$ of Figure~\ref{fig:x86-2-concrete}).}
  7247. \label{fig:x86-3-concrete}
  7248. \end{figure}
  7249. \begin{figure}[tp]
  7250. \fbox{
  7251. \begin{minipage}{0.96\textwidth}
  7252. \small
  7253. \[
  7254. \begin{array}{lcl}
  7255. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  7256. \mid \BYTEREG{\Reg} } \\
  7257. &\mid& \gray{ (\key{Global}~\Var) } \mid \FUNREF{\itm{label}} \\
  7258. \Instr &::=& \ldots \mid \INDCALLQ{\Arg}{\itm{int}}
  7259. \mid \TAILJMP{\Arg}{\itm{int}}\\
  7260. &\mid& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  7261. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  7262. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  7263. x86_3 &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  7264. \end{array}
  7265. \]
  7266. \end{minipage}
  7267. }
  7268. \caption{The abstract syntax of x86$_3$ (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  7269. \label{fig:x86-3}
  7270. \end{figure}
  7271. An assignment of a function reference to a variable becomes a
  7272. load-effective-address instruction as follows: \\
  7273. \begin{tabular}{lcl}
  7274. \begin{minipage}{0.35\textwidth}
  7275. \begin{lstlisting}
  7276. |$\itm{lhs}$| = (fun-ref |$f$|);
  7277. \end{lstlisting}
  7278. \end{minipage}
  7279. &
  7280. $\Rightarrow$\qquad\qquad
  7281. &
  7282. \begin{minipage}{0.3\textwidth}
  7283. \begin{lstlisting}
  7284. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  7285. \end{lstlisting}
  7286. \end{minipage}
  7287. \end{tabular} \\
  7288. Regarding function definitions, we need to remove the parameters and
  7289. instead perform parameter passing using the conventions discussed in
  7290. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  7291. registers. We recommend turning the parameters into local variables
  7292. and generating instructions at the beginning of the function to move
  7293. from the argument passing registers to these local variables.
  7294. \begin{lstlisting}
  7295. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  7296. |$\Rightarrow$|
  7297. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  7298. \end{lstlisting}
  7299. The $G'$ control-flow graph is the same as $G$ except that the
  7300. \code{start} block is modified to add the instructions for moving from
  7301. the argument registers to the parameter variables. So the \code{start}
  7302. block of $G$ shown on the left is changed to the code on the right.
  7303. \begin{center}
  7304. \begin{minipage}{0.3\textwidth}
  7305. \begin{lstlisting}
  7306. start:
  7307. |$\itm{instr}_1$|
  7308. |$\vdots$|
  7309. |$\itm{instr}_n$|
  7310. \end{lstlisting}
  7311. \end{minipage}
  7312. $\Rightarrow$
  7313. \begin{minipage}{0.3\textwidth}
  7314. \begin{lstlisting}
  7315. start:
  7316. movq %rdi, |$x_1$|
  7317. movq %rsi, |$x_2$|
  7318. |$\vdots$|
  7319. |$\itm{instr}_1$|
  7320. |$\vdots$|
  7321. |$\itm{instr}_n$|
  7322. \end{lstlisting}
  7323. \end{minipage}
  7324. \end{center}
  7325. By changing the parameters to local variables, we are giving the
  7326. register allocator control over which registers or stack locations to
  7327. use for them. If you implemented the move-biasing challenge
  7328. (Section~\ref{sec:move-biasing}), the register allocator will try to
  7329. assign the parameter variables to the corresponding argument register,
  7330. in which case the \code{patch-instructions} pass will remove the
  7331. \code{movq} instruction. This happens in the example translation in
  7332. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  7333. the \code{add} function.
  7334. %
  7335. Also, note that the register allocator will perform liveness analysis
  7336. on this sequence of move instructions and build the interference
  7337. graph. So, for example, $x_1$ will be marked as interfering with
  7338. \code{rsi} and that will prevent the assignment of $x_1$ to
  7339. \code{rsi}, which is good, because that would overwrite the argument
  7340. that needs to move into $x_2$.
  7341. Next, consider the compilation of function calls. In the mirror image
  7342. of handling the parameters of function definitions, the arguments need
  7343. to be moved to the argument passing registers. The function call
  7344. itself is performed with an indirect function call. The return value
  7345. from the function is stored in \code{rax}, so it needs to be moved
  7346. into the \itm{lhs}.
  7347. \begin{lstlisting}
  7348. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  7349. |$\Rightarrow$|
  7350. movq |$\itm{arg}_1$|, %rdi
  7351. movq |$\itm{arg}_2$|, %rsi
  7352. |$\vdots$|
  7353. callq *|\itm{fun}|
  7354. movq %rax, |\itm{lhs}|
  7355. \end{lstlisting}
  7356. The \code{IndirectCallq} AST node includes an integer for the arity of
  7357. the function, i.e., the number of parameters. That information is
  7358. useful in the \code{uncover-live} pass for determining which
  7359. argument-passing registers are potentially read during the call.
  7360. For tail calls, the parameter passing is the same as non-tail calls:
  7361. generate instructions to move the arguments into to the argument
  7362. passing registers. After that we need to pop the frame from the
  7363. procedure call stack. However, we do not yet know how big the frame
  7364. is; that gets determined during register allocation. So instead of
  7365. generating those instructions here, we invent a new instruction that
  7366. means ``pop the frame and then do an indirect jump'', which we name
  7367. \code{TailJmp}. The abstract syntax for this instruction includes an
  7368. argument that specifies where to jump and an integer that represents
  7369. the arity of the function being called.
  7370. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  7371. using the label \code{start} for the initial block of a program, and
  7372. in Section~\ref{sec:select-r1} we recommended labeling the conclusion
  7373. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  7374. can be compiled to an assignment to \code{rax} followed by a jump to
  7375. \code{conclusion}. With the addition of function definitions, we will
  7376. have a starting block and conclusion for each function, but their
  7377. labels need to be unique. We recommend prepending the function's name
  7378. to \code{start} and \code{conclusion}, respectively, to obtain unique
  7379. labels. (Alternatively, one could \code{gensym} labels for the start
  7380. and conclusion and store them in the $\itm{info}$ field of the
  7381. function definition.)
  7382. \section{Register Allocation}
  7383. \label{sec:register-allocation-r4}
  7384. \subsection{Liveness Analysis}
  7385. \label{sec:liveness-analysis-r4}
  7386. \index{liveness analysis}
  7387. %% The rest of the passes need only minor modifications to handle the new
  7388. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  7389. %% \code{leaq}.
  7390. The \code{IndirectCallq} instruction should be treated like
  7391. \code{Callq} regarding its written locations $W$, in that they should
  7392. include all the caller-saved registers. Recall that the reason for
  7393. that is to force call-live variables to be assigned to callee-saved
  7394. registers or to be spilled to the stack.
  7395. Regarding the set of read locations $R$ the arity field of
  7396. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  7397. argument-passing registers should be considered as read by those
  7398. instructions.
  7399. \subsection{Build Interference Graph}
  7400. \label{sec:build-interference-r4}
  7401. With the addition of function definitions, we compute an interference
  7402. graph for each function (not just one for the whole program).
  7403. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  7404. spill vector-typed variables that are live during a call to the
  7405. \code{collect}. With the addition of functions to our language, we
  7406. need to revisit this issue. Many functions perform allocation and
  7407. therefore have calls to the collector inside of them. Thus, we should
  7408. not only spill a vector-typed variable when it is live during a call
  7409. to \code{collect}, but we should spill the variable if it is live
  7410. during any function call. Thus, in the \code{build-interference} pass,
  7411. we recommend adding interference edges between call-live vector-typed
  7412. variables and the callee-saved registers (in addition to the usual
  7413. addition of edges between call-live variables and the caller-saved
  7414. registers).
  7415. \subsection{Allocate Registers}
  7416. The primary change to the \code{allocate-registers} pass is adding an
  7417. auxiliary function for handling definitions (the \Def{} non-terminal
  7418. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  7419. logic is the same as described in
  7420. Chapter~\ref{ch:register-allocation-r1}, except now register
  7421. allocation is performed many times, once for each function definition,
  7422. instead of just once for the whole program.
  7423. \section{Patch Instructions}
  7424. In \code{patch-instructions}, you should deal with the x86
  7425. idiosyncrasy that the destination argument of \code{leaq} must be a
  7426. register. Additionally, you should ensure that the argument of
  7427. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  7428. code generation more convenient, because we trample many registers
  7429. before the tail call (as explained in the next section).
  7430. \section{Print x86}
  7431. For the \code{print-x86} pass, the cases for \code{FunRef} and
  7432. \code{IndirectCallq} are straightforward: output their concrete
  7433. syntax.
  7434. \begin{lstlisting}
  7435. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  7436. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  7437. \end{lstlisting}
  7438. The \code{TailJmp} node requires a bit work. A straightforward
  7439. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  7440. before the jump we need to pop the current frame. This sequence of
  7441. instructions is the same as the code for the conclusion of a function,
  7442. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  7443. Regarding function definitions, you will need to generate a prelude
  7444. and conclusion for each one. This code is similar to the prelude and
  7445. conclusion that you generated for the \code{main} function in
  7446. Chapter~\ref{ch:tuples}. To review, the prelude of every function
  7447. should carry out the following steps.
  7448. \begin{enumerate}
  7449. \item Start with \code{.global} and \code{.align} directives followed
  7450. by the label for the function. (See Figure~\ref{fig:add-fun} for an
  7451. example.)
  7452. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  7453. pointer.
  7454. \item Push to the stack all of the callee-saved registers that were
  7455. used for register allocation.
  7456. \item Move the stack pointer \code{rsp} down by the size of the stack
  7457. frame for this function, which depends on the number of regular
  7458. spills. (Aligned to 16 bytes.)
  7459. \item Move the root stack pointer \code{r15} up by the size of the
  7460. root-stack frame for this function, which depends on the number of
  7461. spilled vectors. \label{root-stack-init}
  7462. \item Initialize to zero all of the entries in the root-stack frame.
  7463. \item Jump to the start block.
  7464. \end{enumerate}
  7465. The prelude of the \code{main} function has one additional task: call
  7466. the \code{initialize} function to set up the garbage collector and
  7467. move the value of the global \code{rootstack\_begin} in
  7468. \code{r15}. This should happen before step \ref{root-stack-init}
  7469. above, which depends on \code{r15}.
  7470. The conclusion of every function should do the following.
  7471. \begin{enumerate}
  7472. \item Move the stack pointer back up by the size of the stack frame
  7473. for this function.
  7474. \item Restore the callee-saved registers by popping them from the
  7475. stack.
  7476. \item Move the root stack pointer back down by the size of the
  7477. root-stack frame for this function.
  7478. \item Restore \code{rbp} by popping it from the stack.
  7479. \item Return to the caller with the \code{retq} instruction.
  7480. \end{enumerate}
  7481. \begin{exercise}\normalfont
  7482. Expand your compiler to handle $R_4$ as outlined in this chapter.
  7483. Create 5 new programs that use functions, including examples that pass
  7484. functions and return functions from other functions, recursive
  7485. functions, functions that create vectors, and functions that make tail
  7486. calls. Test your compiler on these new programs and all of your
  7487. previously created test programs.
  7488. \end{exercise}
  7489. \begin{figure}[tbp]
  7490. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7491. \node (R4) at (0,2) {\large $R_4$};
  7492. \node (R4-2) at (3,2) {\large $R_4$};
  7493. %\node (R4-3) at (6,2) {\large $R_4$};
  7494. \node (F1-1) at (12,0) {\large $F_1$};
  7495. \node (F1-2) at (9,0) {\large $F_1$};
  7496. \node (F1-3) at (6,0) {\large $F_1$};
  7497. \node (F1-4) at (3,0) {\large $F_1$};
  7498. \node (C3-2) at (3,-2) {\large $C_3$};
  7499. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  7500. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  7501. \node (x86-4) at (9,-4) {\large $\text{x86}_3$};
  7502. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  7503. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  7504. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  7505. %\path[->,bend left=15] (R4) edge [above] node
  7506. % {\ttfamily\footnotesize\color{red} type-check} (R4-2);
  7507. \path[->,bend left=15] (R4) edge [above] node
  7508. {\ttfamily\footnotesize uniquify} (R4-2);
  7509. \path[->,bend left=15] (R4-2) edge [right] node
  7510. {\ttfamily\footnotesize\color{red} reveal-functions} (F1-1);
  7511. \path[->,bend left=15] (F1-1) edge [below] node
  7512. {\ttfamily\footnotesize\color{red} limit-functions} (F1-2);
  7513. \path[->,bend right=15] (F1-2) edge [above] node
  7514. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  7515. \path[->,bend right=15] (F1-3) edge [above] node
  7516. {\ttfamily\footnotesize\color{red} remove-complex.} (F1-4);
  7517. \path[->,bend left=15] (F1-4) edge [right] node
  7518. {\ttfamily\footnotesize\color{red} explicate-control} (C3-2);
  7519. \path[->,bend right=15] (C3-2) edge [left] node
  7520. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  7521. \path[->,bend left=15] (x86-2) edge [left] node
  7522. {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  7523. \path[->,bend right=15] (x86-2-1) edge [below] node
  7524. {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  7525. \path[->,bend right=15] (x86-2-2) edge [left] node
  7526. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7527. \path[->,bend left=15] (x86-3) edge [above] node
  7528. {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  7529. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  7530. \end{tikzpicture}
  7531. \caption{Diagram of the passes for $R_4$, a language with functions.}
  7532. \label{fig:R4-passes}
  7533. \end{figure}
  7534. Figure~\ref{fig:R4-passes} gives an overview of the passes for
  7535. compiling $R_4$ to x86.
  7536. \section{An Example Translation}
  7537. \label{sec:functions-example}
  7538. Figure~\ref{fig:add-fun} shows an example translation of a simple
  7539. function in $R_4$ to x86. The figure also includes the results of the
  7540. \code{explicate-control} and \code{select-instructions} passes.
  7541. \begin{figure}[htbp]
  7542. \begin{tabular}{ll}
  7543. \begin{minipage}{0.5\textwidth}
  7544. % s3_2.rkt
  7545. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7546. (define (add [x : Integer] [y : Integer])
  7547. : Integer
  7548. (+ x y))
  7549. (add 40 2)
  7550. \end{lstlisting}
  7551. $\Downarrow$
  7552. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7553. (define (add86 [x87 : Integer]
  7554. [y88 : Integer]) : Integer
  7555. add86start:
  7556. return (+ x87 y88);
  7557. )
  7558. (define (main) : Integer ()
  7559. mainstart:
  7560. tmp89 = (fun-ref add86);
  7561. (tail-call tmp89 40 2)
  7562. )
  7563. \end{lstlisting}
  7564. \end{minipage}
  7565. &
  7566. $\Rightarrow$
  7567. \begin{minipage}{0.5\textwidth}
  7568. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7569. (define (add86) : Integer
  7570. add86start:
  7571. movq %rdi, x87
  7572. movq %rsi, y88
  7573. movq x87, %rax
  7574. addq y88, %rax
  7575. jmp add11389conclusion
  7576. )
  7577. (define (main) : Integer
  7578. mainstart:
  7579. leaq (fun-ref add86), tmp89
  7580. movq $40, %rdi
  7581. movq $2, %rsi
  7582. tail-jmp tmp89
  7583. )
  7584. \end{lstlisting}
  7585. $\Downarrow$
  7586. \end{minipage}
  7587. \end{tabular}
  7588. \begin{tabular}{ll}
  7589. \begin{minipage}{0.3\textwidth}
  7590. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7591. .globl add86
  7592. .align 16
  7593. add86:
  7594. pushq %rbp
  7595. movq %rsp, %rbp
  7596. jmp add86start
  7597. add86start:
  7598. movq %rdi, %rax
  7599. addq %rsi, %rax
  7600. jmp add86conclusion
  7601. add86conclusion:
  7602. popq %rbp
  7603. retq
  7604. \end{lstlisting}
  7605. \end{minipage}
  7606. &
  7607. \begin{minipage}{0.5\textwidth}
  7608. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7609. .globl main
  7610. .align 16
  7611. main:
  7612. pushq %rbp
  7613. movq %rsp, %rbp
  7614. movq $16384, %rdi
  7615. movq $16384, %rsi
  7616. callq initialize
  7617. movq rootstack_begin(%rip), %r15
  7618. jmp mainstart
  7619. mainstart:
  7620. leaq add86(%rip), %rcx
  7621. movq $40, %rdi
  7622. movq $2, %rsi
  7623. movq %rcx, %rax
  7624. popq %rbp
  7625. jmp *%rax
  7626. mainconclusion:
  7627. popq %rbp
  7628. retq
  7629. \end{lstlisting}
  7630. \end{minipage}
  7631. \end{tabular}
  7632. \caption{Example compilation of a simple function to x86.}
  7633. \label{fig:add-fun}
  7634. \end{figure}
  7635. % Challenge idea: inlining! (simple version)
  7636. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7637. \chapter{Lexically Scoped Functions}
  7638. \label{ch:lambdas}
  7639. \index{lambda}
  7640. \index{lexical scoping}
  7641. This chapter studies lexically scoped functions as they appear in
  7642. functional languages such as Racket. By lexical scoping we mean that a
  7643. function's body may refer to variables whose binding site is outside
  7644. of the function, in an enclosing scope.
  7645. %
  7646. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  7647. $R_5$, which extends $R_4$ with anonymous functions using the
  7648. \key{lambda} form. The body of the \key{lambda}, refers to three
  7649. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  7650. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  7651. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  7652. parameter of function \code{f}. The \key{lambda} is returned from the
  7653. function \code{f}. The main expression of the program includes two
  7654. calls to \code{f} with different arguments for \code{x}, first
  7655. \code{5} then \code{3}. The functions returned from \code{f} are bound
  7656. to variables \code{g} and \code{h}. Even though these two functions
  7657. were created by the same \code{lambda}, they are really different
  7658. functions because they use different values for \code{x}. Applying
  7659. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  7660. \code{15} produces \code{22}. The result of this program is \code{42}.
  7661. \begin{figure}[btp]
  7662. % s4_6.rkt
  7663. \begin{lstlisting}
  7664. (define (f [x : Integer]) : (Integer -> Integer)
  7665. (let ([y 4])
  7666. (lambda: ([z : Integer]) : Integer
  7667. (+ x (+ y z)))))
  7668. (let ([g (f 5)])
  7669. (let ([h (f 3)])
  7670. (+ (g 11) (h 15))))
  7671. \end{lstlisting}
  7672. \caption{Example of a lexically scoped function.}
  7673. \label{fig:lexical-scoping}
  7674. \end{figure}
  7675. The approach that we take for implementing lexically scoped
  7676. functions is to compile them into top-level function definitions,
  7677. translating from $R_5$ into $R_4$. However, the compiler will need to
  7678. provide special treatment for variable occurrences such as \code{x}
  7679. and \code{y} in the body of the \code{lambda} of
  7680. Figure~\ref{fig:lexical-scoping}. After all, an $R_4$ function may not
  7681. refer to variables defined outside of it. To identify such variable
  7682. occurrences, we review the standard notion of free variable.
  7683. \begin{definition}
  7684. A variable is \emph{free in expression} $e$ if the variable occurs
  7685. inside $e$ but does not have an enclosing binding in $e$.\index{free
  7686. variable}
  7687. \end{definition}
  7688. For example, in the expression \code{(+ x (+ y z))} the variables
  7689. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  7690. only \code{x} and \code{y} are free in the following expression
  7691. because \code{z} is bound by the \code{lambda}.
  7692. \begin{lstlisting}
  7693. (lambda: ([z : Integer]) : Integer
  7694. (+ x (+ y z)))
  7695. \end{lstlisting}
  7696. So the free variables of a \code{lambda} are the ones that will need
  7697. special treatment. We need to arrange for some way to transport, at
  7698. runtime, the values of those variables from the point where the
  7699. \code{lambda} was created to the point where the \code{lambda} is
  7700. applied. An efficient solution to the problem, due to
  7701. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  7702. free variables together with the function pointer for the lambda's
  7703. code, an arrangement called a \emph{flat closure} (which we shorten to
  7704. just ``closure''). \index{closure}\index{flat closure} Fortunately,
  7705. we have all the ingredients to make closures, Chapter~\ref{ch:tuples}
  7706. gave us vectors and Chapter~\ref{ch:functions} gave us function
  7707. pointers. The function pointer resides at index $0$ and the
  7708. values for the free variables will fill in the rest of the vector.
  7709. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  7710. how closures work. It's a three-step dance. The program first calls
  7711. function \code{f}, which creates a closure for the \code{lambda}. The
  7712. closure is a vector whose first element is a pointer to the top-level
  7713. function that we will generate for the \code{lambda}, the second
  7714. element is the value of \code{x}, which is \code{5}, and the third
  7715. element is \code{4}, the value of \code{y}. The closure does not
  7716. contain an element for \code{z} because \code{z} is not a free
  7717. variable of the \code{lambda}. Creating the closure is step 1 of the
  7718. dance. The closure is returned from \code{f} and bound to \code{g}, as
  7719. shown in Figure~\ref{fig:closures}.
  7720. %
  7721. The second call to \code{f} creates another closure, this time with
  7722. \code{3} in the second slot (for \code{x}). This closure is also
  7723. returned from \code{f} but bound to \code{h}, which is also shown in
  7724. Figure~\ref{fig:closures}.
  7725. \begin{figure}[tbp]
  7726. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  7727. \caption{Example closure representation for the \key{lambda}'s
  7728. in Figure~\ref{fig:lexical-scoping}.}
  7729. \label{fig:closures}
  7730. \end{figure}
  7731. Continuing with the example, consider the application of \code{g} to
  7732. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  7733. obtain the function pointer in the first element of the closure and
  7734. call it, passing in the closure itself and then the regular arguments,
  7735. in this case \code{11}. This technique for applying a closure is step
  7736. 2 of the dance.
  7737. %
  7738. But doesn't this \code{lambda} only take 1 argument, for parameter
  7739. \code{z}? The third and final step of the dance is generating a
  7740. top-level function for a \code{lambda}. We add an additional
  7741. parameter for the closure and we insert a \code{let} at the beginning
  7742. of the function for each free variable, to bind those variables to the
  7743. appropriate elements from the closure parameter.
  7744. %
  7745. This three-step dance is known as \emph{closure conversion}. We
  7746. discuss the details of closure conversion in
  7747. Section~\ref{sec:closure-conversion} and the code generated from the
  7748. example in Section~\ref{sec:example-lambda}. But first we define the
  7749. syntax and semantics of $R_5$ in Section~\ref{sec:r5}.
  7750. \section{The $R_5$ Language}
  7751. \label{sec:r5}
  7752. The concrete and abstract syntax for $R_5$, a language with anonymous
  7753. functions and lexical scoping, is defined in
  7754. Figures~\ref{fig:r5-concrete-syntax} and ~\ref{fig:r5-syntax}. It adds
  7755. the \key{lambda} form to the grammar for $R_4$, which already has
  7756. syntax for function application.
  7757. \begin{figure}[tp]
  7758. \centering
  7759. \fbox{
  7760. \begin{minipage}{0.96\textwidth}
  7761. \small
  7762. \[
  7763. \begin{array}{lcl}
  7764. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7765. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}
  7766. \mid (\Type\ldots \; \key{->}\; \Type)} \\
  7767. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  7768. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  7769. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  7770. &\mid& \gray{\key{\#t} \mid \key{\#f}
  7771. \mid (\key{and}\;\Exp\;\Exp)
  7772. \mid (\key{or}\;\Exp\;\Exp)
  7773. \mid (\key{not}\;\Exp) } \\
  7774. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  7775. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  7776. (\key{vector-ref}\;\Exp\;\Int)} \\
  7777. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  7778. \mid (\Exp \; \Exp\ldots) } \\
  7779. &\mid& \LP \key{procedure-arity}~\Exp\RP \\
  7780. &\mid& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  7781. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  7782. R_5 &::=& \gray{\Def\ldots \; \Exp}
  7783. \end{array}
  7784. \]
  7785. \end{minipage}
  7786. }
  7787. \caption{The concrete syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-concrete-syntax})
  7788. with \key{lambda}.}
  7789. \label{fig:r5-concrete-syntax}
  7790. \end{figure}
  7791. \begin{figure}[tp]
  7792. \centering
  7793. \fbox{
  7794. \begin{minipage}{0.96\textwidth}
  7795. \small
  7796. \[
  7797. \begin{array}{lcl}
  7798. \itm{op} &::=& \ldots \mid \code{procedure-arity} \\
  7799. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  7800. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  7801. &\mid& \gray{ \BOOL{\itm{bool}}
  7802. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  7803. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  7804. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  7805. &\mid& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  7806. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  7807. R_5 &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  7808. \end{array}
  7809. \]
  7810. \end{minipage}
  7811. }
  7812. \caption{The abstract syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax}).}
  7813. \label{fig:r5-syntax}
  7814. \end{figure}
  7815. \index{interpreter}
  7816. \label{sec:interp-R5}
  7817. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  7818. $R_5$. The clause for \key{lambda} saves the current environment
  7819. inside the returned \key{lambda}. Then the clause for \key{Apply} uses
  7820. the environment from the \key{lambda}, the \code{lam-env}, when
  7821. interpreting the body of the \key{lambda}. The \code{lam-env}
  7822. environment is extended with the mapping of parameters to argument
  7823. values.
  7824. \begin{figure}[tbp]
  7825. \begin{lstlisting}
  7826. (define interp-R5-class
  7827. (class interp-R4-class
  7828. (super-new)
  7829. (define/override (interp-op op)
  7830. (match op
  7831. ['procedure-arity
  7832. (lambda (v)
  7833. (match v
  7834. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  7835. [else (error 'interp-op "expected a function, not ~a" v)]))]
  7836. [else (super interp-op op)]))
  7837. (define/override ((interp-exp env) e)
  7838. (define recur (interp-exp env))
  7839. (match e
  7840. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  7841. `(function ,xs ,body ,env)]
  7842. [else ((super interp-exp env) e)]))
  7843. ))
  7844. (define (interp-R5 p)
  7845. (send (new interp-R5-class) interp-program p))
  7846. \end{lstlisting}
  7847. \caption{Interpreter for $R_5$.}
  7848. \label{fig:interp-R5}
  7849. \end{figure}
  7850. \label{sec:type-check-r5}
  7851. \index{type checking}
  7852. Figure~\ref{fig:type-check-R5} shows how to type check the new
  7853. \key{lambda} form. The body of the \key{lambda} is checked in an
  7854. environment that includes the current environment (because it is
  7855. lexically scoped) and also includes the \key{lambda}'s parameters. We
  7856. require the body's type to match the declared return type.
  7857. \begin{figure}[tbp]
  7858. \begin{lstlisting}
  7859. (define (type-check-R5 env)
  7860. (lambda (e)
  7861. (match e
  7862. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  7863. (define-values (new-body bodyT)
  7864. ((type-check-exp (append (map cons xs Ts) env)) body))
  7865. (define ty `(,@Ts -> ,rT))
  7866. (cond
  7867. [(equal? rT bodyT)
  7868. (values (HasType (Lambda params rT new-body) ty) ty)]
  7869. [else
  7870. (error "mismatch in return type" bodyT rT)])]
  7871. ...
  7872. )))
  7873. \end{lstlisting}
  7874. \caption{Type checking the \key{lambda}'s in $R_5$.}
  7875. \label{fig:type-check-R5}
  7876. \end{figure}
  7877. \section{Reveal Functions and the $F_2$ language}
  7878. \label{sec:reveal-functions-r5}
  7879. To support the \code{procedure-arity} operator we need to communicate
  7880. the arity of a function to the point of closure creation. We can
  7881. accomplish this by replacing the $\FUNREF{\Var}$ struct with one that
  7882. has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$. The
  7883. output of this pass is the language $F_2$, whose syntax is defined in
  7884. Figure~\ref{fig:f2-syntax}.
  7885. \begin{figure}[tp]
  7886. \centering
  7887. \fbox{
  7888. \begin{minipage}{0.96\textwidth}
  7889. \[
  7890. \begin{array}{lcl}
  7891. \Exp &::=& \ldots \mid \FUNREFARITY{\Var}{\Int}\\
  7892. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7893. F_2 &::=& \gray{\PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}}
  7894. \end{array}
  7895. \]
  7896. \end{minipage}
  7897. }
  7898. \caption{The abstract syntax $F_2$, an extension of $R_5$
  7899. (Figure~\ref{fig:r5-syntax}).}
  7900. \label{fig:f2-syntax}
  7901. \end{figure}
  7902. \section{Closure Conversion}
  7903. \label{sec:closure-conversion}
  7904. \index{closure conversion}
  7905. The compiling of lexically-scoped functions into top-level function
  7906. definitions is accomplished in the pass \code{convert-to-closures}
  7907. that comes after \code{reveal-functions} and before
  7908. \code{limit-functions}.
  7909. As usual, we implement the pass as a recursive function over the
  7910. AST. All of the action is in the clauses for \key{Lambda} and
  7911. \key{Apply}. We transform a \key{Lambda} expression into an expression
  7912. that creates a closure, that is, a vector whose first element is a
  7913. function pointer and the rest of the elements are the free variables
  7914. of the \key{Lambda}. We use the struct \code{Closure} here instead of
  7915. using \code{vector} so that we can distinguish closures from vectors
  7916. in Section~\ref{sec:optimize-closures} and to record the arity. In
  7917. the generated code below, the \itm{name} is a unique symbol generated
  7918. to identify the function and the \itm{arity} is the number of
  7919. parameters (the length of \itm{ps}).
  7920. \begin{lstlisting}
  7921. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  7922. |$\Rightarrow$|
  7923. (Closure |\itm{arity}| (cons (FunRef |\itm{name}|) |\itm{fvs}|))
  7924. \end{lstlisting}
  7925. In addition to transforming each \key{Lambda} into a \key{Closure}, we
  7926. create a top-level function definition for each \key{Lambda}, as
  7927. shown below.\\
  7928. \begin{minipage}{0.8\textwidth}
  7929. \begin{lstlisting}
  7930. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  7931. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  7932. ...
  7933. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  7934. |\itm{body'}|)...))
  7935. \end{lstlisting}
  7936. \end{minipage}\\
  7937. The \code{clos} parameter refers to the closure. Translate the type
  7938. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  7939. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The types
  7940. $\itm{fvts}$ are the types of the free variables in the lambda and the
  7941. underscore \code{\_} is a dummy type that we use because it is rather
  7942. difficult to give a type to the function in the closure's
  7943. type.\footnote{To give an accurate type to a closure, we would need to
  7944. add existential types to the type checker~\citep{Minamide:1996ys}.}
  7945. The dummy type is considered to be equal to any other type during type
  7946. checking. The sequence of \key{Let} forms bind the free variables to
  7947. their values obtained from the closure.
  7948. Closure conversion turns functions into vectors, so the type
  7949. annotations in the program must also be translated. We recommend
  7950. defining a auxiliary recursive function for this purpose. Function
  7951. types should be translated as follows.
  7952. \begin{lstlisting}
  7953. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  7954. |$\Rightarrow$|
  7955. (Vector ((Vector _) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  7956. \end{lstlisting}
  7957. The above type says that the first thing in the vector is a function
  7958. pointer. The first parameter of the function pointer is a vector (a
  7959. closure) and the rest of the parameters are the ones from the original
  7960. function, with types $T'_1, \ldots, T'_n$. The \code{Vector} type for
  7961. the closure omits the types of the free variables because 1) those
  7962. types are not available in this context and 2) we do not need them in
  7963. the code that is generated for function application.
  7964. We transform function application into code that retrieves the
  7965. function pointer from the closure and then calls the function, passing
  7966. in the closure as the first argument. We bind $e'$ to a temporary
  7967. variable to avoid code duplication.
  7968. \begin{lstlisting}
  7969. (Apply |$e$| |\itm{es}|)
  7970. |$\Rightarrow$|
  7971. (Let |\itm{tmp}| |$e'$|
  7972. (Apply (Prim 'vector-ref (list (Var |\itm{tmp}|) (Int 0))) (cons |\itm{tmp}| |\itm{es'}|)))
  7973. \end{lstlisting}
  7974. There is also the question of what to do with references top-level
  7975. function definitions. To maintain a uniform translation of function
  7976. application, we turn function references into closures.
  7977. \begin{tabular}{lll}
  7978. \begin{minipage}{0.3\textwidth}
  7979. \begin{lstlisting}
  7980. (FunRefArity |$f$| |$n$|)
  7981. \end{lstlisting}
  7982. \end{minipage}
  7983. &
  7984. $\Rightarrow$
  7985. &
  7986. \begin{minipage}{0.5\textwidth}
  7987. \begin{lstlisting}
  7988. (Closure |$n$| (FunRef |$f$|) '())
  7989. \end{lstlisting}
  7990. \end{minipage}
  7991. \end{tabular} \\
  7992. %
  7993. The top-level function definitions need to be updated as well to take
  7994. an extra closure parameter.
  7995. \section{An Example Translation}
  7996. \label{sec:example-lambda}
  7997. Figure~\ref{fig:lexical-functions-example} shows the result of
  7998. \code{reveal-functions} and \code{convert-to-closures} for the example
  7999. program demonstrating lexical scoping that we discussed at the
  8000. beginning of this chapter.
  8001. \begin{figure}[tbp]
  8002. \begin{minipage}{0.8\textwidth}
  8003. % tests/lambda_test_6.rkt
  8004. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8005. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  8006. (let ([y8 4])
  8007. (lambda: ([z9 : Integer]) : Integer
  8008. (+ x7 (+ y8 z9)))))
  8009. (define (main) : Integer
  8010. (let ([g0 ((fun-ref-arity f6 1) 5)])
  8011. (let ([h1 ((fun-ref-arity f6 1) 3)])
  8012. (+ (g0 11) (h1 15)))))
  8013. \end{lstlisting}
  8014. $\Rightarrow$
  8015. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8016. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  8017. (let ([y8 4])
  8018. (closure 1 (list (fun-ref lambda2) x7 y8))))
  8019. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  8020. (let ([x7 (vector-ref fvs3 1)])
  8021. (let ([y8 (vector-ref fvs3 2)])
  8022. (+ x7 (+ y8 z9)))))
  8023. (define (main) : Integer
  8024. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6)))])
  8025. ((vector-ref clos5 0) clos5 5))])
  8026. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6)))])
  8027. ((vector-ref clos6 0) clos6 3))])
  8028. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  8029. \end{lstlisting}
  8030. \end{minipage}
  8031. \caption{Example of closure conversion.}
  8032. \label{fig:lexical-functions-example}
  8033. \end{figure}
  8034. \begin{exercise}\normalfont
  8035. Expand your compiler to handle $R_5$ as outlined in this chapter.
  8036. Create 5 new programs that use \key{lambda} functions and make use of
  8037. lexical scoping. Test your compiler on these new programs and all of
  8038. your previously created test programs.
  8039. \end{exercise}
  8040. \section{Expose Allocation}
  8041. \label{sec:expose-allocation-r5}
  8042. Compile the $\CLOSURE{\itm{arity}}{\LP\Exp\ldots\RP}$ form into code
  8043. that allocates and initializes a vector, similar to the translation of
  8044. the \code{vector} operator in Section~\ref{sec:expose-allocation}.
  8045. The only difference is replacing the use of
  8046. \ALLOC{\itm{len}}{\itm{type}} with
  8047. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  8048. \section{Explicate Control and $C_4$}
  8049. \label{sec:explicate-r5}
  8050. The output language of \code{explicate-control} is $C_4$ whose
  8051. abstract syntax is defined in Figure~\ref{fig:c4-syntax}. The only
  8052. difference with respect to $C_3$ is the addition of the
  8053. \code{AllocateClosure} form to the grammar for $\Exp$. The handling
  8054. of \code{AllocateClosure} in the \code{explicate-control} pass is
  8055. similar to the handling of other expressions such as primitive
  8056. operators.
  8057. \begin{figure}[tp]
  8058. \fbox{
  8059. \begin{minipage}{0.96\textwidth}
  8060. \small
  8061. \[
  8062. \begin{array}{lcl}
  8063. \Exp &::= & \ldots
  8064. \mid \ALLOCCLOS{\Int}{\Type}{\Int} \\
  8065. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  8066. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  8067. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  8068. \mid \GOTO{\itm{label}} } \\
  8069. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  8070. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  8071. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  8072. C_4 & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  8073. \end{array}
  8074. \]
  8075. \end{minipage}
  8076. }
  8077. \caption{The abstract syntax of $C_4$, extending $C_3$ (Figure~\ref{fig:c3-syntax}).}
  8078. \label{fig:c4-syntax}
  8079. \end{figure}
  8080. \section{Select Instructions}
  8081. \label{sec:select-instructions-R5}
  8082. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  8083. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  8084. (Section~\ref{sec:select-instructions-gc}). The only difference is
  8085. that you should place the \itm{arity} in the tag that is stored at
  8086. position $0$ of the vector. Recall that in
  8087. Section~\ref{sec:select-instructions-gc} we used the first $56$ bits
  8088. of the 64-bit tag, but that the rest were unused. So the arity goes
  8089. into the tag in bit positions $57$ through $63$.
  8090. Compile the \code{procedure-arity} operator into a sequence of
  8091. instructions that access the tag from position $0$ of the vector and
  8092. shift it by $57$ bits to the right.
  8093. \begin{figure}[p]
  8094. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8095. \node (R4) at (0,2) {\large $R_4$};
  8096. \node (R4-2) at (3,2) {\large $R_4$};
  8097. \node (R4-3) at (6,2) {\large $R_4$};
  8098. \node (F1-1) at (12,0) {\large $F_1$};
  8099. \node (F1-2) at (9,0) {\large $F_1$};
  8100. \node (F1-3) at (6,0) {\large $F_1$};
  8101. \node (F1-4) at (3,0) {\large $F_1$};
  8102. \node (F1-5) at (0,0) {\large $F_1$};
  8103. \node (C3-2) at (3,-2) {\large $C_3$};
  8104. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  8105. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  8106. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  8107. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  8108. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  8109. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  8110. \path[->,bend left=15] (R4) edge [above] node
  8111. {\ttfamily\footnotesize shrink} (R4-2);
  8112. \path[->,bend left=15] (R4-2) edge [above] node
  8113. {\ttfamily\footnotesize uniquify} (R4-3);
  8114. \path[->,bend left=15] (R4-3) edge [right] node
  8115. {\ttfamily\footnotesize\color{red} reveal-functions} (F1-1);
  8116. \path[->,bend left=15] (F1-1) edge [below] node
  8117. {\ttfamily\footnotesize\color{red} convert-to-clos.} (F1-2);
  8118. \path[->,bend right=15] (F1-2) edge [above] node
  8119. {\ttfamily\footnotesize limit-fun.} (F1-3);
  8120. \path[->,bend right=15] (F1-3) edge [above] node
  8121. {\ttfamily\footnotesize\color{red} expose-alloc.} (F1-4);
  8122. \path[->,bend right=15] (F1-4) edge [above] node
  8123. {\ttfamily\footnotesize remove-complex.} (F1-5);
  8124. \path[->,bend right=15] (F1-5) edge [right] node
  8125. {\ttfamily\footnotesize explicate-control} (C3-2);
  8126. \path[->,bend left=15] (C3-2) edge [left] node
  8127. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  8128. \path[->,bend right=15] (x86-2) edge [left] node
  8129. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  8130. \path[->,bend right=15] (x86-2-1) edge [below] node
  8131. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  8132. \path[->,bend right=15] (x86-2-2) edge [left] node
  8133. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  8134. \path[->,bend left=15] (x86-3) edge [above] node
  8135. {\ttfamily\footnotesize patch-instr.} (x86-4);
  8136. \path[->,bend left=15] (x86-4) edge [right] node
  8137. {\ttfamily\footnotesize print-x86} (x86-5);
  8138. \end{tikzpicture}
  8139. \caption{Diagram of the passes for $R_5$, a language with lexically-scoped
  8140. functions.}
  8141. \label{fig:R5-passes}
  8142. \end{figure}
  8143. Figure~\ref{fig:R5-passes} provides an overview of all the passes needed
  8144. for the compilation of $R_5$.
  8145. \clearpage
  8146. \section{Challenge: Optimize Closures}
  8147. \label{sec:optimize-closures}
  8148. In this chapter we compiled lexically-scoped functions into a
  8149. relatively efficient representation: flat closures. However, even this
  8150. representation comes with some overhead. For example, consider the
  8151. following program with a function \code{tail-sum} that does not have
  8152. any free variables and where all the uses of \code{tail-sum} are in
  8153. applications where we know that only \code{tail-sum} is being applied
  8154. (and not any other functions).
  8155. \begin{center}
  8156. \begin{minipage}{0.95\textwidth}
  8157. \begin{lstlisting}
  8158. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  8159. (if (eq? n 0)
  8160. r
  8161. (tail-sum (- n 1) (+ n r))))
  8162. (+ (tail-sum 5 0) 27)
  8163. \end{lstlisting}
  8164. \end{minipage}
  8165. \end{center}
  8166. As described in this chapter, we uniformly apply closure conversion to
  8167. all functions, obtaining the following output for this program.
  8168. \begin{center}
  8169. \begin{minipage}{0.95\textwidth}
  8170. \begin{lstlisting}
  8171. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [r3 : Integer]) : Integer
  8172. (if (eq? n2 0)
  8173. r3
  8174. (let ([clos4 (closure (list (fun-ref tail_sum1)))])
  8175. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 r3)))))
  8176. (define (main) : Integer
  8177. (+ (let ([clos6 (closure (list (fun-ref tail_sum1)))])
  8178. ((vector-ref clos6 0) clos6 5 0)) 27))
  8179. \end{lstlisting}
  8180. \end{minipage}
  8181. \end{center}
  8182. In the previous Chapter, there would be no allocation in the program
  8183. and the calls to \code{tail-sum} would be direct calls. In contrast,
  8184. the above program allocates memory for each \code{closure} and the
  8185. calls to \code{tail-sum} are indirect. These two differences incur
  8186. considerable overhead in a program such as this one, where the
  8187. allocations and indirect calls occur inside a tight loop.
  8188. One might think that this problem is trivial to solve: can't we just
  8189. recognize calls of the form \code{((fun-ref $f$) $e_1 \ldots e_n$)}
  8190. and compile them to direct calls \code{((fun-ref $f$) $e'_1 \ldots
  8191. e'_n$)} instead of treating it like a call to a closure? We would
  8192. also drop the \code{fvs5} parameter of \code{tail\_sum1}.
  8193. %
  8194. However, this problem is not so trivial because a global function may
  8195. ``escape'' and become involved in applications that also involve
  8196. closures. Consider the following example in which the application
  8197. \code{(f 41)} needs to be compiled into a closure application, because
  8198. the \code{lambda} may get bound to \code{f}, but the \code{add1}
  8199. function might also get bound to \code{f}.
  8200. \begin{lstlisting}
  8201. (define (add1 [x : Integer]) : Integer
  8202. (+ x 1))
  8203. (let ([y (read)])
  8204. (let ([f (if (eq? (read) 0)
  8205. add1
  8206. (lambda: ([x : Integer]) : Integer (- x y)))])
  8207. (f 41)))
  8208. \end{lstlisting}
  8209. If a global function name is used in any way other than as the
  8210. operator in a direct call, then we say that the function
  8211. \emph{escapes}. If a global function does not escape, then we do not
  8212. need to perform closure conversion on the function.
  8213. \begin{exercise}\normalfont
  8214. Implement an auxiliary function for detecting which global
  8215. functions escape. Using that function, implement an improved version
  8216. of closure conversion that does not apply closure conversion to
  8217. global functions that do not escape but instead compiles them as
  8218. regular functions. Create several new test cases that check whether
  8219. you properly detect whether global functions escape or not.
  8220. \end{exercise}
  8221. So far we have reduced the overhead of calling global functions, but
  8222. it would also be nice to reduce the overhead of calling a
  8223. \code{lambda} when we can determine at compile time which
  8224. \code{lambda} will be called. We refer to such calls as \emph{known
  8225. calls}. Consider the following example in which a \code{lambda} is
  8226. bound to \code{f} and then applied.
  8227. \begin{lstlisting}
  8228. (let ([y (read)])
  8229. (let ([f (lambda: ([x : Integer]) : Integer
  8230. (+ x y))])
  8231. (f 21)))
  8232. \end{lstlisting}
  8233. Closure conversion compiles \code{(f 21)} into an indirect call:
  8234. \begin{lstlisting}
  8235. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  8236. (let ([y2 (vector-ref fvs6 1)])
  8237. (+ x3 y2)))
  8238. (define (main) : Integer
  8239. (let ([y2 (read)])
  8240. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  8241. ((vector-ref f4 0) f4 21))))
  8242. \end{lstlisting}
  8243. but we can instead compile the application \code{(f 21)} into a direct call
  8244. to \code{lambda5}:
  8245. \begin{lstlisting}
  8246. (define (main) : Integer
  8247. (let ([y2 (read)])
  8248. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  8249. ((fun-ref lambda5) f4 21))))
  8250. \end{lstlisting}
  8251. The problem of determining which lambda will be called from a
  8252. particular application is quite challenging in general and the topic
  8253. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  8254. following exercise we recommend that you compile an application to a
  8255. direct call when the operator is a variable and the variable is
  8256. \code{let}-bound to a closure. This can be accomplished by maintaining
  8257. an environment mapping \code{let}-bound variables to function names.
  8258. Extend the environment whenever you encounter a closure on the
  8259. right-hand side of a \code{let}, mapping the \code{let}-bound variable
  8260. to the name of the global function for the closure. This pass should
  8261. come after closure conversion.
  8262. \begin{exercise}\normalfont
  8263. Implement a compiler pass, named \code{optimize-known-calls}, that
  8264. compiles known calls into direct calls. Verify that your compiler is
  8265. successful in this regard on several example programs.
  8266. \end{exercise}
  8267. These exercises only scratches the surface of optimizing of
  8268. closures. A good next step for the interested reader is to look at the
  8269. work of \citet{Keep:2012ab}.
  8270. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8271. \chapter{Loops and Assignment}
  8272. \label{ch:loop}
  8273. In this chapter we study two features that are the hallmarks of
  8274. imperative programming languages: loops and assignments to local
  8275. variables. The following example demonstrates these new features by
  8276. computing the sum of the first five positive integers.
  8277. % similar to loop_test_1.rkt
  8278. \begin{lstlisting}
  8279. (let ([sum 0])
  8280. (let ([i 5])
  8281. (begin
  8282. (while (> i 0)
  8283. (begin
  8284. (set! sum (+ sum i))
  8285. (set! i (- i 1))))
  8286. sum)))
  8287. \end{lstlisting}
  8288. The \code{while} loop consists of a condition and a body.
  8289. %
  8290. The \code{set!} consists of a variable and a right-hand-side expression.
  8291. %
  8292. The primary purpose of both the \code{while} loop and \code{set!} is
  8293. to cause side effects, so it is convenient to also include in $R_8$ a
  8294. language feature for sequencing side effects: the \code{begin}
  8295. expression. It consists of one or more subexpressions that are
  8296. evaluated left-to-right.
  8297. %
  8298. The concrete syntax of $R_8$ is defined in
  8299. Figure~\ref{fig:r8-concrete-syntax} and its abstract syntax is defined
  8300. in Figure~\ref{fig:r8-syntax}.
  8301. \begin{figure}[tp]
  8302. \centering
  8303. \fbox{
  8304. \begin{minipage}{0.96\textwidth}
  8305. \small
  8306. \[
  8307. \begin{array}{lcl}
  8308. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  8309. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  8310. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  8311. &\mid& \gray{\key{\#t} \mid \key{\#f}
  8312. \mid (\key{and}\;\Exp\;\Exp)
  8313. \mid (\key{or}\;\Exp\;\Exp)
  8314. \mid (\key{not}\;\Exp) } \\
  8315. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  8316. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  8317. (\key{vector-ref}\;\Exp\;\Int)} \\
  8318. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  8319. \mid (\Exp \; \Exp\ldots) } \\
  8320. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP
  8321. \mid \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  8322. &\mid& \CSETBANG{\Var}{\Exp}
  8323. \mid \CBEGIN{\Exp\ldots}{\Exp}
  8324. \mid \CWHILE{\Exp}{\Exp} \\
  8325. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  8326. R_8 &::=& \gray{\Def\ldots \; \Exp}
  8327. \end{array}
  8328. \]
  8329. \end{minipage}
  8330. }
  8331. \caption{The concrete syntax of $R_8$, extending $R_5$ (Figure~\ref{fig:r5-concrete-syntax})
  8332. with \key{lambda}.}
  8333. \label{fig:r8-concrete-syntax}
  8334. \end{figure}
  8335. \begin{figure}[tp]
  8336. \centering
  8337. \fbox{
  8338. \begin{minipage}{0.96\textwidth}
  8339. \small
  8340. \[
  8341. \begin{array}{lcl}
  8342. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  8343. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  8344. &\mid& \gray{ \BOOL{\itm{bool}}
  8345. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  8346. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  8347. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  8348. &\mid& \gray{ \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp} }\\
  8349. &\mid& \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  8350. \mid \WHILE{\Exp}{\Exp} \\
  8351. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  8352. R_5 &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  8353. \end{array}
  8354. \]
  8355. \end{minipage}
  8356. }
  8357. \caption{The abstract syntax of $R_8$, extending $R_5$ (Figure~\ref{fig:r5-syntax}).}
  8358. \label{fig:r8-syntax}
  8359. \end{figure}
  8360. The definitional interpreter for $R_8$ is shown in
  8361. Figure~\ref{fig:interp-R8}. We add three new cases for \code{SetBang},
  8362. \code{WhileLoop}, and \code{Begin} and we make changes to the cases
  8363. for \code{Var}, \code{Let}, and \code{Apply} regarding variables. To
  8364. support assignment to variables and to make their lifetimes indefinite
  8365. (see the second example in Section~\ref{sec:assignment-scoping}), we
  8366. box the value that is bound to each variable (in \code{Let}) and
  8367. function parameter (in \code{Apply}). The case for \code{Var} unboxes
  8368. the value.
  8369. %
  8370. Now to discuss the new cases. For \code{SetBang}, we lookup the
  8371. variable in the environment to obtain a boxed value and then we change
  8372. it using \code{set-box!} to the result of evaluating the right-hand
  8373. side. The result value of a \code{SetBang} is \code{void}.
  8374. %
  8375. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  8376. if the result is true, 2) evaluate the body.
  8377. The result value of a \code{while} loop is also \code{void}.
  8378. %
  8379. Finally, the $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  8380. subexpressions \itm{es} for their effects and then evaluates
  8381. and returns the result from \itm{body}.
  8382. \begin{figure}[tbp]
  8383. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8384. (define interp-R8-class
  8385. (class interp-R6-class
  8386. (super-new)
  8387. (define/override ((interp-exp env) e)
  8388. (define recur (interp-exp env))
  8389. (match e
  8390. [(SetBang x rhs)
  8391. (set-box! (lookup x env) (recur rhs))]
  8392. [(WhileLoop cnd body)
  8393. (define (loop)
  8394. (cond [(recur cnd) (recur body) (loop)]
  8395. [else (void)]))
  8396. (loop)]
  8397. [(Begin es body)
  8398. (for ([e es]) (recur e))
  8399. (recur body)]
  8400. [else ((super interp-exp env) e)]))
  8401. ))
  8402. (define (interp-R8 p)
  8403. (send (new interp-R8-class) interp-program p))
  8404. \end{lstlisting}
  8405. \caption{Interpreter for $R_8$.}
  8406. \label{fig:interp-R8}
  8407. \end{figure}
  8408. The type checker for $R_8$ is define in
  8409. Figure~\ref{fig:type-check-R8}. For \code{SetBang}, the type of the
  8410. variable and the right-hand-side must agree. The result type is
  8411. \code{Void}. For the \code{WhileLoop}, the condition must be a
  8412. \code{Boolean}. The result type is also \code{Void}. For
  8413. \code{Begin}, the result type is the type of its last subexpression.
  8414. \begin{figure}[tbp]
  8415. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8416. (define type-check-R8-class
  8417. (class type-check-R6-class
  8418. (super-new)
  8419. (inherit check-type-equal?)
  8420. (define/override (type-check-exp env)
  8421. (lambda (e)
  8422. (define recur (type-check-exp env))
  8423. (match e
  8424. [(SetBang x rhs)
  8425. (define-values (rhs^ rhsT) (recur rhs))
  8426. (define varT (dict-ref env x))
  8427. (check-type-equal? rhsT varT e)
  8428. (values (SetBang x rhs^) 'Void)]
  8429. [(WhileLoop cnd body)
  8430. (define-values (cnd^ Tc) (recur cnd))
  8431. (check-type-equal? Tc 'Boolean e)
  8432. (define-values (body^ Tbody) ((type-check-exp env) body))
  8433. (values (WhileLoop cnd^ body^) 'Void)]
  8434. [(Begin es body)
  8435. (define-values (es^ ts)
  8436. (for/lists (l1 l2) ([e es]) (recur e)))
  8437. (define-values (body^ Tbody) (recur body))
  8438. (values (Begin es^ body^) Tbody)]
  8439. [else ((super type-check-exp env) e)])))
  8440. ))
  8441. (define (type-check-R8 p)
  8442. (send (new type-check-R8-class) type-check-program p))
  8443. \end{lstlisting}
  8444. \caption{Type checking \key{SetBang}, \key{WhileLoop},
  8445. and \code{Begin} in $R_8$.}
  8446. \label{fig:type-check-R8}
  8447. \end{figure}
  8448. At first glance, the translation of these language features to x86
  8449. seems straightforward because the $C_3$ intermediate language already
  8450. supports all of the ingredients that we need: assignment, \code{goto},
  8451. conditional branching, and sequencing. However, there are two
  8452. complications that arise which we discuss in the next two
  8453. sections. After that we introduce one new compiler pass and the
  8454. changes necessary to the existing passes.
  8455. \section{Assignment and Lexically Scoped Functions}
  8456. \label{sec:assignment-scoping}
  8457. The addition of assignment raises a problem with our approach to
  8458. implementing lexically-scoped functions. Consider the following
  8459. example in which function \code{f} has a free variable \code{x} that
  8460. is changed after \code{f} is created but before the call to \code{f}.
  8461. % loop_test_11.rkt
  8462. \begin{lstlisting}
  8463. (let ([x 0])
  8464. (let ([y 0])
  8465. (let ([z 20])
  8466. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  8467. (begin
  8468. (set! x 10)
  8469. (set! y 12)
  8470. (f y))))))
  8471. \end{lstlisting}
  8472. The correct output for this example is \code{42} because the call to
  8473. \code{f} is required to use the current value of \code{x} (which is
  8474. \code{10}). Unfortunately, the closure conversion pass
  8475. (Section~\ref{sec:closure-conversion}) generates code for the
  8476. \code{lambda} that copies the old value of \code{x} into a
  8477. closure. Thus, if we naively add support for assignment to our current
  8478. compiler, the output of this program would be \code{32}.
  8479. A first attempt at solving this problem would be to save a pointer to
  8480. \code{x} in the closure and change the occurrences of \code{x} inside
  8481. the lambda to dereference the pointer. Of course, this would require
  8482. assigning \code{x} to the stack and not to a register. However, the
  8483. problem goes a bit deeper. Consider the following example in which we
  8484. create a counter abstraction by creating a pair of functions that
  8485. share the free variable \code{x}.
  8486. % similar to loop_test_10.rkt
  8487. \begin{lstlisting}
  8488. (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  8489. (vector
  8490. (lambda: () : Integer x)
  8491. (lambda: () : Void (set! x (+ 1 x)))))
  8492. (let ([counter (f 0)])
  8493. (let ([get (vector-ref counter 0)])
  8494. (let ([inc (vector-ref counter 1)])
  8495. (begin
  8496. (inc)
  8497. (get)))))
  8498. \end{lstlisting}
  8499. In this example, the lifetime of \code{x} extends beyond the lifetime
  8500. of the call to \code{f}. Thus, if we were to store \code{x} on the
  8501. stack frame for the call to \code{f}, it would be gone by the time we
  8502. call \code{inc} and \code{get}, leaving us with dangling pointers for
  8503. \code{x}. This example demonstrates that when a variable occurs free
  8504. inside a \code{lambda}, its lifetime becomes indefinite. Thus, the
  8505. value of the variable needs to live on the heap. The verb ``box'' is
  8506. often used for allocating a single value on the heap, producing a
  8507. pointer, and ``unbox'' for dereferencing the pointer.
  8508. We recommend solving these problems by ``boxing'' the local variables
  8509. that are in the intersection of 1) variables that appear on the
  8510. left-hand-side of a \code{set!} and 2) variables that occur free
  8511. inside a \code{lambda}. We shall introduce a new pass named
  8512. \code{convert-assignments} in Section~\ref{sec:convert-assignments} to
  8513. perform this translation. But before diving into the compiler passes,
  8514. we one more problem to discuss.
  8515. \section{Cyclic Control Flow and Dataflow Analysis}
  8516. \label{sec:dataflow-analysis}
  8517. Up until this point the control-flow graphs generated in
  8518. \code{explicate-control} were guaranteed to be acyclic. However, each
  8519. \code{while} loop introduces a cycle in the control-flow graph.
  8520. But does that matter?
  8521. %
  8522. Indeed it does. Recall that for register allocation, the compiler
  8523. performs liveness analysis to determine which variables can share the
  8524. same register. In Section~\ref{sec:liveness-analysis-r2} we analyze
  8525. the control-flow graph in reverse topological order, but topological
  8526. order is only well-defined for acyclic graphs.
  8527. Let us return to the example of computing the sum of the first five
  8528. positive integers. Here is the program after instruction selection but
  8529. before register allocation.
  8530. \begin{center}
  8531. \begin{minipage}{0.45\textwidth}
  8532. \begin{lstlisting}
  8533. (define (main) : Integer
  8534. mainstart:
  8535. movq $0, sum1
  8536. movq $5, i2
  8537. jmp block5
  8538. block5:
  8539. movq i2, tmp3
  8540. cmpq tmp3, $0
  8541. jl block7
  8542. jmp block8
  8543. \end{lstlisting}
  8544. \end{minipage}
  8545. \begin{minipage}{0.45\textwidth}
  8546. \begin{lstlisting}
  8547. block7:
  8548. addq i2, sum1
  8549. movq $1, tmp4
  8550. negq tmp4
  8551. addq tmp4, i2
  8552. jmp block5
  8553. block8:
  8554. movq $27, %rax
  8555. addq sum1, %rax
  8556. jmp mainconclusion
  8557. )
  8558. \end{lstlisting}
  8559. \end{minipage}
  8560. \end{center}
  8561. Recall that liveness analysis works backwards, starting at the end
  8562. of each function. For this example we could start with \code{block8}
  8563. because we know what is live at the beginning of the conclusion,
  8564. just \code{rax} and \code{rsp}. So the live-before set
  8565. for \code{block8} is $\{\ttm{rsp},\ttm{sum1}\}$.
  8566. %
  8567. Next we might try to analyze \code{block5} or \code{block7}, but
  8568. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  8569. we are stuck.
  8570. The way out of this impasse comes from the realization that one can
  8571. perform liveness analysis starting with an empty live-after set to
  8572. compute an under-approximation of the live-before set. By
  8573. \emph{under-approximation}, we mean that the set only contains
  8574. variables that are really live, but it may be missing some. Next, the
  8575. under-approximations for each block can be improved by 1) updating the
  8576. live-after set for each block using the approximate live-before sets
  8577. from the other blocks and 2) perform liveness analysis again on each
  8578. block. In fact, by iterating this process, the under-approximations
  8579. eventually become the correct solutions!
  8580. %
  8581. This approach of iteratively analyzing a control-flow graph is
  8582. applicable to many static analysis problems and goes by the name
  8583. \emph{dataflow analysis}\index{dataflow analysis}. It was invented by
  8584. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  8585. Washington.
  8586. Let us apply this approach to the above example. We use the empty set
  8587. for the initial live-before set for each block. Let $m_0$ be the
  8588. following mapping from label names to sets of locations (variables and
  8589. registers).
  8590. \begin{center}
  8591. \begin{lstlisting}
  8592. mainstart: {}
  8593. block5: {}
  8594. block7: {}
  8595. block8: {}
  8596. \end{lstlisting}
  8597. \end{center}
  8598. Using the above live-before approximations, we determine the
  8599. live-after for each block and then apply liveness analysis to each
  8600. block. This produces our next approximation $m_1$ of the live-before
  8601. sets.
  8602. \begin{center}
  8603. \begin{lstlisting}
  8604. mainstart: {}
  8605. block5: {i2}
  8606. block7: {i2, sum1}
  8607. block8: {rsp, sum1}
  8608. \end{lstlisting}
  8609. \end{center}
  8610. For the second round, the live-after for \code{mainstart} is the
  8611. current live-before for \code{block5}, which is \code{\{i2\}}. So the
  8612. liveness analysis for \code{mainstart} computes the empty set. The
  8613. live-after for \code{block5} is the union of the live-before sets for
  8614. \code{block7} and \code{block8}, which is \code{\{i2 , rsp, sum1\}}.
  8615. So the liveness analysis for \code{block5} computes \code{\{i2 , rsp,
  8616. sum1\}}. The live-after for \code{block7} is the live-before for
  8617. \code{block5} (from the previous iteration), which is \code{\{i2\}}.
  8618. So the liveness analysis for \code{block7} remains \code{\{i2,
  8619. sum1\}}. Together these yield the following approximation $m_2$ of
  8620. the live-before sets.
  8621. \begin{center}
  8622. \begin{lstlisting}
  8623. mainstart: {}
  8624. block5: {i2, rsp, sum1}
  8625. block7: {i2, sum1}
  8626. block8: {rsp, sum1}
  8627. \end{lstlisting}
  8628. \end{center}
  8629. In the preceding iteration, only \code{block5} changed, so we can
  8630. limit our attention to \code{mainstart} and \code{block7}, the two
  8631. blocks that jump to \code{block5}. As a result, the live-before sets
  8632. for \code{mainstart} and \code{block7} are updated to include
  8633. \code{rsp}, yielding the following approximation $m_3$.
  8634. \begin{center}
  8635. \begin{lstlisting}
  8636. mainstart: {rsp}
  8637. block5: {i2, rsp, sum1}
  8638. block7: {i2, rsp, sum1}
  8639. block8: {rsp, sum1}
  8640. \end{lstlisting}
  8641. \end{center}
  8642. Because \code{block7} changed, we analyze \code{block5} once more, but
  8643. its live-before set remains \code{\{ i2, rsp, sum1 \}}. At this point
  8644. our approximations have converged, so $m_3$ is the solution.
  8645. This iteration process is guaranteed to converge to a solution by the
  8646. Kleene Fixed-Point Theorem, a general theorem about functions on
  8647. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  8648. any collection that comes with a partial ordering $\sqsubseteq$ on its
  8649. elements, a least element $\bot$ (pronounced bottom), and a join
  8650. operator $\sqcup$.\index{lattice}\index{bottom}\index{partial
  8651. ordering}\index{join}\footnote{Technically speaking, we will be
  8652. working with join semi-lattices.} When two elements are ordered $m_i
  8653. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  8654. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  8655. approximation than $m_i$. The bottom element $\bot$ represents the
  8656. complete lack of information, i.e., the worst approximation. The join
  8657. operator takes two lattice elements and combines their information,
  8658. i.e., it produces the least upper bound of the two.\index{least upper
  8659. bound}
  8660. A dataflow analysis typically involves two lattices: one lattice to
  8661. represent abstract states and another lattice that aggregates the
  8662. abstract states of all the blocks in the control-flow graph. For
  8663. liveness analysis, an abstract state is a set of locations. We form
  8664. the lattice $L$ by taking its elements to be sets of locations, the
  8665. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  8666. set, and the join operator to be set union.
  8667. %
  8668. We form a second lattice $M$ by taking its elements to be mappings
  8669. from the block labels to sets of locations (elements of $L$). We
  8670. order the mappings point-wise, using the ordering of $L$. So given any
  8671. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  8672. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  8673. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  8674. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  8675. We can think of one iteration of liveness analysis as being a function
  8676. $f$ on the lattice $M$. It takes a mapping as input and computes a new
  8677. mapping.
  8678. \[
  8679. f(m_i) = m_{i+1}
  8680. \]
  8681. Next let us think for a moment about what a final solution $m_s$
  8682. should look like. If we perform liveness analysis using the solution
  8683. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  8684. solution should be a \emph{fixed point} of the function $f$.\index{fixed point}
  8685. \[
  8686. f(m_s) = m_s
  8687. \]
  8688. Furthermore, the solution should only include locations that are
  8689. forced to be there by performing liveness analysis on the program, so
  8690. the solution should be the \emph{least} fixed point.\index{least fixed point}
  8691. The Kleene Fixed-Point Theorem states that if a function $f$ is
  8692. monotone (better inputs produce better outputs), then the least fixed
  8693. point of $f$ is the least upper bound of the \emph{ascending Kleene
  8694. chain} obtained by starting at $\bot$ and iterating $f$ as
  8695. follows.\index{Kleene Fixed-Point Theorem}
  8696. \[
  8697. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  8698. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  8699. \]
  8700. When a lattice contains only finitely-long ascending chains, then
  8701. every Kleene chain tops out at some fixed point after a number of
  8702. iterations of $f$. So that fixed point is also a least upper
  8703. bound of the chain.
  8704. \[
  8705. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  8706. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  8707. \]
  8708. The liveness analysis is indeed a monotone function and the lattice
  8709. $M$ only has finitely-long ascending chains because there are only a
  8710. finite number of variables and blocks in the program. Thus we are
  8711. guaranteed that iteratively applying liveness analysis to all blocks
  8712. in the program will eventually produce the least fixed point solution.
  8713. Next let us consider dataflow analysis in general and discuss the
  8714. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  8715. %
  8716. The algorithm has four parameters: the control-flow graph \code{G}, a
  8717. function \code{transfer} that applies the analysis to one block, the
  8718. \code{bottom} and \code{join} operator for the lattice of abstract
  8719. states. The algorithm begins by creating the bottom mapping,
  8720. represented by a hash table. It then pushes all of the nodes in the
  8721. control-flow graph onto the work list (a queue). The algorithm repeats
  8722. the \code{while} loop as long as there are items in the work list. In
  8723. each iteration, a node is popped from the work list and processed. The
  8724. \code{input} for the node is computed by taking the join of the
  8725. abstract states of all the predecessor nodes. The \code{transfer}
  8726. function is then applied to obtain the \code{output} abstract
  8727. state. If the output differs from the previous state for this block,
  8728. the mapping for this block is updated and its successor nodes are
  8729. pushed onto the work list.
  8730. \begin{figure}[tb]
  8731. \begin{lstlisting}
  8732. (define (analyze-dataflow G transfer bottom join)
  8733. (define mapping (make-hash))
  8734. (for ([v (in-vertices G)])
  8735. (dict-set! mapping v bottom))
  8736. (define worklist (make-queue))
  8737. (for ([v (in-vertices G)])
  8738. (enqueue! worklist v))
  8739. (define trans-G (transpose G))
  8740. (while (not (queue-empty? worklist))
  8741. (define node (dequeue! worklist))
  8742. (define input (for/fold ([state bottom])
  8743. ([pred (in-neighbors trans-G node)])
  8744. (join state (dict-ref mapping pred))))
  8745. (define output (transfer node input))
  8746. (cond [(not (equal? output (dict-ref mapping node)))
  8747. (dict-set! mapping node output)
  8748. (for ([v (in-neighbors G node)])
  8749. (enqueue! worklist v))]))
  8750. mapping)
  8751. \end{lstlisting}
  8752. \caption{Generic work list algorithm for dataflow analysis}
  8753. \label{fig:generic-dataflow}
  8754. \end{figure}
  8755. Having discussed the two complications that arise from adding support
  8756. for assignment and loops, we turn to discussing the one new compiler
  8757. pass and the significant changes to existing passes.
  8758. \section{Convert Assignments}
  8759. \label{sec:convert-assignments}
  8760. Recall that in Section~\ref{sec:assignment-scoping} we learned that
  8761. the combination of assignments and lexically-scoped functions requires
  8762. that we box those variables that are both assigned-to and that appear
  8763. free inside a \code{lambda}. The purpose of the
  8764. \code{convert-assignments} pass is to carry out that transformation.
  8765. We recommend placing this pass after \code{uniquify} but before
  8766. \code{reveal-functions}.
  8767. Consider again the first example from
  8768. Section~\ref{sec:assignment-scoping}:
  8769. \begin{lstlisting}
  8770. (let ([x 0])
  8771. (let ([y 0])
  8772. (let ([z 20])
  8773. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  8774. (begin
  8775. (set! x 10)
  8776. (set! y 12)
  8777. (f y))))))
  8778. \end{lstlisting}
  8779. The variables \code{x} and \code{y} are assigned-to. The variables
  8780. \code{x} and \code{z} occur free inside the \code{lambda}. Thus,
  8781. variable \code{x} needs to be boxed but not \code{y} and \code{z}.
  8782. The boxing of \code{x} consists of three transformations: initialize
  8783. \code{x} with a vector, replace reads from \code{x} with
  8784. \code{vector-ref}'s, and replace each \code{set!} on \code{x} with a
  8785. \code{vector-set!}. The output of \code{convert-assignments} for this
  8786. example is as follows.
  8787. \begin{lstlisting}
  8788. (define (main) : Integer
  8789. (let ([x0 (vector 0)])
  8790. (let ([y1 0])
  8791. (let ([z2 20])
  8792. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  8793. (+ a3 (+ (vector-ref x0 0) z2)))])
  8794. (begin
  8795. (vector-set! x0 0 10)
  8796. (set! y1 12)
  8797. (f4 y1)))))))
  8798. \end{lstlisting}
  8799. \paragraph{Assigned \& Free}
  8800. We recommend defining an auxiliary function named
  8801. \code{assigned\&free} that takes an expression and simultaneously
  8802. computes 1) a set of assigned variables $A$, 2) a set $F$ of variables
  8803. that occur free within lambda's, and 3) a new version of the
  8804. expression that records which bound variables occurred in the
  8805. intersection of $A$ and $F$. You can use the struct
  8806. \code{AssignedFree} to do this. Consider the case for
  8807. $\LET{x}{\itm{rhs}}{\itm{body}}$. Suppose the the recursive call on
  8808. $\itm{rhs}$ produces $\itm{rhs}'$, $A_r$, and $F_r$ and the recursive
  8809. call on the $\itm{body}$ produces $\itm{body}'$, $A_b$, and $F_b$. If
  8810. $x$ is in $A_b\cap F_b$, then transforms the \code{Let} as follows.
  8811. \begin{lstlisting}
  8812. (Let |$x$| |$rhs$| |$body$|)
  8813. |$\Rightarrow$|
  8814. (Let (AssignedFree |$x$|) |$rhs'$| |$body'$|)
  8815. \end{lstlisting}
  8816. If $x$ is not in $A_b\cap F_b$ then omit the use of \code{AssignedFree}.
  8817. The set of assigned variables for this \code{Let} is
  8818. $A_r \cup (A_b - \{x\})$
  8819. and the set of variables free in lambda's is
  8820. $F_r \cup (F_b - \{x\})$.
  8821. The case for $\SETBANG{x}{\itm{rhs}}$ is straightforward but
  8822. important. Recursively process \itm{rhs} to obtain \itm{rhs'}, $A_r$,
  8823. and $F_r$. The result is $\SETBANG{x}{\itm{rhs'}}$, $\{x\} \cup A_r$,
  8824. and $F_r$.
  8825. The case for $\LAMBDA{\itm{params}}{T}{\itm{body}}$ is a bit more
  8826. involved. Let \itm{body'}, $A_b$, and $F_b$ be the result of
  8827. recursively processing \itm{body}. Wrap each of parameter that occurs
  8828. in $A_b \cap F_b$ with \code{AssignedFree} to produce \itm{params'}.
  8829. Let $P$ be the set of parameter names in \itm{params}. The result is
  8830. $\LAMBDA{\itm{params'}}{T}{\itm{body'}}$, $A_b - P$, and $(F_b \cup
  8831. \mathrm{FV}(\itm{body})) - P$, where $\mathrm{FV}$ computes the free
  8832. variables of an expression (see Chapter~\ref{ch:lambdas}).
  8833. \paragraph{Convert Assignments}
  8834. Next we discuss the \code{convert-assignment} pass with its auxiliary
  8835. functions for expressions and definitions. The function for
  8836. expressions, \code{cnvt-assign-exp}, should take an expression and a
  8837. set of assigned-and-free variables (obtained from the result of
  8838. \code{assigned\&free}. In the case for $\VAR{x}$, if $x$ is
  8839. assigned-and-free, then unbox it by translating $\VAR{x}$ to a
  8840. \code{vector-ref}.
  8841. \begin{lstlisting}
  8842. (Var |$x$|)
  8843. |$\Rightarrow$|
  8844. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  8845. \end{lstlisting}
  8846. %
  8847. In the case for $\LET{\LP\code{AssignedFree}\,
  8848. x\RP}{\itm{rhs}}{\itm{body}}$, recursively process \itm{rhs} to
  8849. obtain \itm{rhs'}. Next, recursively process \itm{body} to obtain
  8850. \itm{body'} but with $x$ added to the set of assigned-and-free
  8851. variables. Translate the let-expression as follows to bind $x$ to a
  8852. boxed value.
  8853. \begin{lstlisting}
  8854. (Let (AssignedFree |$x$|) |$rhs$| |$body$|)
  8855. |$\Rightarrow$|
  8856. (Let |$x$| (Prim 'vector (list |$rhs'$|)) |$body'$|)
  8857. \end{lstlisting}
  8858. %
  8859. In the case for $\SETBANG{x}{\itm{rhs}}$, recursively process
  8860. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in the assigned-and-free
  8861. variables, translate the \code{set!} into a \code{vector-set!}
  8862. as follows.
  8863. \begin{lstlisting}
  8864. (SetBang |$x$| |$\itm{rhs}$|)
  8865. |$\Rightarrow$|
  8866. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  8867. \end{lstlisting}
  8868. %
  8869. The case for \code{Lambda} is non-trivial, but it is similar to the
  8870. case for function definitions, which we discuss next.
  8871. The auxiliary function for definitions, \code{cnvt-assign-def},
  8872. applies assignment conversion to function definitions.
  8873. We translate a function definition as follows.
  8874. \begin{lstlisting}
  8875. (Def |$f$| |$\itm{params}$| |$T$| |$\itm{info}$| |$\itm{body_1}$|)
  8876. |$\Rightarrow$|
  8877. (Def |$f$| |$\itm{params'}$| |$T$| |$\itm{info}$| |$\itm{body_4}$|)
  8878. \end{lstlisting}
  8879. So it remains to explain \itm{params'} and $\itm{body}_4$.
  8880. Let \itm{body_2}, $A_b$, and $F_b$ be the result of
  8881. \code{assigned\&free} on $\itm{body_1}$.
  8882. Let $P$ be the parameter names in \itm{params}.
  8883. We then apply \code{cnvt-assign-exp} to $\itm{body_2}$ to
  8884. obtain \itm{body_3}, passing $A_b \cap F_b \cap P$
  8885. as the set of assigned-and-free variables.
  8886. Finally, we obtain \itm{body_4} by wrapping \itm{body_3}
  8887. in a sequence of let-expressions that box the parameters
  8888. that are in $A_b \cap F_b$.
  8889. %
  8890. Regarding \itm{params'}, change the names of the parameters that are
  8891. in $A_b \cap F_b$ to maintain uniqueness (and so the let-bound
  8892. variables can retain the original names). Recall the second example in
  8893. Section~\ref{sec:assignment-scoping} involving a counter
  8894. abstraction. The following is the output of assignment version for
  8895. function \code{f}.
  8896. \begin{lstlisting}
  8897. (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  8898. (vector
  8899. (lambda: () : Integer x1)
  8900. (lambda: () : Void (set! x1 (+ 1 x1)))))
  8901. |$\Rightarrow$|
  8902. (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  8903. (let ([x1 (vector param_x1)])
  8904. (vector (lambda: () : Integer (vector-ref x1 0))
  8905. (lambda: () : Void
  8906. (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  8907. \end{lstlisting}
  8908. \section{Remove Complex Operands}
  8909. \label{sec:rco-loop}
  8910. The three new language forms, \code{while}, \code{set!}, and
  8911. \code{begin} are all complex expressions and their subexpressions are
  8912. allowed to be complex. Figure~\ref{fig:r4-anf-syntax} defines the
  8913. output language $R_4^{\dagger}$ of this pass.
  8914. \begin{figure}[tp]
  8915. \centering
  8916. \fbox{
  8917. \begin{minipage}{0.96\textwidth}
  8918. \small
  8919. \[
  8920. \begin{array}{rcl}
  8921. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  8922. \mid \VOID{} } \\
  8923. \Exp &::=& \ldots \mid \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  8924. &\mid& \WHILE{\Exp}{\Exp} \mid \SETBANG{\Var}{\Exp}
  8925. \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  8926. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  8927. R^{\dagger}_8 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  8928. \end{array}
  8929. \]
  8930. \end{minipage}
  8931. }
  8932. \caption{$R_8^{\dagger}$ is $R_8$ in administrative normal form (ANF).}
  8933. \label{fig:r8-anf-syntax}
  8934. \end{figure}
  8935. As usual, when a complex expression appears in a grammar position that
  8936. needs to be atomic, such as the argument of a primitive operator, we
  8937. must introduce a temporary variable and bind it to the complex
  8938. expression. This approach applies, unchanged, to handle the new
  8939. language forms. For example, in the following code there are two
  8940. \code{begin} expressions appearing as arguments to \code{+}. The
  8941. output of \code{rco-exp} is shown below, in which the \code{begin}
  8942. expressions have been bound to temporary variables. Recall that
  8943. \code{let} expressions in $R_8^{\dagger}$ are allowed to have
  8944. arbitrary expressions in their right-hand-side expression, so it is
  8945. fine to place \code{begin} there.
  8946. \begin{lstlisting}
  8947. (let ([x0 10])
  8948. (let ([y1 0])
  8949. (+ (+ (begin (set! y1 (read)) x0)
  8950. (begin (set! x0 (read)) y1))
  8951. x0)))
  8952. |$\Rightarrow$|
  8953. (let ([x0 10])
  8954. (let ([y1 0])
  8955. (let ([tmp2 (begin (set! y1 (read)) x0)])
  8956. (let ([tmp3 (begin (set! x0 (read)) y1)])
  8957. (let ([tmp4 (+ tmp2 tmp3)])
  8958. (+ tmp4 x0))))))
  8959. \end{lstlisting}
  8960. \section{Explicate Control and $C_7$}
  8961. \label{sec:explicate-loop}
  8962. Recall that in the \code{explicate-control} pass we define one helper
  8963. function for each kind of position in the program. For the $R_1$
  8964. language of integers and variables we needed kinds of positions:
  8965. assignment and tail. The \code{if} expressions of $R_2$ introduced
  8966. predicate positions. For $R_8$, the \code{begin} expression introduces
  8967. yet another kind of position: effect position. Except for the last
  8968. subexpression, the subexpressions inside a \code{begin} are evaluated
  8969. only for their effect. Their result values are discarded. We can
  8970. generate better code by taking this fact into account.
  8971. The output language of \code{explicate-control} is $C_7$
  8972. (Figure~\ref{fig:c7-syntax}), which is nearly identical to $C_3$. The
  8973. only difference is that \code{Call}, \code{vector-set!}, and
  8974. \code{read} may also appear as statements.
  8975. \begin{figure}[tp]
  8976. \fbox{
  8977. \begin{minipage}{0.96\textwidth}
  8978. \small
  8979. \[
  8980. \begin{array}{lcl}
  8981. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  8982. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  8983. &\mid& \CALL{\Atm}{\LP\Atm\ldots\RP} \mid \READ{}\\
  8984. &\mid& \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP \\
  8985. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  8986. C_7 & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  8987. \end{array}
  8988. \]
  8989. \end{minipage}
  8990. }
  8991. \caption{The abstract syntax of $C_7$, extending $C_3$ (Figure~\ref{fig:c3-syntax}).}
  8992. \label{fig:c7-syntax}
  8993. \end{figure}
  8994. The new auxiliary function \code{explicate-effect} takes an expression
  8995. (in an effect position) and a promise of a continuation block. The
  8996. function returns a promise for a $\Tail$ that includes the generated
  8997. code for the input expression followed by the continuation block. If
  8998. the expression is obviously pure, that is, never causes side effects,
  8999. then the expression can be removed, so the result is just the
  9000. continuation block.
  9001. %
  9002. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  9003. case. First, you will need a fresh label $\itm{loop}$ for the top of
  9004. the loop. Recursively process the \itm{body} (in effect position)
  9005. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  9006. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  9007. \itm{body'} as the then-branch and the continuation block as the
  9008. else-branch. The result should be added to the control-flow graph with
  9009. the label \itm{loop}. The result for the whole \code{while} loop is a
  9010. \code{goto} to the \itm{loop} label. Note that the loop should only be
  9011. added to the control-flow graph if the loop is indeed used, which can
  9012. be accomplished using \code{delay}.
  9013. The auxiliary functions for tail, assignment, and predicate positions
  9014. need to be updated. The three new language forms, \code{while},
  9015. \code{set!}, and \code{begin}, can appear in assignment and tail
  9016. positions. Only \code{begin} may appear in predicate positions; the
  9017. other two have result type \code{Void}.
  9018. \section{Select Instructions}
  9019. \label{sec:select-instructions-loop}
  9020. Only three small additions are needed in the
  9021. \code{select-instructions} pass to handle the changes to $C_7$. That
  9022. is, \code{Call}, \code{read}, and \code{vector-set!} may now appear as
  9023. stand-alone statements instead of only appearing on the right-hand
  9024. side of an assignment statement. The code generation is nearly
  9025. identical; just leave off the instruction for moving the result into
  9026. the left-hand side.
  9027. \section{Register Allocation}
  9028. \label{sec:register-allocation-loop}
  9029. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  9030. loops in $R_8$ means that the control-flow graphs may contain cycles,
  9031. which complicates the liveness analysis needed for register
  9032. allocation.
  9033. \subsection{Liveness Analysis}
  9034. \label{sec:liveness-analysis-r8}
  9035. We recommend using the generic \code{analyze-dataflow} function that
  9036. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  9037. perform liveness analysis, replacing the code in
  9038. \code{uncover-live-CFG} that processed the basic blocks in topological
  9039. order (Section~\ref{sec:liveness-analysis-r2}).
  9040. The \code{analyze-dataflow} function has four parameters.
  9041. \begin{enumerate}
  9042. \item The first parameter \code{G} should be a directed graph from the
  9043. \code{racket/graph} package (see the sidebar in
  9044. Section~\ref{sec:build-interference}) that represents the
  9045. control-flow graph.
  9046. \item The second parameter \code{transfer} is a function that applies
  9047. liveness analysis to a basic block. It takes two parameters: the
  9048. label for the block to analyze and the live-after set for that
  9049. block. The transfer function should return the live-before set for
  9050. the block. Also, as a side-effect, it should update the block's
  9051. $\itm{info}$ with the liveness information for each instruction. To
  9052. implement the \code{transfer} function, you should be able to reuse
  9053. the code you already have for analyzing basic blocks.
  9054. \item The third and fourth parameters of \code{analyze-dataflow} are
  9055. \code{bottom} and \code{join} for the lattice of abstract states,
  9056. i.e. sets of locations. The bottom of the lattice is the empty set
  9057. \code{(set)} and the join operator is \code{set-union}.
  9058. \end{enumerate}
  9059. \begin{figure}[p]
  9060. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9061. \node (R4) at (0,2) {\large $R_8$};
  9062. \node (R4-2) at (3,2) {\large $R_8$};
  9063. \node (R4-3) at (6,2) {\large $R_8$};
  9064. \node (R4-4) at (9,2) {\large $R_8$};
  9065. \node (F1-1) at (12,0) {\large $F_1$};
  9066. \node (F1-2) at (9,0) {\large $F_1$};
  9067. \node (F1-3) at (6,0) {\large $F_1$};
  9068. \node (F1-4) at (3,0) {\large $F_1$};
  9069. \node (F1-5) at (0,0) {\large $F_1$};
  9070. \node (C3-2) at (3,-2) {\large $C_3$};
  9071. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  9072. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  9073. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  9074. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  9075. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  9076. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  9077. %% \path[->,bend left=15] (R4) edge [above] node
  9078. %% {\ttfamily\footnotesize\color{red} type-check} (R4-2);
  9079. \path[->,bend left=15] (R4) edge [above] node
  9080. {\ttfamily\footnotesize shrink} (R4-2);
  9081. \path[->,bend left=15] (R4-2) edge [above] node
  9082. {\ttfamily\footnotesize uniquify} (R4-3);
  9083. \path[->,bend left=15] (R4-3) edge [above] node
  9084. {\ttfamily\footnotesize\color{red} convert-assignments} (R4-4);
  9085. \path[->,bend left=15] (R4-4) edge [left] node
  9086. {\ttfamily\footnotesize reveal-functions} (F1-1);
  9087. \path[->,bend left=15] (F1-1) edge [below] node
  9088. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  9089. \path[->,bend right=15] (F1-2) edge [above] node
  9090. {\ttfamily\footnotesize limit-fun.} (F1-3);
  9091. \path[->,bend right=15] (F1-3) edge [above] node
  9092. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9093. \path[->,bend right=15] (F1-4) edge [above] node
  9094. {\ttfamily\footnotesize\color{red} remove-complex.} (F1-5);
  9095. \path[->,bend right=15] (F1-5) edge [right] node
  9096. {\ttfamily\footnotesize\color{red} explicate-control} (C3-2);
  9097. \path[->,bend left=15] (C3-2) edge [left] node
  9098. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  9099. \path[->,bend right=15] (x86-2) edge [left] node
  9100. {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  9101. \path[->,bend right=15] (x86-2-1) edge [below] node
  9102. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  9103. \path[->,bend right=15] (x86-2-2) edge [left] node
  9104. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  9105. \path[->,bend left=15] (x86-3) edge [above] node
  9106. {\ttfamily\footnotesize patch-instr.} (x86-4);
  9107. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  9108. \end{tikzpicture}
  9109. \caption{Diagram of the passes for $R_8$ (loops and assignment).}
  9110. \label{fig:R8-passes}
  9111. \end{figure}
  9112. Figure~\ref{fig:R8-passes} provides an overview of all the passes needed
  9113. for the compilation of $R_8$.
  9114. % TODO: challenge assignment
  9115. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9116. \chapter{Dynamic Typing}
  9117. \label{ch:type-dynamic}
  9118. \index{dynamic typing}
  9119. In this chapter we discuss the compilation of $R_7$, a dynamically
  9120. typed language and a subset of the Racket language. In contrast, the
  9121. previous chapters have studies the compilation of Typed Racket. In
  9122. dynamically typed languages, a given expression may produce a value of
  9123. a different type each time it is executed. Consider the following
  9124. example with a conditional \code{if} expression that may return a
  9125. Boolean or an integer depending on the input to the program.
  9126. \begin{lstlisting}
  9127. (not (if (eq? (read) 1) #f 0))
  9128. \end{lstlisting}
  9129. Languages that allow expressions to produce different kinds of values
  9130. are called \emph{polymorphic}, a word composed of the Greek roots
  9131. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  9132. are several kinds of polymorphism in programming languages, such as
  9133. subtype polymorphism and parametric
  9134. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  9135. study in this chapter does not have a special name but it is the kind
  9136. that arises in dynamically typed languages.
  9137. Another characteristic of dynamically typed languages is that
  9138. primitive operations, such as \code{not}, are often defined to operate
  9139. on many different types of values. In fact, in Racket, the \code{not}
  9140. operator produces a result for any kind of value: given \code{\#f} it
  9141. returns \code{\#t} and given anything else it returns \code{\#f}.
  9142. Furthermore, even when primitive operations restrict their inputs to
  9143. values of a certain type, this restriction is enforced at runtime
  9144. instead of during compilation. For example, the following vector
  9145. reference results in a run-time contract violation because the index
  9146. must be in integer, not a Boolean such as \code{\#t}.
  9147. \begin{lstlisting}
  9148. (vector-ref (vector 42) #t)
  9149. \end{lstlisting}
  9150. \begin{figure}[tp]
  9151. \centering
  9152. \fbox{
  9153. \begin{minipage}{0.97\textwidth}
  9154. \[
  9155. \begin{array}{rcl}
  9156. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  9157. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp}
  9158. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} \\
  9159. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  9160. &\mid& \key{\#t} \mid \key{\#f}
  9161. \mid \CBINOP{\key{and}}{\Exp}{\Exp}
  9162. \mid \CBINOP{\key{or}}{\Exp}{\Exp}
  9163. \mid \CUNIOP{\key{not}}{\Exp} \\
  9164. &\mid& \LP\itm{cmp}\;\Exp\;\Exp\RP \mid \CIF{\Exp}{\Exp}{\Exp} \\
  9165. &\mid& \LP\key{vector}\;\Exp\ldots\RP \mid
  9166. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  9167. &\mid& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \mid \LP\key{void}\RP \\
  9168. &\mid& \LP\Exp \; \Exp\ldots\RP
  9169. \mid \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  9170. & \mid & \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP\\
  9171. & \mid & \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \mid \LP\key{void?}\;\Exp\RP \\
  9172. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  9173. R_7 &::=& \Def\ldots\; \Exp
  9174. \end{array}
  9175. \]
  9176. \end{minipage}
  9177. }
  9178. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  9179. \label{fig:r7-concrete-syntax}
  9180. \end{figure}
  9181. \begin{figure}[tp]
  9182. \centering
  9183. \fbox{
  9184. \begin{minipage}{0.96\textwidth}
  9185. \small
  9186. \[
  9187. \begin{array}{lcl}
  9188. \Exp &::=& \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  9189. &\mid& \PRIM{\itm{op}}{\Exp\ldots} \\
  9190. &\mid& \BOOL{\itm{bool}}
  9191. \mid \IF{\Exp}{\Exp}{\Exp} \\
  9192. &\mid& \VOID{} \mid \APPLY{\Exp}{\Exp\ldots} \\
  9193. &\mid& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  9194. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  9195. R_7 &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  9196. \end{array}
  9197. \]
  9198. \end{minipage}
  9199. }
  9200. \caption{The abstract syntax of $R_7$.}
  9201. \label{fig:r7-syntax}
  9202. \end{figure}
  9203. The concrete and abstract syntax of $R_7$, our subset of Racket, is
  9204. defined in Figures~\ref{fig:r7-concrete-syntax} and
  9205. \ref{fig:r7-syntax}.
  9206. %
  9207. There is no type checker for $R_7$ because it is not a statically
  9208. typed language (it's dynamically typed!).
  9209. %
  9210. The definitional interpreter for $R_7$ is presented in
  9211. Figure~\ref{fig:interp-R7}.
  9212. \begin{figure}[tbp]
  9213. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9214. (define (interp-R7-exp env)
  9215. (lambda (ast)
  9216. (define recur (interp-R7-exp env))
  9217. (match ast
  9218. [(Var x) (lookup x env)]
  9219. [(Int n) `(tagged ,n Integer)]
  9220. [(Bool b) `(tagged ,b Boolean)]
  9221. [(Prim 'read '()) `(tagged ,(read-fixnum) Integer)]
  9222. [(Lambda xs rt body)
  9223. `(tagged (lambda ,xs ,body ,env) (,@(for/list ([x xs]) 'Any) -> Any))]
  9224. [(Prim 'vector es)
  9225. `(tagged ,(apply vector (for/list ([e es]) (recur e)))
  9226. (Vector ,@(for/list ([e es]) 'Any)))]
  9227. [(Prim 'vector-set! (list e1 n e2))
  9228. (define vec (value-of-any (recur e1)))
  9229. (define i (value-of-any (recur n)))
  9230. (vector-set! vec i (recur e2))
  9231. `(tagged ,(void) Void)]
  9232. [(Prim 'vector-ref (list e1 n))
  9233. (define vec (value-of-any (recur e1)))
  9234. (define i (value-of-any (recur n)))
  9235. (vector-ref vec i)]
  9236. [(Let x e body)
  9237. (define v (recur e))
  9238. ((interp-R7-exp (cons (cons x v) env)) body)]
  9239. [(Prim 'and (list e1 e2))
  9240. (recur (If e1 e2 (Bool #f)))]
  9241. [(Prim 'or (list e1 e2))
  9242. (define v1 (recur e1))
  9243. (match (value-of-any v1) [#f (recur e2)] [else v1])]
  9244. [(Prim 'eq? (list l r))
  9245. `(tagged ,(equal? (recur l) (recur r)) Boolean)]
  9246. [(If q t f)
  9247. (match (value-of-any (recur q)) [#f (recur f)] [else (recur t)])]
  9248. [(Prim op es)
  9249. (tag-value
  9250. (apply (interp-op op) (for/list ([e es]) (value-of-any (recur e)))))]
  9251. [(Apply f es)
  9252. (define new-args (map recur es))
  9253. (let ([f-val (value-of-any (recur f))])
  9254. (match f-val
  9255. [`(function (,xs ...) ,body ,lam-env)
  9256. (define new-env (append (map cons xs new-args) lam-env))
  9257. ((interp-R7-exp new-env) body)]
  9258. [else (error "interp-R7-exp, expected function, not" f-val)]))]
  9259. )))
  9260. \end{lstlisting}
  9261. \caption{Interpreter for the $R_7$ language.}
  9262. \label{fig:interp-R7}
  9263. \end{figure}
  9264. Let us consider how we might compile $R_7$ to x86, thinking about the
  9265. first example above. Our bit-level representation of the Boolean
  9266. \code{\#f} is zero and similarly for the integer \code{0}. However,
  9267. \code{(not \#f)} should produce \code{\#t} whereas \code{(not 0)}
  9268. should produce \code{\#f}. Furthermore, the behavior of \code{not}, in
  9269. general, cannot be determined at compile time, but depends on the
  9270. runtime type of its input, as in the example above that depends on the
  9271. result of \code{(read)}.
  9272. The way around this problem is to include information about a value's
  9273. runtime type in the value itself, so that this information can be
  9274. inspected by operators such as \code{not}. In particular, we
  9275. steal the 3 right-most bits from our 64-bit values to encode the
  9276. runtime type. We use $001$ to identify integers, $100$ for
  9277. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  9278. void value. We refer to these 3 bits as the \emph{tag} and we
  9279. define the following auxiliary function.
  9280. \begin{align*}
  9281. \itm{tagof}(\key{Integer}) &= 001 \\
  9282. \itm{tagof}(\key{Boolean}) &= 100 \\
  9283. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  9284. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  9285. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  9286. \itm{tagof}(\key{Void}) &= 101
  9287. \end{align*}
  9288. (We say more about the new \key{Vectorof} type shortly.)
  9289. This stealing of 3 bits comes at some
  9290. price: our integers are reduced to ranging from $-2^{60}$ to
  9291. $2^{60}$. The stealing does not adversely affect vectors and
  9292. procedures because those values are addresses, and our addresses are
  9293. 8-byte aligned so the rightmost 3 bits are unused, they are always
  9294. $000$. Thus, we do not lose information by overwriting the rightmost 3
  9295. bits with the tag and we can simply zero-out the tag to recover the
  9296. original address.
  9297. In some sense, these tagged values are a new kind of value. Indeed,
  9298. we can extend our \emph{typed} language with tagged values by adding a
  9299. new type to classify them, called \key{Any}, and with operations for
  9300. creating and using tagged values, yielding the $R_6$ language that we
  9301. define in Section~\ref{sec:r6-lang}. The $R_6$ language provides the
  9302. fundamental support for polymorphism and runtime types that we need to
  9303. support dynamic typing.
  9304. There is an interesting interaction between tagged values and garbage
  9305. collection. A variable of type \code{Any} might refer to a vector and
  9306. therefore it might be a root that needs to be inspected and copied
  9307. during garbage collection. Thus, we need to treat variables of type
  9308. \code{Any} in a similar way to variables of type \code{Vector} for
  9309. purposes of register allocation, which we discuss in
  9310. Section~\ref{sec:register-allocation-r6}. One concern is that, if a
  9311. variable of type \code{Any} is spilled, it must be spilled to the root
  9312. stack. But this means that the garbage collector needs to be able to
  9313. differentiate between (1) plain old pointers to tuples, (2) a tagged
  9314. value that points to a tuple, and (3) a tagged value that is not a
  9315. tuple. We enable this differentiation by choosing not to use the tag
  9316. $000$ in $\itm{tagof}$. Instead, that bit pattern is reserved for
  9317. identifying plain old pointers to tuples. That way, if one of the
  9318. first three bits is set, then we have a tagged value and inspecting
  9319. the tag can differentiation between vectors ($010$) and the other
  9320. kinds of values.
  9321. We implement our untyped language $R_7$ by compiling it to $R_6$
  9322. (Section~\ref{sec:compile-r7}), but first we describe the how to
  9323. extend our compiler to handle the new features of $R_6$
  9324. (Sections~\ref{sec:shrink-r6}, \ref{sec:select-r6}, and
  9325. \ref{sec:register-allocation-r6}).
  9326. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  9327. \label{sec:r6-lang}
  9328. \begin{figure}[tp]
  9329. \centering
  9330. \fbox{
  9331. \begin{minipage}{0.97\textwidth}\small
  9332. \[
  9333. \begin{array}{lcl}
  9334. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  9335. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \LP\key{Vectorof}\;\Type\RP \mid \key{Void}} \\
  9336. &\mid& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \mid \key{Any} \\
  9337. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void} \mid \LP\key{Vectorof}\;\key{Any}\RP \mid \LP\key{Vector}\; \key{Any}\ldots\RP \\
  9338. &\mid& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  9339. \Exp &::=& \ldots
  9340. \mid \CINJECT{\Exp}{\FType}\RP \mid \CPROJECT{\Exp}{\FType} \\
  9341. & \mid & \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP\\
  9342. & \mid & \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \mid \LP\key{void?}\;\Exp\RP \\
  9343. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  9344. R_6 &::=& \gray{\Def\ldots \; \Exp}
  9345. \end{array}
  9346. \]
  9347. \end{minipage}
  9348. }
  9349. \caption{The concrete syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax})
  9350. with \key{Any}.}
  9351. \label{fig:r6-concrete-syntax}
  9352. \end{figure}
  9353. \begin{figure}[tp]
  9354. \centering
  9355. \fbox{
  9356. \begin{minipage}{0.96\textwidth}
  9357. \small
  9358. \[
  9359. \begin{array}{lcl}
  9360. \itm{op} &::= & \code{boolean?} \mid \code{integer?} \mid \code{vector?}
  9361. \mid \code{procedure?} \mid \code{void?} \\
  9362. \Exp &::=& \ldots
  9363. \mid \INJECT{\Exp}{\FType} \mid \PROJECT{\Exp}{\FType} \\
  9364. \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  9365. R_5 &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  9366. \end{array}
  9367. \]
  9368. \end{minipage}
  9369. }
  9370. \caption{The abstract syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax}).}
  9371. \label{fig:r6-syntax}
  9372. \end{figure}
  9373. The concrete and abstract syntax of $R_6$ is defined in
  9374. Figures~\ref{fig:r6-concrete-syntax} and \ref{fig:r6-syntax}. The
  9375. $\LP\key{inject}\; e\; T\RP$ form converts the value produced by
  9376. expression $e$ of type $T$ into a tagged value. The
  9377. $\LP\key{project}\;e\;T\RP$ form converts the tagged value produced by
  9378. expression $e$ into a value of type $T$ or else halts the program if
  9379. the type tag is not equivalent to $T$. We treat
  9380. $\LP\key{Vectorof}\;\key{Any}\RP$ as equivalent to
  9381. $\LP\key{Vector}\;\key{Any}\;\ldots\RP$.
  9382. %
  9383. Note that in both \key{inject} and \key{project}, the type $T$ is
  9384. restricted to the flat types $\FType$, which simplifies the
  9385. implementation and corresponds with what is needed for compiling
  9386. untyped Racket.
  9387. The type predicates such as $\LP\key{boolean?}\,e\RP$ expect the
  9388. expression $e$ to produce a tagged value; they return \key{\#t} if the
  9389. tag corresponds to the predicate and they return \key{\#f} otherwise.
  9390. The type checker for $R_6$ is shown in
  9391. Figures~\ref{fig:type-check-R6-part-1} and
  9392. \ref{fig:type-check-R6-part-2} and uses the auxiliary functions in
  9393. Figure~\ref{fig:type-check-R6-aux}.
  9394. %
  9395. The interpreter for $R_6$ is in Figure~\ref{fig:interp-R6} and the
  9396. auxiliary function \code{apply-project} is in Figure~\ref{fig:apply-project}.
  9397. \begin{figure}[btp]
  9398. \begin{lstlisting}[basicstyle=\ttfamily\small]
  9399. (define type-check-R6-class
  9400. (class type-check-R5-class
  9401. (super-new)
  9402. (inherit check-type-equal?)
  9403. (define/override (type-check-exp env)
  9404. (lambda (e)
  9405. (define recur (type-check-exp env))
  9406. (match e
  9407. [(Prim 'vector-length (list e))
  9408. (define-values (e^ t) (recur e))
  9409. (match t
  9410. [(or `(Vector ,_ ...) `(Vectorof ,_))
  9411. (values (Prim 'vector-length (list e^)) 'Integer)]
  9412. [else (error 'type-check "expected a vector, not ~a\nin ~v" t e)])]
  9413. [(Prim 'vector-ref (list e1 ei))
  9414. (define-values (e^ t) (recur e1))
  9415. (define-values (i it) (recur ei))
  9416. (check-type-equal? it 'Integer e)
  9417. (match (list t i)
  9418. [(list `(Vector ,ts ...) (Int i^))
  9419. (unless (and (0 . <= . i^) (i^ . < . (length ts)))
  9420. (error 'type-check-exp "invalid index ~a in ~a" i^ e))
  9421. (let ([t (list-ref ts i^)])
  9422. (values (Prim 'vector-ref (list e^ (Int i^))) t))]
  9423. [(list `(Vectorof ,t) i)
  9424. (values (Prim 'vector-ref (list e^ i)) t)]
  9425. [else (error "expected a vector in vector-ref, not" t)])]
  9426. [(Prim 'vector-set! (list e-vec e-i e-arg))
  9427. (define-values (e-vec^ t-vec) (recur e-vec))
  9428. (define-values (i it) (recur e-i))
  9429. (define-values (e-arg^ t-arg) (recur e-arg))
  9430. (check-type-equal? it 'Integer e)
  9431. (match (list t-vec i)
  9432. [(list `(Vector ,ts ...) (Int i^))
  9433. (unless (and (0 . <= . i^) (i^ . < . (length ts)))
  9434. (error 'type-check-exp "invalid index ~a in ~a" i^ e))
  9435. (check-type-equal? (list-ref ts i^) t-arg e)
  9436. (values (Prim 'vector-set! (list e-vec^ (Int i^) e-arg^)) 'Void)]
  9437. [(list `(Vectorof ,t) i)
  9438. (check-type-equal? t t-arg e)
  9439. (values (Prim 'vector-set! (list e-vec^ i e-arg^)) 'Void)]
  9440. [else
  9441. (error 'type-check-exp "expected a vector, not ~a" t-vec)])]
  9442. \end{lstlisting}
  9443. \caption{Type checker for the $R_6$ language, part 1.}
  9444. \label{fig:type-check-R6-part-1}
  9445. \end{figure}
  9446. \begin{figure}[btp]
  9447. \begin{lstlisting}[basicstyle=\ttfamily\small]
  9448. [(Inject e1 ty)
  9449. (unless (flat-ty? ty)
  9450. (error 'type-check "may only inject from flat type, not ~a" ty))
  9451. (define-values (new-e1 e-ty) (recur e1))
  9452. (check-type-equal? e-ty ty e)
  9453. (values (Inject new-e1 ty) 'Any)]
  9454. [(ValueOf e ty)
  9455. (define-values (new-e e-ty) (recur e))
  9456. (values (ValueOf new-e ty) ty)]
  9457. [(Project e1 ty)
  9458. (unless (flat-ty? ty)
  9459. (error 'type-check "may only project to flat type, not ~a" ty))
  9460. (define-values (new-e1 e-ty) (recur e1))
  9461. (check-type-equal? e-ty 'Any e)
  9462. (values (Project new-e1 ty) ty)]
  9463. [(Prim pred (list e1))
  9464. #:when (set-member? (type-predicates) pred)
  9465. (define-values (new-e1 e-ty) (recur e1))
  9466. (check-type-equal? e-ty 'Any e)
  9467. (values (Prim pred (list new-e1)) 'Boolean)]
  9468. [(If cnd thn els)
  9469. (define-values (cnd^ Tc) (recur cnd))
  9470. (define-values (thn^ Tt) (recur thn))
  9471. (define-values (els^ Te) (recur els))
  9472. (check-type-equal? Tc 'Boolean cnd)
  9473. (check-type-equal? Tt Te e)
  9474. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  9475. [(Exit) (values (Exit) '_)]
  9476. [(Prim 'eq? (list arg1 arg2))
  9477. (define-values (e1 t1) (recur arg1))
  9478. (define-values (e2 t2) (recur arg2))
  9479. (match* (t1 t2)
  9480. ;; allow comparison of vectors of different element types
  9481. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  9482. [(`(Vectorof ,t1) `(Vectorof ,t2)) (void)]
  9483. [(other wise) (check-type-equal? t1 t2 e)])
  9484. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  9485. [else ((super type-check-exp env) e)])))
  9486. ))
  9487. \end{lstlisting}
  9488. \caption{Type checker for the $R_6$ language, part 2.}
  9489. \label{fig:type-check-R6-part-2}
  9490. \end{figure}
  9491. \begin{figure}[tbp]
  9492. \begin{lstlisting}
  9493. (define/override (operator-types)
  9494. (append
  9495. '((integer? . ((Any) . Boolean))
  9496. (vector? . ((Any) . Boolean))
  9497. (procedure? . ((Any) . Boolean))
  9498. (void? . ((Any) . Boolean))
  9499. (tag-of-any . ((Any) . Integer))
  9500. (make-any . ((_ Integer) . Any))
  9501. )
  9502. (super operator-types)))
  9503. (define/public (type-predicates)
  9504. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  9505. (define/public (combine-types t1 t2)
  9506. (match (list t1 t2)
  9507. [(list '_ t2) t2]
  9508. [(list t1 '_) t1]
  9509. [(list `(Vector ,ts1 ...)
  9510. `(Vector ,ts2 ...))
  9511. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  9512. (combine-types t1 t2)))]
  9513. [(list `(,ts1 ... -> ,rt1)
  9514. `(,ts2 ... -> ,rt2))
  9515. `(,@(for/list ([t1 ts1] [t2 ts2])
  9516. (combine-types t1 t2))
  9517. -> ,(combine-types rt1 rt2))]
  9518. [else t1]))
  9519. (define/public (flat-ty? ty)
  9520. (match ty
  9521. [(or `Integer `Boolean '_ `Void) #t]
  9522. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  9523. [`(Vectorof Any) #t]
  9524. [`(,ts ... -> ,rt)
  9525. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  9526. [else #f]))
  9527. \end{lstlisting}
  9528. \caption{Auxiliary methods for type checking $R_6$.}
  9529. \label{fig:type-check-R6-aux}
  9530. \end{figure}
  9531. % to do: add rules for vector-ref, etc. for Vectorof
  9532. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  9533. \begin{figure}[btp]
  9534. \begin{lstlisting}
  9535. (define interp-R6-class
  9536. (class interp-R5-class
  9537. (super-new)
  9538. (define/override (interp-op op)
  9539. (match op
  9540. ['boolean? (match-lambda
  9541. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  9542. [else #f])]
  9543. ['integer? (match-lambda
  9544. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  9545. [else #f])]
  9546. ['vector? (match-lambda
  9547. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  9548. [else #f])]
  9549. ['procedure? (match-lambda
  9550. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  9551. [else #f])]
  9552. ['eq? (match-lambda*
  9553. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  9554. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  9555. [ls (apply (super interp-op op) ls)])]
  9556. ['make-any (lambda (v tg) `(tagged ,v ,tg))]
  9557. ['tag-of-any
  9558. (match-lambda
  9559. [`(tagged ,v^ ,tg) tg]
  9560. [v (error 'interp-op "expected tagged value, not ~a" v)])]
  9561. [else (super interp-op op)]))
  9562. (define/override ((interp-exp env) e)
  9563. (define recur (interp-exp env))
  9564. (match e
  9565. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  9566. [(Project e ty2) (apply-project (recur e) ty2)]
  9567. [(ValueOf e ty)
  9568. (match (recur e)
  9569. [`(tagged ,v^ ,tg) v^]
  9570. [v (error 'interp-op "expected tagged value, not ~a" v)])]
  9571. [(Exit) (error 'interp-exp "exiting")]
  9572. [else ((super interp-exp env) e)]))
  9573. ))
  9574. (define (interp-R6 p)
  9575. (send (new interp-R6-class) interp-program p))
  9576. \end{lstlisting}
  9577. \caption{Interpreter for $R_6$.}
  9578. \label{fig:interp-R6}
  9579. \end{figure}
  9580. \begin{figure}[tbp]
  9581. \begin{lstlisting}
  9582. (define (apply-project v ty2)
  9583. (define tag2 (any-tag ty2))
  9584. (match v
  9585. [`(tagged ,v1 ,tag1)
  9586. (cond [(eq? tag1 tag2)
  9587. (match ty2
  9588. [`(Vector ,ts ...)
  9589. (cond [(eq? (vector-length v1) (length ts)) v1]
  9590. [else
  9591. (error 'apply-project
  9592. "length ~a does not match vector type length ~a"
  9593. (vector-length v1) (length ts))])]
  9594. [`(,ts ... -> ,rt)
  9595. (match v1
  9596. [`(function ,xs ,body ,env)
  9597. (cond [(eq? (length xs) (length ts)) v1]
  9598. [else
  9599. (error 'apply-project
  9600. "arity ~a does not match type arity ~a"
  9601. (length xs) (length ts))])]
  9602. [else (error 'apply-project "expected a function, not ~a" v1)])]
  9603. [else v1])]
  9604. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  9605. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  9606. \end{lstlisting}
  9607. \caption{Auxiliary function to apply a projection.}
  9608. \label{fig:apply-project}
  9609. \end{figure}
  9610. \clearpage
  9611. \section{Check Bounds}
  9612. \label{sec:check-bounds-r6}
  9613. Regarding the \code{vector-ref} or \code{vector-set!} operations, when
  9614. the type of the vector argument is \code{Vectorof}, the type checker
  9615. for $R_6$ (Figure~\ref{fig:type-check-R6-part-1}) does not guarantee
  9616. that the index is within bounds. Thus, we need to insert code to
  9617. perform bounds checking at runtime.
  9618. \begin{lstlisting}
  9619. (vector-ref |$e_1$| |$e_2$|)
  9620. |$\Rightarrow$|
  9621. (let ([v |$e'_1$|])
  9622. (let ([i |$e'_2$|])
  9623. (if (and (<= 0 i) (< i (vector-length v)))
  9624. (vector-ref v i)
  9625. (exit))))
  9626. \end{lstlisting}
  9627. \begin{lstlisting}
  9628. (vector-set! |$e_1$| |$e_2$| |$e_3$|)
  9629. |$\Rightarrow$|
  9630. (let ([v |$e'_1$|])
  9631. (let ([i |$e'_2$|])
  9632. (if (and (<= 0 i) (< i (vector-length v)))
  9633. (vector-set! v i |$e'_3$|)
  9634. (exit))))
  9635. \end{lstlisting}
  9636. Because this pass depends on type information, we recommend
  9637. implementing it as an extension to the type checker for $R_6$, as
  9638. sketched in the following code. When the vector argument is of type
  9639. \code{Vector}, your code should mimic what is done in the type checker
  9640. for $R_6$. If the vector argument is type \code{Vectorof}, your code
  9641. should perform the above transformations.
  9642. \begin{center}
  9643. \begin{minipage}{0.96\textwidth}
  9644. \begin{lstlisting}
  9645. (define check-bounds-R6-class
  9646. (class type-check-R6-class
  9647. (super-new)
  9648. (inherit check-type-equal?)
  9649. (define/override (type-check-exp env)
  9650. (lambda (e)
  9651. (match e
  9652. [(Prim 'vector-ref (list e1 ei)) ... ]
  9653. [(Prim 'vector-set! (list e-vec e-i e-arg)) ...]
  9654. [else ((super type-check-exp env) e)])))
  9655. ))
  9656. (define (check-bounds-R6 p)
  9657. (send (new check-bounds-R6-class) type-check-program p))
  9658. \end{lstlisting}
  9659. \end{minipage}
  9660. \end{center}
  9661. \section{Shrink $R_6$}
  9662. \label{sec:shrink-r6}
  9663. % TODO: define R'_6
  9664. In the \code{shrink} pass we recommend compiling \code{project} into
  9665. an \code{if} expression that checks whether the value's tag matches
  9666. the target type; if it does, the value is converted to a value of the
  9667. target type by removing the tag; if it does not, the program exits.
  9668. To perform these actions we need a new primitive operation,
  9669. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  9670. The \code{tag-of-any} operation retrieves the type tag from a tagged
  9671. value of type \code{Any}. The \code{ValueOf} form retrieves the
  9672. underlying value from a tagged value. The \code{ValueOf} form
  9673. includes the type for the underlying value which is used by the type
  9674. checker. Finally, the \code{Exit} form ends the execution of the
  9675. program.
  9676. If the target type of the projection is \code{Boolean} or
  9677. \code{Integer}, then \code{Project} can be translated as follows.
  9678. \begin{center}
  9679. \begin{minipage}{1.0\textwidth}
  9680. \begin{lstlisting}
  9681. (Project |$e$| |$\FType$|)
  9682. |$\Rightarrow$|
  9683. (Let |$\itm{tmp}$| |$e'$|
  9684. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  9685. (Int |$\itm{tagof}(\FType)$|)))
  9686. (ValueOf |$\itm{tmp}$| |$\FType$|)
  9687. (Exit)))
  9688. \end{lstlisting}
  9689. \end{minipage}
  9690. \end{center}
  9691. If the target type of the projection is a vector or function type,
  9692. then there is a bit more work to do. For vectors, check that the
  9693. length of the vector type matches the length of the vector (using the
  9694. \code{vector-length} primitive). For functions, check that the number
  9695. of parameters in the function type matches the function's arity (using
  9696. \code{procedure-arity}).
  9697. Regarding \code{inject}, we recommend compiling it to a slightly
  9698. lower-level primitive operation named \code{make-any}. This operation
  9699. takes a tag instead of a type. \\
  9700. \begin{center}
  9701. \begin{minipage}{1.0\textwidth}
  9702. \begin{lstlisting}
  9703. (Inject |$e$| |$\FType$|)
  9704. |$\Rightarrow$|
  9705. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  9706. \end{lstlisting}
  9707. \end{minipage}
  9708. \end{center}
  9709. We recommend translating the type predicates (\code{boolean?}, etc.)
  9710. into uses of \code{tag-of-any} and \code{eq?}.
  9711. \section{Remove Complex Operands}
  9712. \label{sec:rco-r6}
  9713. The \code{ValueOf} and \code{Exit} forms are both complex expressions.
  9714. The subexpression of \code{ValueOf} must be atomic.
  9715. \section{Explicate Control and $C_5$}
  9716. \label{sec:explicate-r6}
  9717. The output of \code{explicate-control} is the $C_5$ language whose
  9718. syntax is defined in Figure~\ref{fig:c5-syntax}. The \code{ValueOf}
  9719. form that we added to $R_6$ remains an expression and the \code{Exit}
  9720. expression becomes a statement.
  9721. \begin{figure}[tp]
  9722. \fbox{
  9723. \begin{minipage}{0.96\textwidth}
  9724. \small
  9725. \[
  9726. \begin{array}{lcl}
  9727. \Exp &::= & \ldots
  9728. \mid \VALUEOF{\Exp}{\FType} \\
  9729. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  9730. \mid \LP\key{Collect} \,\itm{int}\RP }\\
  9731. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  9732. \mid \GOTO{\itm{label}} } \\
  9733. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  9734. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  9735. \mid \LP\key{Exit}\RP \\
  9736. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  9737. C_4 & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  9738. \end{array}
  9739. \]
  9740. \end{minipage}
  9741. }
  9742. \caption{The abstract syntax of $C_5$, extending $C_4$ (Figure~\ref{fig:c4-syntax}).}
  9743. \label{fig:c5-syntax}
  9744. \end{figure}
  9745. \section{Select Instructions}
  9746. \label{sec:select-r6}
  9747. % TODO: talk about vector-ref and vector-set! -Jeremy
  9748. %% Recall instruction selection for `vector-ref`:
  9749. %% (Assign lhs (Prim 'vector-ref (list evec (Int n))))
  9750. %% ===>
  9751. %% movq evec', %r11
  9752. %% movq offset(%r11), lhs'
  9753. %% where offset is 8(n+1)
  9754. %% If the index is not of the form `(Int i)`, but an arbitrary
  9755. %% expression, then instead of computing the offset `8(n+1)` at compile
  9756. %% time, you can generate the following instructions. Note the use of the
  9757. %% new instruction `imulq`.
  9758. %% (Assign lhs (Prim 'vector-ref (list evec en)))
  9759. %% ===>
  9760. %% movq en', %r11
  9761. %% addq $1, %r11
  9762. %% imulq $8, %r11
  9763. %% addq evec', %r11
  9764. %% movq 0(%r11) lhs'
  9765. %% The same idea applies to `vector-set!`.
  9766. \paragraph{Make-any}
  9767. We recommend compiling the \key{make-any} primitive as follows if the
  9768. tag is for \key{Integer} or \key{Boolean}. The \key{salq} instruction
  9769. shifts the destination to the left by the number of bits specified its
  9770. source argument (in this case $3$, the length of the tag) and it
  9771. preserves the sign of the integer. We use the \key{orq} instruction to
  9772. combine the tag and the value to form the tagged value. \\
  9773. \begin{lstlisting}
  9774. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  9775. |$\Rightarrow$|
  9776. movq |$e'$|, |\itm{lhs'}|
  9777. salq $3, |\itm{lhs'}|
  9778. orq $|$\itm{tag}$|, |\itm{lhs'}|
  9779. \end{lstlisting}
  9780. The instruction selection for vectors and procedures is different
  9781. because their is no need to shift them to the left. The rightmost 3
  9782. bits are already zeros as described above. So we just combine the
  9783. value and the tag using \key{orq}. \\
  9784. \begin{lstlisting}
  9785. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  9786. |$\Rightarrow$|
  9787. movq |$e'$|, |\itm{lhs'}|
  9788. orq $|$\itm{tag}$|, |\itm{lhs'}|
  9789. \end{lstlisting}
  9790. \paragraph{Tag-of-any}
  9791. Recall that the \code{tag-of-any} operation extracts the type tag from
  9792. a value of type \code{Any}. The type tag is the bottom three bits, so
  9793. we obtain the tag by taking the bitwise-and of the value with $111$
  9794. ($7$ in decimal).
  9795. \begin{lstlisting}
  9796. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  9797. |$\Rightarrow$|
  9798. movq |$e'$|, |\itm{lhs'}|
  9799. andq $7, |\itm{lhs'}|
  9800. \end{lstlisting}
  9801. \paragraph{ValueOf}
  9802. Like \key{make-any}, the instructions for \key{ValueOf} are different
  9803. depending on whether the type $T$ is a pointer (vector or procedure)
  9804. or not (Integer or Boolean). The following shows the instruction
  9805. selection for Integer and Boolean. We produce an untagged value by
  9806. shifting it to the right by 3 bits.
  9807. \begin{lstlisting}
  9808. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  9809. |$\Rightarrow$|
  9810. movq |$e'$|, |\itm{lhs'}|
  9811. sarq $3, |\itm{lhs'}|
  9812. \end{lstlisting}
  9813. %
  9814. In the case for vectors and procedures, there is no need to
  9815. shift. Instead we just need to zero-out the rightmost 3 bits. We
  9816. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  9817. decimal) and apply \code{bitwise-not} to obtain $\ldots 11111000$ (-8
  9818. in decimal) which we \code{movq} into the destination $\itm{lhs}$. We
  9819. then apply \code{andq} with the tagged value to get the desired
  9820. result. \\
  9821. \begin{lstlisting}
  9822. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  9823. |$\Rightarrow$|
  9824. movq $|$-8$|, |\itm{lhs'}|
  9825. andq |$e'$|, |\itm{lhs'}|
  9826. \end{lstlisting}
  9827. %% \paragraph{Type Predicates} We leave it to the reader to
  9828. %% devise a sequence of instructions to implement the type predicates
  9829. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  9830. \section{Register Allocation for $R_6$}
  9831. \label{sec:register-allocation-r6}
  9832. \index{register allocation}
  9833. As mentioned above, a variable of type \code{Any} might refer to a
  9834. vector. Thus, the register allocator for $R_6$ needs to treat variable
  9835. of type \code{Any} in the same way that it treats variables of type
  9836. \code{Vector} for purposes of garbage collection. In particular,
  9837. \begin{itemize}
  9838. \item If a variable of type \code{Any} is live during a function call,
  9839. then it must be spilled. One way to accomplish this is to augment
  9840. \code{build-interference} to mark all variables that are live after
  9841. a \code{callq} as interfering with all the registers.
  9842. \item If a variable of type \code{Any} is spilled, it must be spilled
  9843. to the root stack instead of the normal procedure call stack.
  9844. \end{itemize}
  9845. \begin{exercise}\normalfont
  9846. Expand your compiler to handle $R_6$ as discussed in the last few
  9847. sections. Create 5 new programs that use the \code{Any} type and the
  9848. new operations (\code{inject}, \code{project}, \code{boolean?},
  9849. etc.). Test your compiler on these new programs and all of your
  9850. previously created test programs.
  9851. \end{exercise}
  9852. \section{Compiling $R_7$ to $R_6$}
  9853. \label{sec:compile-r7}
  9854. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  9855. $R_7$ forms into $R_6$. An important invariant of this pass is that
  9856. given a subexpression $e$ in the $R_7$ program, the pass will produce
  9857. an expression $e'$ in $R_6$ that has type \key{Any}. For example, the
  9858. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  9859. the Boolean \code{\#t}, which must be injected to produce an
  9860. expression of type \key{Any}.
  9861. %
  9862. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  9863. addition, is representative of compilation for many primitive
  9864. operations: the arguments have type \key{Any} and must be projected to
  9865. \key{Integer} before the addition can be performed.
  9866. The compilation of \key{lambda} (third row of
  9867. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  9868. produce type annotations: we simply use \key{Any}.
  9869. %
  9870. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  9871. has to account for some differences in behavior between $R_7$ and
  9872. $R_6$. The $R_7$ language is more permissive than $R_6$ regarding what
  9873. kind of values can be used in various places. For example, the
  9874. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  9875. the arguments need not be of the same type (in that case the
  9876. result is \code{\#f}).
  9877. \begin{figure}[btp]
  9878. \centering
  9879. \begin{tabular}{|lll|} \hline
  9880. \begin{minipage}{0.27\textwidth}
  9881. \begin{lstlisting}
  9882. #t
  9883. \end{lstlisting}
  9884. \end{minipage}
  9885. &
  9886. $\Rightarrow$
  9887. &
  9888. \begin{minipage}{0.6\textwidth}
  9889. \begin{lstlisting}
  9890. (inject #t Boolean)
  9891. \end{lstlisting}
  9892. \end{minipage}
  9893. \\[2ex]\hline
  9894. \begin{minipage}{0.27\textwidth}
  9895. \begin{lstlisting}
  9896. (+ |$e_1$| |$e_2$|)
  9897. \end{lstlisting}
  9898. \end{minipage}
  9899. &
  9900. $\Rightarrow$
  9901. &
  9902. \begin{minipage}{0.6\textwidth}
  9903. \begin{lstlisting}
  9904. (inject
  9905. (+ (project |$e'_1$| Integer)
  9906. (project |$e'_2$| Integer))
  9907. Integer)
  9908. \end{lstlisting}
  9909. \end{minipage}
  9910. \\[2ex]\hline
  9911. \begin{minipage}{0.27\textwidth}
  9912. \begin{lstlisting}
  9913. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  9914. \end{lstlisting}
  9915. \end{minipage}
  9916. &
  9917. $\Rightarrow$
  9918. &
  9919. \begin{minipage}{0.6\textwidth}
  9920. \begin{lstlisting}
  9921. (inject
  9922. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  9923. (Any|$\ldots$|Any -> Any))
  9924. \end{lstlisting}
  9925. \end{minipage}
  9926. \\[2ex]\hline
  9927. \begin{minipage}{0.27\textwidth}
  9928. \begin{lstlisting}
  9929. (|$e_0$| |$e_1 \ldots e_n$|)
  9930. \end{lstlisting}
  9931. \end{minipage}
  9932. &
  9933. $\Rightarrow$
  9934. &
  9935. \begin{minipage}{0.6\textwidth}
  9936. \begin{lstlisting}
  9937. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  9938. \end{lstlisting}
  9939. \end{minipage}
  9940. \\[2ex]\hline
  9941. \begin{minipage}{0.27\textwidth}
  9942. \begin{lstlisting}
  9943. (vector-ref |$e_1$| |$e_2$|)
  9944. \end{lstlisting}
  9945. \end{minipage}
  9946. &
  9947. $\Rightarrow$
  9948. &
  9949. \begin{minipage}{0.6\textwidth}
  9950. \begin{lstlisting}
  9951. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  9952. (let ([tmp2 (project |$e'_2$| Integer)])
  9953. (vector-ref tmp1 tmp2)))
  9954. \end{lstlisting}
  9955. \end{minipage}
  9956. \\[2ex]\hline
  9957. \begin{minipage}{0.27\textwidth}
  9958. \begin{lstlisting}
  9959. (if |$e_1$| |$e_2$| |$e_3$|)
  9960. \end{lstlisting}
  9961. \end{minipage}
  9962. &
  9963. $\Rightarrow$
  9964. &
  9965. \begin{minipage}{0.6\textwidth}
  9966. \begin{lstlisting}
  9967. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  9968. \end{lstlisting}
  9969. \end{minipage}
  9970. \\[2ex]\hline
  9971. \begin{minipage}{0.27\textwidth}
  9972. \begin{lstlisting}
  9973. (eq? |$e_1$| |$e_2$|)
  9974. \end{lstlisting}
  9975. \end{minipage}
  9976. &
  9977. $\Rightarrow$
  9978. &
  9979. \begin{minipage}{0.6\textwidth}
  9980. \begin{lstlisting}
  9981. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  9982. \end{lstlisting}
  9983. \end{minipage}
  9984. \\[2ex]\hline
  9985. \end{tabular}
  9986. \caption{Compiling $R_7$ to $R_6$.}
  9987. \label{fig:compile-r7-r6}
  9988. \end{figure}
  9989. \begin{exercise}\normalfont
  9990. Expand your compiler to handle $R_7$ as outlined in this chapter.
  9991. Create tests for $R_7$ by adapting ten of your previous test programs
  9992. by removing type annotations. Add 5 more tests programs that
  9993. specifically rely on the language being dynamically typed. That is,
  9994. they should not be legal programs in a statically typed language, but
  9995. nevertheless, they should be valid $R_7$ programs that run to
  9996. completion without error.
  9997. \end{exercise}
  9998. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9999. \chapter{Gradual Typing}
  10000. \label{ch:gradual-typing}
  10001. \index{gradual typing}
  10002. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  10003. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10004. \chapter{Parametric Polymorphism}
  10005. \label{ch:parametric-polymorphism}
  10006. \index{parametric polymorphism}
  10007. \index{generics}
  10008. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  10009. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  10010. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10011. %% \chapter{High-level Optimization}
  10012. %% \label{ch:high-level-optimization}
  10013. %% This chapter will present a procedure inlining pass based on the
  10014. %% algorithm of \citet{Waddell:1997fk}.
  10015. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10016. \chapter{Appendix}
  10017. \section{Interpreters}
  10018. \label{appendix:interp}
  10019. \index{interpreter}
  10020. We provide interpreters for each of the source languages $R_0$, $R_1$,
  10021. $\ldots$ in the files \code{interp-R0.rkt}, \code{interp-R1.rkt}, etc.
  10022. The interpreters for the intermediate languages $C_0$ and $C_1$ are in
  10023. \code{interp-C0.rkt} and \code{interp-C1.rkt}. The interpreters for
  10024. $C_2$, $C_3$, pseudo-x86, and x86 are in the \key{interp.rkt} file.
  10025. \section{Utility Functions}
  10026. \label{appendix:utilities}
  10027. The utility functions described in this section are in the
  10028. \key{utilities.rkt} file of the support code.
  10029. \paragraph{\code{interp-tests}}
  10030. The \key{interp-tests} function runs the compiler passes and the
  10031. interpreters on each of the specified tests to check whether each pass
  10032. is correct. The \key{interp-tests} function has the following
  10033. parameters:
  10034. \begin{description}
  10035. \item[name (a string)] a name to identify the compiler,
  10036. \item[typechecker] a function of exactly one argument that either
  10037. raises an error using the \code{error} function when it encounters a
  10038. type error, or returns \code{\#f} when it encounters a type
  10039. error. If there is no type error, the type checker returns the
  10040. program.
  10041. \item[passes] a list with one entry per pass. An entry is a list with
  10042. four things:
  10043. \begin{enumerate}
  10044. \item a string giving the name of the pass,
  10045. \item the function that implements the pass (a translator from AST
  10046. to AST),
  10047. \item a function that implements the interpreter (a function from
  10048. AST to result value) for the output language,
  10049. \item and a type checker for the output language. Type checkers for
  10050. the $R$ and $C$ languages are provided in the support code. For
  10051. example, the type checkers for $R_1$ and $C_0$ are in
  10052. \code{type-check-R1.rkt}. The type checker entry is optional. The
  10053. support code does not provide type checkers for the x86 languages.
  10054. \end{enumerate}
  10055. \item[source-interp] an interpreter for the source language. The
  10056. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  10057. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  10058. \item[tests] a list of test numbers that specifies which tests to
  10059. run. (see below)
  10060. \end{description}
  10061. %
  10062. The \key{interp-tests} function assumes that the subdirectory
  10063. \key{tests} has a collection of Racket programs whose names all start
  10064. with the family name, followed by an underscore and then the test
  10065. number, ending with the file extension \key{.rkt}. Also, for each test
  10066. program that calls \code{read} one or more times, there is a file with
  10067. the same name except that the file extension is \key{.in} that
  10068. provides the input for the Racket program. If the test program is
  10069. expected to fail type checking, then there should be an empty file of
  10070. the same name but with extension \key{.tyerr}.
  10071. \paragraph{\code{compiler-tests}}
  10072. runs the compiler passes to generate x86 (a \key{.s} file) and then
  10073. runs the GNU C compiler (gcc) to generate machine code. It runs the
  10074. machine code and checks that the output is $42$. The parameters to the
  10075. \code{compiler-tests} function are similar to those of the
  10076. \code{interp-tests} function, and consist of
  10077. \begin{itemize}
  10078. \item a compiler name (a string),
  10079. \item a type checker,
  10080. \item description of the passes,
  10081. \item name of a test-family, and
  10082. \item a list of test numbers.
  10083. \end{itemize}
  10084. \paragraph{\code{compile-file}}
  10085. takes a description of the compiler passes (see the comment for
  10086. \key{interp-tests}) and returns a function that, given a program file
  10087. name (a string ending in \key{.rkt}), applies all of the passes and
  10088. writes the output to a file whose name is the same as the program file
  10089. name but with \key{.rkt} replaced with \key{.s}.
  10090. \paragraph{\code{read-program}}
  10091. takes a file path and parses that file (it must be a Racket program)
  10092. into an abstract syntax tree.
  10093. \paragraph{\code{parse-program}}
  10094. takes an S-expression representation of an abstract syntax tree and converts it into
  10095. the struct-based representation.
  10096. \paragraph{\code{assert}}
  10097. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  10098. and displays the message \key{msg} if the Boolean \key{bool} is false.
  10099. \paragraph{\code{lookup}}
  10100. % remove discussion of lookup? -Jeremy
  10101. takes a key and an alist, and returns the first value that is
  10102. associated with the given key, if there is one. If not, an error is
  10103. triggered. The alist may contain both immutable pairs (built with
  10104. \key{cons}) and mutable pairs (built with \key{mcons}).
  10105. %The \key{map2} function ...
  10106. \section{x86 Instruction Set Quick-Reference}
  10107. \label{sec:x86-quick-reference}
  10108. \index{x86}
  10109. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  10110. do. We write $A \to B$ to mean that the value of $A$ is written into
  10111. location $B$. Address offsets are given in bytes. The instruction
  10112. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  10113. registers (such as \code{\%rax}), or memory references (such as
  10114. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  10115. reference per instruction. Other operands must be immediates or
  10116. registers.
  10117. \begin{table}[tbp]
  10118. \centering
  10119. \begin{tabular}{l|l}
  10120. \textbf{Instruction} & \textbf{Operation} \\ \hline
  10121. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  10122. \texttt{negq} $A$ & $- A \to A$ \\
  10123. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  10124. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  10125. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  10126. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  10127. \texttt{retq} & Pops the return address and jumps to it \\
  10128. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  10129. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  10130. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  10131. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  10132. be an immediate) \\
  10133. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  10134. matches the condition code of the instruction, otherwise go to the
  10135. next instructions. The condition codes are \key{e} for ``equal'',
  10136. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  10137. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  10138. \texttt{jl} $L$ & \\
  10139. \texttt{jle} $L$ & \\
  10140. \texttt{jg} $L$ & \\
  10141. \texttt{jge} $L$ & \\
  10142. \texttt{jmp} $L$ & Jump to label $L$ \\
  10143. \texttt{movq} $A$, $B$ & $A \to B$ \\
  10144. \texttt{movzbq} $A$, $B$ &
  10145. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  10146. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  10147. and the extra bytes of $B$ are set to zero.} \\
  10148. & \\
  10149. & \\
  10150. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  10151. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  10152. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  10153. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  10154. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  10155. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  10156. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  10157. description of the condition codes. $A$ must be a single byte register
  10158. (e.g., \texttt{al} or \texttt{cl}).} \\
  10159. \texttt{setl} $A$ & \\
  10160. \texttt{setle} $A$ & \\
  10161. \texttt{setg} $A$ & \\
  10162. \texttt{setge} $A$ &
  10163. \end{tabular}
  10164. \vspace{5pt}
  10165. \caption{Quick-reference for the x86 instructions used in this book.}
  10166. \label{tab:x86-instr}
  10167. \end{table}
  10168. \cleardoublepage
  10169. \addcontentsline{toc}{chapter}{Index}
  10170. \printindex
  10171. \cleardoublepage
  10172. \bibliographystyle{plainnat}
  10173. \bibliography{all}
  10174. \addcontentsline{toc}{chapter}{Bibliography}
  10175. \end{document}
  10176. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  10177. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  10178. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  10179. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  10180. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator jane
  10181. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  10182. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  10183. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  10184. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs Tt
  10185. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  10186. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  10187. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  10188. %% LocalWords: boolean type-check notq cmpq sete movzbq jmp al xorq
  10189. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  10190. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  10191. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  10192. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  10193. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  10194. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  10195. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  10196. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  10197. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  10198. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  10199. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  10200. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  10201. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  10202. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  10203. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  10204. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  10205. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  10206. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  10207. % LocalWords: struct symtab Friedman's MacOS Nystrom alist sam kate
  10208. % LocalWords: alists arity github unordered pqueue exprs ret param
  10209. % LocalWords: tyerr bytereg dh dl JmpIf HasType Osterlund Jacek TODO
  10210. % LocalWords: Gamari GlobalValue ProgramDefsExp prm ProgramDefs vn
  10211. % LocalWords: FunRef TailCall tailjmp IndirectCallq TailJmp Gilray
  10212. % LocalWords: dereference unbox Dataflow versa dataflow Kildall rhs
  10213. % LocalWords: Kleene enqueue dequeue AssignedFree FV cnvt SetBang tg
  10214. % LocalWords: ValueOf typechecker