book.tex 303 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106
  1. % Why direct style instead of continuation passing style?
  2. %% Student project ideas:
  3. %% * high-level optimizations like procedure inlining, etc.
  4. %% * closure optimization
  5. %% * adding letrec to the language
  6. %% (Thought: in the book and regular course, replace top-level defines
  7. %% with letrec.)
  8. %% * alternative back ends (ARM, LLVM)
  9. %% * alternative calling convention (a la Dybvig)
  10. %% * lazy evaluation
  11. %% * gradual typing
  12. %% * continuations (frames in heap a la SML or segmented stack a la Dybvig)
  13. %% * exceptions
  14. %% * self hosting
  15. %% * I/O
  16. %% * foreign function interface
  17. %% * quasi-quote and unquote
  18. %% * macros (too difficult?)
  19. %% * alternative garbage collector
  20. %% * alternative register allocator
  21. %% * parametric polymorphism
  22. %% * type classes (too difficulty?)
  23. %% * loops (too easy? combine with something else?)
  24. %% * loop optimization (fusion, etc.)
  25. %% * deforestation
  26. %% * records and subtyping
  27. %% * object-oriented features
  28. %% - objects, object types, and structural subtyping (e.g. Abadi & Cardelli)
  29. %% - class-based objects and nominal subtyping (e.g. Featherweight Java)
  30. %% * multi-threading, fork join, futures, implicit parallelism
  31. %% * dataflow analysis, type analysis and specialization
  32. \documentclass[11pt]{book}
  33. \usepackage[T1]{fontenc}
  34. \usepackage[utf8]{inputenc}
  35. \usepackage{lmodern}
  36. \usepackage{hyperref}
  37. \usepackage{graphicx}
  38. \usepackage[english]{babel}
  39. \usepackage{listings}
  40. \usepackage{amsmath}
  41. \usepackage{amsthm}
  42. \usepackage{amssymb}
  43. \usepackage{natbib}
  44. \usepackage{stmaryrd}
  45. \usepackage{xypic}
  46. \usepackage{semantic}
  47. \usepackage{wrapfig}
  48. \usepackage{multirow}
  49. \usepackage{color}
  50. \usepackage{upquote}
  51. \definecolor{lightgray}{gray}{1}
  52. \newcommand{\black}[1]{{\color{black} #1}}
  53. \newcommand{\gray}[1]{{\color{lightgray} #1}}
  54. %% For pictures
  55. \usepackage{tikz}
  56. \usetikzlibrary{arrows.meta}
  57. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  58. % Computer Modern is already the default. -Jeremy
  59. %\renewcommand{\ttdefault}{cmtt}
  60. \definecolor{comment-red}{rgb}{0.8,0,0}
  61. \if{0}
  62. % Peanut gallery comments:
  63. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  64. \newcommand{\margincomment}[1]{\marginpar{#1}}
  65. \else
  66. \newcommand{\rn}[1]{}
  67. \newcommand{\margincomment}[1]{}
  68. \fi
  69. \lstset{%
  70. language=Lisp,
  71. basicstyle=\ttfamily\small,
  72. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then},
  73. deletekeywords={read},
  74. escapechar=|,
  75. columns=flexible,
  76. moredelim=[is][\color{red}]{~}{~}
  77. }
  78. \newtheorem{theorem}{Theorem}
  79. \newtheorem{lemma}[theorem]{Lemma}
  80. \newtheorem{corollary}[theorem]{Corollary}
  81. \newtheorem{proposition}[theorem]{Proposition}
  82. \newtheorem{constraint}[theorem]{Constraint}
  83. \newtheorem{definition}[theorem]{Definition}
  84. \newtheorem{exercise}[theorem]{Exercise}
  85. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  86. % 'dedication' environment: To add a dedication paragraph at the start of book %
  87. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  88. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  89. \newenvironment{dedication}
  90. {
  91. \cleardoublepage
  92. \thispagestyle{empty}
  93. \vspace*{\stretch{1}}
  94. \hfill\begin{minipage}[t]{0.66\textwidth}
  95. \raggedright
  96. }
  97. {
  98. \end{minipage}
  99. \vspace*{\stretch{3}}
  100. \clearpage
  101. }
  102. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  103. % Chapter quote at the start of chapter %
  104. % Source: http://tex.stackexchange.com/a/53380 %
  105. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  106. \makeatletter
  107. \renewcommand{\@chapapp}{}% Not necessary...
  108. \newenvironment{chapquote}[2][2em]
  109. {\setlength{\@tempdima}{#1}%
  110. \def\chapquote@author{#2}%
  111. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  112. \itshape}
  113. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  114. \makeatother
  115. \input{defs}
  116. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  117. \title{\Huge \textbf{Essentials of Compilation} \\
  118. \huge An Incremental Approach}
  119. \author{\textsc{Jeremy G. Siek} \\
  120. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  121. Indiana University \\
  122. \\
  123. with contributions from: \\
  124. Carl Factora \\
  125. Andre Kuhlenschmidt \\
  126. Ryan R. Newton \\
  127. Ryan Scott \\
  128. Cameron Swords \\
  129. Michael M. Vitousek \\
  130. Michael Vollmer
  131. }
  132. \begin{document}
  133. \frontmatter
  134. \maketitle
  135. \begin{dedication}
  136. This book is dedicated to the programming language wonks at Indiana
  137. University.
  138. \end{dedication}
  139. \tableofcontents
  140. \listoffigures
  141. %\listoftables
  142. \mainmatter
  143. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  144. \chapter*{Preface}
  145. The tradition of compiler writing at Indiana University goes back to
  146. research and courses about programming languages by Daniel Friedman in
  147. the 1970's and 1980's. Dan conducted research on lazy
  148. evaluation~\citep{Friedman:1976aa} in the context of
  149. Lisp~\citep{McCarthy:1960dz} and then studied
  150. continuations~\citep{Felleisen:kx} and
  151. macros~\citep{Kohlbecker:1986dk} in the context of the
  152. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  153. of those courses, Kent Dybvig, went on to build Chez
  154. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  155. compiler for Scheme. After completing his Ph.D. at the University of
  156. North Carolina, Kent returned to teach at Indiana University.
  157. Throughout the 1990's and 2000's, Kent continued development of Chez
  158. Scheme and taught the compiler course.
  159. The compiler course evolved to incorporate novel pedagogical ideas
  160. while also including elements of effective real-world compilers. One
  161. of Dan's ideas was to split the compiler into many small ``passes'' so
  162. that the code for each pass would be easy to understood in isolation.
  163. (In contrast, most compilers of the time were organized into only a
  164. few monolithic passes for reasons of compile-time efficiency.) Kent,
  165. with later help from his students Dipanwita Sarkar and Andrew Keep,
  166. developed infrastructure to support this approach and evolved the
  167. course, first to use micro-sized passes and then into even smaller
  168. nano passes~\citep{Sarkar:2004fk,Keep:2012aa}. Jeremy Siek was a
  169. student in this compiler course in the early 2000's, as part of his
  170. Ph.D. studies at Indiana University. Needless to say, Jeremy enjoyed
  171. the course immensely!
  172. During that time, another student named Abdulaziz Ghuloum observed
  173. that the front-to-back organization of the course made it difficult
  174. for students to understand the rationale for the compiler
  175. design. Abdulaziz proposed an incremental approach in which the
  176. students build the compiler in stages; they start by implementing a
  177. complete compiler for a very small subset of the input language and in
  178. each subsequent stage they add a language feature and add or modify
  179. passes to handle the new feature~\citep{Ghuloum:2006bh}. In this way,
  180. the students see how the language features motivate aspects of the
  181. compiler design.
  182. After graduating from Indiana University in 2005, Jeremy went on to
  183. teach at the University of Colorado. He adapted the nano pass and
  184. incremental approaches to compiling a subset of the Python
  185. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  186. on the surface but there is a large overlap in the compiler techniques
  187. required for the two languages. Thus, Jeremy was able to teach much of
  188. the same content from the Indiana compiler course. He very much
  189. enjoyed teaching the course organized in this way, and even better,
  190. many of the students learned a lot and got excited about compilers.
  191. Jeremy returned to teach at Indiana University in 2013. In his
  192. absence the compiler course had switched from the front-to-back
  193. organization to a back-to-front organization. Seeing how well the
  194. incremental approach worked at Colorado, he started porting and
  195. adapting the structure of the Colorado course back into the land of
  196. Scheme. In the meantime Indiana had moved on from Scheme to Racket, so
  197. the course is now about compiling a subset of Racket (and Typed
  198. Racket) to the x86 assembly language. The compiler is implemented in
  199. Racket 7.1~\citep{plt-tr}.
  200. This is the textbook for the incremental version of the compiler
  201. course at Indiana University (Spring 2016 - present) and it is the
  202. first open textbook for an Indiana compiler course. With this book we
  203. hope to make the Indiana compiler course available to people that have
  204. not had the chance to study in Bloomington in person. Many of the
  205. compiler design decisions in this book are drawn from the assignment
  206. descriptions of \cite{Dybvig:2010aa}. We have captured what we think
  207. are the most important topics from \cite{Dybvig:2010aa} but we have
  208. omitted topics that we think are less interesting conceptually and we
  209. have made simplifications to reduce complexity. In this way, this
  210. book leans more towards pedagogy than towards the efficiency of the
  211. generated code. Also, the book differs in places where we saw the
  212. opportunity to make the topics more fun, such as in relating register
  213. allocation to Sudoku (Chapter~\ref{ch:register-allocation-r1}).
  214. \section*{Prerequisites}
  215. The material in this book is challenging but rewarding. It is meant to
  216. prepare students for a lifelong career in programming languages.
  217. The book uses the Racket language both for the implementation of the
  218. compiler and for the language that is compiled, so a student should be
  219. proficient with Racket (or Scheme) prior to reading this book. There
  220. are many excellent resources for learning Scheme and
  221. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. It
  222. is helpful but not necessary for the student to have prior exposure to
  223. the x86 (or x86-64) assembly language~\citep{Intel:2015aa}, as one might
  224. obtain from a computer systems
  225. course~\citep{Bryant:2005aa,Bryant:2010aa}. This book introduces the
  226. parts of x86-64 assembly language that are needed.
  227. %\section*{Structure of book}
  228. % You might want to add short description about each chapter in this book.
  229. %\section*{About the companion website}
  230. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  231. %\begin{itemize}
  232. % \item A link to (freely downlodable) latest version of this document.
  233. % \item Link to download LaTeX source for this document.
  234. % \item Miscellaneous material (e.g. suggested readings etc).
  235. %\end{itemize}
  236. \section*{Acknowledgments}
  237. Many people have contributed to the ideas, techniques, organization,
  238. and teaching of the materials in this book. We especially thank the
  239. following people.
  240. \begin{itemize}
  241. \item Bor-Yuh Evan Chang
  242. \item Kent Dybvig
  243. \item Daniel P. Friedman
  244. \item Ronald Garcia
  245. \item Abdulaziz Ghuloum
  246. \item Jay McCarthy
  247. \item Dipanwita Sarkar
  248. \item Andrew Keep
  249. \item Oscar Waddell
  250. \item Michael Wollowski
  251. \end{itemize}
  252. \mbox{}\\
  253. \noindent Jeremy G. Siek \\
  254. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  255. %\noindent Spring 2016
  256. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  257. \chapter{Preliminaries}
  258. \label{ch:trees-recur}
  259. In this chapter we review the basic tools that are needed to implement
  260. a compiler. Programs are typically input by a programmer as text,
  261. i.e., a sequence of characters. The program-as-text representation is
  262. called \emph{concrete syntax}. We use concrete syntax to concisely
  263. write down and talk about programs. Inside the compiler, we use
  264. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  265. that efficiently supports the operations that the compiler needs to
  266. perform.
  267. %
  268. The translation from concrete syntax to abstract syntax is a process
  269. called \emph{parsing}~\cite{Aho:1986qf}. We do not cover the theory
  270. and implementation of parsing in this book. A parser is provided in
  271. the supporting materials for translating from concrete syntax to
  272. abstract syntax for the languages used in this book.
  273. ASTs can be represented in many different ways inside the compiler,
  274. depending on the programming language used to write the compiler.
  275. %
  276. We use Racket's \code{struct} feature to represent ASTs
  277. (Section~\ref{sec:ast}). We use grammars to define the abstract syntax
  278. of programming languages (Section~\ref{sec:grammar}) and pattern
  279. matching to inspect individual nodes in an AST
  280. (Section~\ref{sec:pattern-matching}). We use recursion to construct
  281. and deconstruct entire ASTs (Section~\ref{sec:recursion}). This
  282. chapter provides an brief introduction to these ideas.
  283. \section{Abstract Syntax Trees and Racket Structures}
  284. \label{sec:ast}
  285. Compilers use abstract syntax trees to represent programs because
  286. compilers often need to ask questions like: for a given part of a
  287. program, what kind of language feature is it? What are the sub-parts
  288. of this part of the program? Consider the program on the left and its
  289. AST on the right. This program is an addition and it has two
  290. sub-parts, a read operation and a negation. The negation has another
  291. sub-part, the integer constant \code{8}. By using a tree to represent
  292. the program, we can easily follow the links to go from one part of a
  293. program to its sub-parts.
  294. \begin{center}
  295. \begin{minipage}{0.4\textwidth}
  296. \begin{lstlisting}
  297. (+ (read) (- 8))
  298. \end{lstlisting}
  299. \end{minipage}
  300. \begin{minipage}{0.4\textwidth}
  301. \begin{equation}
  302. \begin{tikzpicture}
  303. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  304. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  305. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  306. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  307. \draw[->] (plus) to (read);
  308. \draw[->] (plus) to (minus);
  309. \draw[->] (minus) to (8);
  310. \end{tikzpicture}
  311. \label{eq:arith-prog}
  312. \end{equation}
  313. \end{minipage}
  314. \end{center}
  315. We use the standard terminology for trees to describe ASTs: each
  316. circle above is called a \emph{node}. The arrows connect a node to its
  317. \emph{children} (which are also nodes). The top-most node is the
  318. \emph{root}. Every node except for the root has a \emph{parent} (the
  319. node it is the child of). If a node has no children, it is a
  320. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  321. %% Recall that an \emph{symbolic expression} (S-expression) is either
  322. %% \begin{enumerate}
  323. %% \item an atom, or
  324. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  325. %% where $e_1$ and $e_2$ are each an S-expression.
  326. %% \end{enumerate}
  327. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  328. %% null value \code{'()}, etc. We can create an S-expression in Racket
  329. %% simply by writing a backquote (called a quasi-quote in Racket)
  330. %% followed by the textual representation of the S-expression. It is
  331. %% quite common to use S-expressions to represent a list, such as $a, b
  332. %% ,c$ in the following way:
  333. %% \begin{lstlisting}
  334. %% `(a . (b . (c . ())))
  335. %% \end{lstlisting}
  336. %% Each element of the list is in the first slot of a pair, and the
  337. %% second slot is either the rest of the list or the null value, to mark
  338. %% the end of the list. Such lists are so common that Racket provides
  339. %% special notation for them that removes the need for the periods
  340. %% and so many parenthesis:
  341. %% \begin{lstlisting}
  342. %% `(a b c)
  343. %% \end{lstlisting}
  344. %% The following expression creates an S-expression that represents AST
  345. %% \eqref{eq:arith-prog}.
  346. %% \begin{lstlisting}
  347. %% `(+ (read) (- 8))
  348. %% \end{lstlisting}
  349. %% When using S-expressions to represent ASTs, the convention is to
  350. %% represent each AST node as a list and to put the operation symbol at
  351. %% the front of the list. The rest of the list contains the children. So
  352. %% in the above case, the root AST node has operation \code{`+} and its
  353. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  354. %% diagram \eqref{eq:arith-prog}.
  355. %% To build larger S-expressions one often needs to splice together
  356. %% several smaller S-expressions. Racket provides the comma operator to
  357. %% splice an S-expression into a larger one. For example, instead of
  358. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  359. %% we could have first created an S-expression for AST
  360. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  361. %% S-expression.
  362. %% \begin{lstlisting}
  363. %% (define ast1.4 `(- 8))
  364. %% (define ast1.1 `(+ (read) ,ast1.4))
  365. %% \end{lstlisting}
  366. %% In general, the Racket expression that follows the comma (splice)
  367. %% can be any expression that produces an S-expression.
  368. We define a Racket \code{struct} for each kind of node. For this
  369. chapter we require just two kinds of nodes: one for integer constants
  370. and one for primitive operations. The following is the \code{struct}
  371. definition for integer constants.
  372. \begin{lstlisting}
  373. (struct Int (value))
  374. \end{lstlisting}
  375. An integer node includes just one thing: the integer value.
  376. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  377. \begin{lstlisting}
  378. (define eight (Int 8))
  379. \end{lstlisting}
  380. We say that the value created by \code{(Int 8)} is an
  381. \emph{instance} of the \code{Int} structure.
  382. The following is the \code{struct} definition for primitives operations.
  383. \begin{lstlisting}
  384. (struct Prim (op arg*))
  385. \end{lstlisting}
  386. A primitive operation node includes an operator symbol \code{op}
  387. and a list of children \code{arg*}. For example, to create
  388. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  389. \begin{lstlisting}
  390. (define neg-eight (Prim '- (list eight)))
  391. \end{lstlisting}
  392. Primitive operations may have zero or more children. The \code{read}
  393. operator has zero children:
  394. \begin{lstlisting}
  395. (define rd (Prim 'read '()))
  396. \end{lstlisting}
  397. whereas the addition operator has two children:
  398. \begin{lstlisting}
  399. (define ast1.1 (Prim '+ (list rd neg-eight)))
  400. \end{lstlisting}
  401. We have made a design choice regarding the \code{Prim} structure.
  402. Instead of using one structure for many different operations
  403. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  404. structure for each operation, as follows.
  405. \begin{lstlisting}
  406. (struct Read ())
  407. (struct Add (left right))
  408. (struct Neg (value))
  409. \end{lstlisting}
  410. The reason we choose to use just one structure is that in many parts
  411. of the compiler the code for the different primitive operators is the
  412. same, so we might as well just write that code once, which is enabled
  413. by using a single structure.
  414. When compiling a program such as \eqref{eq:arith-prog}, we need to
  415. know that the operation associated with the root node is addition and
  416. we need to be able to access its two children. Racket provides pattern
  417. matching over structures to support these kinds of queries, as we
  418. shall see in Section~\ref{sec:pattern-matching}.
  419. In this book, we often write down the concrete syntax of a program
  420. even when we really have in mind the AST because the concrete syntax
  421. is more concise. We recommend that, in your mind, you always think of
  422. programs as abstract syntax trees.
  423. \section{Grammars}
  424. \label{sec:grammar}
  425. A programming language can be thought of as a \emph{set} of programs.
  426. The set is typically infinite (one can always create larger and larger
  427. programs), so one cannot simply describe a language by listing all of
  428. the programs in the language. Instead we write down a set of rules, a
  429. \emph{grammar}, for building programs. Grammars are often used to
  430. define the concrete syntax of a language, but they can also be used to
  431. describe the abstract syntax. We shall write our rules in a variant of
  432. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}. As an
  433. example, we describe a small language, named $R_0$, that consists of
  434. integers and arithmetic operations.
  435. The first grammar rule for the abstract syntax of $R_0$ says that an
  436. instance of the \code{Int} structure is an expression:
  437. \begin{equation}
  438. \Exp ::= \INT{\Int} \label{eq:arith-int}
  439. \end{equation}
  440. %
  441. Each rule has a left-hand-side and a right-hand-side. The way to read
  442. a rule is that if you have all the program parts on the
  443. right-hand-side, then you can create an AST node and categorize it
  444. according to the left-hand-side.
  445. %
  446. A name such as $\Exp$ that is
  447. defined by the grammar rules is a \emph{non-terminal}.
  448. %
  449. The name $\Int$ is a also a non-terminal, but instead of defining it
  450. with a grammar rule, we define it with the following explanation. We
  451. make the simplifying design decision that all of the languages in this
  452. book only handle machine-representable integers. On most modern
  453. machines this corresponds to integers represented with 64-bits, i.e.,
  454. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  455. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  456. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  457. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  458. that the sequence of decimals represent an integer in range $-2^{62}$
  459. to $2^{62}-1$.
  460. The second grammar rule is the \texttt{read} operation that receives
  461. an input integer from the user of the program.
  462. \begin{equation}
  463. \Exp ::= \READ{} \label{eq:arith-read}
  464. \end{equation}
  465. The third rule says that, given an $\Exp$ node, you can build another
  466. $\Exp$ node by negating it.
  467. \begin{equation}
  468. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  469. \end{equation}
  470. Symbols in typewriter font such as \key{-} and \key{read} are
  471. \emph{terminal} symbols and must literally appear in the program for
  472. the rule to be applicable.
  473. We can apply the rules to build ASTs in the $R_0$
  474. language. For example, by rule \eqref{eq:arith-int}, \texttt{(Int 8)} is an
  475. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  476. an $\Exp$.
  477. \begin{center}
  478. \begin{minipage}{0.4\textwidth}
  479. \begin{lstlisting}
  480. (Prim '- (list (Int 8)))
  481. \end{lstlisting}
  482. \end{minipage}
  483. \begin{minipage}{0.25\textwidth}
  484. \begin{equation}
  485. \begin{tikzpicture}
  486. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  487. \node[draw, circle] (8) at (0, -1.2) {$8$};
  488. \draw[->] (minus) to (8);
  489. \end{tikzpicture}
  490. \label{eq:arith-neg8}
  491. \end{equation}
  492. \end{minipage}
  493. \end{center}
  494. The next grammar rule defines addition expressions:
  495. \begin{equation}
  496. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  497. \end{equation}
  498. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  499. $R_0$. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  500. \eqref{eq:arith-read} and we have already shown that \code{(Prim '-
  501. (list (Int 8)))} is an $\Exp$, so we apply rule \eqref{eq:arith-add}
  502. to show that
  503. \begin{lstlisting}
  504. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  505. \end{lstlisting}
  506. is an $\Exp$ in the $R_0$ language.
  507. If you have an AST for which the above rules do not apply, then the
  508. AST is not in $R_0$. For example, the program \code{(- (read) (+ 8))}
  509. is not in $R_0$ because there are no rules for \code{+} with only one
  510. argument, nor for \key{-} with two arguments. Whenever we define a
  511. language with a grammar, the language only includes those programs
  512. that are justified by the rules.
  513. The last grammar rule for $R_0$ states that there is a \code{Program}
  514. node to mark the top of the whole program:
  515. \[
  516. R_0 ::= \PROGRAM{\code{'()}}{\Exp}
  517. \]
  518. The \code{Program} structure is defined as follows
  519. \begin{lstlisting}
  520. (struct Program (info body))
  521. \end{lstlisting}
  522. where \code{body} is an expression. In later chapters, the \code{info}
  523. part will be used to store auxiliary information but for now it is
  524. just the empty list.
  525. It is common to have many grammar rules with the same left-hand side
  526. but different right-hand sides, such as the rules for $\Exp$ in the
  527. grammar of $R_0$. As a short-hand, a vertical bar can be used to
  528. combine several right-hand-sides into a single rule.
  529. We collect all of the grammar rules for the abstract syntax of $R_0$
  530. in Figure~\ref{fig:r0-syntax}. The concrete syntax for $R_0$ is
  531. defined in Figure~\ref{fig:r0-concrete-syntax}.
  532. The \code{read-program} function provided in \code{utilities.rkt} of
  533. the support materials reads a program in from a file (the sequence of
  534. characters in the concrete syntax of Racket) and parses it into an
  535. abstract syntax tree. See the description of \code{read-program} in
  536. Appendix~\ref{appendix:utilities} for more details.
  537. \begin{figure}[tp]
  538. \fbox{
  539. \begin{minipage}{0.96\textwidth}
  540. \[
  541. \begin{array}{rcl}
  542. \begin{array}{rcl}
  543. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)\\
  544. R_0 &::=& \Exp
  545. \end{array}
  546. \end{array}
  547. \]
  548. \end{minipage}
  549. }
  550. \caption{The concrete syntax of $R_0$.}
  551. \label{fig:r0-concrete-syntax}
  552. \end{figure}
  553. \begin{figure}[tp]
  554. \fbox{
  555. \begin{minipage}{0.96\textwidth}
  556. \[
  557. \begin{array}{rcl}
  558. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  559. &\mid& \ADD{\Exp}{\Exp} \\
  560. R_0 &::=& \PROGRAM{\code{'()}}{\Exp}
  561. \end{array}
  562. \]
  563. \end{minipage}
  564. }
  565. \caption{The abstract syntax of $R_0$.}
  566. \label{fig:r0-syntax}
  567. \end{figure}
  568. \section{Pattern Matching}
  569. \label{sec:pattern-matching}
  570. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  571. the parts of an AST node. Racket provides the \texttt{match} form to
  572. access the parts of a structure. Consider the following example and
  573. the output on the right.
  574. \begin{center}
  575. \begin{minipage}{0.5\textwidth}
  576. \begin{lstlisting}
  577. (match ast1.1
  578. [(Prim op (list child1 child2))
  579. (print op)])
  580. \end{lstlisting}
  581. \end{minipage}
  582. \vrule
  583. \begin{minipage}{0.25\textwidth}
  584. \begin{lstlisting}
  585. '+
  586. \end{lstlisting}
  587. \end{minipage}
  588. \end{center}
  589. In the above example, the \texttt{match} form takes the AST
  590. \eqref{eq:arith-prog} and binds its parts to the three pattern
  591. variables \texttt{op}, \texttt{child1}, and \texttt{child2}. In
  592. general, a match clause consists of a \emph{pattern} and a
  593. \emph{body}. Patterns are recursively defined to be either a pattern
  594. variable, a structure name followed by a pattern for each of the
  595. structure's arguments, or an S-expression (symbols, lists, etc.).
  596. (See Chapter 12 of The Racket
  597. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  598. and Chapter 9 of The Racket
  599. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  600. for a complete description of \code{match}.)
  601. %
  602. The body of a match clause may contain arbitrary Racket code. The
  603. pattern variables can be used in the scope of the body.
  604. A \code{match} form may contain several clauses, as in the following
  605. function \code{leaf?} that recognizes when an $R_0$ node is
  606. a leaf. The \code{match} proceeds through the clauses in order,
  607. checking whether the pattern can match the input AST. The
  608. body of the first clause that matches is executed. The output of
  609. \code{leaf?} for several ASTs is shown on the right.
  610. \begin{center}
  611. \begin{minipage}{0.6\textwidth}
  612. \begin{lstlisting}
  613. (define (leaf? arith)
  614. (match arith
  615. [(Int n) #t]
  616. [(Prim 'read '()) #t]
  617. [(Prim '- (list c1)) #f]
  618. [(Prim '+ (list c1 c2)) #f]))
  619. (leaf? (Prim 'read '()))
  620. (leaf? (Prim '- (list (Int 8))))
  621. (leaf? (Int 8))
  622. \end{lstlisting}
  623. \end{minipage}
  624. \vrule
  625. \begin{minipage}{0.25\textwidth}
  626. \begin{lstlisting}
  627. #t
  628. #f
  629. #t
  630. \end{lstlisting}
  631. \end{minipage}
  632. \end{center}
  633. When writing a \code{match}, we refer to the grammar definition to
  634. identify which non-terminal we are expecting to match against, then we
  635. make sure that 1) we have one clause for each alternative of that
  636. non-terminal and 2) that the pattern in each clause corresponds to the
  637. corresponding right-hand side of a grammar rule. For the \code{match}
  638. in the \code{leaf?} function, we refer to the grammar for $R_0$ in
  639. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  640. alternatives, so the \code{match} has 4 clauses. The pattern in each
  641. clause corresponds to the right-hand side of a grammar rule. For
  642. example, the pattern \code{(Prim '+ (list c1 c2))} corresponds to the
  643. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  644. patterns, replace non-terminals such as $\Exp$ with pattern variables
  645. of your choice (e.g. \code{c1} and \code{c2}).
  646. \section{Recursion}
  647. \label{sec:recursion}
  648. Programs are inherently recursive. For example, an $R_0$ expression is
  649. often made of smaller expressions. Thus, the natural way to process an
  650. entire program is with a recursive function. As a first example of
  651. such a recursive function, we define \texttt{exp?} below, which takes
  652. an arbitrary value and determines whether or not it is an $R_0$
  653. expression.
  654. %
  655. When a recursive function is defined using a sequence of match clauses
  656. that correspond to a grammar, and the body of each clause makes a
  657. recursive call on each child node, then we say the function is defined
  658. by \emph{structural recursion}\footnote{This principle of structuring
  659. code according to the data definition is advocated in the book
  660. \emph{How to Design Programs}
  661. \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}. Below we also
  662. define a second function, named \code{R0?}, that determines whether a
  663. value is an $R_0$ program. In general we can expect to write one
  664. recursive function to handle each non-terminal in a grammar.
  665. %
  666. \begin{center}
  667. \begin{minipage}{0.7\textwidth}
  668. \begin{lstlisting}
  669. (define (exp? ast)
  670. (match ast
  671. [(Int n) #t]
  672. [(Prim 'read '()) #t]
  673. [(Prim '- (list e)) (exp? e)]
  674. [(Prim '+ (list e1 e2))
  675. (and (exp? e1) (exp? e2))]
  676. [else #f]))
  677. (define (R0? ast)
  678. (match ast
  679. [(Program '() e) (exp? e)]
  680. [else #f]))
  681. (R0? (Program '() ast1.1)
  682. (R0? (Program '()
  683. (Prim '- (list (Prim 'read '())
  684. (Prim '+ (list (Num 8)))))))
  685. \end{lstlisting}
  686. \end{minipage}
  687. \vrule
  688. \begin{minipage}{0.25\textwidth}
  689. \begin{lstlisting}
  690. #t
  691. #f
  692. \end{lstlisting}
  693. \end{minipage}
  694. \end{center}
  695. You may be tempted to merge the two functions into one, like this:
  696. \begin{center}
  697. \begin{minipage}{0.5\textwidth}
  698. \begin{lstlisting}
  699. (define (R0? ast)
  700. (match ast
  701. [(Int n) #t]
  702. [(Prim 'read '()) #t]
  703. [(Prim '- (list e)) (R0? e)]
  704. [(Prim '+ (list e1 e2)) (and (R0? e1) (R0? e2))]
  705. [(Program '() e) (R0? e)]
  706. [else #f]))
  707. \end{lstlisting}
  708. \end{minipage}
  709. \end{center}
  710. %
  711. Sometimes such a trick will save a few lines of code, especially when
  712. it comes to the \code{Program} wrapper. Yet this style is generally
  713. \emph{not} recommended because it can get you into trouble.
  714. %
  715. For example, the above function is subtly wrong:
  716. \lstinline{(R0? (Program '() (Program '() (Int 3))))}
  717. will return true, when it should return false.
  718. %% NOTE FIXME - must check for consistency on this issue throughout.
  719. \section{Interpreters}
  720. \label{sec:interp-R0}
  721. The meaning, or semantics, of a program is typically defined in the
  722. specification of the language. For example, the Scheme language is
  723. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  724. defined in its reference manual~\citep{plt-tr}. In this book we use an
  725. interpreter to define the meaning of each language that we consider,
  726. following Reynolds' advice~\citep{reynolds72:_def_interp}. An
  727. interpreter that is designated (by some people) as the definition of a
  728. language is called a \emph{definitional interpreter}. We warm up by
  729. creating a definitional interpreter for the $R_0$ language, which
  730. serves as a second example of structural recursion. The
  731. \texttt{interp-R0} function is defined in
  732. Figure~\ref{fig:interp-R0}. The body of the function is a match on the
  733. input program followed by a call to the \lstinline{interp-exp} helper
  734. function, which in turn has one match clause per grammar rule for
  735. $R_0$ expressions.
  736. \begin{figure}[tbp]
  737. \begin{lstlisting}
  738. (define (interp-exp e)
  739. (match e
  740. [(Int n) n]
  741. [(Prim 'read '())
  742. (define r (read))
  743. (cond [(fixnum? r) r]
  744. [else (error 'interp-R1 "expected an integer" r)])]
  745. [(Prim '- (list e))
  746. (define v (interp-exp e))
  747. (fx- 0 v)]
  748. [(Prim '+ (list e1 e2))
  749. (define v1 (interp-exp e1))
  750. (define v2 (interp-exp e2))
  751. (fx+ v1 v2)]
  752. ))
  753. (define (interp-R0 p)
  754. (match p
  755. [(Program '() e) (interp-exp e)]
  756. ))
  757. \end{lstlisting}
  758. \caption{Interpreter for the $R_0$ language.}
  759. \label{fig:interp-R0}
  760. \end{figure}
  761. Let us consider the result of interpreting a few $R_0$ programs. The
  762. following program adds two integers.
  763. \begin{lstlisting}
  764. (+ 10 32)
  765. \end{lstlisting}
  766. The result is \key{42}. We wrote the above program in concrete syntax,
  767. whereas the parsed abstract syntax is:
  768. \begin{lstlisting}
  769. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  770. \end{lstlisting}
  771. The next example demonstrates that expressions may be nested within
  772. each other, in this case nesting several additions and negations.
  773. \begin{lstlisting}
  774. (+ 10 (- (+ 12 20)))
  775. \end{lstlisting}
  776. What is the result of the above program?
  777. As mentioned previously, the $R_0$ language does not support
  778. arbitrarily-large integers, but only $63$-bit integers, so we
  779. interpret the arithmetic operations of $R_0$ using fixnum arithmetic
  780. in Racket.
  781. Suppose
  782. \[
  783. n = 999999999999999999
  784. \]
  785. which indeed fits in $63$-bits. What happens when we run the
  786. following program in our interpreter?
  787. \begin{lstlisting}
  788. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  789. \end{lstlisting}
  790. It produces an error:
  791. \begin{lstlisting}
  792. fx+: result is not a fixnum
  793. \end{lstlisting}
  794. We establish the convention that if running the definitional
  795. interpreter on a program produces an error, then the meaning of that
  796. program is \emph{unspecified}. That means a compiler for the language
  797. is under no obligations regarding that program; it may or may not
  798. produce an executable, and if it does, that executable can do
  799. anything. This convention applies to the languages defined in this
  800. book, as a way to simplify the student's task of implementing them,
  801. but this convention is not applicable to all programming languages.
  802. Moving on to the last feature of the $R_0$ language, the \key{read}
  803. operation prompts the user of the program for an integer. Recall that
  804. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  805. \code{8}. So if we run
  806. \begin{lstlisting}
  807. (interp-R0 ast1.1)
  808. \end{lstlisting}
  809. and if the input is \code{50}, then we get the answer to life, the
  810. universe, and everything: \code{42}!\footnote{\emph{The Hitchhiker's
  811. Guide to the Galaxy} by Douglas Adams.}
  812. We include the \key{read} operation in $R_0$ so a clever student
  813. cannot implement a compiler for $R_0$ that simply runs the interpreter
  814. during compilation to obtain the output and then generates the trivial
  815. code to produce the output. (Yes, a clever student did this in the
  816. first instance of this course.)
  817. The job of a compiler is to translate a program in one language into a
  818. program in another language so that the output program behaves the
  819. same way as the input program does according to its definitional
  820. interpreter. This idea is depicted in the following diagram. Suppose
  821. we have two languages, $\mathcal{L}_1$ and $\mathcal{L}_2$, and an
  822. interpreter for each language. Suppose that the compiler translates
  823. program $P_1$ in language $\mathcal{L}_1$ into program $P_2$ in
  824. language $\mathcal{L}_2$. Then interpreting $P_1$ and $P_2$ on their
  825. respective interpreters with input $i$ should yield the same output
  826. $o$.
  827. \begin{equation} \label{eq:compile-correct}
  828. \begin{tikzpicture}[baseline=(current bounding box.center)]
  829. \node (p1) at (0, 0) {$P_1$};
  830. \node (p2) at (3, 0) {$P_2$};
  831. \node (o) at (3, -2.5) {$o$};
  832. \path[->] (p1) edge [above] node {compile} (p2);
  833. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  834. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  835. \end{tikzpicture}
  836. \end{equation}
  837. In the next section we see our first example of a compiler.
  838. \section{Example Compiler: a Partial Evaluator}
  839. \label{sec:partial-evaluation}
  840. In this section we consider a compiler that translates $R_0$ programs
  841. into $R_0$ programs that may be more efficient, that is, this compiler
  842. is an optimizer. This optimizer eagerly computes the parts of the
  843. program that do not depend on any inputs, a process known as
  844. \emph{partial evaluation}~\cite{Jones:1993uq}. For example, given the
  845. following program
  846. \begin{lstlisting}
  847. (+ (read) (- (+ 5 3)))
  848. \end{lstlisting}
  849. our compiler will translate it into the program
  850. \begin{lstlisting}
  851. (+ (read) -8)
  852. \end{lstlisting}
  853. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  854. evaluator for the $R_0$ language. The output of the partial evaluator
  855. is an $R_0$ program. In Figure~\ref{fig:pe-arith}, the structural
  856. recursion over $\Exp$ is captured in the \code{pe-exp} function
  857. whereas the code for partially evaluating the negation and addition
  858. operations is factored into two separate helper functions:
  859. \code{pe-neg} and \code{pe-add}. The input to these helper
  860. functions is the output of partially evaluating the children.
  861. \begin{figure}[tbp]
  862. \begin{lstlisting}
  863. (define (pe-neg r)
  864. (match r
  865. [(Int n) (Int (fx- 0 n))]
  866. [else (Prim '- (list r))]))
  867. (define (pe-add r1 r2)
  868. (match* (r1 r2)
  869. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  870. [(_ _) (Prim '+ (list r1 r2))]))
  871. (define (pe-exp e)
  872. (match e
  873. [(Int n) (Int n)]
  874. [(Prim 'read '()) (Prim 'read '())]
  875. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  876. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]
  877. ))
  878. (define (pe-R0 p)
  879. (match p
  880. [(Program info e) (Program info (pe-exp e))]
  881. ))
  882. \end{lstlisting}
  883. \caption{A partial evaluator for $R_0$ expressions.}
  884. \label{fig:pe-arith}
  885. \end{figure}
  886. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  887. arguments are integers and if they are, perform the appropriate
  888. arithmetic. Otherwise, they create an AST node for the operation
  889. (either negation or addition).
  890. To gain some confidence that the partial evaluator is correct, we can
  891. test whether it produces programs that get the same result as the
  892. input programs. That is, we can test whether it satisfies Diagram
  893. \eqref{eq:compile-correct}. The following code runs the partial
  894. evaluator on several examples and tests the output program. The
  895. \texttt{parse-program} and \texttt{assert} functions are defined in
  896. Appendix~\ref{appendix:utilities}.\\
  897. \begin{minipage}{1.0\textwidth}
  898. \begin{lstlisting}
  899. (define (test-pe p)
  900. (assert "testing pe-R0"
  901. (equal? (interp-R0 p) (interp-R0 (pe-R0 p)))))
  902. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  903. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  904. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  905. \end{lstlisting}
  906. \end{minipage}
  907. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  908. \chapter{Integers and Variables}
  909. \label{ch:int-exp}
  910. This chapter is about compiling the subset of Racket that includes
  911. integer arithmetic and local variable binding, which we name $R_1$, to
  912. x86-64 assembly code~\citep{Intel:2015aa}. Henceforth we shall refer
  913. to x86-64 simply as x86. The chapter begins with a description of the
  914. $R_1$ language (Section~\ref{sec:s0}) followed by a description of x86
  915. (Section~\ref{sec:x86}). The x86 assembly language is large, so we
  916. discuss only what is needed for compiling $R_1$. We introduce more of
  917. x86 in later chapters. Once we have introduced $R_1$ and x86, we
  918. reflect on their differences and come up with a plan to break down the
  919. translation from $R_1$ to x86 into a handful of steps
  920. (Section~\ref{sec:plan-s0-x86}). The rest of the sections in this
  921. chapter give detailed hints regarding each step
  922. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  923. to give enough hints that the well-prepared reader, together with a
  924. few friends, can implement a compiler from $R_1$ to x86 in a couple
  925. weeks while at the same time leaving room for some fun and creativity.
  926. To give the reader a feeling for the scale of this first compiler, the
  927. instructor solution for the $R_1$ compiler is less than 500 lines of
  928. code.
  929. \section{The $R_1$ Language}
  930. \label{sec:s0}
  931. The $R_1$ language extends the $R_0$ language with variable
  932. definitions. The concrete syntax of the $R_1$ language is defined by
  933. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  934. syntax is defined in Figure~\ref{fig:r1-syntax}. The non-terminal
  935. \Var{} may be any Racket identifier. As in $R_0$, \key{read} is a
  936. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  937. operator. Similar to $R_0$, the abstract syntax of $R_1$ includes the
  938. \key{Program} struct to mark the top of the program.
  939. %% The $\itm{info}$
  940. %% field of the \key{Program} structure contains an \emph{association
  941. %% list} (a list of key-value pairs) that is used to communicate
  942. %% auxiliary data from one compiler pass the next.
  943. Despite the simplicity of the $R_1$ language, it is rich enough to
  944. exhibit several compilation techniques.
  945. \begin{figure}[btp]
  946. \centering
  947. \fbox{
  948. \begin{minipage}{0.96\textwidth}
  949. \[
  950. \begin{array}{rcl}
  951. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)
  952. \mid \Var \\
  953. &\mid& (\key{let}~([\Var~\Exp])~\Exp) \\
  954. R_1 &::=& \Exp
  955. \end{array}
  956. \]
  957. \end{minipage}
  958. }
  959. \caption{The concrete syntax of $R_1$.}
  960. \label{fig:r1-concrete-syntax}
  961. \end{figure}
  962. \begin{figure}[btp]
  963. \centering
  964. \fbox{
  965. \begin{minipage}{0.96\textwidth}
  966. \[
  967. \begin{array}{rcl}
  968. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  969. &\mid& \ADD{\Exp}{\Exp}
  970. \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  971. R_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  972. \end{array}
  973. \]
  974. \end{minipage}
  975. }
  976. \caption{The abstract syntax of $R_1$.}
  977. \label{fig:r1-syntax}
  978. \end{figure}
  979. Let us dive further into the syntax and semantics of the $R_1$
  980. language. The \key{Let} feature defines a variable for use within its
  981. body and initializes the variable with the value of an expression.
  982. The abstract syntax for \key{Let} is defined in Figure~\ref{fig:r1-syntax}.
  983. The concrete syntax for \key{Let} is
  984. \begin{lstlisting}
  985. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  986. \end{lstlisting}
  987. For example, the following program initializes \code{x} to $32$ and then
  988. evaluates the body \code{(+ 10 x)}, producing $42$.
  989. \begin{lstlisting}
  990. (let ([x (+ 12 20)]) (+ 10 x))
  991. \end{lstlisting}
  992. When there are multiple \key{let}'s for the same variable, the closest
  993. enclosing \key{let} is used. That is, variable definitions overshadow
  994. prior definitions. Consider the following program with two \key{let}'s
  995. that define variables named \code{x}. Can you figure out the result?
  996. \begin{lstlisting}
  997. (let ([x 32]) (+ (let ([x 10]) x) x))
  998. \end{lstlisting}
  999. For the purposes of depicting which variable uses correspond to which
  1000. definitions, the following shows the \code{x}'s annotated with
  1001. subscripts to distinguish them. Double check that your answer for the
  1002. above is the same as your answer for this annotated version of the
  1003. program.
  1004. \begin{lstlisting}
  1005. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1006. \end{lstlisting}
  1007. The initializing expression is always evaluated before the body of the
  1008. \key{let}, so in the following, the \key{read} for \code{x} is
  1009. performed before the \key{read} for \code{y}. Given the input
  1010. $52$ then $10$, the following produces $42$ (not $-42$).
  1011. \begin{lstlisting}
  1012. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1013. \end{lstlisting}
  1014. Figure~\ref{fig:interp-R1} shows the definitional interpreter for the
  1015. $R_1$ language. It extends the interpreter for $R_0$ with two new
  1016. \key{match} clauses for variables and for \key{let}. For \key{let},
  1017. we need a way to communicate the value of a variable to all the uses
  1018. of a variable. To accomplish this, we maintain a mapping from
  1019. variables to values, which is called an \emph{environment}. For
  1020. simplicity, here we use an association list to represent the
  1021. environment. The \code{interp-R1} function takes the current
  1022. environment, \code{env}, as an extra parameter. When the interpreter
  1023. encounters a variable, it finds the corresponding value using the
  1024. \code{dict-ref} function from the \code{racket/dict} package. When
  1025. the interpreter encounters a \key{Let}, it evaluates the initializing
  1026. expression, extends the environment with the result value bound to the
  1027. variable (using \code{dict-set}), then evaluates the body of the
  1028. \key{Let}.
  1029. \begin{figure}[tbp]
  1030. \begin{lstlisting}
  1031. (define (interp-exp env)
  1032. (lambda (e)
  1033. (match e
  1034. [(Int n) n]
  1035. [(Prim 'read '())
  1036. (define r (read))
  1037. (cond [(fixnum? r) r]
  1038. [else (error 'interp-R1 "expected an integer" r)])]
  1039. [(Prim '- (list e))
  1040. (define v ((interp-exp env) e))
  1041. (fx- 0 v)]
  1042. [(Prim '+ (list e1 e2))
  1043. (define v1 ((interp-exp env) e1))
  1044. (define v2 ((interp-exp env) e2))
  1045. (fx+ v1 v2)]
  1046. [(Var x) (dict-ref env x)]
  1047. [(Let x e body)
  1048. (define new-env (dict-set env x ((interp-exp env) e)))
  1049. ((interp-exp new-env) body)]
  1050. )))
  1051. (define (interp-R1 p)
  1052. (match p
  1053. [(Program info e) ((interp-exp '()) e)]
  1054. ))
  1055. \end{lstlisting}
  1056. \caption{Interpreter for the $R_1$ language.}
  1057. \label{fig:interp-R1}
  1058. \end{figure}
  1059. The goal for this chapter is to implement a compiler that translates
  1060. any program $P_1$ written in the $R_1$ language into an x86 assembly
  1061. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1062. computer as the $P_1$ program interpreted by \code{interp-R1}. That
  1063. is, they both output the same integer $n$. We depict this correctness
  1064. criteria in the following diagram.
  1065. \[
  1066. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1067. \node (p1) at (0, 0) {$P_1$};
  1068. \node (p2) at (4, 0) {$P_2$};
  1069. \node (o) at (4, -2) {$n$};
  1070. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1071. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  1072. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  1073. \end{tikzpicture}
  1074. \]
  1075. In the next section we introduce enough of the x86 assembly
  1076. language to compile $R_1$.
  1077. \section{The x86 Assembly Language}
  1078. \label{sec:x86}
  1079. Figure~\ref{fig:x86-a} defines the concrete syntax for the subset of
  1080. the x86 assembly language needed for this chapter.
  1081. %
  1082. An x86 program is a sequence of instructions. The program is stored in
  1083. the computer's memory and the computer has a \emph{program counter}
  1084. that points to the address of the next instruction to be executed. For
  1085. most instructions, once the instruction is executed, the program
  1086. counter is incremented to point to the immediately following
  1087. instruction in memory. Most x86 instructions take two operands, where
  1088. each operand is either an integer constant (called \emph{immediate
  1089. value}), a \emph{register}, or a \emph{memory} location. A register
  1090. is a special kind of variable. Each one holds a 64-bit value; there
  1091. are 16 registers in the computer and their names are given in
  1092. Figure~\ref{fig:x86-a}. The computer's memory as a mapping of 64-bit
  1093. addresses to 64-bit values%
  1094. \footnote{This simple story suffices for describing how sequential
  1095. programs access memory but is not sufficient for multi-threaded
  1096. programs. However, multi-threaded execution is beyond the scope of
  1097. this book.}.
  1098. %
  1099. We use the AT\&T syntax expected by the GNU assembler, which comes
  1100. with the \key{gcc} compiler that we use for compiling assembly code to
  1101. machine code.
  1102. %
  1103. Appendix~\ref{sec:x86-quick-reference} is a quick-reference for all of
  1104. the x86 instructions used in this book.
  1105. % to do: finish treatment of imulq
  1106. % it's needed for vector's in R6/R7
  1107. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1108. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1109. && \key{r8} \mid \key{r9} \mid \key{r10}
  1110. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1111. \mid \key{r14} \mid \key{r15}}
  1112. \begin{figure}[tp]
  1113. \fbox{
  1114. \begin{minipage}{0.96\textwidth}
  1115. \[
  1116. \begin{array}{lcl}
  1117. \Reg &::=& \allregisters{} \\
  1118. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1119. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1120. \key{subq} \; \Arg\key{,} \Arg \mid
  1121. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1122. && \key{callq} \; \mathit{label} \mid
  1123. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \itm{label}\key{:}\; \Instr \\
  1124. \Prog &::= & \key{.globl main}\\
  1125. & & \key{main:} \; \Instr^{+}
  1126. \end{array}
  1127. \]
  1128. \end{minipage}
  1129. }
  1130. \caption{A subset of the x86 assembly language (AT\&T syntax).}
  1131. \label{fig:x86-a}
  1132. \end{figure}
  1133. An immediate value is written using the notation \key{\$}$n$ where $n$
  1134. is an integer.
  1135. %
  1136. A register is written with a \key{\%} followed by the register name,
  1137. such as \key{\%rax}.
  1138. %
  1139. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1140. which obtains the address stored in register $r$ and then adds $n$
  1141. bytes to the address. The resulting address is used to either load or
  1142. store to memory depending on whether it occurs as a source or
  1143. destination argument of an instruction.
  1144. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1145. source $s$ and destination $d$, applies the arithmetic operation, then
  1146. writes the result back to the destination $d$.
  1147. %
  1148. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1149. stores the result in $d$.
  1150. %
  1151. The $\key{callq}\,\mathit{label}$ instruction executes the procedure
  1152. specified by the label. We discuss procedure calls in more detail
  1153. later in this chapter and in Chapter~\ref{ch:functions}.
  1154. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  1155. to \code{(+ 10 32)}. The \key{globl} directive says that the
  1156. \key{main} procedure is externally visible, which is necessary so
  1157. that the operating system can call it. The label \key{main:}
  1158. indicates the beginning of the \key{main} procedure which is where
  1159. the operating system starts executing this program. The instruction
  1160. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  1161. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  1162. $10$ in \key{rax} and puts the result, $42$, back into
  1163. \key{rax}.
  1164. %
  1165. The last instruction, \key{retq}, finishes the \key{main} function by
  1166. returning the integer in \key{rax} to the operating system. The
  1167. operating system interprets this integer as the program's exit
  1168. code. By convention, an exit code of 0 indicates that a program
  1169. completed successfully, and all other exit codes indicate various
  1170. errors. Nevertheless, we return the result of the program as the exit
  1171. code.
  1172. %\begin{wrapfigure}{r}{2.25in}
  1173. \begin{figure}[tbp]
  1174. \begin{lstlisting}
  1175. .globl main
  1176. main:
  1177. movq $10, %rax
  1178. addq $32, %rax
  1179. retq
  1180. \end{lstlisting}
  1181. \caption{An x86 program equivalent to $\BINOP{+}{10}{32}$.}
  1182. \label{fig:p0-x86}
  1183. %\end{wrapfigure}
  1184. \end{figure}
  1185. Unfortunately, x86 varies in a couple ways depending on what operating
  1186. system it is assembled in. The code examples shown here are correct on
  1187. Linux and most Unix-like platforms, but when assembled on Mac OS X,
  1188. labels like \key{main} must be prefixed with an underscore, as in
  1189. \key{\_main}.
  1190. We exhibit the use of memory for storing intermediate results in the
  1191. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1192. equivalent to $\BINOP{+}{52}{ \UNIOP{-}{10} }$. This program uses a
  1193. region of memory called the \emph{procedure call stack} (or
  1194. \emph{stack} for short). The stack consists of a separate \emph{frame}
  1195. for each procedure call. The memory layout for an individual frame is
  1196. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1197. \emph{stack pointer} and points to the item at the top of the
  1198. stack. The stack grows downward in memory, so we increase the size of
  1199. the stack by subtracting from the stack pointer. Some operating
  1200. systems require the frame size to be a multiple of 16 bytes. In the
  1201. context of a procedure call, the \emph{return address} is the next
  1202. instruction after the call instruction on the caller side. During a
  1203. function call, the return address is pushed onto the stack. The
  1204. register \key{rbp} is the \emph{base pointer} which serves two
  1205. purposes: 1) it saves the location of the stack pointer for the
  1206. calling procedure and 2) it is used to access variables associated
  1207. with the current procedure. The base pointer of the calling procedure
  1208. is pushed onto the stack after the return address. We number the
  1209. variables from $1$ to $n$. Variable $1$ is stored at address
  1210. $-8\key{(\%rbp)}$, variable $2$ at $-16\key{(\%rbp)}$, etc.
  1211. \begin{figure}[tbp]
  1212. \begin{lstlisting}
  1213. start:
  1214. movq $10, -8(%rbp)
  1215. negq -8(%rbp)
  1216. movq -8(%rbp), %rax
  1217. addq $52, %rax
  1218. jmp conclusion
  1219. .globl main
  1220. main:
  1221. pushq %rbp
  1222. movq %rsp, %rbp
  1223. subq $16, %rsp
  1224. jmp start
  1225. conclusion:
  1226. addq $16, %rsp
  1227. popq %rbp
  1228. retq
  1229. \end{lstlisting}
  1230. \caption{An x86 program equivalent to $\BINOP{+}{52}{\UNIOP{-}{10} }$.}
  1231. \label{fig:p1-x86}
  1232. \end{figure}
  1233. \begin{figure}[tbp]
  1234. \centering
  1235. \begin{tabular}{|r|l|} \hline
  1236. Position & Contents \\ \hline
  1237. 8(\key{\%rbp}) & return address \\
  1238. 0(\key{\%rbp}) & old \key{rbp} \\
  1239. -8(\key{\%rbp}) & variable $1$ \\
  1240. -16(\key{\%rbp}) & variable $2$ \\
  1241. \ldots & \ldots \\
  1242. 0(\key{\%rsp}) & variable $n$\\ \hline
  1243. \end{tabular}
  1244. \caption{Memory layout of a frame.}
  1245. \label{fig:frame}
  1246. \end{figure}
  1247. Getting back to the program in Figure~\ref{fig:p1-x86}, the first
  1248. three instructions are the typical \emph{prelude} for a procedure.
  1249. The instruction \key{pushq \%rbp} saves the base pointer for the
  1250. caller onto the stack and subtracts $8$ from the stack pointer. The
  1251. second instruction \key{movq \%rsp, \%rbp} changes the base pointer to
  1252. the top of the stack. The instruction \key{subq \$16, \%rsp} moves the
  1253. stack pointer down to make enough room for storing variables. This
  1254. program needs one variable ($8$ bytes) but because the frame size is
  1255. required to be a multiple of 16 bytes, the space for variables is
  1256. rounded to 16 bytes.
  1257. The four instructions under the label \code{start} carry out the work
  1258. of computing $\BINOP{+}{52}{\UNIOP{-}{10} }$. The first instruction
  1259. \key{movq \$10, -8(\%rbp)} stores $10$ in variable $1$. The
  1260. instruction \key{negq -8(\%rbp)} changes variable $1$ to $-10$. The
  1261. instruction \key{movq \$52, \%rax} places $52$ in the register \key{rax} and
  1262. finally \key{addq -8(\%rbp), \%rax} adds the contents of variable $1$ to
  1263. \key{rax}, at which point \key{rax} contains $42$.
  1264. The three instructions under the label \code{conclusion} are the
  1265. typical \emph{finale} of a procedure. The first two instructions are
  1266. necessary to get the state of the machine back to where it was at the
  1267. beginning of the procedure. The instruction \key{addq \$16, \%rsp}
  1268. moves the stack pointer back to point at the old base pointer. The
  1269. amount added here needs to match the amount that was subtracted in the
  1270. prelude of the procedure. Then \key{popq \%rbp} returns the old base
  1271. pointer to \key{rbp} and adds $8$ to the stack pointer. The last
  1272. instruction, \key{retq}, jumps back to the procedure that called this
  1273. one and adds 8 to the stack pointer, which returns the stack pointer
  1274. to where it was prior to the procedure call.
  1275. The compiler will need a convenient representation for manipulating
  1276. x86 programs, so we define an abstract syntax for x86 in
  1277. Figure~\ref{fig:x86-ast-a}. We refer to this language as $x86_0$ with
  1278. a subscript $0$ because later we introduce extended versions of this
  1279. assembly language. The main difference compared to the concrete syntax
  1280. of x86 (Figure~\ref{fig:x86-a}) is that it does not allow labeled
  1281. instructions to appear anywhere, but instead organizes instructions
  1282. into groups called \emph{blocks} and associates a label with every
  1283. block, which is why the \key{CFG} struct (for control-flow graph)
  1284. includes an association list mapping labels to blocks. The reason for
  1285. this organization becomes apparent in Chapter~\ref{ch:bool-types} when
  1286. we introduce conditional branching.
  1287. \begin{figure}[tp]
  1288. \fbox{
  1289. \begin{minipage}{0.96\textwidth}
  1290. \small
  1291. \[
  1292. \begin{array}{lcl}
  1293. \Reg &::=& \allregisters{} \\
  1294. \Arg &::=& \IMM{\Int} \mid \REG{\code{'}\Reg}
  1295. \mid \DEREF{\Reg}{\Int} \\
  1296. \Instr &::=& \BININSTR{\code{'addq}}{\Arg}{\Arg}
  1297. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} \\
  1298. &\mid& \BININSTR{\code{'movq}}{\Arg}{\Arg}
  1299. \mid \UNIINSTR{\code{'negq}}{\Arg}\\
  1300. &\mid& \CALLQ{\itm{label}} \mid \RETQ{}
  1301. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \\
  1302. \Block &::= & \BLOCK{\itm{info}}{\Instr^{+}} \\
  1303. x86_0 &::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}^{+}}}
  1304. \end{array}
  1305. \]
  1306. \end{minipage}
  1307. }
  1308. \caption{Abstract syntax of $x86_0$ assembly.}
  1309. \label{fig:x86-ast-a}
  1310. \end{figure}
  1311. \section{Planning the trip to x86 via the $C_0$ language}
  1312. \label{sec:plan-s0-x86}
  1313. To compile one language to another it helps to focus on the
  1314. differences between the two languages because the compiler will need
  1315. to bridge those differences. What are the differences between $R_1$
  1316. and x86 assembly? Here are some of the most important ones:
  1317. \begin{enumerate}
  1318. \item[(a)] x86 arithmetic instructions typically have two arguments
  1319. and update the second argument in place. In contrast, $R_1$
  1320. arithmetic operations take two arguments and produce a new value.
  1321. An x86 instruction may have at most one memory-accessing argument.
  1322. Furthermore, some instructions place special restrictions on their
  1323. arguments.
  1324. \item[(b)] An argument of an $R_1$ operator can be any expression,
  1325. whereas x86 instructions restrict their arguments to be integers
  1326. constants, registers, and memory locations.
  1327. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1328. sequence of instructions and jumps to labeled positions, whereas in
  1329. $R_1$ the order of evaluation is a left-to-right depth-first
  1330. traversal of the abstract syntax tree.
  1331. \item[(d)] An $R_1$ program can have any number of variables whereas
  1332. x86 has 16 registers and the procedure calls stack.
  1333. \item[(e)] Variables in $R_1$ can overshadow other variables with the
  1334. same name. The registers and memory locations of x86 all have unique
  1335. names or addresses.
  1336. \end{enumerate}
  1337. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1338. the problem into several steps, dealing with the above differences one
  1339. at a time. Each of these steps is called a \emph{pass} of the
  1340. compiler.
  1341. %
  1342. This terminology comes from each step traverses (i.e. passes over) the
  1343. AST of the program.
  1344. %
  1345. We begin by sketching how we might implement each pass, and give them
  1346. names. We then figure out an ordering of the passes and the
  1347. input/output language for each pass. The very first pass has $R_1$ as
  1348. its input language and the last pass has x86 as its output
  1349. language. In between we can choose whichever language is most
  1350. convenient for expressing the output of each pass, whether that be
  1351. $R_1$, x86, or new \emph{intermediate languages} of our own design.
  1352. Finally, to implement each pass we write one recursive function per
  1353. non-terminal in the grammar of the input language of the pass.
  1354. \begin{description}
  1355. \item[Pass \key{select-instructions}] To handle the difference between
  1356. $R_1$ operations and x86 instructions we convert each $R_1$
  1357. operation to a short sequence of instructions that accomplishes the
  1358. same task.
  1359. \item[Pass \key{remove-complex-opera*}] To ensure that each
  1360. subexpression (i.e. operator and operand, and hence the name
  1361. \key{opera*}) is an \emph{atomic} expression (a variable or
  1362. integer), we introduce temporary variables to hold the results
  1363. of subexpressions.
  1364. \item[Pass \key{explicate-control}] To make the execution order of the
  1365. program explicit, we convert from the abstract syntax tree
  1366. representation into a \emph{control-flow graph} in which each node
  1367. contains a sequence of statements and the edges between nodes say
  1368. where to go at the end of the sequence.
  1369. \item[Pass \key{assign-homes}] To handle the difference between the
  1370. variables in $R_1$ versus the registers and stack locations in x86,
  1371. we assignment of each variable to a register or stack location.
  1372. \item[Pass \key{uniquify}] This pass deals with the shadowing of variables
  1373. by renaming every variable to a unique name, so that shadowing no
  1374. longer occurs.
  1375. \end{description}
  1376. The next question is: in what order should we apply these passes? This
  1377. question can be challenging because it is difficult to know ahead of
  1378. time which orders will be better (easier to implement, produce more
  1379. efficient code, etc.) so oftentimes trial-and-error is
  1380. involved. Nevertheless, we can try to plan ahead and make educated
  1381. choices regarding the ordering.
  1382. Let us consider the ordering of \key{uniquify} and
  1383. \key{remove-complex-opera*}. The assignment of subexpressions to
  1384. temporary variables involves introducing new variables and moving
  1385. subexpressions, which might change the shadowing of variables and
  1386. inadvertently change the behavior of the program. But if we apply
  1387. \key{uniquify} first, this will not be an issue. Of course, this means
  1388. that in \key{remove-complex-opera*}, we need to ensure that the
  1389. temporary variables that it creates are unique.
  1390. What should be the ordering of \key{explicate-control} with respect to
  1391. \key{uniquify}? The \key{uniquify} pass should come first because
  1392. \key{explicate-control} changes all the \key{let}-bound variables to
  1393. become local variables whose scope is the entire program, which would
  1394. confuse variables with the same name.
  1395. %
  1396. Likewise, we place \key{explicate-control} after
  1397. \key{remove-complex-opera*} because \key{explicate-control} removes
  1398. the \key{let} form, but it is convenient to use \key{let} in the
  1399. output of \key{remove-complex-opera*}.
  1400. %
  1401. Regarding \key{assign-homes}, it is helpful to place
  1402. \key{explicate-control} first because \key{explicate-control} changes
  1403. \key{let}-bound variables into program-scope variables. This means
  1404. that the \key{assign-homes} pass can read off the variables from the
  1405. $\itm{info}$ of the \key{Program} AST node instead of traversing the
  1406. entire program in search of \key{let}-bound variables.
  1407. Last, we need to decide on the ordering of \key{select-instructions}
  1408. and \key{assign-homes}. These two passes are intertwined, creating a
  1409. Gordian Knot. To do a good job of assigning homes, it is helpful to
  1410. have already determined which instructions will be used, because x86
  1411. instructions have restrictions about which of their arguments can be
  1412. registers versus stack locations. One might want to give preferential
  1413. treatment to variables that occur in register-argument positions. On
  1414. the other hand, it may turn out to be impossible to make sure that all
  1415. such variables are assigned to registers, and then one must redo the
  1416. selection of instructions. Some compilers handle this problem by
  1417. iteratively repeating these two passes until a good solution is found.
  1418. We shall use a simpler approach in which \key{select-instructions}
  1419. comes first, followed by the \key{assign-homes}, then a third
  1420. pass named \key{patch-instructions} that uses a reserved register to
  1421. patch-up outstanding problems regarding instructions with too many
  1422. memory accesses. The disadvantage of this approach is some programs
  1423. may not execute as efficiently as they would if we used the iterative
  1424. approach and used all of the registers for variables.
  1425. \begin{figure}[tbp]
  1426. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1427. \node (R1) at (0,2) {\large $R_1$};
  1428. \node (R1-2) at (3,2) {\large $R_1$};
  1429. \node (R1-3) at (6,2) {\large $R_1$};
  1430. %\node (C0-1) at (6,0) {\large $C_0$};
  1431. \node (C0-2) at (3,0) {\large $C_0$};
  1432. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_0$};
  1433. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_0$};
  1434. \node (x86-4) at (9,-2) {\large $\text{x86}_0$};
  1435. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}_0$};
  1436. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1437. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  1438. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-2);
  1439. %\path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  1440. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1441. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1442. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1443. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1444. \end{tikzpicture}
  1445. \caption{Overview of the passes for compiling $R_1$. }
  1446. \label{fig:R1-passes}
  1447. \end{figure}
  1448. Figure~\ref{fig:R1-passes} presents the ordering of the compiler
  1449. passes in the form of a graph. Each pass is an edge and the
  1450. input/output language of each pass is a node in the graph. The output
  1451. of \key{uniquify} and \key{remove-complex-opera*} are programs that
  1452. are still in the $R_1$ language, but the output of the pass
  1453. \key{explicate-control} is in a different language $C_0$ that is
  1454. designed to make the order of evaluation explicit in its syntax, which
  1455. we introduce in the next section. The \key{select-instruction} pass
  1456. translates from $C_0$ to a variant of x86. The \key{assign-homes} and
  1457. \key{patch-instructions} passes input and output variants of x86
  1458. assembly. The last pass in Figure~\ref{fig:R1-passes} is
  1459. \key{print-x86}, which converts from the abstract syntax of
  1460. $\text{x86}_0$ to the concrete syntax of x86.
  1461. In the next sections we discuss the $C_0$ language and the
  1462. $\text{x86}^{*}_0$ and $\text{x86}^{\dagger}_0$ dialects of x86. The
  1463. remainder of this chapter gives hints regarding the implementation of
  1464. each of the compiler passes in Figure~\ref{fig:R1-passes}.
  1465. \subsection{The $C_0$ Intermediate Language}
  1466. The output of \key{explicate-control} is similar to the $C$
  1467. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1468. categories for expressions and statements, so we name it $C_0$. The
  1469. concrete syntax for $C_0$ is defined in
  1470. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for $C_0$
  1471. is defined in Figure~\ref{fig:c0-syntax}.
  1472. %
  1473. The $C_0$ language supports the same operators as $R_1$ but the
  1474. arguments of operators are restricted to atomic expressions (variables
  1475. and integers), thanks to the \key{remove-complex-opera*} pass. In the
  1476. literature this style of intermediate language is called
  1477. administrative normal form, or ANF for
  1478. short~\citep{Danvy:1991fk,Flanagan:1993cg}. Instead of \key{Let}
  1479. expressions, $C_0$ has assignment statements which can be executed in
  1480. sequence using the \key{Seq} form. A sequence of statements always
  1481. ends with \key{Return}, a guarantee that is baked into the grammar
  1482. rules for the \itm{tail} non-terminal. The naming of this non-terminal
  1483. comes from the term \emph{tail position}, which refers to an
  1484. expression that is the last one to execute within a function. (A
  1485. expression in tail position may contain subexpressions, and those may
  1486. or may not be in tail position depending on the kind of expression.)
  1487. A $C_0$ program consists of a control-flow graph (represented as an
  1488. association list mapping labels to tails). This is more general than
  1489. necessary for the present chapter, as we do not yet need to introduce
  1490. \key{goto} for jumping to labels, but it saves us from having to
  1491. change the syntax of the program construct in
  1492. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1493. \key{start}, and the whole program is its tail.
  1494. %
  1495. The $\itm{info}$ field of the \key{Program} form, after the
  1496. \key{explicate-control} pass, contains a mapping from the symbol
  1497. \key{locals} to a list of variables, that is, a list of all the
  1498. variables used in the program. At the start of the program, these
  1499. variables are uninitialized; they become initialized on their first
  1500. assignment.
  1501. \begin{figure}[tbp]
  1502. \fbox{
  1503. \begin{minipage}{0.96\textwidth}
  1504. \[
  1505. \begin{array}{lcl}
  1506. \Atm &::=& \Int \mid \Var \\
  1507. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  1508. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  1509. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  1510. C_0 & ::= & (\itm{label}\key{:}~ \Tail)^{+}
  1511. \end{array}
  1512. \]
  1513. \end{minipage}
  1514. }
  1515. \caption{The concrete syntax of the $C_0$ intermediate language.}
  1516. \label{fig:c0-concrete-syntax}
  1517. \end{figure}
  1518. \begin{figure}[tbp]
  1519. \fbox{
  1520. \begin{minipage}{0.96\textwidth}
  1521. \[
  1522. \begin{array}{lcl}
  1523. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1524. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1525. &\mid& \ADD{\Atm}{\Atm}\\
  1526. \Stmt &::=& \ASSIGN{\Var}{\Exp} \\
  1527. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1528. C_0 & ::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}^{+}}}
  1529. \end{array}
  1530. \]
  1531. \end{minipage}
  1532. }
  1533. \caption{The abstract syntax of the $C_0$ intermediate language.}
  1534. \label{fig:c0-syntax}
  1535. \end{figure}
  1536. %% The \key{select-instructions} pass is optimistic in the sense that it
  1537. %% treats variables as if they were all mapped to registers. The
  1538. %% \key{select-instructions} pass generates a program that consists of
  1539. %% x86 instructions but that still uses variables, so it is an
  1540. %% intermediate language that is technically different than x86, which
  1541. %% explains the asterisks in the diagram above.
  1542. %% In this Chapter we shall take the easy road to implementing
  1543. %% \key{assign-homes} and simply map all variables to stack locations.
  1544. %% The topic of Chapter~\ref{ch:register-allocation-r1} is implementing a
  1545. %% smarter approach in which we make a best-effort to map variables to
  1546. %% registers, resorting to the stack only when necessary.
  1547. %% Once variables have been assigned to their homes, we can finalize the
  1548. %% instruction selection by dealing with an idiosyncrasy of x86
  1549. %% assembly. Many x86 instructions have two arguments but only one of the
  1550. %% arguments may be a memory reference (and the stack is a part of
  1551. %% memory). Because some variables may get mapped to stack locations,
  1552. %% some of our generated instructions may violate this restriction. The
  1553. %% purpose of the \key{patch-instructions} pass is to fix this problem by
  1554. %% replacing every violating instruction with a short sequence of
  1555. %% instructions that use the \key{rax} register. Once we have implemented
  1556. %% a good register allocator (Chapter~\ref{ch:register-allocation-r1}), the
  1557. %% need to patch instructions will be relatively rare.
  1558. \subsection{The dialects of x86}
  1559. The x86$^{*}_0$ language, pronounced ``pseudo x86'', is the output of
  1560. the pass \key{select-instructions}. It extends $x86_0$ with an
  1561. unbounded number of program-scope variables and has looser rules
  1562. regarding instruction arguments. The x86$^{\dagger}$ language, the
  1563. output of \key{print-x86}, is the concrete syntax for x86.
  1564. \section{Uniquify Variables}
  1565. \label{sec:uniquify-s0}
  1566. The \code{uniquify} pass compiles arbitrary $R_1$ programs into $R_1$
  1567. programs in which every \key{let} uses a unique variable name. For
  1568. example, the \code{uniquify} pass should translate the program on the
  1569. left into the program on the right. \\
  1570. \begin{tabular}{lll}
  1571. \begin{minipage}{0.4\textwidth}
  1572. \begin{lstlisting}
  1573. (let ([x 32])
  1574. (+ (let ([x 10]) x) x))
  1575. \end{lstlisting}
  1576. \end{minipage}
  1577. &
  1578. $\Rightarrow$
  1579. &
  1580. \begin{minipage}{0.4\textwidth}
  1581. \begin{lstlisting}
  1582. (let ([x.1 32])
  1583. (+ (let ([x.2 10]) x.2) x.1))
  1584. \end{lstlisting}
  1585. \end{minipage}
  1586. \end{tabular} \\
  1587. %
  1588. The following is another example translation, this time of a program
  1589. with a \key{let} nested inside the initializing expression of another
  1590. \key{let}.\\
  1591. \begin{tabular}{lll}
  1592. \begin{minipage}{0.4\textwidth}
  1593. \begin{lstlisting}
  1594. (let ([x (let ([x 4])
  1595. (+ x 1))])
  1596. (+ x 2))
  1597. \end{lstlisting}
  1598. \end{minipage}
  1599. &
  1600. $\Rightarrow$
  1601. &
  1602. \begin{minipage}{0.4\textwidth}
  1603. \begin{lstlisting}
  1604. (let ([x.2 (let ([x.1 4])
  1605. (+ x.1 1))])
  1606. (+ x.2 2))
  1607. \end{lstlisting}
  1608. \end{minipage}
  1609. \end{tabular}
  1610. We recommend implementing \code{uniquify} by creating a function named
  1611. \code{uniquify-exp} that is structurally recursive function and mostly
  1612. just copies the input program. However, when encountering a \key{let},
  1613. it should generate a unique name for the variable (the Racket function
  1614. \code{gensym} is handy for this) and associate the old name with the
  1615. new unique name in an association list. The \code{uniquify-exp}
  1616. function will need to access this association list when it gets to a
  1617. variable reference, so we add another parameter to \code{uniquify-exp}
  1618. for the association list. It is quite common for a compiler pass to
  1619. need a map to store extra information about variables. Such maps are
  1620. traditionally called \emph{symbol tables}.
  1621. The skeleton of the \code{uniquify-exp} function is shown in
  1622. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1623. convenient to partially apply it to a symbol table and then apply it
  1624. to different expressions, as in the last clause for primitive
  1625. operations in Figure~\ref{fig:uniquify-s0}. The \key{for/list} form
  1626. is useful for applying a function to each element of a list to produce
  1627. a new list.
  1628. \begin{exercise}
  1629. \normalfont % I don't like the italics for exercises. -Jeremy
  1630. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1631. implement the clauses for variables and for the \key{let} form.
  1632. \end{exercise}
  1633. \begin{figure}[tbp]
  1634. \begin{lstlisting}
  1635. (define (uniquify-exp symtab)
  1636. (lambda (e)
  1637. (match e
  1638. [(Var x) ___]
  1639. [(Int n) (Int n)]
  1640. [(Let x e body) ___]
  1641. [(Prim op es)
  1642. (Prim op (for/list ([e es]) ((uniquify-exp symtab) e)))]
  1643. )))
  1644. (define (uniquify p)
  1645. (match p
  1646. [(Program info e)
  1647. (Program info ((uniquify-exp '()) e))]
  1648. )))
  1649. \end{lstlisting}
  1650. \caption{Skeleton for the \key{uniquify} pass.}
  1651. \label{fig:uniquify-s0}
  1652. \end{figure}
  1653. \begin{exercise}
  1654. \normalfont % I don't like the italics for exercises. -Jeremy
  1655. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1656. and checking whether the output programs produce the same result as
  1657. the input programs. The $R_1$ programs should be designed to test the
  1658. most interesting parts of the \key{uniquify} pass, that is, the
  1659. programs should include \key{let} forms, variables, and variables
  1660. that overshadow each other. The five programs should be in a
  1661. subdirectory named \key{tests} and they should have the same file name
  1662. except for a different integer at the end of the name, followed by the
  1663. ending \key{.rkt}. Use the \key{interp-tests} function
  1664. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1665. your \key{uniquify} pass on the example programs. See the
  1666. \key{run-tests.rkt} script in the student support code for an example
  1667. of how to use \key{interp-tests}.
  1668. \end{exercise}
  1669. \section{Remove Complex Operands}
  1670. \label{sec:remove-complex-opera-r1}
  1671. The \code{remove-complex-opera*} pass compiles $R_1$ programs into
  1672. $R_1$ programs in which the arguments of operations are atomic
  1673. expressions. Put another way, this pass removes complex operands,
  1674. such as the expression \code{(- 10)} in the program below. This is
  1675. accomplished by introducing a new \key{let}-bound variable, binding
  1676. the complex operand to the new variable, and then using the new
  1677. variable in place of the complex operand, as shown in the output of
  1678. \code{remove-complex-opera*} on the right.\\
  1679. \begin{tabular}{lll}
  1680. \begin{minipage}{0.4\textwidth}
  1681. % s0_19.rkt
  1682. \begin{lstlisting}
  1683. (+ 52 (- 10))
  1684. \end{lstlisting}
  1685. \end{minipage}
  1686. &
  1687. $\Rightarrow$
  1688. &
  1689. \begin{minipage}{0.4\textwidth}
  1690. \begin{lstlisting}
  1691. (let ([tmp.1 (- 10)])
  1692. (+ 52 tmp.1))
  1693. \end{lstlisting}
  1694. \end{minipage}
  1695. \end{tabular}
  1696. We recommend implementing this pass with two mutually recursive
  1697. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1698. \code{rco-atom} to subexpressions that need to become atomic and to
  1699. apply \code{rco-exp} to subexpressions that can be atomic or complex.
  1700. Both functions take an $R_1$ expression as input. The \code{rco-exp}
  1701. function returns an expression. The \code{rco-atom} function returns
  1702. two things: an atomic expression and association list mapping
  1703. temporary variables to complex subexpressions. You can return multiple
  1704. things from a function using Racket's \key{values} form and you can
  1705. receive multiple things from a function call using the
  1706. \key{define-values} form. If you are not familiar with these features,
  1707. review the Racket documentation. Also, the \key{for/lists} form is
  1708. useful for applying a function to each element of a list, in the case
  1709. where the function returns multiple values.
  1710. The following shows the output of \code{rco-atom} on the expression
  1711. \code{(- 10)} (using concrete syntax to be concise).
  1712. \begin{tabular}{lll}
  1713. \begin{minipage}{0.4\textwidth}
  1714. \begin{lstlisting}
  1715. (- 10)
  1716. \end{lstlisting}
  1717. \end{minipage}
  1718. &
  1719. $\Rightarrow$
  1720. &
  1721. \begin{minipage}{0.4\textwidth}
  1722. \begin{lstlisting}
  1723. tmp.1
  1724. ((tmp.1 . (- 10)))
  1725. \end{lstlisting}
  1726. \end{minipage}
  1727. \end{tabular}
  1728. Take special care of programs such as the next one that \key{let}-bind
  1729. variables with integers or other variables. You should leave them
  1730. unchanged, as shown in to the program on the right \\
  1731. \begin{tabular}{lll}
  1732. \begin{minipage}{0.4\textwidth}
  1733. % s0_20.rkt
  1734. \begin{lstlisting}
  1735. (let ([a 42])
  1736. (let ([b a])
  1737. b))
  1738. \end{lstlisting}
  1739. \end{minipage}
  1740. &
  1741. $\Rightarrow$
  1742. &
  1743. \begin{minipage}{0.4\textwidth}
  1744. \begin{lstlisting}
  1745. (let ([a 42])
  1746. (let ([b a])
  1747. b))
  1748. \end{lstlisting}
  1749. \end{minipage}
  1750. \end{tabular} \\
  1751. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  1752. produce the following output.\\
  1753. \begin{minipage}{0.4\textwidth}
  1754. \begin{lstlisting}
  1755. (let ([tmp.1 42])
  1756. (let ([a tmp.1])
  1757. (let ([tmp.2 a])
  1758. (let ([b tmp.2])
  1759. b))))
  1760. \end{lstlisting}
  1761. \end{minipage}
  1762. \begin{exercise}
  1763. \normalfont Implement the \code{remove-complex-opera*} pass and test
  1764. it on all of the example programs that you created to test the
  1765. \key{uniquify} pass and create three new example programs that are
  1766. designed to exercise the interesting code in the
  1767. \code{remove-complex-opera*} pass. Use the \key{interp-tests} function
  1768. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1769. your passes on the example programs.
  1770. \end{exercise}
  1771. \section{Explicate Control}
  1772. \label{sec:explicate-control-r1}
  1773. The \code{explicate-control} pass compiles $R_1$ programs into $C_0$
  1774. programs that make the order of execution explicit in their
  1775. syntax. For now this amounts to flattening \key{let} constructs into a
  1776. sequence of assignment statements. For example, consider the following
  1777. $R_1$ program.\\
  1778. % s0_11.rkt
  1779. \begin{minipage}{0.96\textwidth}
  1780. \begin{lstlisting}
  1781. (let ([y (let ([x 20])
  1782. (+ x (let ([x 22]) x)))])
  1783. y)
  1784. \end{lstlisting}
  1785. \end{minipage}\\
  1786. %
  1787. The output of the previous pass and of \code{explicate-control} is
  1788. shown below. Recall that the right-hand-side of a \key{let} executes
  1789. before its body, so the order of evaluation for this program is to
  1790. assign \code{20} to \code{x.1}, assign \code{22} to \code{x.2}, assign
  1791. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  1792. output of \code{explicate-control} makes this ordering explicit.\\
  1793. \begin{tabular}{lll}
  1794. \begin{minipage}{0.4\textwidth}
  1795. \begin{lstlisting}
  1796. (let ([y (let ([x.1 20])
  1797. (let ([x.2 22])
  1798. (+ x.1 x.2)))])
  1799. y)
  1800. \end{lstlisting}
  1801. \end{minipage}
  1802. &
  1803. $\Rightarrow$
  1804. &
  1805. \begin{minipage}{0.4\textwidth}
  1806. \begin{lstlisting}
  1807. locals: y x.1 x.2
  1808. start:
  1809. x.1 = 20;
  1810. x.2 = 22;
  1811. y = (+ x.1 x.2);
  1812. return y;
  1813. \end{lstlisting}
  1814. \end{minipage}
  1815. \end{tabular}
  1816. We recommend implementing \code{explicate-control} using two mutually
  1817. recursive functions: \code{explicate-tail} and
  1818. \code{explicate-assign}. The first function should be applied to
  1819. expressions in tail position whereas the second should be applied to
  1820. expressions that occur on the right-hand-side of a \key{let}. The
  1821. \code{explicate-tail} function takes an $R_1$ expression as input and
  1822. produces a $C_0$ $\Tail$ (see Figure~\ref{fig:c0-syntax}) and a list
  1823. of formerly \key{let}-bound variables. The \code{explicate-assign}
  1824. function takes an $R_1$ expression, the variable that it is to be
  1825. assigned to, and $C_0$ code (a $\Tail$) that should come after the
  1826. assignment (e.g., the code generated for the body of the \key{let}).
  1827. It returns a $\Tail$ and a list of variables. The top-level
  1828. \code{explicate-control} function should invoke \code{explicate-tail}
  1829. on the body of the \key{program} and then associate the \code{locals}
  1830. symbol with the resulting list of variables in the $\itm{info}$ field,
  1831. as in the above example.
  1832. \section{Select Instructions}
  1833. \label{sec:select-r1}
  1834. In the \code{select-instructions} pass we begin the work of
  1835. translating from $C_0$ to $\text{x86}^{*}_0$. The target language of
  1836. this pass is a variable of x86 that still uses variables, so we add an
  1837. AST node of the form $\VAR{\itm{var}}$ to the $\text{x86}_0$ abstract
  1838. syntax of Figure~\ref{fig:x86-ast-a}. We recommend implementing the
  1839. \code{select-instructions} in terms of three auxiliary functions, one
  1840. for each of the non-terminals of $C_0$: $\Atm$, $\Stmt$, and $\Tail$.
  1841. The cases for $\Atm$ are straightforward, variables stay
  1842. the same and integer constants are changed to immediates:
  1843. $\INT{n}$ changes to $\IMM{n}$.
  1844. Next we consider the cases for $\Stmt$, starting with arithmetic
  1845. operations. For example, in $C_0$ an addition operation can take the
  1846. form below, to the left of the $\Rightarrow$. To translate to x86, we
  1847. need to use the \key{addq} instruction which does an in-place
  1848. update. So we must first move \code{10} to \code{x}. \\
  1849. \begin{tabular}{lll}
  1850. \begin{minipage}{0.4\textwidth}
  1851. \begin{lstlisting}
  1852. x = (+ 10 32);
  1853. \end{lstlisting}
  1854. \end{minipage}
  1855. &
  1856. $\Rightarrow$
  1857. &
  1858. \begin{minipage}{0.4\textwidth}
  1859. \begin{lstlisting}
  1860. movq $10, x
  1861. addq $32, x
  1862. \end{lstlisting}
  1863. \end{minipage}
  1864. \end{tabular} \\
  1865. %
  1866. There are cases that require special care to avoid generating
  1867. needlessly complicated code. If one of the arguments of the addition
  1868. is the same as the left-hand side of the assignment, then there is no
  1869. need for the extra move instruction. For example, the following
  1870. assignment statement can be translated into a single \key{addq}
  1871. instruction.\\
  1872. \begin{tabular}{lll}
  1873. \begin{minipage}{0.4\textwidth}
  1874. \begin{lstlisting}
  1875. x = (+ 10 x);
  1876. \end{lstlisting}
  1877. \end{minipage}
  1878. &
  1879. $\Rightarrow$
  1880. &
  1881. \begin{minipage}{0.4\textwidth}
  1882. \begin{lstlisting}
  1883. addq $10, x
  1884. \end{lstlisting}
  1885. \end{minipage}
  1886. \end{tabular} \\
  1887. The \key{read} operation does not have a direct counterpart in x86
  1888. assembly, so we have instead implemented this functionality in the C
  1889. language, with the function \code{read\_int} in the file
  1890. \code{runtime.c}. In general, we refer to all of the functionality in
  1891. this file as the \emph{runtime system}, or simply the \emph{runtime}
  1892. for short. When compiling your generated x86 assembly code, you need
  1893. to compile \code{runtime.c} to \code{runtime.o} (an ``object file'',
  1894. using \code{gcc} option \code{-c}) and link it into the
  1895. executable. For our purposes of code generation, all you need to do is
  1896. translate an assignment of \key{read} into some variable $\itm{lhs}$
  1897. (for left-hand side) into a call to the \code{read\_int} function
  1898. followed by a move from \code{rax} to the left-hand side. The move
  1899. from \code{rax} is needed because the return value from
  1900. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  1901. \begin{tabular}{lll}
  1902. \begin{minipage}{0.4\textwidth}
  1903. \begin{lstlisting}
  1904. |$\itm{lhs}$| = (read);
  1905. \end{lstlisting}
  1906. \end{minipage}
  1907. &
  1908. $\Rightarrow$
  1909. &
  1910. \begin{minipage}{0.4\textwidth}
  1911. \begin{lstlisting}
  1912. callq read_int
  1913. movq %rax, |$\itm{lhs}$|
  1914. \end{lstlisting}
  1915. \end{minipage}
  1916. \end{tabular} \\
  1917. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  1918. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  1919. assignment to the \key{rax} register followed by a jump to the
  1920. conclusion of the program (so the conclusion needs to be labeled).
  1921. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  1922. recursively and append the resulting instructions.
  1923. \begin{exercise}
  1924. \normalfont
  1925. Implement the \key{select-instructions} pass and test it on all of the
  1926. example programs that you created for the previous passes and create
  1927. three new example programs that are designed to exercise all of the
  1928. interesting code in this pass. Use the \key{interp-tests} function
  1929. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1930. your passes on the example programs.
  1931. \end{exercise}
  1932. \section{Assign Homes}
  1933. \label{sec:assign-r1}
  1934. The \key{assign-homes} pass compiles $\text{x86}^{*}_0$ programs to
  1935. $\text{x86}^{*}_0$ programs that no longer use program variables.
  1936. Thus, the \key{assign-homes} pass is responsible for placing all of
  1937. the program variables in registers or on the stack. For runtime
  1938. efficiency, it is better to place variables in registers, but as there
  1939. are only 16 registers, some programs must necessarily resort to
  1940. placing some variables on the stack. In this chapter we focus on the
  1941. mechanics of placing variables on the stack. We study an algorithm for
  1942. placing variables in registers in
  1943. Chapter~\ref{ch:register-allocation-r1}.
  1944. Consider again the following $R_1$ program.
  1945. % s0_20.rkt
  1946. \begin{lstlisting}
  1947. (let ([a 42])
  1948. (let ([b a])
  1949. b))
  1950. \end{lstlisting}
  1951. For reference, we repeat the output of \code{select-instructions} on
  1952. the left and show the output of \code{assign-homes} on the right.
  1953. Recall that \key{explicate-control} associated the list of
  1954. variables with the \code{locals} symbol in the program's $\itm{info}$
  1955. field, so \code{assign-homes} has convenient access to the them. In
  1956. this example, we assign variable \code{a} to stack location
  1957. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.\\
  1958. \begin{tabular}{l}
  1959. \begin{minipage}{0.4\textwidth}
  1960. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1961. locals: a b
  1962. start:
  1963. movq $42, a
  1964. movq a, b
  1965. movq b, %rax
  1966. jmp conclusion
  1967. \end{lstlisting}
  1968. \end{minipage}
  1969. {$\Rightarrow$}
  1970. \begin{minipage}{0.4\textwidth}
  1971. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1972. stack-space: 16
  1973. start:
  1974. movq $42, -8(%rbp)
  1975. movq -8(%rbp), -16(%rbp)
  1976. movq -16(%rbp), %rax
  1977. jmp conclusion
  1978. \end{lstlisting}
  1979. \end{minipage}
  1980. \end{tabular} \\
  1981. In the process of assigning variables to stack locations, it is
  1982. convenient to compute and store the size of the frame (in bytes) in
  1983. the $\itm{info}$ field of the \key{Program} node, with the key
  1984. \code{stack-space}, which will be needed later to generate the
  1985. procedure conclusion. Some operating systems place restrictions on
  1986. the frame size. For example, Mac OS X requires the frame size to be a
  1987. multiple of 16 bytes.
  1988. \begin{exercise}
  1989. \normalfont Implement the \key{assign-homes} pass and test it on all
  1990. of the example programs that you created for the previous passes pass.
  1991. We recommend that \key{assign-homes} take an extra parameter that is a
  1992. mapping of variable names to homes (stack locations for now). Use the
  1993. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  1994. \key{utilities.rkt} to test your passes on the example programs.
  1995. \end{exercise}
  1996. \section{Patch Instructions}
  1997. \label{sec:patch-s0}
  1998. The \code{patch-instructions} pass compiles $\text{x86}^{*}_0$
  1999. programs to $\text{x86}_0$ programs by making sure that each
  2000. instruction adheres to the restrictions of the x86 assembly language.
  2001. In particular, at most one argument of an instruction may be a memory
  2002. reference.
  2003. We return to the following running example.
  2004. % s0_20.rkt
  2005. \begin{lstlisting}
  2006. (let ([a 42])
  2007. (let ([b a])
  2008. b))
  2009. \end{lstlisting}
  2010. After the \key{assign-homes} pass, the above program has been translated to
  2011. the following. \\
  2012. \begin{minipage}{0.5\textwidth}
  2013. \begin{lstlisting}
  2014. stack-space: 16
  2015. start:
  2016. movq $42, -8(%rbp)
  2017. movq -8(%rbp), -16(%rbp)
  2018. movq -16(%rbp), %rax
  2019. jmp conclusion
  2020. \end{lstlisting}
  2021. \end{minipage}\\
  2022. The second \key{movq} instruction is problematic because both
  2023. arguments are stack locations. We suggest fixing this problem by
  2024. moving from the source location to the register \key{rax} and then
  2025. from \key{rax} to the destination location, as follows.
  2026. \begin{lstlisting}
  2027. movq -8(%rbp), %rax
  2028. movq %rax, -16(%rbp)
  2029. \end{lstlisting}
  2030. \begin{exercise}
  2031. \normalfont
  2032. Implement the \key{patch-instructions} pass and test it on all of the
  2033. example programs that you created for the previous passes and create
  2034. three new example programs that are designed to exercise all of the
  2035. interesting code in this pass. Use the \key{interp-tests} function
  2036. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2037. your passes on the example programs.
  2038. \end{exercise}
  2039. \section{Print x86}
  2040. \label{sec:print-x86}
  2041. The last step of the compiler from $R_1$ to x86 is to convert the
  2042. $\text{x86}_0$ AST (defined in Figure~\ref{fig:x86-ast-a}) to the
  2043. string representation (defined in Figure~\ref{fig:x86-a}). The Racket
  2044. \key{format} and \key{string-append} functions are useful in this
  2045. regard. The main work that this step needs to perform is to create the
  2046. \key{main} function and the standard instructions for its prelude and
  2047. conclusion, as shown in Figure~\ref{fig:p1-x86} of
  2048. Section~\ref{sec:x86}. You need to know the number of stack-allocated
  2049. variables, so we suggest computing it in the \key{assign-homes} pass
  2050. (Section~\ref{sec:assign-r1}) and storing it in the $\itm{info}$ field
  2051. of the \key{program} node.
  2052. %% Your compiled code should print the result of the program's execution
  2053. %% by using the \code{print\_int} function provided in
  2054. %% \code{runtime.c}. If your compiler has been implemented correctly so
  2055. %% far, this final result should be stored in the \key{rax} register.
  2056. %% We'll talk more about how to perform function calls with arguments in
  2057. %% general later on, but for now, place the following after the compiled
  2058. %% code for the $R_1$ program but before the conclusion:
  2059. %% \begin{lstlisting}
  2060. %% movq %rax, %rdi
  2061. %% callq print_int
  2062. %% \end{lstlisting}
  2063. %% These lines move the value in \key{rax} into the \key{rdi} register, which
  2064. %% stores the first argument to be passed into \key{print\_int}.
  2065. If you want your program to run on Mac OS X, your code needs to
  2066. determine whether or not it is running on a Mac, and prefix
  2067. underscores to labels like \key{main}. You can determine the platform
  2068. with the Racket call \code{(system-type 'os)}, which returns
  2069. \code{'macosx}, \code{'unix}, or \code{'windows}.
  2070. %% In addition to
  2071. %% placing underscores on \key{main}, you need to put them in front of
  2072. %% \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  2073. %% \_print\_int}).
  2074. \begin{exercise}
  2075. \normalfont Implement the \key{print-x86} pass and test it on all of
  2076. the example programs that you created for the previous passes. Use the
  2077. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  2078. \key{utilities.rkt} to test your complete compiler on the example
  2079. programs. See the \key{run-tests.rkt} script in the student support
  2080. code for an example of how to use \key{compiler-tests}. Also, remember
  2081. to compile the provided \key{runtime.c} file to \key{runtime.o} using
  2082. \key{gcc}.
  2083. \end{exercise}
  2084. \section{Challenge: Partial Evaluator for $R_1$}
  2085. \label{sec:pe-R1}
  2086. This section describes optional challenge exercises that involve
  2087. adapting and improving the partial evaluator for $R_0$ that was
  2088. introduced in Section~\ref{sec:partial-evaluation}.
  2089. \begin{exercise}\label{ex:pe-R1}
  2090. \normalfont
  2091. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2092. (Figure~\ref{fig:pe-arith}) so that it applies to $R_1$ programs
  2093. instead of $R_0$ programs. Recall that $R_1$ adds \key{let} binding
  2094. and variables to the $R_0$ language, so you will need to add cases for
  2095. them in the \code{pe-exp} function. Also, note that the \key{program}
  2096. form changes slightly to include an $\itm{info}$ field. Once
  2097. complete, add the partial evaluation pass to the front of your
  2098. compiler and make sure that your compiler still passes all of the
  2099. tests.
  2100. \end{exercise}
  2101. The next exercise builds on Exercise~\ref{ex:pe-R1}.
  2102. \begin{exercise}
  2103. \normalfont
  2104. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2105. \code{pe-add} auxiliary functions with functions that know more about
  2106. arithmetic. For example, your partial evaluator should translate
  2107. \begin{lstlisting}
  2108. (+ 1 (+ (read) 1))
  2109. \end{lstlisting}
  2110. into
  2111. \begin{lstlisting}
  2112. (+ 2 (read))
  2113. \end{lstlisting}
  2114. To accomplish this, the \code{pe-exp} function should produce output
  2115. in the form of the $\itm{residual}$ non-terminal of the following
  2116. grammar.
  2117. \[
  2118. \begin{array}{lcl}
  2119. \itm{inert} &::=& \Var \mid (\key{read}) \mid (\key{-} \;(\key{read}))
  2120. \mid (\key{+} \; \itm{inert} \; \itm{inert})\\
  2121. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \itm{inert}) \mid \itm{inert}
  2122. \end{array}
  2123. \]
  2124. The \code{pe-add} and \code{pe-neg} functions may therefore assume
  2125. that their inputs are $\itm{residual}$ expressions and they should
  2126. return $\itm{residual}$ expressions. Once the improvements are
  2127. complete, make sure that your compiler still passes all of the tests.
  2128. After all, fast code is useless if it produces incorrect results!
  2129. \end{exercise}
  2130. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2131. \chapter{Register Allocation}
  2132. \label{ch:register-allocation-r1}
  2133. In Chapter~\ref{ch:int-exp} we placed all variables on the stack to
  2134. make our life easier. However, we can improve the performance of the
  2135. generated code if we instead place some variables into registers. The
  2136. CPU can access a register in a single cycle, whereas accessing the
  2137. stack takes many cycles if the relevant data is in cache or many more
  2138. to access main memory if the data is not in cache.
  2139. Figure~\ref{fig:reg-eg} shows a program with four variables that
  2140. serves as a running example. We show the source program and also the
  2141. output of instruction selection. At that point the program is almost
  2142. x86 assembly but not quite; it still contains variables instead of
  2143. stack locations or registers.
  2144. \begin{figure}
  2145. \begin{minipage}{0.45\textwidth}
  2146. Example $R_1$ program:
  2147. % s0_22.rkt
  2148. \begin{lstlisting}
  2149. (let ([v 1])
  2150. (let ([w 46])
  2151. (let ([x (+ v 7)])
  2152. (let ([y (+ 4 x)])
  2153. (let ([z (+ x w)])
  2154. (+ z (- y)))))))
  2155. \end{lstlisting}
  2156. \end{minipage}
  2157. \begin{minipage}{0.45\textwidth}
  2158. After instruction selection:
  2159. \begin{lstlisting}
  2160. locals: v w x y z t.1
  2161. start:
  2162. movq $1, v
  2163. movq $46, w
  2164. movq v, x
  2165. addq $7, x
  2166. movq x, y
  2167. addq $4, y
  2168. movq x, z
  2169. addq w, z
  2170. movq y, t.1
  2171. negq t.1
  2172. movq z, %rax
  2173. addq t.1, %rax
  2174. jmp conclusion
  2175. \end{lstlisting}
  2176. \end{minipage}
  2177. \caption{An example program for register allocation.}
  2178. \label{fig:reg-eg}
  2179. \end{figure}
  2180. The goal of register allocation is to fit as many variables into
  2181. registers as possible. A program sometimes has more variables than
  2182. registers, so we cannot map each variable to a different
  2183. register. Fortunately, it is common for different variables to be
  2184. needed during different periods of time during program execution, and
  2185. in such cases several variables can be mapped to the same register.
  2186. Consider variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}.
  2187. After the variable \code{x} is moved to \code{z} it is no longer
  2188. needed. Variable \code{y}, on the other hand, is used only after this
  2189. point, so \code{x} and \code{y} could share the same register. The
  2190. topic of Section~\ref{sec:liveness-analysis-r1} is how to compute
  2191. where a variable is needed. Once we have that information, we compute
  2192. which variables are needed at the same time, i.e., which ones
  2193. \emph{interfere}, and represent this relation as an undirected graph
  2194. whose vertices are variables and edges indicate when two variables
  2195. interfere with each other (Section~\ref{sec:build-interference}). We
  2196. then model register allocation as a graph coloring problem, which we
  2197. discuss in Section~\ref{sec:graph-coloring}.
  2198. In the event that we run out of registers despite these efforts, we
  2199. place the remaining variables on the stack, similar to what we did in
  2200. Chapter~\ref{ch:int-exp}. It is common to use the verb \emph{spill}
  2201. for assigning a variable to a stack location. The process of spilling
  2202. variables is handled as part of the graph coloring process described
  2203. in \ref{sec:graph-coloring}.
  2204. \section{Registers and Calling Conventions}
  2205. \label{sec:calling-conventions}
  2206. As we perform register allocation, we need to be aware of the
  2207. conventions that govern the way in which registers interact with
  2208. function calls, such as calls to the \code{read\_int} function. The
  2209. convention for x86 is that the caller is responsible for freeing up
  2210. some registers, the \emph{caller-saved registers}, prior to the
  2211. function call, and the callee is responsible for saving and restoring
  2212. some other registers, the \emph{callee-saved registers}, before and
  2213. after using them. The caller-saved registers are
  2214. \begin{lstlisting}
  2215. rax rdx rcx rsi rdi r8 r9 r10 r11
  2216. \end{lstlisting}
  2217. while the callee-saved registers are
  2218. \begin{lstlisting}
  2219. rsp rbp rbx r12 r13 r14 r15
  2220. \end{lstlisting}
  2221. Another way to think about this caller/callee convention is the
  2222. following. The caller should assume that all the caller-saved registers
  2223. get overwritten with arbitrary values by the callee. On the other
  2224. hand, the caller can safely assume that all the callee-saved registers
  2225. contain the same values after the call that they did before the call.
  2226. The callee can freely use any of the caller-saved registers. However,
  2227. if the callee wants to use a callee-saved register, the callee must
  2228. arrange to put the original value back in the register prior to
  2229. returning to the caller, which is usually accomplished by saving and
  2230. restoring the value from the stack.
  2231. \section{Liveness Analysis}
  2232. \label{sec:liveness-analysis-r1}
  2233. A variable is \emph{live} if the variable is used at some later point
  2234. in the program and there is not an intervening assignment to the
  2235. variable.
  2236. %
  2237. To understand the latter condition, consider the following code
  2238. fragment in which there are two writes to \code{b}. Are \code{a} and
  2239. \code{b} both live at the same time?
  2240. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2241. movq $5, a
  2242. movq $30, b
  2243. movq a, c
  2244. movq $10, b
  2245. addq b, c
  2246. \end{lstlisting}
  2247. The answer is no because the integer \code{30} written to \code{b} on
  2248. line 2 is never used. The variable \code{b} is read on line 5 and
  2249. there is an intervening write to \code{b} on line 4, so the read on
  2250. line 5 receives the value written on line 4, not line 2.
  2251. The live variables can be computed by traversing the instruction
  2252. sequence back to front (i.e., backwards in execution order). Let
  2253. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2254. $L_{\mathsf{after}}(k)$ for the set of live variables after
  2255. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2256. variables before instruction $I_k$. The live variables after an
  2257. instruction are always the same as the live variables before the next
  2258. instruction.
  2259. \begin{equation} \label{eq:live-after-before-next}
  2260. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2261. \end{equation}
  2262. To start things off, there are no live variables after the last
  2263. instruction, so
  2264. \begin{equation}\label{eq:live-last-empty}
  2265. L_{\mathsf{after}}(n) = \emptyset
  2266. \end{equation}
  2267. We then apply the following rule repeatedly, traversing the
  2268. instruction sequence back to front.
  2269. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2270. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2271. \end{equation}
  2272. where $W(k)$ are the variables written to by instruction $I_k$ and
  2273. $R(k)$ are the variables read by instruction $I_k$.
  2274. Let us walk through the above example, applying these formulas
  2275. starting with the instruction on line 5. We collect the answers in the
  2276. below listing. The $L_{\mathsf{after}}$ for the \code{addq b, c}
  2277. instruction is $\emptyset$ because it is the last instruction
  2278. (formula~\ref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  2279. this instruction is $\{b,c\}$ because it reads from variables $b$ and
  2280. $c$ (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that
  2281. is
  2282. \[
  2283. L_{\mathsf{before}}(5) = (\emptyset - \{c\}) \cup \{ b, c \} = \{ b, c \}
  2284. \]
  2285. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2286. the live-before set from line 5 to be the live-after set for this
  2287. instruction (formula~\ref{eq:live-after-before-next}).
  2288. \[
  2289. L_{\mathsf{after}}(4) = \{ b, c \}
  2290. \]
  2291. This move instruction writes to $b$ and does not read from any
  2292. variables, so we have the following live-before set
  2293. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2294. \[
  2295. L_{\mathsf{before}}(4) = (\{b,c\} - \{b\}) \cup \emptyset = \{ c \}
  2296. \]
  2297. Moving on more quickly, the live-before for instruction \code{movq a, c}
  2298. is $\{a\}$ because it writes to $\{c\}$ and reads from $\{a\}$
  2299. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2300. live-before for \code{movq \$30, b} is $\{a\}$ because it writes to a
  2301. variable that is not live and does not read from a variable.
  2302. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2303. because it writes to variable $a$.
  2304. \begin{center}
  2305. \begin{minipage}{0.45\textwidth}
  2306. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2307. movq $5, a
  2308. movq $30, b
  2309. movq a, c
  2310. movq $10, b
  2311. addq b, c
  2312. \end{lstlisting}
  2313. \end{minipage}
  2314. \vrule\hspace{10pt}
  2315. \begin{minipage}{0.45\textwidth}
  2316. \begin{align*}
  2317. L_{\mathsf{before}}(1)= \emptyset,
  2318. L_{\mathsf{after}}(1)= \{a\}\\
  2319. L_{\mathsf{before}}(2)= \{a\},
  2320. L_{\mathsf{after}}(2)= \{a\}\\
  2321. L_{\mathsf{before}}(3)= \{a\},
  2322. L_{\mathsf{after}}(2)= \{c\}\\
  2323. L_{\mathsf{before}}(4)= \{c\},
  2324. L_{\mathsf{after}}(4)= \{b,c\}\\
  2325. L_{\mathsf{before}}(5)= \{b,c\},
  2326. L_{\mathsf{after}}(5)= \emptyset
  2327. \end{align*}
  2328. \end{minipage}
  2329. \end{center}
  2330. Figure~\ref{fig:live-eg} shows the results of live variables analysis
  2331. for the running example program, with each instruction aligned with
  2332. its $L_{\mathtt{after}}$ set to make the figure easy to read.
  2333. \begin{figure}[tbp]
  2334. \hspace{20pt}
  2335. \begin{minipage}{0.45\textwidth}
  2336. \begin{lstlisting}[numbers=left]
  2337. movq $1, v
  2338. movq $46, w
  2339. movq v, x
  2340. addq $7, x
  2341. movq x, y
  2342. addq $4, y
  2343. movq x, z
  2344. addq w, z
  2345. movq y, t.1
  2346. negq t.1)
  2347. movq z, %rax
  2348. addq t.1, %rax
  2349. jmp conclusion
  2350. \end{lstlisting}
  2351. \end{minipage}
  2352. \vrule\hspace{10pt}
  2353. \begin{minipage}{0.45\textwidth}
  2354. \begin{lstlisting}
  2355. |$\{\}$|
  2356. |$\{v \}$|
  2357. |$\{v,w\}$|
  2358. |$\{w,x\}$|
  2359. |$\{w,x\}$|
  2360. |$\{w,x,y\}$|
  2361. |$\{w,x,y\}$|
  2362. |$\{w,y,z\}$|
  2363. |$\{y,z\}$|
  2364. |$\{z,t.1\}$|
  2365. |$\{z,t.1\}$|
  2366. |$\{t.1\}$|
  2367. |$\{\}$|
  2368. |$\{\}$|
  2369. \end{lstlisting}
  2370. \end{minipage}
  2371. \caption{The running example annotated with live-after sets.}
  2372. \label{fig:live-eg}
  2373. \end{figure}
  2374. \begin{exercise}\normalfont
  2375. Implement the compiler pass named \code{uncover-live} that computes
  2376. the live-after sets. We recommend storing the live-after sets (a list
  2377. of lists of variables) in the $\itm{info}$ field of the \key{Block}
  2378. structure.
  2379. %
  2380. We recommend organizing your code to use a helper function that takes
  2381. a list of instructions and an initial live-after set (typically empty)
  2382. and returns the list of live-after sets.
  2383. %
  2384. We recommend creating helper functions to 1) compute the set of
  2385. variables that appear in an argument (of an instruction), 2) compute
  2386. the variables read by an instruction which corresponds to the $R$
  2387. function discussed above, and 3) the variables written by an
  2388. instruction which corresponds to $W$.
  2389. \end{exercise}
  2390. \section{Building the Interference Graph}
  2391. \label{sec:build-interference}
  2392. Based on the liveness analysis, we know where each variable is needed.
  2393. However, during register allocation, we need to answer questions of
  2394. the specific form: are variables $u$ and $v$ live at the same time?
  2395. (And therefore cannot be assigned to the same register.) To make this
  2396. question easier to answer, we create an explicit data structure, an
  2397. \emph{interference graph}. An interference graph is an undirected
  2398. graph that has an edge between two variables if they are live at the
  2399. same time, that is, if they interfere with each other.
  2400. The most obvious way to compute the interference graph is to look at
  2401. the set of live variables between each statement in the program and
  2402. add an edge to the graph for every pair of variables in the same set.
  2403. This approach is less than ideal for two reasons. First, it can be
  2404. expensive because it takes $O(n^2)$ time to look at every pair in a
  2405. set of $n$ live variables. Second, there is a special case in which
  2406. two variables that are live at the same time do not actually interfere
  2407. with each other: when they both contain the same value because we have
  2408. assigned one to the other.
  2409. A better way to compute the interference graph is to focus on the
  2410. writes~\cite{Appel:2003fk}. We do not want the write performed by an
  2411. instruction to overwrite something in a live variable. So for each
  2412. instruction, we create an edge between the variable being written to
  2413. and all the \emph{other} live variables. (One should not create self
  2414. edges.) For a \key{callq} instruction, think of all caller-saved
  2415. registers as being written to, so an edge must be added between every
  2416. live variable and every caller-saved register. For \key{movq}, we deal
  2417. with the above-mentioned special case by not adding an edge between a
  2418. live variable $v$ and destination $d$ if $v$ matches the source of the
  2419. move. So we have the following three rules.
  2420. \begin{enumerate}
  2421. \item If instruction $I_k$ is an arithmetic instruction such as
  2422. \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2423. L_{\mathsf{after}}(k)$ unless $v = d$.
  2424. \item If instruction $I_k$ is of the form \key{callq}
  2425. $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2426. register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2427. \item If instruction $I_k$ is a move: \key{movq} $s$\key{,} $d$, then add
  2428. the edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v =
  2429. d$ or $v = s$.
  2430. \end{enumerate}
  2431. \margincomment{JM: I think you could give examples of each one of these
  2432. using the example program and use those to help explain why these
  2433. rules are correct.\\
  2434. JS: Agreed.}
  2435. Working from the top to bottom of Figure~\ref{fig:live-eg}, we obtain
  2436. the following interference for the instruction at the specified line
  2437. number.
  2438. \begin{quote}
  2439. Line 2: no interference,\\
  2440. Line 3: $w$ interferes with $v$,\\
  2441. Line 4: $x$ interferes with $w$,\\
  2442. Line 5: $x$ interferes with $w$,\\
  2443. Line 6: $y$ interferes with $w$,\\
  2444. Line 7: $y$ interferes with $w$ and $x$,\\
  2445. Line 8: $z$ interferes with $w$ and $y$,\\
  2446. Line 9: $z$ interferes with $y$, \\
  2447. Line 10: $t.1$ interferes with $z$, \\
  2448. Line 11: $t.1$ interferes with $z$, \\
  2449. Line 12: no interference, \\
  2450. Line 13: no interference. \\
  2451. Line 14: no interference.
  2452. \end{quote}
  2453. The resulting interference graph is shown in
  2454. Figure~\ref{fig:interfere}.
  2455. \begin{figure}[tbp]
  2456. \large
  2457. \[
  2458. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2459. \node (v) at (0,0) {$v$};
  2460. \node (w) at (2,0) {$w$};
  2461. \node (x) at (4,0) {$x$};
  2462. \node (t1) at (6,-2) {$t.1$};
  2463. \node (y) at (2,-2) {$y$};
  2464. \node (z) at (4,-2) {$z$};
  2465. \draw (v) to (w);
  2466. \foreach \i in {w,x,y}
  2467. {
  2468. \foreach \j in {w,x,y}
  2469. {
  2470. \draw (\i) to (\j);
  2471. }
  2472. }
  2473. \draw (z) to (w);
  2474. \draw (z) to (y);
  2475. \draw (t1) to (z);
  2476. \end{tikzpicture}
  2477. \]
  2478. \caption{The interference graph of the example program.}
  2479. \label{fig:interfere}
  2480. \end{figure}
  2481. %% Our next concern is to choose a data structure for representing the
  2482. %% interference graph. There are many choices for how to represent a
  2483. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2484. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2485. %% data structure is to study the algorithm that uses the data structure,
  2486. %% determine what operations need to be performed, and then choose the
  2487. %% data structure that provide the most efficient implementations of
  2488. %% those operations. Often times the choice of data structure can have an
  2489. %% effect on the time complexity of the algorithm, as it does here. If
  2490. %% you skim the next section, you will see that the register allocation
  2491. %% algorithm needs to ask the graph for all of its vertices and, given a
  2492. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2493. %% correct choice of graph representation is that of an adjacency
  2494. %% list. There are helper functions in \code{utilities.rkt} for
  2495. %% representing graphs using the adjacency list representation:
  2496. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2497. %% (Appendix~\ref{appendix:utilities}).
  2498. %% %
  2499. %% \margincomment{\footnotesize To do: change to use the
  2500. %% Racket graph library. \\ --Jeremy}
  2501. %% %
  2502. %% In particular, those functions use a hash table to map each vertex to
  2503. %% the set of adjacent vertices, and the sets are represented using
  2504. %% Racket's \key{set}, which is also a hash table.
  2505. \begin{exercise}\normalfont
  2506. Implement the compiler pass named \code{build-interference} according
  2507. to the algorithm suggested above. We recommend using the Racket
  2508. \code{graph} package to create and inspect the interference graph.
  2509. The output graph of this pass should be stored in the $\itm{info}$
  2510. field of the program, under the key \code{conflicts}.
  2511. \end{exercise}
  2512. \section{Graph Coloring via Sudoku}
  2513. \label{sec:graph-coloring}
  2514. We come to the main event, mapping variables to registers (or to stack
  2515. locations in the event that we run out of registers). We need to make
  2516. sure that two variables do not get mapped to the same register if the
  2517. two variables interfere with each other. Thinking about the
  2518. interference graph, this means that adjacent vertices must be mapped
  2519. to different registers. If we think of registers as colors, the
  2520. register allocation problem becomes the widely-studied graph coloring
  2521. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2522. The reader may be more familiar with the graph coloring problem than he
  2523. or she realizes; the popular game of Sudoku is an instance of the
  2524. graph coloring problem. The following describes how to build a graph
  2525. out of an initial Sudoku board.
  2526. \begin{itemize}
  2527. \item There is one vertex in the graph for each Sudoku square.
  2528. \item There is an edge between two vertices if the corresponding squares
  2529. are in the same row, in the same column, or if the squares are in
  2530. the same $3\times 3$ region.
  2531. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2532. \item Based on the initial assignment of numbers to squares in the
  2533. Sudoku board, assign the corresponding colors to the corresponding
  2534. vertices in the graph.
  2535. \end{itemize}
  2536. If you can color the remaining vertices in the graph with the nine
  2537. colors, then you have also solved the corresponding game of Sudoku.
  2538. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2539. the corresponding graph with colored vertices. We map the Sudoku
  2540. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2541. sampling of the vertices (the colored ones) because showing edges for
  2542. all of the vertices would make the graph unreadable.
  2543. \begin{figure}[tbp]
  2544. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2545. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2546. \caption{A Sudoku game board and the corresponding colored graph.}
  2547. \label{fig:sudoku-graph}
  2548. \end{figure}
  2549. Given that Sudoku is an instance of graph coloring, one can use Sudoku
  2550. strategies to come up with an algorithm for allocating registers. For
  2551. example, one of the basic techniques for Sudoku is called Pencil
  2552. Marks. The idea is to use a process of elimination to determine what
  2553. numbers no longer make sense for a square and write down those
  2554. numbers in the square (writing very small). For example, if the number
  2555. $1$ is assigned to a square, then by process of elimination, you can
  2556. write the pencil mark $1$ in all the squares in the same row, column,
  2557. and region. Many Sudoku computer games provide automatic support for
  2558. Pencil Marks.
  2559. %
  2560. The Pencil Marks technique corresponds to the notion of
  2561. \emph{saturation} due to \cite{Brelaz:1979eu}. The saturation of a
  2562. vertex, in Sudoku terms, is the set of numbers that are no longer
  2563. available. In graph terminology, we have the following definition:
  2564. \begin{equation*}
  2565. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  2566. \text{ and } \mathrm{color}(v) = c \}
  2567. \end{equation*}
  2568. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  2569. edge with $u$.
  2570. Using the Pencil Marks technique leads to a simple strategy for
  2571. filling in numbers: if there is a square with only one possible number
  2572. left, then choose that number! But what if there are no squares with
  2573. only one possibility left? One brute-force approach is to try them
  2574. all: choose the first and if it ultimately leads to a solution,
  2575. great. If not, backtrack and choose the next possibility. One good
  2576. thing about Pencil Marks is that it reduces the degree of branching in
  2577. the search tree. Nevertheless, backtracking can be horribly time
  2578. consuming. One way to reduce the amount of backtracking is to use the
  2579. most-constrained-first heuristic. That is, when choosing a square,
  2580. always choose one with the fewest possibilities left (the vertex with
  2581. the highest saturation). The idea is that choosing highly constrained
  2582. squares earlier rather than later is better because later on there may
  2583. not be any possibilities left for those squares.
  2584. In some sense, register allocation is easier than Sudoku because the
  2585. register allocator can choose to map variables to stack locations when
  2586. the registers run out. Thus, it makes sense to drop backtracking in
  2587. favor of greedy search, that is, make the best choice at the time and
  2588. keep going. We still wish to minimize the number of colors needed, so
  2589. keeping the most-constrained-first heuristic is a good idea.
  2590. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  2591. algorithm for register allocation based on saturation and the
  2592. most-constrained-first heuristic. It is roughly equivalent to the
  2593. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2594. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just as in
  2595. Sudoku, the algorithm represents colors with integers. The first $k$
  2596. colors corresponding to the $k$ registers in a given machine and the
  2597. rest of the integers corresponding to stack locations.
  2598. \begin{figure}[btp]
  2599. \centering
  2600. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2601. Algorithm: DSATUR
  2602. Input: a graph |$G$|
  2603. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  2604. |$W \gets \mathit{vertices}(G)$|
  2605. while |$W \neq \emptyset$| do
  2606. pick a vertex |$u$| from |$W$| with the highest saturation,
  2607. breaking ties randomly
  2608. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  2609. |$\mathrm{color}[u] \gets c$|
  2610. |$W \gets W - \{u\}$|
  2611. \end{lstlisting}
  2612. \caption{The saturation-based greedy graph coloring algorithm.}
  2613. \label{fig:satur-algo}
  2614. \end{figure}
  2615. With this algorithm in hand, let us return to the running example and
  2616. consider how to color the interference graph in
  2617. Figure~\ref{fig:interfere}. Initially, all of the vertices are not yet
  2618. colored and they are unsaturated, so we annotate each of them with a
  2619. dash for their color and an empty set for the saturation.
  2620. \[
  2621. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2622. \node (v) at (0,0) {$v:-,\{\}$};
  2623. \node (w) at (3,0) {$w:-,\{\}$};
  2624. \node (x) at (6,0) {$x:-,\{\}$};
  2625. \node (y) at (3,-1.5) {$y:-,\{\}$};
  2626. \node (z) at (6,-1.5) {$z:-,\{\}$};
  2627. \node (t1) at (9,-1.5) {$t.1:-,\{\}$};
  2628. \draw (v) to (w);
  2629. \foreach \i in {w,x,y}
  2630. {
  2631. \foreach \j in {w,x,y}
  2632. {
  2633. \draw (\i) to (\j);
  2634. }
  2635. }
  2636. \draw (z) to (w);
  2637. \draw (z) to (y);
  2638. \draw (t1) to (z);
  2639. \end{tikzpicture}
  2640. \]
  2641. The algorithm says to select a maximally saturated vertex and color it
  2642. $0$. In this case we have a 7-way tie, so we arbitrarily pick
  2643. $t.1$. We then mark color $0$ as no longer available for $z$ because
  2644. it interferes with $t.1$.
  2645. \[
  2646. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2647. \node (v) at (0,0) {$v:-,\{\}$};
  2648. \node (w) at (3,0) {$w:-,\{\}$};
  2649. \node (x) at (6,0) {$x:-,\{\}$};
  2650. \node (y) at (3,-1.5) {$y:-,\{\}$};
  2651. \node (z) at (6,-1.5) {$z:-,\{\mathbf{0}\}$};
  2652. \node (t1) at (9,-1.5) {$t.1:\mathbf{0},\{\}$};
  2653. \draw (v) to (w);
  2654. \foreach \i in {w,x,y}
  2655. {
  2656. \foreach \j in {w,x,y}
  2657. {
  2658. \draw (\i) to (\j);
  2659. }
  2660. }
  2661. \draw (z) to (w);
  2662. \draw (z) to (y);
  2663. \draw (t1) to (z);
  2664. \end{tikzpicture}
  2665. \]
  2666. Next we repeat the process, selecting another maximally saturated
  2667. vertex, which is $z$, and color it with the first available number,
  2668. which is $1$.
  2669. \[
  2670. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2671. \node (v) at (0,0) {$v:-,\{\}$};
  2672. \node (w) at (3,0) {$w:-,\{\mathbf{1}\}$};
  2673. \node (x) at (6,0) {$x:-,\{\}$};
  2674. \node (y) at (3,-1.5) {$y:-,\{\mathbf{1}\}$};
  2675. \node (z) at (6,-1.5) {$z:\mathbf{1},\{0\}$};
  2676. \node (t1) at (9,-1.5) {$t.1:0,\{\mathbf{1}\}$};
  2677. \draw (t1) to (z);
  2678. \draw (v) to (w);
  2679. \foreach \i in {w,x,y}
  2680. {
  2681. \foreach \j in {w,x,y}
  2682. {
  2683. \draw (\i) to (\j);
  2684. }
  2685. }
  2686. \draw (z) to (w);
  2687. \draw (z) to (y);
  2688. \end{tikzpicture}
  2689. \]
  2690. The most saturated vertices are now $w$ and $y$. We color $y$ with the
  2691. first available color, which is $0$.
  2692. \[
  2693. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2694. \node (v) at (0,0) {$v:-,\{\}$};
  2695. \node (w) at (3,0) {$w:-,\{\mathbf{0},1\}$};
  2696. \node (x) at (6,0) {$x:-,\{\mathbf{0},\}$};
  2697. \node (y) at (3,-1.5) {$y:\mathbf{0},\{1\}$};
  2698. \node (z) at (6,-1.5) {$z:1,\{\mathbf{0}\}$};
  2699. \node (t1) at (9,-1.5) {$t.1:0,\{1\}$};
  2700. \draw (t1) to (z);
  2701. \draw (v) to (w);
  2702. \foreach \i in {w,x,y}
  2703. {
  2704. \foreach \j in {w,x,y}
  2705. {
  2706. \draw (\i) to (\j);
  2707. }
  2708. }
  2709. \draw (z) to (w);
  2710. \draw (z) to (y);
  2711. \end{tikzpicture}
  2712. \]
  2713. Vertex $w$ is now the most highly saturated, so we color $w$ with $2$.
  2714. We cannot choose $0$ or $1$ because those numbers are in $w$'s
  2715. saturation set. Indeed, $w$ interferes with $y$ and $z$, whose colors
  2716. are $0$ and $1$ respectively.
  2717. \[
  2718. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2719. \node (v) at (0,0) {$v:-,\{2\}$};
  2720. \node (w) at (3,0) {$w:\mathbf{2},\{0,1\}$};
  2721. \node (x) at (6,0) {$x:-,\{0,\mathbf{2}\}$};
  2722. \node (y) at (3,-1.5) {$y:0,\{1,\mathbf{2}\}$};
  2723. \node (z) at (6,-1.5) {$z:1,\{0,\mathbf{2}\}$};
  2724. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2725. \draw (t1) to (z);
  2726. \draw (v) to (w);
  2727. \foreach \i in {w,x,y}
  2728. {
  2729. \foreach \j in {w,x,y}
  2730. {
  2731. \draw (\i) to (\j);
  2732. }
  2733. }
  2734. \draw (z) to (w);
  2735. \draw (z) to (y);
  2736. \end{tikzpicture}
  2737. \]
  2738. Now $x$ has the highest saturation, so we color it $1$.
  2739. \[
  2740. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2741. \node (v) at (0,0) {$v:-,\{2\}$};
  2742. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  2743. \node (x) at (6,0) {$x:\mathbf{1},\{0,2\}$};
  2744. \node (y) at (3,-1.5) {$y:0,\{\mathbf{1},2\}$};
  2745. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2746. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2747. \draw (t1) to (z);
  2748. \draw (v) to (w);
  2749. \foreach \i in {w,x,y}
  2750. {
  2751. \foreach \j in {w,x,y}
  2752. {
  2753. \draw (\i) to (\j);
  2754. }
  2755. }
  2756. \draw (z) to (w);
  2757. \draw (z) to (y);
  2758. \end{tikzpicture}
  2759. \]
  2760. In the last step of the algorithm, we color $v$ with $0$.
  2761. \[
  2762. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2763. \node (v) at (0,0) {$v:\mathbf{0},\{2\}$};
  2764. \node (w) at (3,0) {$w:2,\{\mathbf{0},1\}$};
  2765. \node (x) at (6,0) {$x:1,\{0,2\}$};
  2766. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  2767. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  2768. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  2769. \draw (t1) to (z);
  2770. \draw (v) to (w);
  2771. \foreach \i in {w,x,y}
  2772. {
  2773. \foreach \j in {w,x,y}
  2774. {
  2775. \draw (\i) to (\j);
  2776. }
  2777. }
  2778. \draw (z) to (w);
  2779. \draw (z) to (y);
  2780. \end{tikzpicture}
  2781. \]
  2782. With the coloring complete, we finalize the assignment of variables to
  2783. registers and stack locations. Recall that if we have $k$ registers,
  2784. we map the first $k$ colors to registers and the rest to stack
  2785. locations. Suppose for the moment that we have just one register to
  2786. use for register allocation, \key{rcx}. Then the following is the
  2787. mapping of colors to registers and stack allocations.
  2788. \[
  2789. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  2790. \]
  2791. Putting this mapping together with the above coloring of the
  2792. variables, we arrive at the following assignment of variables to
  2793. registers and stack locations.
  2794. \begin{gather*}
  2795. \{ v \mapsto \key{\%rcx}, \,
  2796. w \mapsto \key{-16(\%rbp)}, \,
  2797. x \mapsto \key{-8(\%rbp)}, \\
  2798. y \mapsto \key{\%rcx}, \,
  2799. z\mapsto \key{-8(\%rbp)},
  2800. t.1\mapsto \key{\%rcx} \}
  2801. \end{gather*}
  2802. Applying this assignment to our running example, on the left, yields
  2803. the program on the right.
  2804. % why frame size of 32? -JGS
  2805. \begin{center}
  2806. \begin{minipage}{0.3\textwidth}
  2807. \begin{lstlisting}
  2808. movq $1, v
  2809. movq $46, w
  2810. movq v, x
  2811. addq $7, x
  2812. movq x, y
  2813. addq $4, y
  2814. movq x, z
  2815. addq w, z
  2816. movq y, t.1
  2817. negq t.1
  2818. movq z, %rax
  2819. addq t.1, %rax
  2820. jmp conclusion
  2821. \end{lstlisting}
  2822. \end{minipage}
  2823. $\Rightarrow\qquad$
  2824. \begin{minipage}{0.45\textwidth}
  2825. \begin{lstlisting}
  2826. movq $1, %rcx
  2827. movq $46, -16(%rbp)
  2828. movq %rcx, -8(%rbp)
  2829. addq $7, -8(%rbp)
  2830. movq -8(%rbp), %rcx
  2831. addq $4, %rcx
  2832. movq -8(%rbp), -8(%rbp)
  2833. addq -16(%rbp), -8(%rbp)
  2834. movq %rcx, %rcx
  2835. negq %rcx
  2836. movq -8(%rbp), %rax
  2837. addq %rcx, %rax
  2838. jmp conclusion
  2839. \end{lstlisting}
  2840. \end{minipage}
  2841. \end{center}
  2842. The resulting program is almost an x86 program. The remaining step is
  2843. the patch instructions pass. In this example, the trivial move of
  2844. \code{-8(\%rbp)} to itself is deleted and the addition of
  2845. \code{-16(\%rbp)} to \key{-8(\%rbp)} is fixed by going through
  2846. \code{rax} as follows.
  2847. \begin{lstlisting}
  2848. movq -16(%rbp), %rax
  2849. addq %rax, -8(%rbp)
  2850. \end{lstlisting}
  2851. An overview of all of the passes involved in register allocation is
  2852. shown in Figure~\ref{fig:reg-alloc-passes}.
  2853. \begin{figure}[tbp]
  2854. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2855. \node (R1) at (0,2) {\large $R_1$};
  2856. \node (R1-2) at (3,2) {\large $R_1$};
  2857. \node (R1-3) at (6,2) {\large $R_1$};
  2858. \node (C0-1) at (6,0) {\large $C_0$};
  2859. \node (C0-2) at (3,0) {\large $C_0$};
  2860. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  2861. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  2862. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  2863. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  2864. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  2865. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  2866. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  2867. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  2868. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  2869. \path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  2870. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  2871. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  2872. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  2873. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  2874. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  2875. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  2876. \end{tikzpicture}
  2877. \caption{Diagram of the passes for $R_1$ with register allocation.}
  2878. \label{fig:reg-alloc-passes}
  2879. \end{figure}
  2880. \begin{exercise}\normalfont
  2881. Implement the pass \code{allocate-registers}, which should come
  2882. after the \code{build-interference} pass. The three new passes,
  2883. \code{uncover-live}, \code{build-interference}, and
  2884. \code{allocate-registers} replace the \code{assign-homes} pass of
  2885. Section~\ref{sec:assign-r1}.
  2886. We recommend that you create a helper function named
  2887. \code{color-graph} that takes an interference graph and a list of
  2888. all the variables in the program. This function should return a
  2889. mapping of variables to their colors (represented as natural
  2890. numbers). By creating this helper function, you will be able to
  2891. reuse it in Chapter~\ref{ch:functions} when you add support for
  2892. functions.
  2893. Once you have obtained the coloring from \code{color-graph}, you can
  2894. assign the variables to registers or stack locations and then reuse
  2895. code from the \code{assign-homes} pass from
  2896. Section~\ref{sec:assign-r1} to replace the variables with their
  2897. assigned location.
  2898. Test your updated compiler by creating new example programs that
  2899. exercise all of the register allocation algorithm, such as forcing
  2900. variables to be spilled to the stack.
  2901. \end{exercise}
  2902. \section{Print x86 and Conventions for Registers}
  2903. \label{sec:print-x86-reg-alloc}
  2904. Recall that the \code{print-x86} pass generates the prelude and
  2905. conclusion instructions for the \code{main} function.
  2906. %
  2907. The prelude saved the values in \code{rbp} and \code{rsp} and the
  2908. conclusion returned those values to \code{rbp} and \code{rsp}. The
  2909. reason for this is that our \code{main} function must adhere to the
  2910. x86 calling conventions that we described in
  2911. Section~\ref{sec:calling-conventions}. In addition, the \code{main}
  2912. function needs to restore (in the conclusion) any callee-saved
  2913. registers that get used during register allocation. The simplest
  2914. approach is to save and restore all of the callee-saved registers. The
  2915. more efficient approach is to keep track of which callee-saved
  2916. registers were used and only save and restore them. Either way, make
  2917. sure to take this use of stack space into account when you are
  2918. calculating the size of the frame. Also, don't forget that the size of
  2919. the frame needs to be a multiple of 16 bytes.
  2920. \section{Challenge: Move Biasing}
  2921. \label{sec:move-biasing}
  2922. This section describes an optional enhancement to register allocation
  2923. for those students who are looking for an extra challenge or who have
  2924. a deeper interest in register allocation.
  2925. We return to the running example, but we remove the supposition that
  2926. we only have one register to use. So we have the following mapping of
  2927. color numbers to registers.
  2928. \[
  2929. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx} \}
  2930. \]
  2931. Using the same assignment of variables to color numbers that was
  2932. produced by the register allocator described in the last section, we
  2933. get the following program.
  2934. \begin{minipage}{0.3\textwidth}
  2935. \begin{lstlisting}
  2936. movq $1, v
  2937. movq $46, w
  2938. movq v, x
  2939. addq $7, x
  2940. movq x, y
  2941. addq $4, y
  2942. movq x, z
  2943. addq w, z
  2944. movq y, t.1
  2945. negq t.1
  2946. movq z, %rax
  2947. addq t.1, %rax
  2948. jmp conclusion
  2949. \end{lstlisting}
  2950. \end{minipage}
  2951. $\Rightarrow\qquad$
  2952. \begin{minipage}{0.45\textwidth}
  2953. \begin{lstlisting}
  2954. movq $1, %rbx
  2955. movq $46, %rdx
  2956. movq %rbx, %rcx
  2957. addq $7, %rcx
  2958. movq %rcx, %rbx
  2959. addq $4, %rbx
  2960. movq %rcx, %rcx
  2961. addq %rdx, %rcx
  2962. movq %rbx, %rbx
  2963. negq %rbx
  2964. movq %rcx, %rax
  2965. addq %rbx, %rax
  2966. jmp conclusion
  2967. \end{lstlisting}
  2968. \end{minipage}
  2969. While this allocation is quite good, we could do better. For example,
  2970. the variables \key{v} and \key{x} ended up in different registers, but
  2971. if they had been placed in the same register, then the move from
  2972. \key{v} to \key{x} could be removed.
  2973. We say that two variables $p$ and $q$ are \emph{move related} if they
  2974. participate together in a \key{movq} instruction, that is, \key{movq}
  2975. $p$\key{,} $q$ or \key{movq} $q$\key{,} $p$. When the register
  2976. allocator chooses a color for a variable, it should prefer a color
  2977. that has already been used for a move-related variable (assuming that
  2978. they do not interfere). Of course, this preference should not override
  2979. the preference for registers over stack locations. This preference
  2980. should be used as a tie breaker when choosing between registers or
  2981. when choosing between stack locations.
  2982. We recommend representing the move relationships in a graph, similar
  2983. to how we represented interference. The following is the \emph{move
  2984. graph} for our running example.
  2985. \[
  2986. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2987. \node (v) at (0,0) {$v$};
  2988. \node (w) at (3,0) {$w$};
  2989. \node (x) at (6,0) {$x$};
  2990. \node (y) at (3,-1.5) {$y$};
  2991. \node (z) at (6,-1.5) {$z$};
  2992. \node (t1) at (9,-1.5) {$t.1$};
  2993. \draw[bend left=15] (t1) to (y);
  2994. \draw[bend left=15] (v) to (x);
  2995. \draw (x) to (y);
  2996. \draw (x) to (z);
  2997. \end{tikzpicture}
  2998. \]
  2999. Now we replay the graph coloring, pausing to see the coloring of $x$
  3000. and $v$. So we have the following coloring and the most saturated
  3001. vertex is $x$.
  3002. \[
  3003. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3004. \node (v) at (0,0) {$v:-,\{2\}$};
  3005. \node (w) at (3,0) {$w:2,\{0,1\}$};
  3006. \node (x) at (6,0) {$x:-,\{0,2\}$};
  3007. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  3008. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  3009. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  3010. \draw (t1) to (z);
  3011. \draw (v) to (w);
  3012. \foreach \i in {w,x,y}
  3013. {
  3014. \foreach \j in {w,x,y}
  3015. {
  3016. \draw (\i) to (\j);
  3017. }
  3018. }
  3019. \draw (z) to (w);
  3020. \draw (z) to (y);
  3021. \end{tikzpicture}
  3022. \]
  3023. Last time we chose to color $x$ with $1$,
  3024. %
  3025. which so happens to be the color of $z$, and $x$ is move related to
  3026. $z$. This was lucky, and if the program had been a little different,
  3027. and say $z$ had been already assigned to $2$, then $x$ would still get
  3028. $1$ and our luck would have run out. With move biasing, we use the
  3029. fact that $x$ and $z$ are move related to influence the choice of
  3030. color for $x$, in this case choosing $1$ because that is the color of
  3031. $z$.
  3032. \[
  3033. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3034. \node (v) at (0,0) {$v:-,\{2\}$};
  3035. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  3036. \node (x) at (6,0) {$x:\mathbf{1},\{0,2\}$};
  3037. \node (y) at (3,-1.5) {$y:0,\{\mathbf{1},2\}$};
  3038. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  3039. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  3040. \draw (t1) to (z);
  3041. \draw (v) to (w);
  3042. \foreach \i in {w,x,y}
  3043. {
  3044. \foreach \j in {w,x,y}
  3045. {
  3046. \draw (\i) to (\j);
  3047. }
  3048. }
  3049. \draw (z) to (w);
  3050. \draw (z) to (y);
  3051. \end{tikzpicture}
  3052. \]
  3053. Next we consider coloring the variable $v$. We need to avoid choosing
  3054. $2$ because of the interference with $w$. Last time we chose the color
  3055. $0$ because it was the lowest, but this time we know that $v$ is move
  3056. related to $x$, so we choose the color $1$.
  3057. \[
  3058. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3059. \node (v) at (0,0) {$v:\mathbf{1},\{2\}$};
  3060. \node (w) at (3,0) {$w:2,\{0,\mathbf{1}\}$};
  3061. \node (x) at (6,0) {$x:1,\{0,2\}$};
  3062. \node (y) at (3,-1.5) {$y:0,\{1,2\}$};
  3063. \node (z) at (6,-1.5) {$z:1,\{0,2\}$};
  3064. \node (t1) at (9,-1.5) {$t.1:0,\{\}$};
  3065. \draw (t1) to (z);
  3066. \draw (v) to (w);
  3067. \foreach \i in {w,x,y}
  3068. {
  3069. \foreach \j in {w,x,y}
  3070. {
  3071. \draw (\i) to (\j);
  3072. }
  3073. }
  3074. \draw (z) to (w);
  3075. \draw (z) to (y);
  3076. \end{tikzpicture}
  3077. \]
  3078. We apply this register assignment to the running example, on the left,
  3079. to obtain the code on right.
  3080. \begin{minipage}{0.3\textwidth}
  3081. \begin{lstlisting}
  3082. movq $1, v
  3083. movq $46, w
  3084. movq v, x
  3085. addq $7, x
  3086. movq x, y
  3087. addq $4, y
  3088. movq x, z
  3089. addq w, z
  3090. movq y, t.1
  3091. negq t.1
  3092. movq z, %rax
  3093. addq t.1, %rax
  3094. jmp conclusion
  3095. \end{lstlisting}
  3096. \end{minipage}
  3097. $\Rightarrow\qquad$
  3098. \begin{minipage}{0.45\textwidth}
  3099. \begin{lstlisting}
  3100. movq $1, %rcx
  3101. movq $46, %rbx
  3102. movq %rcx, %rcx
  3103. addq $7, %rcx
  3104. movq %rcx, %rdx
  3105. addq $4, %rdx
  3106. movq %rcx, %rcx
  3107. addq %rbx, %rcx
  3108. movq %rdx, %rbx
  3109. negq %rbx
  3110. movq %rcx, %rax
  3111. addq %rbx, %rax
  3112. jmp conclusion
  3113. \end{lstlisting}
  3114. \end{minipage}
  3115. The \code{patch-instructions} then removes the trivial moves from
  3116. \key{v} to \key{x} and from \key{x} to \key{z} to obtain the following
  3117. result.
  3118. \begin{minipage}{0.45\textwidth}
  3119. \begin{lstlisting}
  3120. movq $1 %rcx
  3121. movq $46 %rbx
  3122. addq $7 %rcx
  3123. movq %rcx %rdx
  3124. addq $4 %rdx
  3125. addq %rbx %rcx
  3126. movq %rdx %rbx
  3127. negq %rbx
  3128. movq %rcx %rax
  3129. addq %rbx %rax
  3130. jmp conclusion
  3131. \end{lstlisting}
  3132. \end{minipage}
  3133. \begin{exercise}\normalfont
  3134. Change your implementation of \code{allocate-registers} to take move
  3135. biasing into account. Make sure that your compiler still passes all of
  3136. the previous tests. Create two new tests that include at least one
  3137. opportunity for move biasing and visually inspect the output x86
  3138. programs to make sure that your move biasing is working properly.
  3139. \end{exercise}
  3140. \margincomment{\footnotesize To do: another neat challenge would be to do
  3141. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3142. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3143. \chapter{Booleans and Control Flow}
  3144. \label{ch:bool-types}
  3145. The $R_0$ and $R_1$ languages only had a single kind of value, the
  3146. integers. In this chapter we add a second kind of value, the Booleans,
  3147. to create the $R_2$ language. The Boolean values \emph{true} and
  3148. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  3149. Racket. The $R_2$ language includes several operations that involve
  3150. Booleans (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the
  3151. conditional \key{if} expression. With the addition of \key{if}
  3152. expressions, programs can have non-trivial control flow which has an
  3153. impact on several parts of the compiler. Also, because we now have two
  3154. kinds of values, we need to worry about programs that apply an
  3155. operation to the wrong kind of value, such as \code{(not 1)}.
  3156. There are two language design options for such situations. One option
  3157. is to signal an error and the other is to provide a wider
  3158. interpretation of the operation. The Racket language uses a mixture of
  3159. these two options, depending on the operation and the kind of
  3160. value. For example, the result of \code{(not 1)} in Racket is
  3161. \code{\#f} because Racket treats non-zero integers as if they were
  3162. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  3163. error in Racket stating that \code{car} expects a pair.
  3164. The Typed Racket language makes similar design choices as Racket,
  3165. except much of the error detection happens at compile time instead of
  3166. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  3167. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  3168. reports a compile-time error because Typed Racket expects the type of
  3169. the argument to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  3170. For the $R_2$ language we choose to be more like Typed Racket in that
  3171. we shall perform type checking during compilation. In
  3172. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  3173. is, how to compile a dynamically typed language like Racket. The
  3174. $R_2$ language is a subset of Typed Racket but by no means includes
  3175. all of Typed Racket. Furthermore, for many of the operations we shall
  3176. take a narrower interpretation than Typed Racket, for example,
  3177. rejecting \code{(not 1)}.
  3178. This chapter is organized as follows. We begin by defining the syntax
  3179. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  3180. then introduce the idea of type checking and build a type checker for
  3181. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  3182. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  3183. Section~\ref{sec:c1}. The remaining sections of this Chapter discuss
  3184. how our compiler passes need to change to accommodate Booleans and
  3185. conditional control flow.
  3186. \section{The $R_2$ Language}
  3187. \label{sec:r2-lang}
  3188. The concrete syntax of the $R_2$ language is defined in
  3189. Figure~\ref{fig:r2-concrete-syntax} and the abstract syntax is defined
  3190. in Figure~\ref{fig:r2-syntax}. The $R_2$ language includes all of
  3191. $R_1$ (shown in gray), the Boolean literals \code{\#t} and \code{\#f},
  3192. and the conditional \code{if} expression. Also, we expand the
  3193. operators to include subtraction, \key{and}, \key{or} and \key{not},
  3194. the \key{eq?} operations for comparing two integers or two Booleans,
  3195. and the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  3196. comparing integers.
  3197. \begin{figure}[tp]
  3198. \centering
  3199. \fbox{
  3200. \begin{minipage}{0.96\textwidth}
  3201. \[
  3202. \begin{array}{lcl}
  3203. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3204. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) } \mid (\key{-}\;\Exp\;\Exp) \\
  3205. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) } \\
  3206. &\mid& \key{\#t} \mid \key{\#f}
  3207. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  3208. \mid (\key{not}\;\Exp) \\
  3209. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid (\key{if}~\Exp~\Exp~\Exp) \\
  3210. R_2 &::=& \Exp
  3211. \end{array}
  3212. \]
  3213. \end{minipage}
  3214. }
  3215. \caption{The concrete syntax of $R_2$, extending $R_1$
  3216. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  3217. \label{fig:r2-concrete-syntax}
  3218. \end{figure}
  3219. \begin{figure}[tp]
  3220. \centering
  3221. \fbox{
  3222. \begin{minipage}{0.96\textwidth}
  3223. \[
  3224. \begin{array}{lcl}
  3225. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3226. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3227. \Exp &::=& \gray{\INT{\Int} \mid \READ{} \mid \NEG{\Exp}} \\
  3228. &\mid& \gray{\ADD{\Exp}{\Exp}}
  3229. \mid \BINOP{\code{'-}}{\Exp}{\Exp} \\
  3230. &\mid& \gray{\VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp}} \\
  3231. &\mid& \BOOL{\itm{bool}}
  3232. \mid \AND{\Exp}{\Exp}\\
  3233. &\mid& \OR{\Exp}{\Exp}
  3234. \mid \NOT{\Exp} \\
  3235. &\mid& \BINOP{\code{'}\itm{cmp}}{\Exp}{\Exp} \mid \IF{\Exp}{\Exp}{\Exp} \\
  3236. R_2 &::=& \PROGRAM{\key{'()}}{\Exp}
  3237. \end{array}
  3238. \]
  3239. \end{minipage}
  3240. }
  3241. \caption{The abstract syntax of $R_2$.}
  3242. \label{fig:r2-syntax}
  3243. \end{figure}
  3244. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  3245. the parts that are the same as the interpreter for $R_1$
  3246. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  3247. simply evaluate to themselves. The conditional expression $(\key{if}\,
  3248. \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates the Boolean expression
  3249. \itm{cnd} and then either evaluates \itm{thn} or \itm{els} depending
  3250. on whether \itm{cnd} produced \code{\#t} or \code{\#f}. The logical
  3251. operations \code{not} and \code{and} behave as you might expect, but
  3252. note that the \code{and} operation is short-circuiting. That is, given
  3253. the expression $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not
  3254. evaluated if $e_1$ evaluates to \code{\#f}.
  3255. With the addition of the comparison operations, there are quite a few
  3256. primitive operations and the interpreter code for them is somewhat
  3257. repetitive. In Figure~\ref{fig:interp-R2} we factor out the different
  3258. parts into the \code{interp-op} function and the similar parts into
  3259. the one match clause shown in Figure~\ref{fig:interp-R2}. We do not
  3260. use \code{interp-op} for the \code{and} operation because of the
  3261. short-circuiting behavior in the order of evaluation of its arguments.
  3262. \begin{figure}[tbp]
  3263. \begin{lstlisting}
  3264. (define (interp-op op)
  3265. (match op
  3266. ...
  3267. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  3268. ['eq? (lambda (v1 v2)
  3269. (cond [(or (and (fixnum? v1) (fixnum? v2))
  3270. (and (boolean? v1) (boolean? v2)))
  3271. (eq? v1 v2)]))]
  3272. ['< (lambda (v1 v2)
  3273. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  3274. ['<= (lambda (v1 v2)
  3275. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  3276. ['> (lambda (v1 v2)
  3277. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  3278. ['>= (lambda (v1 v2)
  3279. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  3280. [else (error 'interp-op "unknown operator")]))
  3281. (define (interp-exp env)
  3282. (lambda (e)
  3283. (define recur (interp-exp env))
  3284. (match e
  3285. ...
  3286. [(Bool b) b]
  3287. [(If cnd thn els)
  3288. (define b (recur cnd))
  3289. (match b
  3290. [#t (recur thn)]
  3291. [#f (recur els)])]
  3292. [(Prim 'and (list e1 e2))
  3293. (define v1 (recur e1))
  3294. (match v1
  3295. [#t (match (recur e2) [#t #t] [#f #f])]
  3296. [#f #f])]
  3297. [(Prim op args)
  3298. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  3299. )))
  3300. (define (interp-R2 p)
  3301. (match p
  3302. [(Program info e)
  3303. ((interp-exp '()) e)]
  3304. ))
  3305. \end{lstlisting}
  3306. \caption{Interpreter for the $R_2$ language.}
  3307. \label{fig:interp-R2}
  3308. \end{figure}
  3309. \section{Type Checking $R_2$ Programs}
  3310. \label{sec:type-check-r2}
  3311. It is helpful to think about type checking in two complementary
  3312. ways. A type checker predicts the \emph{type} of value that will be
  3313. produced by each expression in the program. For $R_2$, we have just
  3314. two types, \key{Integer} and \key{Boolean}. So a type checker should
  3315. predict that
  3316. \begin{lstlisting}
  3317. (+ 10 (- (+ 12 20)))
  3318. \end{lstlisting}
  3319. produces an \key{Integer} while
  3320. \begin{lstlisting}
  3321. (and (not #f) #t)
  3322. \end{lstlisting}
  3323. produces a \key{Boolean}.
  3324. As mentioned at the beginning of this chapter, a type checker also
  3325. rejects programs that apply operators to the wrong type of value. Our
  3326. type checker for $R_2$ will signal an error for the below expression
  3327. because, as we have seen above, the expression \code{(+ 10 ...)} has
  3328. type \key{Integer}, and we require the argument of a \code{not} to
  3329. have type \key{Boolean}.
  3330. \begin{lstlisting}
  3331. (not (+ 10 (- (+ 12 20))))
  3332. \end{lstlisting}
  3333. The type checker for $R_2$ is best implemented as a structurally
  3334. recursive function over the AST. Figure~\ref{fig:type-check-R2} shows
  3335. many of the clauses for the \code{type-check-exp} function. Given an
  3336. input expression \code{e}, the type checker either returns the type
  3337. (\key{Integer} or \key{Boolean}) or it signals an error. Of course,
  3338. the type of an integer literal is \code{Integer} and the type of a
  3339. Boolean literal is \code{Boolean}. To handle variables, the type
  3340. checker, like the interpreter, uses an association list. However, in
  3341. this case the association list maps variables to types instead of
  3342. values. Consider the clause for \key{let}. We type check the
  3343. initializing expression to obtain its type \key{T} and then associate
  3344. type \code{T} with the variable \code{x}. When the type checker
  3345. encounters the use of a variable, it can find its type in the
  3346. association list.
  3347. \begin{figure}[tbp]
  3348. \begin{lstlisting}
  3349. (definepublic (type-check-exp env)
  3350. (lambda (e)
  3351. (match e
  3352. [(Var x) (dict-ref env x)]
  3353. [(Int n) 'Integer]
  3354. [(Bool b) 'Boolean]
  3355. [(Let x e body)
  3356. (define Te ((type-check-exp env) e))
  3357. (define Tb ((type-check-exp (dict-set env x Te)) body))
  3358. Tb]
  3359. ...
  3360. [else
  3361. (error "type-check-exp couldn't match" e)])))
  3362. (define (type-check env)
  3363. (lambda (e)
  3364. (match e
  3365. [(Program info body)
  3366. (define Tb ((type-check-exp '()) body))
  3367. (unless (equal? Tb 'Integer)
  3368. (error "result of the program must be an integer, not " Tb))
  3369. (Program info body)]
  3370. )))
  3371. \end{lstlisting}
  3372. \caption{Skeleton of a type checker for the $R_2$ language.}
  3373. \label{fig:type-check-R2}
  3374. \end{figure}
  3375. \begin{exercise}\normalfont
  3376. Complete the implementation of \code{type-check-R2} and test it on 10
  3377. new example programs in $R_2$ that you choose based on how thoroughly
  3378. they test the type checking algorithm. Half of the example programs
  3379. should have a type error, to make sure that your type checker properly
  3380. rejects them. The other half of the example programs should not have
  3381. type errors. Your testing should check that the result of the type
  3382. checker agrees with the value returned by the interpreter, that is, if
  3383. the type checker returns \key{Integer}, then the interpreter should
  3384. return an integer. Likewise, if the type checker returns
  3385. \key{Boolean}, then the interpreter should return \code{\#t} or
  3386. \code{\#f}. Note that if your type checker does not signal an error
  3387. for a program, then interpreting that program should not encounter an
  3388. error. If it does, there is something wrong with your type checker.
  3389. \end{exercise}
  3390. \section{Shrink the $R_2$ Language}
  3391. \label{sec:shrink-r2}
  3392. The $R_2$ language includes several operators that are easily
  3393. expressible in terms of other operators. For example, subtraction is
  3394. expressible in terms of addition and negation.
  3395. \[
  3396. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad (\key{+} \; e_1 \; (\key{-} \; e_2))
  3397. \]
  3398. Several of the comparison operations are expressible in terms of
  3399. less-than and logical negation.
  3400. \[
  3401. (\key{<=}\; e_1 \; e_2) \quad \Rightarrow \quad
  3402. \LET{t_1}{e_1}{(\key{not}\;(\key{<}\;e_2\;t_1))}
  3403. \]
  3404. By performing these translations near the front-end of the compiler,
  3405. the later passes of the compiler do not need to deal with these
  3406. constructs, making those passes shorter. On the other hand, sometimes
  3407. these translations make it more difficult to generate the most
  3408. efficient code with respect to the number of instructions. However,
  3409. these differences typically do not affect the number of accesses to
  3410. memory, which is the primary factor that determines execution time on
  3411. modern computer architectures.
  3412. \begin{exercise}\normalfont
  3413. Implement the pass \code{shrink} that removes subtraction,
  3414. \key{and}, \key{or}, \key{<=}, \key{>}, and \key{>=} from the language
  3415. by translating them to other constructs in $R_2$. Create tests to
  3416. make sure that the behavior of all of these constructs stays the
  3417. same after translation.
  3418. \end{exercise}
  3419. \section{XOR, Comparisons, and Control Flow in x86}
  3420. \label{sec:x86-1}
  3421. To implement the new logical operations, the comparison operations,
  3422. and the \key{if} expression, we need to delve further into the x86
  3423. language. Figure~\ref{fig:x86-1} defines the abstract syntax for a
  3424. larger subset of x86 that includes instructions for logical
  3425. operations, comparisons, and jumps.
  3426. One small challenge is that x86 does not provide an instruction that
  3427. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  3428. However, the \code{xorq} instruction can be used to encode \code{not}.
  3429. The \key{xorq} instruction takes two arguments, performs a pairwise
  3430. exclusive-or operation on each bit of its arguments, and writes the
  3431. results into its second argument. Recall the truth table for
  3432. exclusive-or:
  3433. \begin{center}
  3434. \begin{tabular}{l|cc}
  3435. & 0 & 1 \\ \hline
  3436. 0 & 0 & 1 \\
  3437. 1 & 1 & 0
  3438. \end{tabular}
  3439. \end{center}
  3440. For example, $0011 \mathrel{\mathrm{XOR}} 0101 = 0110$. Notice that
  3441. in the row of the table for the bit $1$, the result is the opposite of the
  3442. second bit. Thus, the \code{not} operation can be implemented by
  3443. \code{xorq} with $1$ as the first argument:
  3444. \begin{align*}
  3445. 0001 \mathrel{\mathrm{XOR}} 0000 &= 0001\\
  3446. 0001 \mathrel{\mathrm{XOR}} 0001 &= 0000
  3447. \end{align*}
  3448. \begin{figure}[tp]
  3449. \fbox{
  3450. \begin{minipage}{0.96\textwidth}
  3451. \small
  3452. \[
  3453. \begin{array}{lcl}
  3454. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\code{'}\Reg} \mid \DEREF{\Reg}{\Int}}
  3455. \mid \BYTEREG{\code{'}\Reg} \\
  3456. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3457. \Instr &::=& \gray{\BININSTR{\code{'addq}}{\Arg}{\Arg}}
  3458. \mid \gray{\BININSTR{\code{'subq}}{\Arg}{\Arg}} \\
  3459. &\mid& \gray{\BININSTR{\code{'movq}}{\Arg}{\Arg}}
  3460. \mid \gray{\UNIINSTR{\code{'negq}}{\Arg}} \\
  3461. &\mid& \gray{\CALLQ{\itm{label}} \mid \RETQ{}}
  3462. \mid \gray{\PUSHQ{\Arg} \mid \POPQ{\Arg}} \\
  3463. &\mid& \BININSTR{\code{'xorq}}{\Arg}{\Arg}
  3464. \mid \BININSTR{\code{'cmpq}}{\Arg}{\Arg}\\
  3465. &\mid& \BININSTR{\code{'set}}{\code{'}\itm{cc}}{\Arg}
  3466. \mid \BININSTR{\code{'movzbq}}{\Arg}{\Arg}\\
  3467. &\mid& \JMP{\itm{label}}
  3468. \mid \JMPIF{\code{'}\itm{cc}}{\itm{label}} \\
  3469. % &\mid& (\key{label} \; \itm{label}) \\
  3470. \Block &::= & \gray{\BLOCK{\itm{info}}{\Instr^{+}}} \\
  3471. x86_1 &::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}^{+}}}}
  3472. \end{array}
  3473. \]
  3474. \end{minipage}
  3475. }
  3476. \caption{The abstract syntax of $x86_1$ (extends x86$_0$ of Figure~\ref{fig:x86-ast-a}).}
  3477. \label{fig:x86-1}
  3478. \end{figure}
  3479. Next we consider the x86 instructions that are relevant for compiling
  3480. the comparison operations. The \key{cmpq} instruction compares its two
  3481. arguments to determine whether one argument is less than, equal, or
  3482. greater than the other argument. The \key{cmpq} instruction is unusual
  3483. regarding the order of its arguments and where the result is
  3484. placed. The argument order is backwards: if you want to test whether
  3485. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  3486. \key{cmpq} is placed in the special EFLAGS register. This register
  3487. cannot be accessed directly but it can be queried by a number of
  3488. instructions, including the \key{set} instruction. The \key{set}
  3489. instruction puts a \key{1} or \key{0} into its destination depending
  3490. on whether the comparison came out according to the condition code
  3491. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  3492. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  3493. The \key{set} instruction has an annoying quirk in that its
  3494. destination argument must be single byte register, such as \code{al},
  3495. which is part of the \code{rax} register. Thankfully, the
  3496. \key{movzbq} instruction can then be used to move from a single byte
  3497. register to a normal 64-bit register.
  3498. For compiling the \key{if} expression, the x86 instructions for
  3499. jumping are relevant. The \key{Jmp} instruction updates the program
  3500. counter to point to the instruction after the indicated label. The
  3501. \key{JmpIf} instruction updates the program counter to point to the
  3502. instruction after the indicated label depending on whether the result
  3503. in the EFLAGS register matches the condition code \itm{cc}, otherwise
  3504. the \key{JmpIf} instruction falls through to the next
  3505. instruction. Because the \key{JmpIf} instruction relies on the EFLAGS
  3506. register, it is quite common for the \key{JmpIf} to be immediately
  3507. preceded by a \key{cmpq} instruction, to set the EFLAGS register.
  3508. Our abstract syntax for \key{JmpIf} differs from the concrete syntax
  3509. for x86 to separate the instruction name from the condition code. For
  3510. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}.
  3511. \section{The $C_1$ Intermediate Language}
  3512. \label{sec:c1}
  3513. As with $R_1$, we shall compile $R_2$ to a C-like intermediate
  3514. language, but we need to grow that intermediate language to handle the
  3515. new features in $R_2$: Booleans and conditional expressions.
  3516. Figure~\ref{fig:c1-syntax} shows the new features of $C_1$; we add
  3517. logic and comparison operators to the $\Exp$ non-terminal, the
  3518. literals \key{\#t} and \key{\#f} to the $\Arg$ non-terminal.
  3519. Regarding control flow, $C_1$ differs considerably from $R_2$.
  3520. Instead of \key{if} expressions, $C_1$ has goto's and conditional
  3521. goto's in the grammar for $\Tail$. This means that a sequence of
  3522. statements may now end with a \code{goto} or a conditional
  3523. \code{goto}, which jumps to one of two labeled pieces of code
  3524. depending on the outcome of the comparison. In
  3525. Section~\ref{sec:explicate-control-r2} we discuss how to translate
  3526. from $R_2$ to $C_1$, bridging this gap between \key{if} expressions
  3527. and \key{goto}'s.
  3528. \begin{figure}[tp]
  3529. \fbox{
  3530. \begin{minipage}{0.96\textwidth}
  3531. \small
  3532. \[
  3533. \begin{array}{lcl}
  3534. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  3535. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  3536. \Exp &::= & \gray{\Atm \mid \READ{} \mid \NEG{\Atm} }\\
  3537. &\mid& \gray{ \ADD{\Atm}{\Atm} }
  3538. \mid \UNIOP{\key{not}}{\Atm} \\
  3539. &\mid& \BINOP{\itm{cmp}}{\Atm}{\Atm} \\
  3540. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} } \\
  3541. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} } \\
  3542. &\mid& \GOTO{\itm{label}} \mid \IFSTMT{\key{(}\itm{cmp}\,\Atm\,\Atm\key{)}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  3543. C_1 & ::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}^{+}}}}
  3544. \end{array}
  3545. \]
  3546. \end{minipage}
  3547. }
  3548. \caption{The abstract syntax of $C_1$, extending $C_0$ with Booleans and conditionals.}
  3549. \label{fig:c1-syntax}
  3550. \end{figure}
  3551. \section{Explicate Control}
  3552. \label{sec:explicate-control-r2}
  3553. Recall that the purpose of \code{explicate-control} is to make the
  3554. order of evaluation explicit in the syntax of the program. With the
  3555. addition of \key{if} in $R_2$, things get more interesting.
  3556. As a motivating example, consider the following program that has an
  3557. \key{if} expression nested in the predicate of another \key{if}.
  3558. % s1_38.rkt
  3559. \begin{center}
  3560. \begin{minipage}{0.96\textwidth}
  3561. \begin{lstlisting}
  3562. (if (if (eq? (read) 1)
  3563. (eq? (read) 0)
  3564. (eq? (read) 2))
  3565. (+ 10 32)
  3566. (+ 700 77))
  3567. \end{lstlisting}
  3568. \end{minipage}
  3569. \end{center}
  3570. %
  3571. The naive way to compile \key{if} and \key{eq?} would be to handle
  3572. each of them in isolation, regardless of their context. Each
  3573. \key{eq?} would be translated into a \key{cmpq} instruction followed
  3574. by a couple instructions to move the result from the EFLAGS register
  3575. into a general purpose register or stack location. Each \key{if} would
  3576. be translated into the combination of a \key{cmpq} and \key{JmpIf}.
  3577. However, if we take context into account we can do better and reduce
  3578. the use of \key{cmpq} and EFLAG-accessing instructions.
  3579. One idea is to try and reorganize the code at the level of $R_2$,
  3580. pushing the outer \key{if} inside the inner one. This would yield the
  3581. following code.
  3582. \begin{center}
  3583. \begin{minipage}{0.96\textwidth}
  3584. \begin{lstlisting}
  3585. (if (eq? (read) 1)
  3586. (if (eq? (read) 0)
  3587. (+ 10 32)
  3588. (+ 700 77))
  3589. (if (eq? (read) 2))
  3590. (+ 10 32)
  3591. (+ 700 77))
  3592. \end{lstlisting}
  3593. \end{minipage}
  3594. \end{center}
  3595. Unfortunately, this approach duplicates the two branches, and a
  3596. compiler must never duplicate code!
  3597. We need a way to perform the above transformation, but without
  3598. duplicating code. The solution is straightforward if we think at the
  3599. level of x86 assembly: we can label the code for each of the branches
  3600. and insert jumps in all the places that need to execute the
  3601. branches. Put another way, we need to move away from abstract syntax
  3602. \emph{trees} and instead use \emph{graphs}. In particular, we shall
  3603. use a standard program representation called a \emph{control flow
  3604. graph} (CFG), due to Frances Elizabeth \citet{Allen:1970uq}. Each
  3605. vertex is a labeled sequence of code, called a \emph{basic block}, and
  3606. each edge represents a jump to another block. The \key{Program}
  3607. construct of $C_0$ and $C_1$ contains a control flow graph represented
  3608. as an association list mapping labels to basic blocks. Each block is
  3609. represented by the $\Tail$ non-terminal.
  3610. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  3611. \code{remove-complex-opera*} pass and then the
  3612. \code{explicate-control} pass on the example program. We walk through
  3613. the output program and then discuss the algorithm.
  3614. %
  3615. Following the order of evaluation in the output of
  3616. \code{remove-complex-opera*}, we first have the \code{(read)} and
  3617. comparison to \code{1} from the predicate of the inner \key{if}. In
  3618. the output of \code{explicate-control}, in the \code{start} block,
  3619. this becomes a \code{(read)} followed by a conditional goto to either
  3620. \code{block61} or \code{block62}. Each of these contains the
  3621. translations of the code \code{(eq? (read) 0)} and \code{(eq? (read)
  3622. 1)}, respectively. Regarding \code{block61}, we start with the
  3623. \code{(read)} and comparison to \code{0} and then have a conditional
  3624. goto, either to \code{block59} or \code{block60}, which indirectly
  3625. take us to \code{block55} and \code{block56}, the two branches of the
  3626. outer \key{if}, i.e., \code{(+ 10 32)} and \code{(+ 700 77)}. The
  3627. story for \code{block62} is similar.
  3628. \begin{figure}[tbp]
  3629. \begin{tabular}{lll}
  3630. \begin{minipage}{0.4\textwidth}
  3631. \begin{lstlisting}
  3632. (if (if (eq? (read) 1)
  3633. (eq? (read) 0)
  3634. (eq? (read) 2))
  3635. (+ 10 32)
  3636. (+ 700 77))
  3637. \end{lstlisting}
  3638. \hspace{40pt}$\Downarrow$
  3639. \begin{lstlisting}
  3640. (if (if (let ([tmp52 (read)])
  3641. (eq? tmp52 1))
  3642. (let ([tmp53 (read)])
  3643. (eq? tmp53 0))
  3644. (let ([tmp54 (read)])
  3645. (eq? tmp54 2)))
  3646. (+ 10 32)
  3647. (+ 700 77))
  3648. \end{lstlisting}
  3649. \end{minipage}
  3650. &
  3651. $\Rightarrow$
  3652. &
  3653. \begin{minipage}{0.55\textwidth}
  3654. \begin{lstlisting}
  3655. block62:
  3656. tmp54 = (read);
  3657. if (eq? tmp54 2) then
  3658. goto block59;
  3659. else
  3660. goto block60;
  3661. block61:
  3662. tmp53 = (read);
  3663. if (eq? tmp53 0) then
  3664. goto block57;
  3665. else
  3666. goto block58;
  3667. block60:
  3668. goto block56;
  3669. block59:
  3670. goto block55;
  3671. block58:
  3672. goto block56;
  3673. block57:
  3674. goto block55;
  3675. block56:
  3676. return (+ 700 77);
  3677. block55:
  3678. return (+ 10 32);
  3679. start:
  3680. tmp52 = (read);
  3681. if (eq? tmp52 1) then
  3682. goto block61;
  3683. else
  3684. goto block62;
  3685. \end{lstlisting}
  3686. \end{minipage}
  3687. \end{tabular}
  3688. \caption{Example translation from $R_2$ to $C_1$
  3689. via the \code{explicate-control}.}
  3690. \label{fig:explicate-control-s1-38}
  3691. \end{figure}
  3692. The nice thing about the output of \code{explicate-control} is that
  3693. there are no unnecessary uses of \code{eq?} and every use of
  3694. \code{eq?} is part of a conditional jump. The down-side of this output
  3695. is that it includes trivial blocks, such as \code{block57} through
  3696. \code{block60}, that only jump to another block. We discuss a solution
  3697. to this problem in Section~\ref{sec:opt-jumps}.
  3698. Recall that in Section~\ref{sec:explicate-control-r1} we implement
  3699. \code{explicate-control} for $R_1$ using two mutually recursive
  3700. functions, \code{explicate-tail} and \code{explicate-assign}. The
  3701. former function translates expressions in tail position whereas the
  3702. later function translates expressions on the right-hand-side of a
  3703. \key{let}. With the addition of \key{if} expression in $R_2$ we have a
  3704. new kind of context to deal with: the predicate position of the
  3705. \key{if}. We need another function, \code{explicate-pred}, that takes
  3706. an $R_2$ expression and two pieces of $C_1$ code (two $\Tail$'s) for
  3707. the then-branch and else-branch. The output of \code{explicate-pred}
  3708. is a $C_1$ $\Tail$ and a list of formerly \key{let}-bound variables.
  3709. However, these three functions also need to
  3710. construct the control-flow graph, which we recommend they do via
  3711. updates to a global variable (be careful!). Next we consider the
  3712. specific additions to the tail and assign functions, and some of cases
  3713. for the pred function.
  3714. The \code{explicate-tail} function needs an additional case for
  3715. \key{if}. The branches of the \key{if} inherit the current context, so
  3716. they are in tail position. Let $B_1$ be the result of
  3717. \code{explicate-tail} on the ``then'' branch of the \key{if} and $B_2$
  3718. be the result of apply \code{explicate-tail} to the ``else''
  3719. branch. Then the \key{if} as a whole translates to the block $B_3$
  3720. which is the result of applying \code{explicate-pred} to the predicate
  3721. $\itm{cnd}$ and the blocks $B_1$ and $B_2$.
  3722. \[
  3723. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  3724. \]
  3725. Next we consider the case for \key{if} in the \code{explicate-assign}
  3726. function. The context of the \key{if} is an assignment to some
  3727. variable $x$ and then the control continues to some block $B_1$. The
  3728. code that we generate for the $\itm{thn}$ and $\itm{els}$ branches
  3729. needs to continue to $B_1$, so we add $B_1$ to the control flow graph
  3730. with a fresh label $\ell_1$. Again, the branches of the \key{if}
  3731. inherit the current context, so that are in assignment positions. Let
  3732. $B_2$ be the result of applying \code{explicate-assign} to the
  3733. $\itm{thn}$ branch, variable $x$, and the block \GOTO{$\ell_1$}. Let
  3734. $B_3$ be the result of applying \code{explicate-assign} to the
  3735. $\itm{else}$ branch, variable $x$, and the block \GOTO{$\ell_1$}. The
  3736. \key{if} translates to the block $B_4$ which is the result of applying
  3737. \code{explicate-pred} to the predicate $\itm{cnd}$ and the blocks
  3738. $B_2$ and $B_3$.
  3739. \[
  3740. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  3741. \]
  3742. The function \code{explicate-pred} will need a case for every
  3743. expression that can have type \code{Boolean}. We detail a few cases
  3744. here and leave the rest for the reader. The input to this function is
  3745. an expression and two blocks, $B_1$ and $B_2$, for the branches of the
  3746. enclosing \key{if}. Suppose the expression is the Boolean \code{\#t}.
  3747. Then we can perform a kind of partial evaluation and translate it to the
  3748. ``then'' branch $B_1$. Likewise, we translate
  3749. \code{\#f} to the ``else`` branch $B_2$.
  3750. \[
  3751. \key{\#t} \quad\Rightarrow\quad B_1,
  3752. \qquad\qquad\qquad
  3753. \key{\#f} \quad\Rightarrow\quad B_2
  3754. \]
  3755. Next, suppose the
  3756. expression is a less-than comparison. We translate it to a conditional
  3757. goto. We need labels for the two branches $B_1$ and $B_2$, so we add
  3758. those blocks to the control flow graph and obtain some labels $\ell_1$
  3759. and $\ell_2$. The translation of the less-than comparison is as
  3760. follows.
  3761. \[
  3762. (\key{<}~e_1~e_2) \quad\Rightarrow\quad
  3763. \begin{array}{l}
  3764. \key{if}~(\key{<}~e_1~e_2)~\key{then} \\
  3765. \qquad\key{goto}~\ell_1\key{;}\\
  3766. \key{else}\\
  3767. \qquad\key{goto}~\ell_2\key{;}
  3768. \end{array}
  3769. \]
  3770. The case for \key{if} in \code{explicate-pred} is particularly
  3771. illuminating, as it deals with the challenges that we discussed above
  3772. regarding the example of the nested \key{if} expressions. Again, we
  3773. add the two input branches $B_1$ and $B_2$ to the control flow graph
  3774. and obtain the labels $\ell_1$ and $\ell_2$. The branches $\itm{thn}$
  3775. and $\itm{els}$ of the current \key{if} inherit their context from the
  3776. current one, i.e., predicate context. So we apply
  3777. \code{explicate-pred} to $\itm{thn}$ with the two blocks
  3778. \GOTO{$\ell_1$} and \GOTO{$\ell_2$}, to obtain $B_3$.
  3779. Proceed in a similar way with the $\itm{els}$ branch, to obtain $B_4$.
  3780. Finally, we apply \code{explicate-pred} to
  3781. the predicate $\itm{cnd}$ and the blocks $B_3$ and $B_4$
  3782. to obtain the result $B_5$.
  3783. \[
  3784. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  3785. \quad\Rightarrow\quad
  3786. B_5
  3787. \]
  3788. \begin{exercise}\normalfont
  3789. Implement the pass \code{explicate-control} by adding the cases for
  3790. \key{if} to the functions for tail and assignment contexts, and
  3791. implement \code{explicate-pred} for predicate contexts. Create test
  3792. cases that exercise all of the new cases in the code for this pass.
  3793. \end{exercise}
  3794. \section{Select Instructions}
  3795. \label{sec:select-r2}
  3796. Recall that the \code{select-instructions} pass lowers from our
  3797. $C$-like intermediate representation to the pseudo-x86 language, which
  3798. is suitable for conducting register allocation. The pass is
  3799. implemented using three auxiliary functions, one for each of the
  3800. non-terminals $\Atm$, $\Stmt$, and $\Tail$.
  3801. For $\Atm$, we have new cases for the Booleans. We take the usual
  3802. approach of encoding them as integers, with true as 1 and false as 0.
  3803. \[
  3804. \key{\#t} \Rightarrow \key{1}
  3805. \qquad
  3806. \key{\#f} \Rightarrow \key{0}
  3807. \]
  3808. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  3809. be implemented in terms of \code{xorq} as we discussed at the
  3810. beginning of this section. Given an assignment
  3811. $\itm{lhs}$ \key{=} \key{(not} $\Arg$\key{);},
  3812. if the left-hand side $\itm{lhs}$ is
  3813. the same as $\Arg$, then just the \code{xorq} suffices.
  3814. \[
  3815. x~\key{=}~ \key{(not}\; x\key{);}
  3816. \quad\Rightarrow\quad
  3817. \key{xorq}~\key{\$}1\key{,}~x
  3818. \]
  3819. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  3820. semantics of x86. Let $\Arg'$ be the result of recursively processing
  3821. $\Arg$. Then we have
  3822. \[
  3823. \itm{lhs}~\key{=}~ \key{(not}\; \Arg\key{);}
  3824. \quad\Rightarrow\quad
  3825. \begin{array}{l}
  3826. \key{movq}~\Arg'\key{,}~\itm{lhs}\\
  3827. \key{xorq}~\key{\$}1\key{,}~\itm{lhs}
  3828. \end{array}
  3829. \]
  3830. Next consider the cases for \code{eq?} and less-than comparison.
  3831. Translating these operations to x86 is slightly involved due to the
  3832. unusual nature of the \key{cmpq} instruction discussed above. We
  3833. recommend translating an assignment from \code{eq?} into the following
  3834. sequence of three instructions. \\
  3835. \begin{tabular}{lll}
  3836. \begin{minipage}{0.4\textwidth}
  3837. \begin{lstlisting}
  3838. |$\itm{lhs}$| = (eq? |$\Arg_1$| |$\Arg_2$|);
  3839. \end{lstlisting}
  3840. \end{minipage}
  3841. &
  3842. $\Rightarrow$
  3843. &
  3844. \begin{minipage}{0.4\textwidth}
  3845. \begin{lstlisting}
  3846. cmpq |$\Arg'_2$|, |$\Arg'_1$|
  3847. sete %al
  3848. movzbq %al, |$\itm{lhs}'$|
  3849. \end{lstlisting}
  3850. \end{minipage}
  3851. \end{tabular} \\
  3852. Regarding the $\Tail$ non-terminal, we have two new cases, for
  3853. \key{goto} and conditional \key{goto}. Both are straightforward
  3854. to handle. A \key{goto} becomes a jump instruction.
  3855. \[
  3856. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  3857. \]
  3858. A conditional \key{goto} becomes a compare instruction followed
  3859. by a conditional jump (for ``then'') and the fall-through is
  3860. to a regular jump (for ``else'').\\
  3861. \begin{tabular}{lll}
  3862. \begin{minipage}{0.4\textwidth}
  3863. \begin{lstlisting}
  3864. if (eq? |$\Arg_1$| |$\Arg_2$|) then
  3865. goto |$\ell_1$|;
  3866. else
  3867. goto |$\ell_2$|;
  3868. \end{lstlisting}
  3869. \end{minipage}
  3870. &
  3871. $\Rightarrow$
  3872. &
  3873. \begin{minipage}{0.4\textwidth}
  3874. \begin{lstlisting}
  3875. cmpq |$\Arg'_2$| |$\Arg'_1$|
  3876. je |$\ell_1$|
  3877. jmp |$\ell_2$|
  3878. \end{lstlisting}
  3879. \end{minipage}
  3880. \end{tabular} \\
  3881. \begin{exercise}\normalfont
  3882. Expand your \code{select-instructions} pass to handle the new features
  3883. of the $R_2$ language. Test the pass on all the examples you have
  3884. created and make sure that you have some test programs that use the
  3885. \code{eq?} and \code{<} operators, creating some if necessary. Test
  3886. the output using the \code{interp-x86} interpreter
  3887. (Appendix~\ref{appendix:interp}).
  3888. \end{exercise}
  3889. \section{Register Allocation}
  3890. \label{sec:register-allocation-r2}
  3891. The changes required for $R_2$ affect liveness analysis, building the
  3892. interference graph, and assigning homes, but the graph coloring
  3893. algorithm itself does not change.
  3894. \subsection{Liveness Analysis}
  3895. \label{sec:liveness-analysis-r2}
  3896. Recall that for $R_1$ we implemented liveness analysis for a single
  3897. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  3898. addition of \key{if} expressions to $R_2$, \code{explicate-control}
  3899. now produces many basic blocks arranged in a control-flow graph. The
  3900. first question we need to consider is: what order should we process
  3901. the basic blocks? Recall that to perform liveness analysis, we need to
  3902. know the live-after set. If a basic block has no successor blocks
  3903. (i.e. no out-edges in the control flow graph), then it has an empty
  3904. live-after set and we can immediately apply liveness analysis to
  3905. it. If a basic block has some successors, then we need to complete
  3906. liveness analysis on those blocks first. Furthermore, we know that
  3907. the control flow graph does not contain any cycles (it is a DAG, that
  3908. is, a directed acyclic graph)\footnote{If we were to add loops to the
  3909. language, then the CFG could contain cycles and we would instead
  3910. need to use the classic worklist algorithm for computing the fixed
  3911. point of the liveness analysis~\citep{Aho:1986qf}.}. Returning to
  3912. the question of what order should we process the basic blocks: the
  3913. answer is reverse topological order. We recommend using the
  3914. \code{tsort} (topological sort) and \code{transpose} functions of the
  3915. Racket \code{graph} package to obtain this ordering.
  3916. The next question is how to compute the live-after set of a block
  3917. given the live-before sets of all its successor blocks. During
  3918. compilation we do not know which way the branch will go, so we do not
  3919. know which of the successor's live-before set to use. The solution
  3920. comes from the observation that there is no harm to the correctness of
  3921. the compiler if we classify more variables as live than the ones that
  3922. are truly live during program execution. Thus, we can take the union
  3923. of the live-before sets from all the successors to be the live-after
  3924. set for the block. Once we have computed the live-after set, we can
  3925. proceed to perform liveness analysis on the block just as we did in
  3926. Section~\ref{sec:liveness-analysis-r1}.
  3927. The helper functions for computing the variables in an instruction's
  3928. argument and for computing the variables read-from ($R$) or written-to
  3929. ($W$) by an instruction need to be updated to handle the new kinds of
  3930. arguments and instructions in x86$_1$.
  3931. \subsection{Build Interference}
  3932. \label{sec:build-interference-r2}
  3933. Many of the new instructions in x86$_1$ can be handled in the same way
  3934. as the instructions in x86$_0$. Thus, if your code was already quite
  3935. general, it will not need to be changed to handle the new
  3936. instructions. If not, I recommend that you change your code to be more
  3937. general. The \key{movzbq} instruction should be handled like the
  3938. \key{movq} instruction.
  3939. %% \subsection{Assign Homes}
  3940. %% \label{sec:assign-homes-r2}
  3941. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  3942. %% to be updated to handle the \key{if} statement, simply by recursively
  3943. %% processing the child nodes. Hopefully your code already handles the
  3944. %% other new instructions, but if not, you can generalize your code.
  3945. \begin{exercise}\normalfont
  3946. Update the \code{register-allocation} pass so that it works for $R_2$
  3947. and test your compiler using your previously created programs on the
  3948. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  3949. \end{exercise}
  3950. \section{Patch Instructions}
  3951. The second argument of the \key{cmpq} instruction must not be an
  3952. immediate value (such as an integer). So if you are comparing two
  3953. immediates, we recommend inserting a \key{movq} instruction to put the
  3954. second argument in \key{rax}.
  3955. %
  3956. The second argument of the \key{movzbq} must be a register.
  3957. %
  3958. There are no special restrictions on the x86 instructions \key{JmpIf}
  3959. and \key{Jmp}.
  3960. \begin{exercise}\normalfont
  3961. Update \code{patch-instructions} to handle the new x86 instructions.
  3962. Test your compiler using your previously created programs on the
  3963. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  3964. \end{exercise}
  3965. \section{An Example Translation}
  3966. Figure~\ref{fig:if-example-x86} shows a simple example program in
  3967. $R_2$ translated to x86, showing the results of
  3968. \code{explicate-control}, \code{select-instructions}, and the final
  3969. x86 assembly code.
  3970. \begin{figure}[tbp]
  3971. \begin{tabular}{lll}
  3972. \begin{minipage}{0.5\textwidth}
  3973. % s1_20.rkt
  3974. \begin{lstlisting}
  3975. (if (eq? (read) 1) 42 0)
  3976. \end{lstlisting}
  3977. $\Downarrow$
  3978. \begin{lstlisting}
  3979. start:
  3980. tmp7951 = (read);
  3981. if (eq? tmp7951 1) then
  3982. goto block7952;
  3983. else
  3984. goto block7953;
  3985. block7952:
  3986. return 42;
  3987. block7953:
  3988. return 0;
  3989. \end{lstlisting}
  3990. $\Downarrow$
  3991. \begin{lstlisting}
  3992. start:
  3993. callq read_int
  3994. movq %rax, tmp7951
  3995. cmpq $1, tmp7951
  3996. je block7952
  3997. jmp block7953
  3998. block7953:
  3999. movq $0, %rax
  4000. jmp conclusion
  4001. block7952:
  4002. movq $42, %rax
  4003. jmp conclusion
  4004. \end{lstlisting}
  4005. \end{minipage}
  4006. &
  4007. $\Rightarrow\qquad$
  4008. \begin{minipage}{0.4\textwidth}
  4009. \begin{lstlisting}
  4010. start:
  4011. callq read_int
  4012. movq %rax, %rcx
  4013. cmpq $1, %rcx
  4014. je block7952
  4015. jmp block7953
  4016. block7953:
  4017. movq $0, %rax
  4018. jmp conclusion
  4019. block7952:
  4020. movq $42, %rax
  4021. jmp conclusion
  4022. .globl main
  4023. main:
  4024. pushq %rbp
  4025. movq %rsp, %rbp
  4026. pushq %r13
  4027. pushq %r12
  4028. pushq %rbx
  4029. pushq %r14
  4030. subq $0, %rsp
  4031. jmp start
  4032. conclusion:
  4033. addq $0, %rsp
  4034. popq %r14
  4035. popq %rbx
  4036. popq %r12
  4037. popq %r13
  4038. popq %rbp
  4039. retq
  4040. \end{lstlisting}
  4041. \end{minipage}
  4042. \end{tabular}
  4043. \caption{Example compilation of an \key{if} expression to x86.}
  4044. \label{fig:if-example-x86}
  4045. \end{figure}
  4046. \begin{figure}[p]
  4047. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4048. \node (R2) at (0,2) {\large $R_2$};
  4049. \node (R2-2) at (3,2) {\large $R_2$};
  4050. \node (R2-3) at (6,2) {\large $R_2$};
  4051. \node (R2-4) at (9,2) {\large $R_2$};
  4052. \node (R2-5) at (12,2) {\large $R_2$};
  4053. \node (C1-1) at (6,0) {\large $C_1$};
  4054. %\node (C1-2) at (3,0) {\large $C_1$};
  4055. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  4056. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  4057. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}$};
  4058. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}$};
  4059. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  4060. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  4061. \path[->,bend left=15] (R2) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R2-2);
  4062. \path[->,bend left=15] (R2-2) edge [above] node {\ttfamily\footnotesize\color{red} shrink} (R2-3);
  4063. \path[->,bend left=15] (R2-3) edge [above] node {\ttfamily\footnotesize uniquify} (R2-4);
  4064. \path[->,bend left=15] (R2-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R2-5);
  4065. \path[->,bend left=15] (R2-5) edge [right] node {\ttfamily\footnotesize\color{red} explicate-control} (C1-1);
  4066. %\path[->,bend right=15] (C1-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C1-2);
  4067. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize\color{red} select-instructions} (x86-2);
  4068. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  4069. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  4070. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4071. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  4072. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize\color{red} print-x86 } (x86-5);
  4073. \end{tikzpicture}
  4074. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  4075. \label{fig:R2-passes}
  4076. \end{figure}
  4077. Figure~\ref{fig:R2-passes} lists all the passes needed for the
  4078. compilation of $R_2$.
  4079. \section{Challenge: Optimize Jumps}
  4080. \label{sec:opt-jumps}
  4081. Recall that in the example output of \code{explicate-control} in
  4082. Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  4083. \code{block60} are trivial blocks, they do nothing but jump to another
  4084. block. The first goal of this challenge assignment is to remove those
  4085. blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  4086. \code{explicate-control} on the left and shows the result of bypassing
  4087. the trivial blocks on the right. Let us focus on \code{block61}. The
  4088. \code{then} branch jumps to \code{block57}, which in turn jumps to
  4089. \code{block55}. The optimized code on the right of
  4090. Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  4091. \code{then} branch jumping directly to \code{block55}. The story is
  4092. similar for the \code{else} branch, as well as for the two branchs in
  4093. \code{block62}. After the jumps in \code{block61} and \code{block62}
  4094. have been optimized in this way, there are no longer any jumps to
  4095. blocks \code{block57} through \code{block60}, so they can be removed.
  4096. \begin{figure}[tbp]
  4097. \begin{tabular}{lll}
  4098. \begin{minipage}{0.4\textwidth}
  4099. \begin{lstlisting}
  4100. block62:
  4101. tmp54 = (read);
  4102. if (eq? tmp54 2) then
  4103. goto block59;
  4104. else
  4105. goto block60;
  4106. block61:
  4107. tmp53 = (read);
  4108. if (eq? tmp53 0) then
  4109. goto block57;
  4110. else
  4111. goto block58;
  4112. block60:
  4113. goto block56;
  4114. block59:
  4115. goto block55;
  4116. block58:
  4117. goto block56;
  4118. block57:
  4119. goto block55;
  4120. block56:
  4121. return (+ 700 77);
  4122. block55:
  4123. return (+ 10 32);
  4124. start:
  4125. tmp52 = (read);
  4126. if (eq? tmp52 1) then
  4127. goto block61;
  4128. else
  4129. goto block62;
  4130. \end{lstlisting}
  4131. \end{minipage}
  4132. &
  4133. $\Rightarrow$
  4134. &
  4135. \begin{minipage}{0.55\textwidth}
  4136. \begin{lstlisting}
  4137. block62:
  4138. tmp54 = (read);
  4139. if (eq? tmp54 2) then
  4140. goto block55;
  4141. else
  4142. goto block56;
  4143. block61:
  4144. tmp53 = (read);
  4145. if (eq? tmp53 0) then
  4146. goto block55;
  4147. else
  4148. goto block56;
  4149. block56:
  4150. return (+ 700 77);
  4151. block55:
  4152. return (+ 10 32);
  4153. start:
  4154. tmp52 = (read);
  4155. if (eq? tmp52 1) then
  4156. goto block61;
  4157. else
  4158. goto block62;
  4159. \end{lstlisting}
  4160. \end{minipage}
  4161. \end{tabular}
  4162. \caption{Optimize jumps by removing trivial blocks.}
  4163. \label{fig:optimize-jumps}
  4164. \end{figure}
  4165. The name of this pass is \code{optimize-jumps}. We recommend
  4166. implementing this pass in two phases. The first phrase builds a hash
  4167. table that maps labels to possibly improved labels. The second phase
  4168. changes the target of each \code{goto} to use the improved label. If
  4169. the label is for a trivial block, then the hash table should map the
  4170. label to the first non-trivial block that can be reached from this
  4171. label by jumping through trivial blocks. If the label is for a
  4172. non-trivial block, then the hash table should map the label to itself;
  4173. we do not want to change jumps to non-trivial blocks.
  4174. The first phase can be accomplished by constructing an empty hash
  4175. table, call it \code{short-cut}, and then iterating over the control
  4176. flow graph. Each time you encouter a block that is just a \code{goto},
  4177. then update the hash table, mapping the block's source to the target
  4178. of the \code{goto}. Also, the hash table may already have mapped some
  4179. labels to the block's source, to you must iterate through the hash
  4180. table and update all of those so that they instead map to the target
  4181. of the \code{goto}.
  4182. For the second phase, we recommend iterating through the $\Tail$ of
  4183. each block in the program, updating the target of every \code{goto}
  4184. according to the mapping in \code{short-cut}.
  4185. \begin{exercise}\normalfont
  4186. Implement the \code{optimize-jumps} pass and check that it remove
  4187. trivial blocks in a few example programs. Then check that your
  4188. compiler still passes all of your tests.
  4189. \end{exercise}
  4190. There is another opportunity for optimizing jumps that is apparent in
  4191. the example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  4192. end with a jump to \code{block7953} and there are no other jumps to
  4193. \code{block7953} in the rest of the program. In this situation we can
  4194. avoid the runtime overhead of this jump by merging \code{block7953}
  4195. into the preceeding block, in this case the \code{start} block.
  4196. Figure~\ref{fig:remove-jumps} shows the output of
  4197. \code{select-instructions} on the left and the result of this
  4198. optimization on the right.
  4199. \begin{figure}[tbp]
  4200. \begin{tabular}{lll}
  4201. \begin{minipage}{0.5\textwidth}
  4202. % s1_20.rkt
  4203. \begin{lstlisting}
  4204. start:
  4205. callq read_int
  4206. movq %rax, tmp7951
  4207. cmpq $1, tmp7951
  4208. je block7952
  4209. jmp block7953
  4210. block7953:
  4211. movq $0, %rax
  4212. jmp conclusion
  4213. block7952:
  4214. movq $42, %rax
  4215. jmp conclusion
  4216. \end{lstlisting}
  4217. \end{minipage}
  4218. &
  4219. $\Rightarrow\qquad$
  4220. \begin{minipage}{0.4\textwidth}
  4221. \begin{lstlisting}
  4222. start:
  4223. callq read_int
  4224. movq %rax, tmp7951
  4225. cmpq $1, tmp7951
  4226. je block7952
  4227. movq $0, %rax
  4228. jmp conclusion
  4229. block7952:
  4230. movq $42, %rax
  4231. jmp conclusion
  4232. \end{lstlisting}
  4233. \end{minipage}
  4234. \end{tabular}
  4235. \caption{Merging basic blocks by removing unnecessary jumps.}
  4236. \label{fig:remove-jumps}
  4237. \end{figure}
  4238. \begin{exercise}\normalfont
  4239. Implement a pass named \code{remove-jumps} that merges basic blocks
  4240. into their preceeding basic block, when there is only one preceeding
  4241. block. Check that your pass accomplishes this goal on several test
  4242. programs and check that your compiler passes all of your tests.
  4243. \end{exercise}
  4244. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4245. \chapter{Tuples and Garbage Collection}
  4246. \label{ch:tuples}
  4247. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  4248. things to discuss in this chapter. \\ --Jeremy}
  4249. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  4250. all the IR grammars are spelled out! \\ --Jeremy}
  4251. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  4252. but keep type annotations on vector creation and local variables, function
  4253. parameters, etc. \\ --Jeremy}
  4254. \margincomment{\scriptsize Be more explicit about how to deal with
  4255. the root stack. \\ --Jeremy}
  4256. In this chapter we study the implementation of mutable tuples (called
  4257. ``vectors'' in Racket). This language feature is the first to use the
  4258. computer's \emph{heap} because the lifetime of a Racket tuple is
  4259. indefinite, that is, a tuple lives forever from the programmer's
  4260. viewpoint. Of course, from an implementer's viewpoint, it is important
  4261. to reclaim the space associated with a tuple when it is no longer
  4262. needed, which is why we also study \emph{garbage collection}
  4263. techniques in this chapter.
  4264. Section~\ref{sec:r3} introduces the $R_3$ language including its
  4265. interpreter and type checker. The $R_3$ language extends the $R_2$
  4266. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  4267. \code{void} value. The reason for including the later is that the
  4268. \code{vector-set!} operation returns a value of type
  4269. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  4270. called the \code{Unit} type in the programming languages
  4271. literature. Racket's \code{Void} type is inhabited by a single value
  4272. \code{void} which corresponds to \code{unit} or \code{()} in the
  4273. literature~\citep{Pierce:2002hj}.}.
  4274. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  4275. copying live objects back and forth between two halves of the
  4276. heap. The garbage collector requires coordination with the compiler so
  4277. that it can see all of the \emph{root} pointers, that is, pointers in
  4278. registers or on the procedure call stack.
  4279. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  4280. discuss all the necessary changes and additions to the compiler
  4281. passes, including a new compiler pass named \code{expose-allocation}.
  4282. \section{The $R_3$ Language}
  4283. \label{sec:r3}
  4284. Figure~\ref{fig:r3-concrete-syntax} defines the concrete syntax for
  4285. $R_3$ and Figure~\ref{fig:r3-syntax} defines the abstract syntax. The
  4286. $R_3$ language includes three new forms for creating a tuple, reading
  4287. an element of a tuple, and writing to an element of a tuple. The
  4288. program in Figure~\ref{fig:vector-eg} shows the usage of tuples in
  4289. Racket. We create a 3-tuple \code{t} and a 1-tuple. The 1-tuple is
  4290. stored at index $2$ of the 3-tuple, demonstrating that tuples are
  4291. first-class values. The element at index $1$ of \code{t} is
  4292. \code{\#t}, so the ``then'' branch of the \key{if} is taken. The
  4293. element at index $0$ of \code{t} is $40$, to which we add $2$, the
  4294. element at index $0$ of the 1-tuple. So the result of the program is
  4295. $42$.
  4296. \begin{figure}[tbp]
  4297. \begin{lstlisting}
  4298. (let ([t (vector 40 #t (vector 2))])
  4299. (if (vector-ref t 1)
  4300. (+ (vector-ref t 0)
  4301. (vector-ref (vector-ref t 2) 0))
  4302. 44))
  4303. \end{lstlisting}
  4304. \caption{Example program that creates tuples and reads from them.}
  4305. \label{fig:vector-eg}
  4306. \end{figure}
  4307. \begin{figure}[tbp]
  4308. \centering
  4309. \fbox{
  4310. \begin{minipage}{0.96\textwidth}
  4311. \[
  4312. \begin{array}{lcl}
  4313. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  4314. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}\\
  4315. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  4316. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  4317. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  4318. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  4319. \mid (\key{and}\;\Exp\;\Exp)
  4320. \mid (\key{or}\;\Exp\;\Exp)
  4321. \mid (\key{not}\;\Exp) } \\
  4322. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  4323. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  4324. &\mid& (\key{vector}\;\Exp^{+})
  4325. \mid (\key{vector-ref}\;\Exp\;\Int) \\
  4326. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)\\
  4327. &\mid& (\key{void}) \\
  4328. R_3 &::=& \Exp
  4329. \end{array}
  4330. \]
  4331. \end{minipage}
  4332. }
  4333. \caption{The concrete syntax of $R_3$, extending $R_2$
  4334. (Figure~\ref{fig:r2-concrete-syntax}).}
  4335. \label{fig:r3-concrete-syntax}
  4336. \end{figure}
  4337. \begin{figure}[tp]
  4338. \centering
  4339. \fbox{
  4340. \begin{minipage}{0.96\textwidth}
  4341. \[
  4342. \begin{array}{lcl}
  4343. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  4344. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  4345. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  4346. &\mid& \gray{ \ADD{\Exp}{\Exp}
  4347. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  4348. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  4349. &\mid& \gray{ \BOOL{\itm{bool}}
  4350. \mid \AND{\Exp}{\Exp} }\\
  4351. &\mid& \gray{ \OR{\Exp}{\Exp}
  4352. \mid \NOT{\Exp} } \\
  4353. &\mid& \gray{ \BINOP{\code{'}\itm{cmp}}{\Exp}{\Exp}
  4354. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  4355. &\mid& \VECTOR{\Exp} \\
  4356. &\mid& \VECREF{\Exp}{\Int}\\
  4357. &\mid& \VECSET{\Exp}{\Int}{\Exp}\\
  4358. &\mid& \VOID{} \\
  4359. R_3 &::=& \PROGRAM{\key{'()}}{\Exp}
  4360. \end{array}
  4361. \]
  4362. \end{minipage}
  4363. }
  4364. \caption{The abstract syntax of $R_3$.}
  4365. \label{fig:r3-syntax}
  4366. \end{figure}
  4367. Tuples are our first encounter with heap-allocated data, which raises
  4368. several interesting issues. First, variable binding performs a
  4369. shallow-copy when dealing with tuples, which means that different
  4370. variables can refer to the same tuple, i.e., different variables can
  4371. be \emph{aliases} for the same thing. Consider the following example
  4372. in which both \code{t1} and \code{t2} refer to the same tuple. Thus,
  4373. the mutation through \code{t2} is visible when referencing the tuple
  4374. from \code{t1}, so the result of this program is \code{42}.
  4375. \begin{center}
  4376. \begin{minipage}{0.96\textwidth}
  4377. \begin{lstlisting}
  4378. (let ([t1 (vector 3 7)])
  4379. (let ([t2 t1])
  4380. (let ([_ (vector-set! t2 0 42)])
  4381. (vector-ref t1 0))))
  4382. \end{lstlisting}
  4383. \end{minipage}
  4384. \end{center}
  4385. The next issue concerns the lifetime of tuples. Of course, they are
  4386. created by the \code{vector} form, but when does their lifetime end?
  4387. Notice that the grammar in Figure~\ref{fig:r3-syntax} does not include
  4388. an operation for deleting tuples. Furthermore, the lifetime of a tuple
  4389. is not tied to any notion of static scoping. For example, the
  4390. following program returns \code{3} even though the variable \code{t}
  4391. goes out of scope prior to accessing the vector.
  4392. \begin{center}
  4393. \begin{minipage}{0.96\textwidth}
  4394. \begin{lstlisting}
  4395. (vector-ref
  4396. (let ([t (vector 3 7)])
  4397. t)
  4398. 0)
  4399. \end{lstlisting}
  4400. \end{minipage}
  4401. \end{center}
  4402. From the perspective of programmer-observable behavior, tuples live
  4403. forever. Of course, if they really lived forever, then many programs
  4404. would run out of memory.\footnote{The $R_3$ language does not have
  4405. looping or recursive function, so it is nigh impossible to write a
  4406. program in $R_3$ that will run out of memory. However, we add
  4407. recursive functions in the next Chapter!} A Racket implementation
  4408. must therefore perform automatic garbage collection.
  4409. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  4410. $R_3$ language. We define the \code{vector}, \code{vector-ref}, and
  4411. \code{vector-set!} operations for $R_3$ in terms of the corresponding
  4412. operations in Racket. One subtle point is that the \code{vector-set!}
  4413. operation returns the \code{\#<void>} value. The \code{\#<void>} value
  4414. can be passed around just like other values inside an $R_3$ program,
  4415. but there are no operations specific to the the \code{\#<void>} value
  4416. in $R_3$. In contrast, Racket defines the \code{void?} predicate that
  4417. returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  4418. otherwise.
  4419. \begin{figure}[tbp]
  4420. \begin{lstlisting}
  4421. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  4422. (define (interp-op op)
  4423. (match op
  4424. ...
  4425. ['vector vector]
  4426. ['vector-ref vector-ref]
  4427. ['vector-set! vector-set!]
  4428. [else (error 'interp-op "unknown operator")]))
  4429. (define (interp-R3 env)
  4430. (lambda (e)
  4431. (match e
  4432. ...
  4433. [else (error 'interp-R3 "unrecognized expression")]
  4434. )))
  4435. \end{lstlisting}
  4436. \caption{Interpreter for the $R_3$ language.}
  4437. \label{fig:interp-R3}
  4438. \end{figure}
  4439. Figure~\ref{fig:typecheck-R3} shows the type checker for $R_3$, which
  4440. deserves some explanation. As we shall see in Section~\ref{sec:GC}, we
  4441. need to know which variables are pointers into the heap, that is,
  4442. which variables are vectors. Also, when allocating a vector, we need
  4443. to know which elements of the vector are pointers. We can obtain this
  4444. information during type checking. The type checker in
  4445. Figure~\ref{fig:typecheck-R3} not only computes the type of an
  4446. expression, it also wraps every sub-expression $e$ with the form
  4447. $(\key{HasType}~e~T)$, where $T$ is $e$'s type.
  4448. % TODO: UPDATE? -Jeremy
  4449. Subsequently, in the \code{uncover-locals} pass
  4450. (Section~\ref{sec:uncover-locals-r3}) this type information is
  4451. propagated to all variables (including the temporaries generated by
  4452. \code{remove-complex-opera*}).
  4453. \begin{figure}[tbp]
  4454. \begin{lstlisting}
  4455. (define (type-check-exp env)
  4456. (lambda (e)
  4457. (define recur (type-check-exp env))
  4458. (match e
  4459. ...
  4460. [(Void) (values (HasType (Void) 'Void) 'Void)]
  4461. [(Prim 'vector es)
  4462. (define-values (e* t*) (for/lists (e* t*) ([e es])
  4463. (recur e)))
  4464. (let ([t `(Vector ,@t*)])
  4465. (values (HasType (Prim 'vector e*) t) t))]
  4466. [(Prim 'vector-ref (list e (Int i)))
  4467. (define-values (e^ t) (recur e))
  4468. (match t
  4469. [`(Vector ,ts ...)
  4470. (unless (and (exact-nonnegative-integer? i) (< i (length ts)))
  4471. (error 'type-check-exp "invalid index ~a" i))
  4472. (let ([t (list-ref ts i)])
  4473. (values
  4474. (HasType (Prim 'vector-ref (list e^ (HasType (Int i) 'Integer))) t)
  4475. t))]
  4476. [else (error "expected a vector in vector-ref, not" t)])]
  4477. [(Prim 'eq? (list e1 e2))
  4478. (define-values (e1^ T1) (recur e1))
  4479. (define-values (e2^ T2) (recur e2))
  4480. (unless (equal? T1 T2)
  4481. (error "arguments of eq? must have the same type, but are not"
  4482. (list T1 T2)))
  4483. (values (HasType (Prim 'eq? (list e1^ e2^)) 'Boolean) 'Boolean)]
  4484. ...
  4485. )))
  4486. \end{lstlisting}
  4487. \caption{Type checker for the $R_3$ language.}
  4488. \label{fig:typecheck-R3}
  4489. \end{figure}
  4490. \section{Garbage Collection}
  4491. \label{sec:GC}
  4492. Here we study a relatively simple algorithm for garbage collection
  4493. that is the basis of state-of-the-art garbage
  4494. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  4495. particular, we describe a two-space copying
  4496. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  4497. perform the
  4498. copy~\citep{Cheney:1970aa}. Figure~\ref{fig:copying-collector} gives a
  4499. coarse-grained depiction of what happens in a two-space collector,
  4500. showing two time steps, prior to garbage collection on the top and
  4501. after garbage collection on the bottom. In a two-space collector, the
  4502. heap is divided into two parts, the FromSpace and the
  4503. ToSpace. Initially, all allocations go to the FromSpace until there is
  4504. not enough room for the next allocation request. At that point, the
  4505. garbage collector goes to work to make more room.
  4506. The garbage collector must be careful not to reclaim tuples that will
  4507. be used by the program in the future. Of course, it is impossible in
  4508. general to predict what a program will do, but we can over approximate
  4509. the will-be-used tuples by preserving all tuples that could be
  4510. accessed by \emph{any} program given the current computer state. A
  4511. program could access any tuple whose address is in a register or on
  4512. the procedure call stack. These addresses are called the \emph{root
  4513. set}. In addition, a program could access any tuple that is
  4514. transitively reachable from the root set. Thus, it is safe for the
  4515. garbage collector to reclaim the tuples that are not reachable in this
  4516. way.
  4517. So the goal of the garbage collector is twofold:
  4518. \begin{enumerate}
  4519. \item preserve all tuple that are reachable from the root set via a
  4520. path of pointers, that is, the \emph{live} tuples, and
  4521. \item reclaim the memory of everything else, that is, the
  4522. \emph{garbage}.
  4523. \end{enumerate}
  4524. A copying collector accomplishes this by copying all of the live
  4525. objects from the FromSpace into the ToSpace and then performs a slight
  4526. of hand, treating the ToSpace as the new FromSpace and the old
  4527. FromSpace as the new ToSpace. In the example of
  4528. Figure~\ref{fig:copying-collector}, there are three pointers in the
  4529. root set, one in a register and two on the stack. All of the live
  4530. objects have been copied to the ToSpace (the right-hand side of
  4531. Figure~\ref{fig:copying-collector}) in a way that preserves the
  4532. pointer relationships. For example, the pointer in the register still
  4533. points to a 2-tuple whose first element is a 3-tuple and second
  4534. element is a 2-tuple. There are four tuples that are not reachable
  4535. from the root set and therefore do not get copied into the ToSpace.
  4536. (The situation in Figure~\ref{fig:copying-collector}, with a
  4537. cycle, cannot be created by a well-typed program in $R_3$. However,
  4538. creating cycles will be possible once we get to $R_6$. We design
  4539. the garbage collector to deal with cycles to begin with, so we will
  4540. not need to revisit this issue.)
  4541. \begin{figure}[tbp]
  4542. \centering
  4543. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  4544. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  4545. \caption{A copying collector in action.}
  4546. \label{fig:copying-collector}
  4547. \end{figure}
  4548. There are many alternatives to copying collectors (and their older
  4549. siblings, the generational collectors) when its comes to garbage
  4550. collection, such as mark-and-sweep and reference counting. The
  4551. strengths of copying collectors are that allocation is fast (just a
  4552. test and pointer increment), there is no fragmentation, cyclic garbage
  4553. is collected, and the time complexity of collection only depends on
  4554. the amount of live data, and not on the amount of
  4555. garbage~\citep{Wilson:1992fk}. The main disadvantage of two-space
  4556. copying collectors is that they use a lot of space, though that
  4557. problem is ameliorated in generational collectors. Racket and Scheme
  4558. programs tend to allocate many small objects and generate a lot of
  4559. garbage, so copying and generational collectors are a good fit. Of
  4560. course, garbage collection is an active research topic, especially
  4561. concurrent garbage collection~\citep{Tene:2011kx}. Researchers are
  4562. continuously developing new techniques and revisiting old
  4563. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa}.
  4564. \subsection{Graph Copying via Cheney's Algorithm}
  4565. \label{sec:cheney}
  4566. Let us take a closer look at how the copy works. The allocated objects
  4567. and pointers can be viewed as a graph and we need to copy the part of
  4568. the graph that is reachable from the root set. To make sure we copy
  4569. all of the reachable vertices in the graph, we need an exhaustive
  4570. graph traversal algorithm, such as depth-first search or breadth-first
  4571. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  4572. take into account the possibility of cycles by marking which vertices
  4573. have already been visited, so as to ensure termination of the
  4574. algorithm. These search algorithms also use a data structure such as a
  4575. stack or queue as a to-do list to keep track of the vertices that need
  4576. to be visited. We shall use breadth-first search and a trick due to
  4577. \citet{Cheney:1970aa} for simultaneously representing the queue and
  4578. copying tuples into the ToSpace.
  4579. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  4580. copy progresses. The queue is represented by a chunk of contiguous
  4581. memory at the beginning of the ToSpace, using two pointers to track
  4582. the front and the back of the queue. The algorithm starts by copying
  4583. all tuples that are immediately reachable from the root set into the
  4584. ToSpace to form the initial queue. When we copy a tuple, we mark the
  4585. old tuple to indicate that it has been visited. (We discuss the
  4586. marking in Section~\ref{sec:data-rep-gc}.) Note that any pointers
  4587. inside the copied tuples in the queue still point back to the
  4588. FromSpace. Once the initial queue has been created, the algorithm
  4589. enters a loop in which it repeatedly processes the tuple at the front
  4590. of the queue and pops it off the queue. To process a tuple, the
  4591. algorithm copies all the tuple that are directly reachable from it to
  4592. the ToSpace, placing them at the back of the queue. The algorithm then
  4593. updates the pointers in the popped tuple so they point to the newly
  4594. copied tuples. Getting back to Figure~\ref{fig:cheney}, in the first
  4595. step we copy the tuple whose second element is $42$ to the back of the
  4596. queue. The other pointer goes to a tuple that has already been copied,
  4597. so we do not need to copy it again, but we do need to update the
  4598. pointer to the new location. This can be accomplished by storing a
  4599. \emph{forwarding} pointer to the new location in the old tuple, back
  4600. when we initially copied the tuple into the ToSpace. This completes
  4601. one step of the algorithm. The algorithm continues in this way until
  4602. the front of the queue is empty, that is, until the front catches up
  4603. with the back.
  4604. \begin{figure}[tbp]
  4605. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  4606. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  4607. \label{fig:cheney}
  4608. \end{figure}
  4609. \subsection{Data Representation}
  4610. \label{sec:data-rep-gc}
  4611. The garbage collector places some requirements on the data
  4612. representations used by our compiler. First, the garbage collector
  4613. needs to distinguish between pointers and other kinds of data. There
  4614. are several ways to accomplish this.
  4615. \begin{enumerate}
  4616. \item Attached a tag to each object that identifies what type of
  4617. object it is~\citep{McCarthy:1960dz}.
  4618. \item Store different types of objects in different
  4619. regions~\citep{Steele:1977ab}.
  4620. \item Use type information from the program to either generate
  4621. type-specific code for collecting or to generate tables that can
  4622. guide the
  4623. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  4624. \end{enumerate}
  4625. Dynamically typed languages, such as Lisp, need to tag objects
  4626. anyways, so option 1 is a natural choice for those languages.
  4627. However, $R_3$ is a statically typed language, so it would be
  4628. unfortunate to require tags on every object, especially small and
  4629. pervasive objects like integers and Booleans. Option 3 is the
  4630. best-performing choice for statically typed languages, but comes with
  4631. a relatively high implementation complexity. To keep this chapter to a
  4632. 2-week time budget, we recommend a combination of options 1 and 2,
  4633. with separate strategies used for the stack and the heap.
  4634. Regarding the stack, we recommend using a separate stack for
  4635. pointers~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}, which
  4636. we call a \emph{root stack} (a.k.a. ``shadow stack''). That is, when a
  4637. local variable needs to be spilled and is of type \code{(Vector
  4638. $\Type_1 \ldots \Type_n$)}, then we put it on the root stack instead
  4639. of the normal procedure call stack. Furthermore, we always spill
  4640. vector-typed variables if they are live during a call to the
  4641. collector, thereby ensuring that no pointers are in registers during a
  4642. collection. Figure~\ref{fig:shadow-stack} reproduces the example from
  4643. Figure~\ref{fig:copying-collector} and contrasts it with the data
  4644. layout using a root stack. The root stack contains the two pointers
  4645. from the regular stack and also the pointer in the second
  4646. register.
  4647. \begin{figure}[tbp]
  4648. \centering \includegraphics[width=0.7\textwidth]{figs/root-stack}
  4649. \caption{Maintaining a root stack to facilitate garbage collection.}
  4650. \label{fig:shadow-stack}
  4651. \end{figure}
  4652. The problem of distinguishing between pointers and other kinds of data
  4653. also arises inside of each tuple. We solve this problem by attaching a
  4654. tag, an extra 64-bits, to each tuple. Figure~\ref{fig:tuple-rep} zooms
  4655. in on the tags for two of the tuples in the example from
  4656. Figure~\ref{fig:copying-collector}. Note that we have drawn the bits
  4657. in a big-endian way, from right-to-left, with bit location 0 (the
  4658. least significant bit) on the far right, which corresponds to the
  4659. directional of the x86 shifting instructions \key{salq} (shift
  4660. left) and \key{sarq} (shift right). Part of each tag is dedicated to
  4661. specifying which elements of the tuple are pointers, the part labeled
  4662. ``pointer mask''. Within the pointer mask, a 1 bit indicates there is
  4663. a pointer and a 0 bit indicates some other kind of data. The pointer
  4664. mask starts at bit location 7. We have limited tuples to a maximum
  4665. size of 50 elements, so we just need 50 bits for the pointer mask. The
  4666. tag also contains two other pieces of information. The length of the
  4667. tuple (number of elements) is stored in bits location 1 through
  4668. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  4669. to be copied to the ToSpace. If the bit has value 1, then this tuple
  4670. has not yet been copied. If the bit has value 0 then the entire tag
  4671. is in fact a forwarding pointer. (The lower 3 bits of an pointer are
  4672. always zero anyways because our tuples are 8-byte aligned.)
  4673. \begin{figure}[tbp]
  4674. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  4675. \caption{Representation for tuples in the heap.}
  4676. \label{fig:tuple-rep}
  4677. \end{figure}
  4678. \subsection{Implementation of the Garbage Collector}
  4679. \label{sec:organize-gz}
  4680. The implementation of the garbage collector needs to do a lot of
  4681. bit-level data manipulation and we need to link it with our
  4682. compiler-generated x86 code. Thus, we recommend implementing the
  4683. garbage collector in C~\citep{Kernighan:1988nx} and putting the code
  4684. in the \code{runtime.c} file. Figure~\ref{fig:gc-header} shows the
  4685. interface to the garbage collector. The \code{initialize} function
  4686. creates the FromSpace, ToSpace, and root stack. The \code{initialize}
  4687. function is meant to be called near the beginning of \code{main},
  4688. before the rest of the program executes. The \code{initialize}
  4689. function puts the address of the beginning of the FromSpace into the
  4690. global variable \code{free\_ptr}. The global \code{fromspace\_end}
  4691. points to the address that is 1-past the last element of the
  4692. FromSpace. (We use half-open intervals to represent chunks of
  4693. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} global
  4694. points to the first element of the root stack.
  4695. As long as there is room left in the FromSpace, your generated code
  4696. can allocate tuples simply by moving the \code{free\_ptr} forward.
  4697. %
  4698. \margincomment{\tiny Should we dedicate a register to the free pointer? \\
  4699. --Jeremy}
  4700. %
  4701. The amount of room left in FromSpace is the difference between the
  4702. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  4703. function should be called when there is not enough room left in the
  4704. FromSpace for the next allocation. The \code{collect} function takes
  4705. a pointer to the current top of the root stack (one past the last item
  4706. that was pushed) and the number of bytes that need to be
  4707. allocated. The \code{collect} function performs the copying collection
  4708. and leaves the heap in a state such that the next allocation will
  4709. succeed.
  4710. \begin{figure}[tbp]
  4711. \begin{lstlisting}
  4712. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  4713. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  4714. int64_t* free_ptr;
  4715. int64_t* fromspace_begin;
  4716. int64_t* fromspace_end;
  4717. int64_t** rootstack_begin;
  4718. \end{lstlisting}
  4719. \caption{The compiler's interface to the garbage collector.}
  4720. \label{fig:gc-header}
  4721. \end{figure}
  4722. \begin{exercise}
  4723. In the file \code{runtime.c} you will find the implementation of
  4724. \code{initialize} and a partial implementation of \code{collect}.
  4725. The \code{collect} function calls another function, \code{cheney},
  4726. to perform the actual copy, and that function is left to the reader
  4727. to implement. The following is the prototype for \code{cheney}.
  4728. \begin{lstlisting}
  4729. static void cheney(int64_t** rootstack_ptr);
  4730. \end{lstlisting}
  4731. The parameter \code{rootstack\_ptr} is a pointer to the top of the
  4732. rootstack (which is an array of pointers). The \code{cheney} function
  4733. also communicates with \code{collect} through the global
  4734. variables \code{fromspace\_begin} and \code{fromspace\_end}
  4735. mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  4736. the ToSpace:
  4737. \begin{lstlisting}
  4738. static int64_t* tospace_begin;
  4739. static int64_t* tospace_end;
  4740. \end{lstlisting}
  4741. The job of the \code{cheney} function is to copy all the live
  4742. objects (reachable from the root stack) into the ToSpace, update
  4743. \code{free\_ptr} to point to the next unused spot in the ToSpace,
  4744. update the root stack so that it points to the objects in the
  4745. ToSpace, and finally to swap the global pointers for the FromSpace
  4746. and ToSpace.
  4747. \end{exercise}
  4748. %% \section{Compiler Passes}
  4749. %% \label{sec:code-generation-gc}
  4750. The introduction of garbage collection has a non-trivial impact on our
  4751. compiler passes. We introduce one new compiler pass called
  4752. \code{expose-allocation} and make non-trivial changes to
  4753. \code{type-check}, \code{flatten}, \code{select-instructions},
  4754. \code{allocate-registers}, and \code{print-x86}. The following
  4755. program will serve as our running example. It creates two tuples, one
  4756. nested inside the other. Both tuples have length one. The example then
  4757. accesses the element in the inner tuple tuple via two vector
  4758. references.
  4759. % tests/s2_17.rkt
  4760. \begin{lstlisting}
  4761. (vector-ref (vector-ref (vector (vector 42)) 0) 0))
  4762. \end{lstlisting}
  4763. Next we proceed to discuss the new \code{expose-allocation} pass.
  4764. \section{Expose Allocation}
  4765. \label{sec:expose-allocation}
  4766. The pass \code{expose-allocation} lowers the \code{vector} creation
  4767. form into a conditional call to the collector followed by the
  4768. allocation. We choose to place the \code{expose-allocation} pass
  4769. before \code{flatten} because \code{expose-allocation} introduces new
  4770. variables, which can be done locally with \code{let}, but \code{let}
  4771. is gone after \code{flatten}. In the following, we show the
  4772. transformation for the \code{vector} form into let-bindings for the
  4773. initializing expressions, by a conditional \code{collect}, an
  4774. \code{allocate}, and the initialization of the vector.
  4775. (The \itm{len} is the length of the vector and \itm{bytes} is how many
  4776. total bytes need to be allocated for the vector, which is 8 for the
  4777. tag plus \itm{len} times 8.)
  4778. \begin{lstlisting}
  4779. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  4780. |$\Longrightarrow$|
  4781. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  4782. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  4783. (global-value fromspace_end))
  4784. (void)
  4785. (collect |\itm{bytes}|))])
  4786. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  4787. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  4788. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  4789. |$v$|) ... )))) ...)
  4790. \end{lstlisting}
  4791. (In the above, we suppressed all of the \code{has-type} forms in the
  4792. output for the sake of readability.) The placement of the initializing
  4793. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and
  4794. the sequence of \code{vector-set!}'s is important, as those expressions
  4795. may trigger garbage collection and we do not want an allocated but
  4796. uninitialized tuple to be present during a garbage collection.
  4797. The output of \code{expose-allocation} is a language that extends
  4798. $R_3$ with the three new forms that we use above in the translation of
  4799. \code{vector}.
  4800. \[
  4801. \begin{array}{lcl}
  4802. \Exp &::=& \cdots
  4803. \mid (\key{collect} \,\itm{int})
  4804. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  4805. \mid (\key{global-value} \,\itm{name})
  4806. \end{array}
  4807. \]
  4808. %% The \code{expose-allocation} inserts an \code{initialize} statement at
  4809. %% the beginning of the program which will instruct the garbage collector
  4810. %% to set up the FromSpace, ToSpace, and all the global variables. The
  4811. %% two arguments of \code{initialize} specify the initial allocated space
  4812. %% for the root stack and for the heap.
  4813. %
  4814. %% The \code{expose-allocation} pass annotates all of the local variables
  4815. %% in the \code{program} form with their type.
  4816. Figure~\ref{fig:expose-alloc-output} shows the output of the
  4817. \code{expose-allocation} pass on our running example.
  4818. \begin{figure}[tbp]
  4819. % tests/s2_17.rkt
  4820. \begin{lstlisting}
  4821. (vector-ref
  4822. (vector-ref
  4823. (let ([vecinit7976
  4824. (let ([vecinit7972 42])
  4825. (let ([collectret7974
  4826. (if (< (+ free_ptr 16) fromspace_end)
  4827. (void)
  4828. (collect 16);
  4829. )])
  4830. (let ([alloc7971 (allocate 1 (Vector Integer))])
  4831. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  4832. alloc7971)
  4833. )
  4834. )
  4835. )
  4836. ])
  4837. (let ([collectret7978
  4838. (if (< (+ free_ptr 16) fromspace_end)
  4839. (void)
  4840. (collect 16);
  4841. )])
  4842. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  4843. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  4844. alloc7975)
  4845. )
  4846. )
  4847. )
  4848. 0)
  4849. 0)
  4850. \end{lstlisting}
  4851. \caption{Output of the \code{expose-allocation} pass, minus
  4852. all of the \code{HasType} forms.}
  4853. \label{fig:expose-alloc-output}
  4854. \end{figure}
  4855. %\clearpage
  4856. \section{Explicate Control and the $C_2$ language}
  4857. \label{sec:explicate-control-r3}
  4858. \begin{figure}[tp]
  4859. \fbox{
  4860. \begin{minipage}{0.96\textwidth}
  4861. \[
  4862. \begin{array}{lcl}
  4863. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }\\
  4864. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  4865. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  4866. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  4867. &\mid& (\key{allocate} \,\itm{int}\,\itm{type})
  4868. \mid (\key{vector-ref}\, \Arg\, \Int) \\
  4869. &\mid& (\key{vector-set!}\,\Arg\,\Int\,\Arg)
  4870. \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) \\
  4871. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp} }
  4872. \mid (\key{collect} \,\itm{int}) \\
  4873. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  4874. &\mid& \gray{(\key{goto}\,\itm{label})
  4875. \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  4876. C_2 & ::= & (\key{program}\;\itm{info}\; ((\itm{label}\,\key{.}\,\Tail)^{+}))
  4877. \end{array}
  4878. \]
  4879. \end{minipage}
  4880. }
  4881. \caption{The $C_2$ language, extending $C_1$
  4882. (Figure~\ref{fig:c1-syntax}) with vectors.}
  4883. \label{fig:c2-syntax}
  4884. \end{figure}
  4885. The output of \code{explicate-control} is a program in the
  4886. intermediate language $C_2$, whose syntax is defined in
  4887. Figure~\ref{fig:c2-syntax}. The new forms of $C_2$ include the
  4888. \key{allocate}, \key{vector-ref}, and \key{vector-set!}, and
  4889. \key{global-value} expressions and the \code{collect} statement. The
  4890. \code{explicate-control} pass can treat these new forms much like the
  4891. other forms.
  4892. \section{Uncover Locals}
  4893. \label{sec:uncover-locals-r3}
  4894. Recall that the \code{explicate-control} function collects all of the
  4895. local variables so that it can store them in the $\itm{info}$ field of
  4896. the \code{Program} structure. Also recall that we need to know the
  4897. types of all the local variables for purposes of identifying the root
  4898. set for the garbage collector. Thus, we create a pass named
  4899. \code{uncover-locals} to collect not just the variables but the
  4900. variables and their types in the form of an association list. Thanks
  4901. to the \code{HasType} nodes, the types are readily available in the
  4902. AST. Figure~\ref{fig:uncover-locals-r3} lists the output of the
  4903. \code{uncover-locals} pass on the running example.
  4904. \begin{figure}[tbp]
  4905. % tests/s2_17.rkt
  4906. \begin{lstlisting}
  4907. program:
  4908. locals:
  4909. vecinit7976 : '(Vector Integer), tmp7980 : 'Integer,
  4910. alloc7975 : '(Vector (Vector Integer)), tmp7983 : 'Integer,
  4911. collectret7974 : 'Void, initret7977 : 'Void,
  4912. collectret7978 : 'Void, tmp7985 : '(Vector Integer),
  4913. tmp7984 : 'Integer, tmp7979 : 'Integer, tmp7982 : 'Integer,
  4914. alloc7971 : '(Vector Integer), tmp7981 : 'Integer, vecinit7972 : 'Integer,
  4915. initret7973 : 'Void,
  4916. block7991:
  4917. (collect 16);
  4918. goto block7989;
  4919. block7990:
  4920. collectret7974 = (void);
  4921. goto block7989;
  4922. block7989:
  4923. alloc7971 = (allocate 1 (Vector Integer));
  4924. initret7973 = (vector-set! alloc7971 0 vecinit7972);
  4925. vecinit7976 = alloc7971;
  4926. tmp7982 = free_ptr;
  4927. tmp7983 = (+ tmp7982 16);
  4928. tmp7984 = fromspace_end;
  4929. if (< tmp7983 tmp7984) then
  4930. goto block7987;
  4931. else
  4932. goto block7988;
  4933. block7988:
  4934. (collect 16);
  4935. goto block7986;
  4936. block7987:
  4937. collectret7978 = (void);
  4938. goto block7986;
  4939. block7986:
  4940. alloc7975 = (allocate 1 (Vector (Vector Integer)));
  4941. initret7977 = (vector-set! alloc7975 0 vecinit7976);
  4942. tmp7985 = (vector-ref alloc7975 0);
  4943. return (vector-ref tmp7985 0);
  4944. start:
  4945. vecinit7972 = 42;
  4946. tmp7979 = free_ptr;
  4947. tmp7980 = (+ tmp7979 16);
  4948. tmp7981 = fromspace_end;
  4949. if (< tmp7980 tmp7981) then
  4950. goto block7990;
  4951. else
  4952. goto block7991;
  4953. \end{lstlisting}
  4954. \caption{Output of \code{uncover-locals} for the running example.}
  4955. \label{fig:uncover-locals-r3}
  4956. \end{figure}
  4957. \clearpage
  4958. \section{Select Instructions}
  4959. \label{sec:select-instructions-gc}
  4960. %% void (rep as zero)
  4961. %% allocate
  4962. %% collect (callq collect)
  4963. %% vector-ref
  4964. %% vector-set!
  4965. %% global-value (postpone)
  4966. In this pass we generate x86 code for most of the new operations that
  4967. were needed to compile tuples, including \code{allocate},
  4968. \code{collect}, \code{vector-ref}, \code{vector-set!}, and
  4969. \code{(void)}. We postpone \code{global-value} to \code{print-x86}.
  4970. The \code{vector-ref} and \code{vector-set!} forms translate into
  4971. \code{movq} instructions with the appropriate \key{deref}. (The
  4972. plus one is to get past the tag at the beginning of the tuple
  4973. representation.)
  4974. \begin{lstlisting}
  4975. (assign |$\itm{lhs}$| (vector-ref |$\itm{vec}$| |$n$|))
  4976. |$\Longrightarrow$|
  4977. (movq |$\itm{vec}'$| (reg r11))
  4978. (movq (deref r11 |$8(n+1)$|) |$\itm{lhs}$|)
  4979. (assign |$\itm{lhs}$| (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|))
  4980. |$\Longrightarrow$|
  4981. (movq |$\itm{vec}'$| (reg r11))
  4982. (movq |$\itm{arg}'$| (deref r11 |$8(n+1)$|))
  4983. (movq (int 0) |$\itm{lhs}$|)
  4984. \end{lstlisting}
  4985. The $\itm{vec}'$ and $\itm{arg}'$ are obtained by recursively
  4986. processing $\itm{vec}$ and $\itm{arg}$. The move of $\itm{vec}'$ to
  4987. register \code{r11} ensures that offsets are only performed with
  4988. register operands. This requires removing \code{r11} from
  4989. consideration by the register allocating.
  4990. We compile the \code{allocate} form to operations on the
  4991. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  4992. is the next free address in the FromSpace, so we move it into the
  4993. \itm{lhs} and then move it forward by enough space for the tuple being
  4994. allocated, which is $8(\itm{len}+1)$ bytes because each element is 8
  4995. bytes (64 bits) and we use 8 bytes for the tag. Last but not least, we
  4996. initialize the \itm{tag}. Refer to Figure~\ref{fig:tuple-rep} to see
  4997. how the tag is organized. We recommend using the Racket operations
  4998. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag.
  4999. The type annotation in the \code{vector} form is used to determine the
  5000. pointer mask region of the tag.
  5001. \begin{lstlisting}
  5002. (assign |$\itm{lhs}$| (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|)))
  5003. |$\Longrightarrow$|
  5004. (movq (global-value free_ptr) |$\itm{lhs}'$|)
  5005. (addq (int |$8(\itm{len}+1)$|) (global-value free_ptr))
  5006. (movq |$\itm{lhs}'$| (reg r11))
  5007. (movq (int |$\itm{tag}$|) (deref r11 0))
  5008. \end{lstlisting}
  5009. The \code{collect} form is compiled to a call to the \code{collect}
  5010. function in the runtime. The arguments to \code{collect} are the top
  5011. of the root stack and the number of bytes that need to be allocated.
  5012. We shall use a dedicated register, \code{r15}, to store the pointer to
  5013. the top of the root stack. So \code{r15} is not available for use by
  5014. the register allocator.
  5015. \begin{lstlisting}
  5016. (collect |$\itm{bytes}$|)
  5017. |$\Longrightarrow$|
  5018. (movq (reg r15) (reg rdi))
  5019. (movq |\itm{bytes}| (reg rsi))
  5020. (callq collect)
  5021. \end{lstlisting}
  5022. \begin{figure}[tp]
  5023. \fbox{
  5024. \begin{minipage}{0.96\textwidth}
  5025. \[
  5026. \begin{array}{lcl}
  5027. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg}
  5028. \mid (\key{deref}\,\Reg\,\Int) } \\
  5029. &\mid& \gray{ (\key{byte-reg}\; \Reg) }
  5030. \mid (\key{global-value}\; \itm{name}) \\
  5031. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  5032. \Instr &::=& \gray{(\key{addq} \; \Arg\; \Arg) \mid
  5033. (\key{subq} \; \Arg\; \Arg) \mid
  5034. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg)} \\
  5035. &\mid& \gray{(\key{callq} \; \mathit{label}) \mid
  5036. (\key{pushq}\;\Arg) \mid
  5037. (\key{popq}\;\Arg) \mid
  5038. (\key{retq})} \\
  5039. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  5040. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  5041. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  5042. \mid (\key{jmp} \; \itm{label})
  5043. \mid (\key{jmp-if}\itm{cc} \; \itm{label})}\\
  5044. &\mid& \gray{(\key{label} \; \itm{label}) } \\
  5045. x86_2 &::= & \gray{ (\key{program} \;\itm{info} \;(\key{type}\;\itm{type})\; \Instr^{+}) }
  5046. \end{array}
  5047. \]
  5048. \end{minipage}
  5049. }
  5050. \caption{The x86$_2$ language (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  5051. \label{fig:x86-2}
  5052. \end{figure}
  5053. The syntax of the $x86_2$ language is defined in
  5054. Figure~\ref{fig:x86-2}. It differs from $x86_1$ just in the addition
  5055. of the form for global variables.
  5056. %
  5057. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  5058. \code{select-instructions} pass on the running example.
  5059. \begin{figure}[tbp]
  5060. \centering
  5061. \begin{minipage}{0.75\textwidth}
  5062. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5063. (program
  5064. ((locals . ((tmp54 . Integer) (tmp51 . Integer) (tmp53 . Integer)
  5065. (alloc43 . (Vector Integer)) (tmp55 . Integer)
  5066. (initret45 . Void) (alloc47 . (Vector (Vector Integer)))
  5067. (collectret46 . Void) (vecinit48 . (Vector Integer))
  5068. (tmp52 . Integer) (tmp57 Vector Integer) (vecinit44 . Integer)
  5069. (tmp56 . Integer) (initret49 . Void) (collectret50 . Void))))
  5070. ((block63 . (block ()
  5071. (movq (reg r15) (reg rdi))
  5072. (movq (int 16) (reg rsi))
  5073. (callq collect)
  5074. (jmp block61)))
  5075. (block62 . (block () (movq (int 0) (var collectret46)) (jmp block61)))
  5076. (block61 . (block ()
  5077. (movq (global-value free_ptr) (var alloc43))
  5078. (addq (int 16) (global-value free_ptr))
  5079. (movq (var alloc43) (reg r11))
  5080. (movq (int 3) (deref r11 0))
  5081. (movq (var alloc43) (reg r11))
  5082. (movq (var vecinit44) (deref r11 8))
  5083. (movq (int 0) (var initret45))
  5084. (movq (var alloc43) (var vecinit48))
  5085. (movq (global-value free_ptr) (var tmp54))
  5086. (movq (var tmp54) (var tmp55))
  5087. (addq (int 16) (var tmp55))
  5088. (movq (global-value fromspace_end) (var tmp56))
  5089. (cmpq (var tmp56) (var tmp55))
  5090. (jmp-if l block59)
  5091. (jmp block60)))
  5092. (block60 . (block ()
  5093. (movq (reg r15) (reg rdi))
  5094. (movq (int 16) (reg rsi))
  5095. (callq collect)
  5096. (jmp block58))
  5097. (block59 . (block ()
  5098. (movq (int 0) (var collectret50))
  5099. (jmp block58)))
  5100. (block58 . (block ()
  5101. (movq (global-value free_ptr) (var alloc47))
  5102. (addq (int 16) (global-value free_ptr))
  5103. (movq (var alloc47) (reg r11))
  5104. (movq (int 131) (deref r11 0))
  5105. (movq (var alloc47) (reg r11))
  5106. (movq (var vecinit48) (deref r11 8))
  5107. (movq (int 0) (var initret49))
  5108. (movq (var alloc47) (reg r11))
  5109. (movq (deref r11 8) (var tmp57))
  5110. (movq (var tmp57) (reg r11))
  5111. (movq (deref r11 8) (reg rax))
  5112. (jmp conclusion)))
  5113. (start . (block ()
  5114. (movq (int 42) (var vecinit44))
  5115. (movq (global-value free_ptr) (var tmp51))
  5116. (movq (var tmp51) (var tmp52))
  5117. (addq (int 16) (var tmp52))
  5118. (movq (global-value fromspace_end) (var tmp53))
  5119. (cmpq (var tmp53) (var tmp52))
  5120. (jmp-if l block62)
  5121. (jmp block63))))))
  5122. \end{lstlisting}
  5123. \end{minipage}
  5124. \caption{Output of the \code{select-instructions} pass.}
  5125. \label{fig:select-instr-output-gc}
  5126. \end{figure}
  5127. \clearpage
  5128. \section{Register Allocation}
  5129. \label{sec:reg-alloc-gc}
  5130. As discussed earlier in this chapter, the garbage collector needs to
  5131. access all the pointers in the root set, that is, all variables that
  5132. are vectors. It will be the responsibility of the register allocator
  5133. to make sure that:
  5134. \begin{enumerate}
  5135. \item the root stack is used for spilling vector-typed variables, and
  5136. \item if a vector-typed variable is live during a call to the
  5137. collector, it must be spilled to ensure it is visible to the
  5138. collector.
  5139. \end{enumerate}
  5140. The later responsibility can be handled during construction of the
  5141. inference graph, by adding interference edges between the call-live
  5142. vector-typed variables and all the callee-saved registers. (They
  5143. already interfere with the caller-saved registers.) The type
  5144. information for variables is in the \code{program} form, so we
  5145. recommend adding another parameter to the \code{build-interference}
  5146. function to communicate this association list.
  5147. The spilling of vector-typed variables to the root stack can be
  5148. handled after graph coloring, when choosing how to assign the colors
  5149. (integers) to registers and stack locations. The \code{program} output
  5150. of this pass changes to also record the number of spills to the root
  5151. stack.
  5152. % build-interference
  5153. %
  5154. % callq
  5155. % extra parameter for var->type assoc. list
  5156. % update 'program' and 'if'
  5157. % allocate-registers
  5158. % allocate spilled vectors to the rootstack
  5159. % don't change color-graph
  5160. \section{Print x86}
  5161. \label{sec:print-x86-gc}
  5162. \margincomment{\scriptsize We need to show the translation to x86 and what
  5163. to do about global-value. \\ --Jeremy}
  5164. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  5165. \code{print-x86} pass on the running example. In the prelude and
  5166. conclusion of the \code{main} function, we treat the root stack very
  5167. much like the regular stack in that we move the root stack pointer
  5168. (\code{r15}) to make room for all of the spills to the root stack,
  5169. except that the root stack grows up instead of down. For the running
  5170. example, there was just one spill so we increment \code{r15} by 8
  5171. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  5172. One issue that deserves special care is that there may be a call to
  5173. \code{collect} prior to the initializing assignments for all the
  5174. variables in the root stack. We do not want the garbage collector to
  5175. accidentally think that some uninitialized variable is a pointer that
  5176. needs to be followed. Thus, we zero-out all locations on the root
  5177. stack in the prelude of \code{main}. In
  5178. Figure~\ref{fig:print-x86-output-gc}, the instruction
  5179. %
  5180. \lstinline{movq $0, (%r15)}
  5181. %
  5182. accomplishes this task. The garbage collector tests each root to see
  5183. if it is null prior to dereferencing it.
  5184. \begin{figure}[htbp]
  5185. \begin{minipage}[t]{0.5\textwidth}
  5186. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5187. _block58:
  5188. movq _free_ptr(%rip), %rcx
  5189. addq $16, _free_ptr(%rip)
  5190. movq %rcx, %r11
  5191. movq $131, 0(%r11)
  5192. movq %rcx, %r11
  5193. movq -8(%r15), %rax
  5194. movq %rax, 8(%r11)
  5195. movq $0, %rdx
  5196. movq %rcx, %r11
  5197. movq 8(%r11), %rcx
  5198. movq %rcx, %r11
  5199. movq 8(%r11), %rax
  5200. jmp _conclusion
  5201. _block59:
  5202. movq $0, %rcx
  5203. jmp _block58
  5204. _block62:
  5205. movq $0, %rcx
  5206. jmp _block61
  5207. _block60:
  5208. movq %r15, %rdi
  5209. movq $16, %rsi
  5210. callq _collect
  5211. jmp _block58
  5212. _block63:
  5213. movq %r15, %rdi
  5214. movq $16, %rsi
  5215. callq _collect
  5216. jmp _block61
  5217. _start:
  5218. movq $42, %rbx
  5219. movq _free_ptr(%rip), %rdx
  5220. addq $16, %rdx
  5221. movq _fromspace_end(%rip), %rcx
  5222. cmpq %rcx, %rdx
  5223. jl _block62
  5224. jmp _block63
  5225. \end{lstlisting}
  5226. \end{minipage}
  5227. \begin{minipage}[t]{0.45\textwidth}
  5228. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5229. _block61:
  5230. movq _free_ptr(%rip), %rcx
  5231. addq $16, _free_ptr(%rip)
  5232. movq %rcx, %r11
  5233. movq $3, 0(%r11)
  5234. movq %rcx, %r11
  5235. movq %rbx, 8(%r11)
  5236. movq $0, %rdx
  5237. movq %rcx, -8(%r15)
  5238. movq _free_ptr(%rip), %rcx
  5239. addq $16, %rcx
  5240. movq _fromspace_end(%rip), %rdx
  5241. cmpq %rdx, %rcx
  5242. jl _block59
  5243. jmp _block60
  5244. .globl _main
  5245. _main:
  5246. pushq %rbp
  5247. movq %rsp, %rbp
  5248. pushq %r12
  5249. pushq %rbx
  5250. pushq %r13
  5251. pushq %r14
  5252. subq $0, %rsp
  5253. movq $16384, %rdi
  5254. movq $16, %rsi
  5255. callq _initialize
  5256. movq _rootstack_begin(%rip), %r15
  5257. movq $0, (%r15)
  5258. addq $8, %r15
  5259. jmp _start
  5260. _conclusion:
  5261. subq $8, %r15
  5262. addq $0, %rsp
  5263. popq %r14
  5264. popq %r13
  5265. popq %rbx
  5266. popq %r12
  5267. popq %rbp
  5268. retq
  5269. \end{lstlisting}
  5270. \end{minipage}
  5271. \caption{Output of the \code{print-x86} pass.}
  5272. \label{fig:print-x86-output-gc}
  5273. \end{figure}
  5274. \margincomment{\scriptsize Suggest an implementation strategy
  5275. in which the students first do the code gen and test that
  5276. without GC (just use a big heap), then after that is debugged,
  5277. implement the GC. \\ --Jeremy}
  5278. \begin{figure}[p]
  5279. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5280. \node (R3) at (0,2) {\large $R_3$};
  5281. \node (R3-2) at (3,2) {\large $R_3$};
  5282. \node (R3-3) at (6,2) {\large $R_3$};
  5283. \node (R3-4) at (9,2) {\large $R_3$};
  5284. \node (R3-5) at (12,2) {\large $R_3$};
  5285. \node (C2-4) at (3,0) {\large $C_2$};
  5286. \node (C2-3) at (6,0) {\large $C_2$};
  5287. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_2$};
  5288. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_2$};
  5289. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}_2$};
  5290. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}_2$};
  5291. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}_2$};
  5292. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}_2$};
  5293. \path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize\color{red} typecheck} (R3-2);
  5294. \path[->,bend left=15] (R3-2) edge [above] node {\ttfamily\footnotesize uniquify} (R3-3);
  5295. \path[->,bend left=15] (R3-3) edge [above] node {\ttfamily\footnotesize\color{red} expose-alloc.} (R3-4);
  5296. \path[->,bend left=15] (R3-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R3-5);
  5297. \path[->,bend left=20] (R3-5) edge [right] node {\ttfamily\footnotesize explicate-control} (C2-3);
  5298. \path[->,bend right=15] (C2-3) edge [above] node {\ttfamily\footnotesize\color{red} uncover-locals} (C2-4);
  5299. \path[->,bend right=15] (C2-4) edge [left] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  5300. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  5301. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  5302. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  5303. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  5304. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  5305. \end{tikzpicture}
  5306. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  5307. \label{fig:R3-passes}
  5308. \end{figure}
  5309. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  5310. for the compilation of $R_3$.
  5311. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5312. \chapter{Functions}
  5313. \label{ch:functions}
  5314. This chapter studies the compilation of functions at the level of
  5315. abstraction of the C language. This corresponds to a subset of Typed
  5316. Racket in which only top-level function definitions are allowed. These
  5317. kind of functions are an important stepping stone to implementing
  5318. lexically-scoped functions in the form of \key{lambda} abstractions,
  5319. which is the topic of Chapter~\ref{ch:lambdas}.
  5320. \section{The $R_4$ Language}
  5321. The syntax for function definitions and function application is shown
  5322. in Figure~\ref{fig:r4-syntax}, where we define the $R_4$ language.
  5323. Programs in $R_4$ start with zero or more function definitions. The
  5324. function names from these definitions are in-scope for the entire
  5325. program, including all other function definitions (so the ordering of
  5326. function definitions does not matter). The syntax for function
  5327. application does not include an explicit keyword, which is error prone
  5328. when using \code{match}. To alleviate this problem, we change the
  5329. syntax from $(\Exp \; \Exp^{*})$ to $(\key{app}\; \Exp \; \Exp^{*})$
  5330. during type checking.
  5331. Functions are first-class in the sense that a function pointer is data
  5332. and can be stored in memory or passed as a parameter to another
  5333. function. Thus, we introduce a function type, written
  5334. \begin{lstlisting}
  5335. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  5336. \end{lstlisting}
  5337. for a function whose $n$ parameters have the types $\Type_1$ through
  5338. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  5339. these functions (with respect to Racket functions) is that they are
  5340. not lexically scoped. That is, the only external entities that can be
  5341. referenced from inside a function body are other globally-defined
  5342. functions. The syntax of $R_4$ prevents functions from being nested
  5343. inside each other.
  5344. \begin{figure}[tp]
  5345. \centering
  5346. \fbox{
  5347. \begin{minipage}{0.96\textwidth}
  5348. \[
  5349. \begin{array}{lcl}
  5350. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  5351. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} } \mid (\Type^{*} \; \key{->}\; \Type) \\
  5352. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  5353. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp)} \\
  5354. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  5355. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5356. \mid (\key{and}\;\Exp\;\Exp)
  5357. \mid (\key{or}\;\Exp\;\Exp)
  5358. \mid (\key{not}\;\Exp)} \\
  5359. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5360. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5361. (\key{vector-ref}\;\Exp\;\Int)} \\
  5362. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  5363. &\mid& (\Exp \; \Exp^{*}) \\
  5364. \Def &::=& (\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  5365. R_4 &::=& (\key{program} \;\itm{info}\; \Def^{*} \; \Exp)
  5366. \end{array}
  5367. \]
  5368. \end{minipage}
  5369. }
  5370. \caption{Syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-syntax})
  5371. with functions.}
  5372. \label{fig:r4-syntax}
  5373. \end{figure}
  5374. The program in Figure~\ref{fig:r4-function-example} is a
  5375. representative example of defining and using functions in $R_4$. We
  5376. define a function \code{map-vec} that applies some other function
  5377. \code{f} to both elements of a vector (a 2-tuple) and returns a new
  5378. vector containing the results. We also define a function \code{add1}
  5379. that does what its name suggests. The program then applies
  5380. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  5381. \code{(vector 1 42)}, from which we return the \code{42}.
  5382. \begin{figure}[tbp]
  5383. \begin{lstlisting}
  5384. (program ()
  5385. (define (map-vec [f : (Integer -> Integer)]
  5386. [v : (Vector Integer Integer)])
  5387. : (Vector Integer Integer)
  5388. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  5389. (define (add1 [x : Integer]) : Integer
  5390. (+ x 1))
  5391. (vector-ref (map-vec add1 (vector 0 41)) 1)
  5392. )
  5393. \end{lstlisting}
  5394. \caption{Example of using functions in $R_4$.}
  5395. \label{fig:r4-function-example}
  5396. \end{figure}
  5397. The definitional interpreter for $R_4$ is in
  5398. Figure~\ref{fig:interp-R4}. The case for the \code{program} form is
  5399. responsible for setting up the mutual recursion between the top-level
  5400. function definitions. We use the classic back-patching approach that
  5401. uses mutable variables and makes two passes over the function
  5402. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  5403. top-level environment using a mutable cons cell for each function
  5404. definition. Note that the \code{lambda} value for each function is
  5405. incomplete; it does not yet include the environment. Once the
  5406. top-level environment is constructed, we then iterate over it and
  5407. update the \code{lambda} value's to use the top-level environment.
  5408. \begin{figure}[tp]
  5409. \begin{lstlisting}
  5410. (define (interp-exp env)
  5411. (lambda (e)
  5412. (define recur (interp-exp env))
  5413. (match e
  5414. ...
  5415. [`(,fun ,args ...)
  5416. (define arg-vals (for/list ([e args]) (recur e)))
  5417. (define fun-val (recur fun))
  5418. (match fun-val
  5419. [`(lambda (,xs ...) ,body ,fun-env)
  5420. (define new-env (append (map cons xs arg-vals) fun-env))
  5421. ((interp-exp new-env) body)]
  5422. [else (error "interp-exp, expected function, not" fun-val)])]
  5423. [else (error 'interp-exp "unrecognized expression")]
  5424. )))
  5425. (define (interp-def d)
  5426. (match d
  5427. [`(define (,f [,xs : ,ps] ...) : ,rt ,body)
  5428. (mcons f `(lambda ,xs ,body ()))]
  5429. ))
  5430. (define (interp-R4 p)
  5431. (match p
  5432. [`(program ,ds ... ,body)
  5433. (let ([top-level (for/list ([d ds]) (interp-def d))])
  5434. (for/list ([b top-level])
  5435. (set-mcdr! b (match (mcdr b)
  5436. [`(lambda ,xs ,body ())
  5437. `(lambda ,xs ,body ,top-level)])))
  5438. ((interp-exp top-level) body))]
  5439. ))
  5440. \end{lstlisting}
  5441. \caption{Interpreter for the $R_4$ language.}
  5442. \label{fig:interp-R4}
  5443. \end{figure}
  5444. \section{Functions in x86}
  5445. \label{sec:fun-x86}
  5446. \margincomment{\tiny Make sure callee-saved registers are discussed
  5447. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  5448. \margincomment{\tiny Talk about the return address on the
  5449. stack and what callq and retq does.\\ --Jeremy }
  5450. The x86 architecture provides a few features to support the
  5451. implementation of functions. We have already seen that x86 provides
  5452. labels so that one can refer to the location of an instruction, as is
  5453. needed for jump instructions. Labels can also be used to mark the
  5454. beginning of the instructions for a function. Going further, we can
  5455. obtain the address of a label by using the \key{leaq} instruction and
  5456. \key{rip}-relative addressing. For example, the following puts the
  5457. address of the \code{add1} label into the \code{rbx} register.
  5458. \begin{lstlisting}
  5459. leaq add1(%rip), %rbx
  5460. \end{lstlisting}
  5461. In Section~\ref{sec:x86} we saw the use of the \code{callq}
  5462. instruction for jumping to a function whose location is given by a
  5463. label. Here we instead will be jumping to a function whose location is
  5464. given by an address, that is, we need to make an \emph{indirect
  5465. function call}. The x86 syntax is to give the register name prefixed
  5466. with an asterisk.
  5467. \begin{lstlisting}
  5468. callq *%rbx
  5469. \end{lstlisting}
  5470. \subsection{Calling Conventions}
  5471. The \code{callq} instruction provides partial support for implementing
  5472. functions, but it does not handle (1) parameter passing, (2) saving
  5473. and restoring frames on the procedure call stack, or (3) determining
  5474. how registers are shared by different functions. These issues require
  5475. coordination between the caller and the callee, which is often
  5476. assembly code written by different programmers or generated by
  5477. different compilers. As a result, people have developed
  5478. \emph{conventions} that govern how functions calls are performed.
  5479. Here we shall use the same conventions used by the \code{gcc}
  5480. compiler~\citep{Matz:2013aa}.
  5481. Regarding (1) parameter passing, the convention is to use the
  5482. following six registers: \code{rdi}, \code{rsi}, \code{rdx},
  5483. \code{rcx}, \code{r8}, and \code{r9}, in that order. If there are more
  5484. than six arguments, then the convention is to use space on the frame
  5485. of the caller for the rest of the arguments. However, to ease the
  5486. implementation of efficient tail calls (Section~\ref{sec:tail-call}),
  5487. we shall arrange to never have more than six arguments.
  5488. %
  5489. The register \code{rax} is for the return value of the function.
  5490. Regarding (2) frames and the procedure call stack, the convention is
  5491. that the stack grows down, with each function call using a chunk of
  5492. space called a frame. The caller sets the stack pointer, register
  5493. \code{rsp}, to the last data item in its frame. The callee must not
  5494. change anything in the caller's frame, that is, anything that is at or
  5495. above the stack pointer. The callee is free to use locations that are
  5496. below the stack pointer.
  5497. Regarding (3) the sharing of registers between different functions,
  5498. recall from Section~\ref{sec:calling-conventions} that the registers
  5499. are divided into two groups, the caller-saved registers and the
  5500. callee-saved registers. The caller should assume that all the
  5501. caller-saved registers get overwritten with arbitrary values by the
  5502. callee. Thus, the caller should either 1) not put values that are live
  5503. across a call in caller-saved registers, or 2) save and restore values
  5504. that are live across calls. We shall recommend option 1). On the flip
  5505. side, if the callee wants to use a callee-saved register, the callee
  5506. must save the contents of those registers on their stack frame and
  5507. then put them back prior to returning to the caller. The base
  5508. pointer, register \code{rbp}, is used as a point-of-reference within a
  5509. frame, so that each local variable can be accessed at a fixed offset
  5510. from the base pointer.
  5511. %
  5512. Figure~\ref{fig:call-frames} shows the layout of the caller and callee
  5513. frames.
  5514. %% If we were to use stack arguments, they would be between the
  5515. %% caller locals and the callee return address.
  5516. \begin{figure}[tbp]
  5517. \centering
  5518. \begin{tabular}{r|r|l|l} \hline
  5519. Caller View & Callee View & Contents & Frame \\ \hline
  5520. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  5521. 0(\key{\%rbp}) & & old \key{rbp} \\
  5522. -8(\key{\%rbp}) & & callee-saved $1$ \\
  5523. \ldots & & \ldots \\
  5524. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  5525. $-8(j+1)$(\key{\%rbp}) & & local $1$ \\
  5526. \ldots & & \ldots \\
  5527. $-8(j+k)$(\key{\%rbp}) & & local $k$ \\
  5528. %% & & \\
  5529. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  5530. %% & \ldots & \ldots \\
  5531. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  5532. \hline
  5533. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  5534. & 0(\key{\%rbp}) & old \key{rbp} \\
  5535. & -8(\key{\%rbp}) & callee-saved $1$ \\
  5536. & \ldots & \ldots \\
  5537. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  5538. & $-8(n+1)$(\key{\%rbp}) & local $1$ \\
  5539. & \ldots & \ldots \\
  5540. & $-8(n+m)$(\key{\%rsp}) & local $m$\\ \hline
  5541. \end{tabular}
  5542. \caption{Memory layout of caller and callee frames.}
  5543. \label{fig:call-frames}
  5544. \end{figure}
  5545. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  5546. %% local variables and for storing the values of callee-saved registers
  5547. %% (we shall refer to all of these collectively as ``locals''), and that
  5548. %% at the beginning of a function we move the stack pointer \code{rsp}
  5549. %% down to make room for them.
  5550. %% We recommend storing the local variables
  5551. %% first and then the callee-saved registers, so that the local variables
  5552. %% can be accessed using \code{rbp} the same as before the addition of
  5553. %% functions.
  5554. %% To make additional room for passing arguments, we shall
  5555. %% move the stack pointer even further down. We count how many stack
  5556. %% arguments are needed for each function call that occurs inside the
  5557. %% body of the function and find their maximum. Adding this number to the
  5558. %% number of locals gives us how much the \code{rsp} should be moved at
  5559. %% the beginning of the function. In preparation for a function call, we
  5560. %% offset from \code{rsp} to set up the stack arguments. We put the first
  5561. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  5562. %% so on.
  5563. %% Upon calling the function, the stack arguments are retrieved by the
  5564. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  5565. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  5566. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  5567. %% the layout of the caller and callee frames. Notice how important it is
  5568. %% that we correctly compute the maximum number of arguments needed for
  5569. %% function calls; if that number is too small then the arguments and
  5570. %% local variables will smash into each other!
  5571. \subsection{Efficient Tail Calls}
  5572. \label{sec:tail-call}
  5573. In general, the amount of stack space used by a program is determined
  5574. by the longest chain of nested function calls. That is, if function
  5575. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  5576. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  5577. $n$ can grow quite large in the case of recursive or mutually
  5578. recursive functions. However, in some cases we can arrange to use only
  5579. constant space, i.e. $O(1)$, instead of $O(n)$.
  5580. If a function call is the last action in a function body, then that
  5581. call is said to be a \emph{tail call}. In such situations, the frame
  5582. of the caller is no longer needed, so we can pop the caller's frame
  5583. before making the tail call. With this approach, a recursive function
  5584. that only makes tail calls will only use $O(1)$ stack space.
  5585. Functional languages like Racket typically rely heavily on recursive
  5586. functions, so they typically guarantee that all tail calls will be
  5587. optimized in this way.
  5588. However, some care is needed with regards to argument passing in tail
  5589. calls. As mentioned above, for arguments beyond the sixth, the
  5590. convention is to use space in the caller's frame for passing
  5591. arguments. But here we've popped the caller's frame and can no longer
  5592. use it. Another alternative is to use space in the callee's frame for
  5593. passing arguments. However, this option is also problematic because
  5594. the caller and callee's frame overlap in memory. As we begin to copy
  5595. the arguments from their sources in the caller's frame, the target
  5596. locations in the callee's frame might overlap with the sources for
  5597. later arguments! We solve this problem by not using the stack for
  5598. parameter passing but instead use the heap, as we describe in the
  5599. Section~\ref{sec:limit-functions-r4}.
  5600. As mentioned above, for a tail call we pop the caller's frame prior to
  5601. making the tail call. The instructions for popping a frame are the
  5602. instructions that we usually place in the conclusion of a
  5603. function. Thus, we also need to place such code immediately before
  5604. each tail call. These instructions include restoring the callee-saved
  5605. registers, so it is good that the argument passing registers are all
  5606. caller-saved registers.
  5607. One last note regarding which instruction to use to make the tail
  5608. call. When the callee is finished, it should not return to the current
  5609. function, but it should return to the function that called the current
  5610. one. Thus, the return address that is already on the stack is the
  5611. right one, and we should not use \key{callq} to make the tail call, as
  5612. that would unnecessarily overwrite the return address. Instead we can
  5613. simply use the \key{jmp} instruction. Like the indirect function call,
  5614. we write an indirect jump with a register prefixed with an asterisk.
  5615. We recommend using \code{rax} to hold the jump target because the
  5616. preceding ``conclusion'' overwrites just about everything else.
  5617. \begin{lstlisting}
  5618. jmp *%rax
  5619. \end{lstlisting}
  5620. %% Now that we have a good understanding of functions as they appear in
  5621. %% $R_4$ and the support for functions in x86, we need to plan the
  5622. %% changes to our compiler, that is, do we need any new passes and/or do
  5623. %% we need to change any existing passes? Also, do we need to add new
  5624. %% kinds of AST nodes to any of the intermediate languages?
  5625. \section{Shrink $R_4$}
  5626. \label{sec:shrink-r4}
  5627. The \code{shrink} pass performs a couple minor modifications to the
  5628. grammar to ease the later passes. This pass adds an empty $\itm{info}$
  5629. field to each function definition:
  5630. \begin{lstlisting}
  5631. (define (|$f$| [|$x_1 : \Type_1$| ...) : |$\Type_r$| |$\Exp$|)
  5632. |$\Rightarrow$| (define (|$f$| [|$x_1 : \Type_1$| ...) : |$\Type_r$| () |$\Exp$|)
  5633. \end{lstlisting}
  5634. and introduces an explicit \code{main} function.\\
  5635. \begin{tabular}{lll}
  5636. \begin{minipage}{0.45\textwidth}
  5637. \begin{lstlisting}
  5638. (program |$\itm{info}$| |$ds$| ... |$\Exp$|)
  5639. \end{lstlisting}
  5640. \end{minipage}
  5641. &
  5642. $\Rightarrow$
  5643. &
  5644. \begin{minipage}{0.45\textwidth}
  5645. \begin{lstlisting}
  5646. (program |$\itm{info}$| |$ds'$| |$\itm{mainDef}$|)
  5647. \end{lstlisting}
  5648. \end{minipage}
  5649. \end{tabular} \\
  5650. where $\itm{mainDef}$ is
  5651. \begin{lstlisting}
  5652. (define (main) : Integer () |$\Exp'$|)
  5653. \end{lstlisting}
  5654. \section{Reveal Functions}
  5655. \label{sec:reveal-functions-r4}
  5656. Going forward, the syntax of $R_4$ is inconvenient for purposes of
  5657. compilation because it conflates the use of function names and local
  5658. variables. This is a problem because we need to compile the use of a
  5659. function name differently than the use of a local variable; we need to
  5660. use \code{leaq} to convert the function name (a label in x86) to an
  5661. address in a register. Thus, it is a good idea to create a new pass
  5662. that changes function references from just a symbol $f$ to
  5663. \code{(fun-ref $f$)}. A good name for this pass is
  5664. \code{reveal-functions} and the output language, $F_1$, is defined in
  5665. Figure~\ref{fig:f1-syntax}.
  5666. \begin{figure}[tp]
  5667. \centering
  5668. \fbox{
  5669. \begin{minipage}{0.96\textwidth}
  5670. \[
  5671. \begin{array}{lcl}
  5672. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  5673. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void} \mid (\Type^{*} \; \key{->}\; \Type)} \\
  5674. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)} \\
  5675. &\mid& \gray{ \Var \mid \LET{\Var}{\Exp}{\Exp} }\\
  5676. &\mid& \gray{ \key{\#t} \mid \key{\#f} \mid
  5677. (\key{not}\;\Exp)} \mid \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  5678. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  5679. (\key{vector-ref}\;\Exp\;\Int)} \\
  5680. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void}) \mid
  5681. (\key{app}\; \Exp \; \Exp^{*})} \\
  5682. &\mid& (\key{fun-ref}\, \itm{label}) \\
  5683. \Def &::=& \gray{(\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  5684. F_1 &::=& \gray{(\key{program}\;\itm{info} \; \Def^{*})}
  5685. \end{array}
  5686. \]
  5687. \end{minipage}
  5688. }
  5689. \caption{The $F_1$ language, an extension of $R_4$
  5690. (Figure~\ref{fig:r4-syntax}).}
  5691. \label{fig:f1-syntax}
  5692. \end{figure}
  5693. %% Distinguishing between calls in tail position and non-tail position
  5694. %% requires the pass to have some notion of context. We recommend using
  5695. %% two mutually recursive functions, one for processing expressions in
  5696. %% tail position and another for the rest.
  5697. Placing this pass after \code{uniquify} is a good idea, because it
  5698. will make sure that there are no local variables and functions that
  5699. share the same name. On the other hand, \code{reveal-functions} needs
  5700. to come before the \code{explicate-control} pass because that pass
  5701. will help us compile \code{fun-ref} into assignment statements.
  5702. \section{Limit Functions}
  5703. \label{sec:limit-functions-r4}
  5704. This pass transforms functions so that they have at most six
  5705. parameters and transforms all function calls so that they pass at most
  5706. six arguments. A simple strategy for imposing an argument limit of
  5707. length $n$ is to take all arguments $i$ where $i \geq n$ and pack them
  5708. into a vector, making that subsequent vector the $n$th argument.
  5709. \begin{tabular}{lll}
  5710. \begin{minipage}{0.2\textwidth}
  5711. \begin{lstlisting}
  5712. (|$f$| |$x_1$| |$\ldots$| |$x_n$|)
  5713. \end{lstlisting}
  5714. \end{minipage}
  5715. &
  5716. $\Rightarrow$
  5717. &
  5718. \begin{minipage}{0.4\textwidth}
  5719. \begin{lstlisting}
  5720. (|$f$| |$x_1$| |$\ldots$| |$x_5$| (vector |$x_6$| |$\ldots$| |$x_n$|))
  5721. \end{lstlisting}
  5722. \end{minipage}
  5723. \end{tabular}
  5724. In the body of the function, all occurrences of the $i$th argument in
  5725. which $i>5$ must be replaced with a \code{vector-ref}.
  5726. \section{Remove Complex Operators and Operands}
  5727. \label{sec:rco-r4}
  5728. The primary decisions to make for this pass is whether to classify
  5729. \code{fun-ref} and \code{app} as either simple or complex
  5730. expressions. Recall that a simple expression will eventually end up as
  5731. just an ``immediate'' argument of an x86 instruction. Function
  5732. application will be translated to a sequence of instructions, so
  5733. \code{app} must be classified as complex expression. Regarding
  5734. \code{fun-ref}, as discussed above, the function label needs to
  5735. be converted to an address using the \code{leaq} instruction. Thus,
  5736. even though \code{fun-ref} seems rather simple, it needs to be
  5737. classified as a complex expression so that we generate an assignment
  5738. statement with a left-hand side that can serve as the target of the
  5739. \code{leaq}.
  5740. \section{Explicate Control and the $C_3$ language}
  5741. \label{sec:explicate-control-r4}
  5742. Figure~\ref{fig:c3-syntax} defines the syntax for $C_3$, the output of
  5743. \key{explicate-control}. The three mutually recursive functions for
  5744. this pass, for assignment, tail, and predicate contexts, must all be
  5745. updated with cases for \code{fun-ref} and \code{app}. In
  5746. assignment and predicate contexts, \code{app} becomes \code{call},
  5747. whereas in tail position \code{app} becomes \code{tailcall}. We
  5748. recommend defining a new function for processing function definitions.
  5749. This code is similar to the case for \code{program} in $R_3$. The
  5750. top-level \code{explicate-control} function that handles the
  5751. \code{program} form of $R_4$ can then apply this new function to all
  5752. the function definitions.
  5753. \begin{figure}[tp]
  5754. \fbox{
  5755. \begin{minipage}{0.96\textwidth}
  5756. \[
  5757. \begin{array}{lcl}
  5758. \Arg &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  5759. \\
  5760. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5761. \Exp &::= & \gray{ \Arg \mid (\key{read}) \mid (\key{-}\;\Arg) \mid (\key{+} \; \Arg\;\Arg)
  5762. \mid (\key{not}\;\Arg) \mid (\itm{cmp}\;\Arg\;\Arg) } \\
  5763. &\mid& \gray{ (\key{allocate}\,\Int\,\Type)
  5764. \mid (\key{vector-ref}\, \Arg\, \Int) } \\
  5765. &\mid& \gray{ (\key{vector-set!}\,\Arg\,\Int\,\Arg) \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) } \\
  5766. &\mid& (\key{fun-ref}\,\itm{label}) \mid (\key{call} \,\Arg\,\Arg^{*}) \\
  5767. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  5768. \mid (\key{collect} \,\itm{int}) }\\
  5769. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  5770. &\mid& \gray{(\key{goto}\,\itm{label})
  5771. \mid \IF{(\itm{cmp}\, \Arg\,\Arg)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  5772. &\mid& (\key{tailcall} \,\Arg\,\Arg^{*}) \\
  5773. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; ((\itm{label}\,\key{.}\,\Tail)^{+})) \\
  5774. C_3 & ::= & (\key{program}\;\itm{info}\;\Def^{*})
  5775. \end{array}
  5776. \]
  5777. \end{minipage}
  5778. }
  5779. \caption{The $C_3$ language, extending $C_2$ (Figure~\ref{fig:c2-syntax}) with functions.}
  5780. \label{fig:c3-syntax}
  5781. \end{figure}
  5782. \section{Uncover Locals}
  5783. \label{sec:uncover-locals-r4}
  5784. The function for processing $\Tail$ should be updated with a case for
  5785. \code{tailcall}. We also recommend creating a new function for
  5786. processing function definitions. Each function definition in $C_3$ has
  5787. its own set of local variables, so the code for function definitions
  5788. should be similar to the case for the \code{program} form in $C_2$.
  5789. \section{Select Instructions}
  5790. \label{sec:select-r4}
  5791. The output of select instructions is a program in the x86$_3$
  5792. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  5793. \begin{figure}[tp]
  5794. \fbox{
  5795. \begin{minipage}{0.96\textwidth}
  5796. \[
  5797. \begin{array}{lcl}
  5798. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg}
  5799. \mid (\key{deref}\,\Reg\,\Int) } \\
  5800. &\mid& \gray{ (\key{byte-reg}\; \Reg)
  5801. \mid (\key{global-value}\; \itm{name}) } \\
  5802. &\mid& (\key{fun-ref}\; \itm{label})\\
  5803. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  5804. \Instr &::=& \gray{ (\key{addq} \; \Arg\; \Arg) \mid
  5805. (\key{subq} \; \Arg\; \Arg) \mid
  5806. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) } \\
  5807. &\mid& \gray{ (\key{callq} \; \mathit{label}) \mid
  5808. (\key{pushq}\;\Arg) \mid
  5809. (\key{popq}\;\Arg) \mid
  5810. (\key{retq}) } \\
  5811. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  5812. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  5813. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  5814. \mid (\key{jmp} \; \itm{label})
  5815. \mid (\key{j}\itm{cc} \; \itm{label})
  5816. \mid (\key{label} \; \itm{label}) } \\
  5817. &\mid& (\key{indirect-callq}\;\Arg ) \mid (\key{tail-jmp}\;\Arg) \\
  5818. &\mid& (\key{leaq}\;\Arg\;\Arg)\\
  5819. \Block &::= & \gray{(\key{block} \;\itm{info}\; \Instr^{+})} \\
  5820. \Def &::= & (\key{define} \; (\itm{label}) \;\itm{info}\; ((\itm{label} \,\key{.}\, \Block)^{+}))\\
  5821. x86_3 &::= & (\key{program} \;\itm{info} \;\Def^{*})
  5822. \end{array}
  5823. \]
  5824. \end{minipage}
  5825. }
  5826. \caption{The x86$_3$ language (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  5827. \label{fig:x86-3}
  5828. \end{figure}
  5829. An assignment of \code{fun-ref} becomes a \code{leaq} instruction
  5830. as follows: \\
  5831. \begin{tabular}{lll}
  5832. \begin{minipage}{0.45\textwidth}
  5833. \begin{lstlisting}
  5834. (assign |$\itm{lhs}$| (fun-ref |$f$|))
  5835. \end{lstlisting}
  5836. \end{minipage}
  5837. &
  5838. $\Rightarrow$
  5839. &
  5840. \begin{minipage}{0.4\textwidth}
  5841. \begin{lstlisting}
  5842. (leaq (fun-ref |$f$|) |$\itm{lhs}$|)
  5843. \end{lstlisting}
  5844. \end{minipage}
  5845. \end{tabular} \\
  5846. Regarding function definitions, we need to remove their parameters and
  5847. instead perform parameter passing in terms of the conventions
  5848. discussed in Section~\ref{sec:fun-x86}. That is, the arguments will be
  5849. in the argument passing registers, and inside the function we should
  5850. generate a \code{movq} instruction for each parameter, to move the
  5851. argument value from the appropriate register to a new local variable
  5852. with the same name as the old parameter.
  5853. Next, consider the compilation of function calls, which have the
  5854. following form upon input to \code{select-instructions}.
  5855. \begin{lstlisting}
  5856. (assign |\itm{lhs}| (call |\itm{fun}| |\itm{args}| |$\ldots$|))
  5857. \end{lstlisting}
  5858. In the mirror image of handling the parameters of function
  5859. definitions, the arguments \itm{args} need to be moved to the argument
  5860. passing registers.
  5861. %
  5862. Once the instructions for parameter passing have been generated, the
  5863. function call itself can be performed with an indirect function call,
  5864. for which I recommend creating the new instruction
  5865. \code{indirect-callq}. Of course, the return value from the function
  5866. is stored in \code{rax}, so it needs to be moved into the \itm{lhs}.
  5867. \begin{lstlisting}
  5868. (indirect-callq |\itm{fun}|)
  5869. (movq (reg rax) |\itm{lhs}|)
  5870. \end{lstlisting}
  5871. Regarding tail calls, the parameter passing is the same as non-tail
  5872. calls: generate instructions to move the arguments into to the
  5873. argument passing registers. After that we need to pop the frame from
  5874. the procedure call stack. However, we do not yet know how big the
  5875. frame is; that gets determined during register allocation. So instead
  5876. of generating those instructions here, we invent a new instruction
  5877. that means ``pop the frame and then do an indirect jump'', which we
  5878. name \code{tail-jmp}.
  5879. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  5880. using the label \code{start} for the initial block of a program, and
  5881. in Section~\ref{sec:select-r1} we recommended labeling the conclusion
  5882. of the program with \code{conclusion}, so that $(\key{return}\;\Arg)$
  5883. can be compiled to an assignment to \code{rax} followed by a jump to
  5884. \code{conclusion}. With the addition of function definitions, we will
  5885. have a starting block and conclusion for each function, but their
  5886. labels need to be unique. We recommend prepending the function's name
  5887. to \code{start} and \code{conclusion}, respectively, to obtain unique
  5888. labels. (Alternatively, one could \code{gensym} labels for the start
  5889. and conclusion and store them in the $\itm{info}$ field of the
  5890. function definition.)
  5891. \section{Uncover Live}
  5892. %% The rest of the passes need only minor modifications to handle the new
  5893. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  5894. %% \code{leaq}.
  5895. Inside \code{uncover-live}, when computing the $W$ set (written
  5896. variables) for an \code{indirect-callq} instruction, we recommend
  5897. including all the caller-saved registers, which will have the affect
  5898. of making sure that no caller-saved register actually needs to be
  5899. saved.
  5900. \section{Build Interference Graph}
  5901. With the addition of function definitions, we compute an interference
  5902. graph for each function (not just one for the whole program).
  5903. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  5904. spill vector-typed variables that are live during a call to the
  5905. \code{collect}. With the addition of functions to our language, we
  5906. need to revisit this issue. Many functions will perform allocation and
  5907. therefore have calls to the collector inside of them. Thus, we should
  5908. not only spill a vector-typed variable when it is live during a call
  5909. to \code{collect}, but we should spill the variable if it is live
  5910. during any function call. Thus, in the \code{build-interference} pass,
  5911. we recommend adding interference edges between call-live vector-typed
  5912. variables and the callee-saved registers (in addition to the usual
  5913. addition of edges between call-live variables and the caller-saved
  5914. registers).
  5915. \section{Patch Instructions}
  5916. In \code{patch-instructions}, you should deal with the x86
  5917. idiosyncrasy that the destination argument of \code{leaq} must be a
  5918. register. Additionally, you should ensure that the argument of
  5919. \code{tail-jmp} is \itm{rax}, our reserved register---this is to make
  5920. code generation more convenient, because we will be trampling many
  5921. registers before the tail call (as explained below).
  5922. \section{Print x86}
  5923. For the \code{print-x86} pass, we recommend the following translations:
  5924. \begin{lstlisting}
  5925. (fun-ref |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  5926. (indirect-callq |\itm{arg}|) |$\Rightarrow$| callq *|\itm{arg}|
  5927. \end{lstlisting}
  5928. Handling \code{tail-jmp} requires a bit more care. A straightforward
  5929. translation of \code{tail-jmp} would be \code{jmp *$\itm{arg}$}, which
  5930. is what we will want to do, but before the jump we need to pop the
  5931. current frame. So we need to restore the state of the registers to the
  5932. point they were at when the current function was called. This
  5933. sequence of instructions is the same as the code for the conclusion of
  5934. a function.
  5935. Note that your \code{print-x86} pass needs to add the code for saving
  5936. and restoring callee-saved registers, if you have not already
  5937. implemented that. This is necessary when generating code for function
  5938. definitions.
  5939. \section{An Example Translation}
  5940. Figure~\ref{fig:add-fun} shows an example translation of a simple
  5941. function in $R_4$ to x86. The figure also includes the results of the
  5942. \code{explicate-control} and \code{select-instructions} passes. We
  5943. have omitted the \code{has-type} AST nodes for readability. Can you
  5944. see any ways to improve the translation?
  5945. \begin{figure}[tbp]
  5946. \begin{tabular}{ll}
  5947. \begin{minipage}{0.45\textwidth}
  5948. % s3_2.rkt
  5949. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5950. (program
  5951. (define (add [x : Integer]
  5952. [y : Integer])
  5953. : Integer (+ x y))
  5954. (add 40 2))
  5955. \end{lstlisting}
  5956. $\Downarrow$
  5957. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5958. (program ()
  5959. (define (add86 [x87 : Integer]
  5960. [y88 : Integer]) : Integer ()
  5961. ((add86start . (return (+ x87 y88)))))
  5962. (define (main) : Integer ()
  5963. ((mainstart .
  5964. (seq (assign tmp89 (fun-ref add86))
  5965. (tailcall tmp89 40 2))))))
  5966. \end{lstlisting}
  5967. \end{minipage}
  5968. &
  5969. $\Rightarrow$
  5970. \begin{minipage}{0.5\textwidth}
  5971. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5972. (program ()
  5973. (define (add86)
  5974. ((locals (x87 . Integer) (y88 . Integer))
  5975. (num-params . 2))
  5976. ((add86start .
  5977. (block ()
  5978. (movq (reg rcx) (var x87))
  5979. (movq (reg rdx) (var y88))
  5980. (movq (var x87) (reg rax))
  5981. (addq (var y88) (reg rax))
  5982. (jmp add86conclusion)))))
  5983. (define (main)
  5984. ((locals . ((tmp89 . (Integer Integer -> Integer))))
  5985. (num-params . 0))
  5986. ((mainstart .
  5987. (block ()
  5988. (leaq (fun-ref add86) (var tmp89))
  5989. (movq (int 40) (reg rcx))
  5990. (movq (int 2) (reg rdx))
  5991. (tail-jmp (var tmp89))))))
  5992. \end{lstlisting}
  5993. $\Downarrow$
  5994. \end{minipage}
  5995. \end{tabular}
  5996. \begin{tabular}{lll}
  5997. \begin{minipage}{0.3\textwidth}
  5998. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5999. _add90start:
  6000. movq %rcx, %rsi
  6001. movq %rdx, %rcx
  6002. movq %rsi, %rax
  6003. addq %rcx, %rax
  6004. jmp _add90conclusion
  6005. .globl _add90
  6006. .align 16
  6007. _add90:
  6008. pushq %rbp
  6009. movq %rsp, %rbp
  6010. pushq %r12
  6011. pushq %rbx
  6012. pushq %r13
  6013. pushq %r14
  6014. subq $0, %rsp
  6015. jmp _add90start
  6016. _add90conclusion:
  6017. addq $0, %rsp
  6018. popq %r14
  6019. popq %r13
  6020. popq %rbx
  6021. popq %r12
  6022. subq $0, %r15
  6023. popq %rbp
  6024. retq
  6025. \end{lstlisting}
  6026. \end{minipage}
  6027. &
  6028. \begin{minipage}{0.3\textwidth}
  6029. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6030. _mainstart:
  6031. leaq _add90(%rip), %rsi
  6032. movq $40, %rcx
  6033. movq $2, %rdx
  6034. movq %rsi, %rax
  6035. addq $0, %rsp
  6036. popq %r14
  6037. popq %r13
  6038. popq %rbx
  6039. popq %r12
  6040. subq $0, %r15
  6041. popq %rbp
  6042. jmp *%rax
  6043. .globl _main
  6044. .align 16
  6045. _main:
  6046. pushq %rbp
  6047. movq %rsp, %rbp
  6048. pushq %r12
  6049. pushq %rbx
  6050. pushq %r13
  6051. pushq %r14
  6052. subq $0, %rsp
  6053. movq $16384, %rdi
  6054. movq $16, %rsi
  6055. callq _initialize
  6056. movq _rootstack_begin(%rip), %r15
  6057. jmp _mainstart
  6058. \end{lstlisting}
  6059. \end{minipage}
  6060. &
  6061. \begin{minipage}{0.3\textwidth}
  6062. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6063. _mainconclusion:
  6064. addq $0, %rsp
  6065. popq %r14
  6066. popq %r13
  6067. popq %rbx
  6068. popq %r12
  6069. subq $0, %r15
  6070. popq %rbp
  6071. retq
  6072. \end{lstlisting}
  6073. \end{minipage}
  6074. \end{tabular}
  6075. \caption{Example compilation of a simple function to x86.}
  6076. \label{fig:add-fun}
  6077. \end{figure}
  6078. \begin{exercise}\normalfont
  6079. Expand your compiler to handle $R_4$ as outlined in this chapter.
  6080. Create 5 new programs that use functions, including examples that pass
  6081. functions and return functions from other functions and including
  6082. recursive functions. Test your compiler on these new programs and all
  6083. of your previously created test programs.
  6084. \end{exercise}
  6085. \begin{figure}[p]
  6086. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6087. \node (R4) at (0,2) {\large $R_4$};
  6088. \node (R4-2) at (3,2) {\large $R_4$};
  6089. \node (R4-3) at (6,2) {\large $R_4$};
  6090. \node (F1-1) at (12,0) {\large $F_1$};
  6091. \node (F1-2) at (9,0) {\large $F_1$};
  6092. \node (F1-3) at (6,0) {\large $F_1$};
  6093. \node (F1-4) at (3,0) {\large $F_1$};
  6094. \node (C3-1) at (6,-2) {\large $C_3$};
  6095. \node (C3-2) at (3,-2) {\large $C_3$};
  6096. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  6097. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  6098. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  6099. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  6100. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  6101. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  6102. \path[->,bend left=15] (R4) edge [above] node
  6103. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  6104. \path[->,bend left=15] (R4-2) edge [above] node
  6105. {\ttfamily\footnotesize uniquify} (R4-3);
  6106. \path[->,bend left=15] (R4-3) edge [right] node
  6107. {\ttfamily\footnotesize\color{red} reveal-functions} (F1-1);
  6108. \path[->,bend left=15] (F1-1) edge [below] node
  6109. {\ttfamily\footnotesize\color{red} limit-functions} (F1-2);
  6110. \path[->,bend right=15] (F1-2) edge [above] node
  6111. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  6112. \path[->,bend right=15] (F1-3) edge [above] node
  6113. {\ttfamily\footnotesize\color{red} remove-complex.} (F1-4);
  6114. \path[->,bend left=15] (F1-4) edge [right] node
  6115. {\ttfamily\footnotesize\color{red} explicate-control} (C3-1);
  6116. \path[->,bend left=15] (C3-1) edge [below] node
  6117. {\ttfamily\footnotesize\color{red} uncover-locals} (C3-2);
  6118. \path[->,bend right=15] (C3-2) edge [left] node
  6119. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  6120. \path[->,bend left=15] (x86-2) edge [left] node
  6121. {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  6122. \path[->,bend right=15] (x86-2-1) edge [below] node
  6123. {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  6124. \path[->,bend right=15] (x86-2-2) edge [left] node
  6125. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6126. \path[->,bend left=15] (x86-3) edge [above] node
  6127. {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  6128. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  6129. \end{tikzpicture}
  6130. \caption{Diagram of the passes for $R_4$, a language with functions.}
  6131. \label{fig:R4-passes}
  6132. \end{figure}
  6133. Figure~\ref{fig:R4-passes} gives an overview of the passes needed for
  6134. the compilation of $R_4$.
  6135. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6136. \chapter{Lexically Scoped Functions}
  6137. \label{ch:lambdas}
  6138. This chapter studies lexically scoped functions as they appear in
  6139. functional languages such as Racket. By lexical scoping we mean that a
  6140. function's body may refer to variables whose binding site is outside
  6141. of the function, in an enclosing scope.
  6142. %
  6143. Consider the example in Figure~\ref{fig:lexical-scoping} featuring an
  6144. anonymous function defined using the \key{lambda} form. The body of
  6145. the \key{lambda}, refers to three variables: \code{x}, \code{y}, and
  6146. \code{z}. The binding sites for \code{x} and \code{y} are outside of
  6147. the \key{lambda}. Variable \code{y} is bound by the enclosing
  6148. \key{let} and \code{x} is a parameter of \code{f}. The \key{lambda} is
  6149. returned from the function \code{f}. Below the definition of \code{f},
  6150. we have two calls to \code{f} with different arguments for \code{x},
  6151. first \code{5} then \code{3}. The functions returned from \code{f} are
  6152. bound to variables \code{g} and \code{h}. Even though these two
  6153. functions were created by the same \code{lambda}, they are really
  6154. different functions because they use different values for
  6155. \code{x}. Finally, we apply \code{g} to \code{11} (producing
  6156. \code{20}) and apply \code{h} to \code{15} (producing \code{22}) so
  6157. the result of this program is \code{42}.
  6158. \begin{figure}[btp]
  6159. % s4_6.rkt
  6160. \begin{lstlisting}
  6161. (define (f [x : Integer]) : (Integer -> Integer)
  6162. (let ([y 4])
  6163. (lambda: ([z : Integer]) : Integer
  6164. (+ x (+ y z)))))
  6165. (let ([g (f 5)])
  6166. (let ([h (f 3)])
  6167. (+ (g 11) (h 15))))
  6168. \end{lstlisting}
  6169. \caption{Example of a lexically scoped function.}
  6170. \label{fig:lexical-scoping}
  6171. \end{figure}
  6172. \section{The $R_5$ Language}
  6173. The syntax for this language with anonymous functions and lexical
  6174. scoping, $R_5$, is defined in Figure~\ref{fig:r5-syntax}. It adds the
  6175. \key{lambda} form to the grammar for $R_4$, which already has syntax
  6176. for function application. In this chapter we shall describe how to
  6177. compile $R_5$ back into $R_4$, compiling lexically-scoped functions
  6178. into a combination of functions (as in $R_4$) and tuples (as in
  6179. $R_3$).
  6180. \begin{figure}[tp]
  6181. \centering
  6182. \fbox{
  6183. \begin{minipage}{0.96\textwidth}
  6184. \[
  6185. \begin{array}{lcl}
  6186. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6187. \mid (\key{Vector}\;\Type^{+}) \mid \key{Void}
  6188. \mid (\Type^{*} \; \key{->}\; \Type)} \\
  6189. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6190. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  6191. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}}\\
  6192. &\mid& \gray{\key{\#t} \mid \key{\#f}
  6193. \mid (\key{and}\;\Exp\;\Exp)
  6194. \mid (\key{or}\;\Exp\;\Exp)
  6195. \mid (\key{not}\;\Exp) } \\
  6196. &\mid& \gray{(\key{eq?}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6197. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  6198. (\key{vector-ref}\;\Exp\;\Int)} \\
  6199. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  6200. &\mid& \gray{(\Exp \; \Exp^{*})} \\
  6201. &\mid& (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp) \\
  6202. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6203. R_5 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  6204. \end{array}
  6205. \]
  6206. \end{minipage}
  6207. }
  6208. \caption{Syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax})
  6209. with \key{lambda}.}
  6210. \label{fig:r5-syntax}
  6211. \end{figure}
  6212. To compile lexically-scoped functions to top-level function
  6213. definitions, the compiler will need to provide special treatment to
  6214. variable occurrences such as \code{x} and \code{y} in the body of the
  6215. \code{lambda} of Figure~\ref{fig:lexical-scoping}, for the functions
  6216. of $R_4$ may not refer to variables defined outside the function. To
  6217. identify such variable occurrences, we review the standard notion of
  6218. free variable.
  6219. \begin{definition}
  6220. A variable is \emph{free with respect to an expression} $e$ if the
  6221. variable occurs inside $e$ but does not have an enclosing binding in
  6222. $e$.
  6223. \end{definition}
  6224. For example, the variables \code{x}, \code{y}, and \code{z} are all
  6225. free with respect to the expression \code{(+ x (+ y z))}. On the
  6226. other hand, only \code{x} and \code{y} are free with respect to the
  6227. following expression because \code{z} is bound by the \code{lambda}.
  6228. \begin{lstlisting}
  6229. (lambda: ([z : Integer]) : Integer
  6230. (+ x (+ y z)))
  6231. \end{lstlisting}
  6232. Once we have identified the free variables of a \code{lambda}, we need
  6233. to arrange for some way to transport, at runtime, the values of those
  6234. variables from the point where the \code{lambda} was created to the
  6235. point where the \code{lambda} is applied. Referring again to
  6236. Figure~\ref{fig:lexical-scoping}, the binding of \code{x} to \code{5}
  6237. needs to be used in the application of \code{g} to \code{11}, but the
  6238. binding of \code{x} to \code{3} needs to be used in the application of
  6239. \code{h} to \code{15}. An efficient solution to the problem, due to
  6240. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  6241. free variables together with the function pointer for the lambda's
  6242. code, an arrangement called a \emph{flat closure} (which we shorten to
  6243. just ``closure'') . Fortunately, we have all the ingredients to make
  6244. closures, Chapter~\ref{ch:tuples} gave us vectors and
  6245. Chapter~\ref{ch:functions} gave us function pointers. The function
  6246. pointer shall reside at index $0$ and the values for free variables
  6247. will fill in the rest of the vector. Figure~\ref{fig:closures} depicts
  6248. the two closures created by the two calls to \code{f} in
  6249. Figure~\ref{fig:lexical-scoping}. Because the two closures came from
  6250. the same \key{lambda}, they share the same function pointer but differ
  6251. in the values for the free variable \code{x}.
  6252. \begin{figure}[tbp]
  6253. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  6254. \caption{Example closure representation for the \key{lambda}'s
  6255. in Figure~\ref{fig:lexical-scoping}.}
  6256. \label{fig:closures}
  6257. \end{figure}
  6258. \section{Interpreting $R_5$}
  6259. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  6260. $R_5$. The clause for \key{lambda} saves the current environment
  6261. inside the returned \key{lambda}. Then the clause for \key{app} uses
  6262. the environment from the \key{lambda}, the \code{lam-env}, when
  6263. interpreting the body of the \key{lambda}. The \code{lam-env}
  6264. environment is extended with the mapping of parameters to argument
  6265. values.
  6266. \begin{figure}[tbp]
  6267. \begin{lstlisting}
  6268. (define (interp-exp env)
  6269. (lambda (e)
  6270. (define recur (interp-exp env))
  6271. (match e
  6272. ...
  6273. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  6274. `(lambda ,xs ,body ,env)]
  6275. [`(app ,fun ,args ...)
  6276. (define fun-val ((interp-exp env) fun))
  6277. (define arg-vals (map (interp-exp env) args))
  6278. (match fun-val
  6279. [`(lambda (,xs ...) ,body ,lam-env)
  6280. (define new-env (append (map cons xs arg-vals) lam-env))
  6281. ((interp-exp new-env) body)]
  6282. [else (error "interp-exp, expected function, not" fun-val)])]
  6283. [else (error 'interp-exp "unrecognized expression")]
  6284. )))
  6285. \end{lstlisting}
  6286. \caption{Interpreter for $R_5$.}
  6287. \label{fig:interp-R5}
  6288. \end{figure}
  6289. \section{Type Checking $R_5$}
  6290. Figure~\ref{fig:typecheck-R5} shows how to type check the new
  6291. \key{lambda} form. The body of the \key{lambda} is checked in an
  6292. environment that includes the current environment (because it is
  6293. lexically scoped) and also includes the \key{lambda}'s parameters. We
  6294. require the body's type to match the declared return type.
  6295. \begin{figure}[tbp]
  6296. \begin{lstlisting}
  6297. (define (typecheck-R5 env)
  6298. (lambda (e)
  6299. (match e
  6300. [`(lambda: ([,xs : ,Ts] ...) : ,rT ,body)
  6301. (define new-env (append (map cons xs Ts) env))
  6302. (define bodyT ((typecheck-R5 new-env) body))
  6303. (cond [(equal? rT bodyT)
  6304. `(,@Ts -> ,rT)]
  6305. [else
  6306. (error "mismatch in return type" bodyT rT)])]
  6307. ...
  6308. )))
  6309. \end{lstlisting}
  6310. \caption{Type checking the \key{lambda}'s in $R_5$.}
  6311. \label{fig:typecheck-R5}
  6312. \end{figure}
  6313. \section{Closure Conversion}
  6314. The compiling of lexically-scoped functions into top-level function
  6315. definitions is accomplished in the pass \code{convert-to-closures}
  6316. that comes after \code{reveal-functions} and before
  6317. \code{limit-functions}.
  6318. As usual, we shall implement the pass as a recursive function over the
  6319. AST. All of the action is in the clauses for \key{lambda} and
  6320. \key{app}. We transform a \key{lambda} expression into an expression
  6321. that creates a closure, that is, creates a vector whose first element
  6322. is a function pointer and the rest of the elements are the free
  6323. variables of the \key{lambda}. The \itm{name} is a unique symbol
  6324. generated to identify the function.
  6325. \begin{tabular}{lll}
  6326. \begin{minipage}{0.4\textwidth}
  6327. \begin{lstlisting}
  6328. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  6329. \end{lstlisting}
  6330. \end{minipage}
  6331. &
  6332. $\Rightarrow$
  6333. &
  6334. \begin{minipage}{0.4\textwidth}
  6335. \begin{lstlisting}
  6336. (vector |\itm{name}| |\itm{fvs}| ...)
  6337. \end{lstlisting}
  6338. \end{minipage}
  6339. \end{tabular} \\
  6340. %
  6341. In addition to transforming each \key{lambda} into a \key{vector}, we
  6342. must create a top-level function definition for each \key{lambda}, as
  6343. shown below.\\
  6344. \begin{minipage}{0.8\textwidth}
  6345. \begin{lstlisting}
  6346. (define (|\itm{name}| [clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps}| ...)
  6347. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  6348. ...
  6349. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  6350. |\itm{body'}|)...))
  6351. \end{lstlisting}
  6352. \end{minipage}\\
  6353. The \code{clos} parameter refers to the closure. The $\itm{ps}$
  6354. parameters are the normal parameters of the \key{lambda}. The types
  6355. $\itm{fvts}$ are the types of the free variables in the lambda and the
  6356. underscore is a dummy type because it is rather difficult to give a
  6357. type to the function in the closure's type, and it does not matter.
  6358. The sequence of \key{let} forms bind the free variables to their
  6359. values obtained from the closure.
  6360. We transform function application into code that retrieves the
  6361. function pointer from the closure and then calls the function, passing
  6362. in the closure as the first argument. We bind $e'$ to a temporary
  6363. variable to avoid code duplication.
  6364. \begin{tabular}{lll}
  6365. \begin{minipage}{0.3\textwidth}
  6366. \begin{lstlisting}
  6367. (app |$e$| |\itm{es}| ...)
  6368. \end{lstlisting}
  6369. \end{minipage}
  6370. &
  6371. $\Rightarrow$
  6372. &
  6373. \begin{minipage}{0.5\textwidth}
  6374. \begin{lstlisting}
  6375. (let ([|\itm{tmp}| |$e'$|])
  6376. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  6377. \end{lstlisting}
  6378. \end{minipage}
  6379. \end{tabular} \\
  6380. There is also the question of what to do with top-level function
  6381. definitions. To maintain a uniform translation of function
  6382. application, we turn function references into closures.
  6383. \begin{tabular}{lll}
  6384. \begin{minipage}{0.3\textwidth}
  6385. \begin{lstlisting}
  6386. (fun-ref |$f$|)
  6387. \end{lstlisting}
  6388. \end{minipage}
  6389. &
  6390. $\Rightarrow$
  6391. &
  6392. \begin{minipage}{0.5\textwidth}
  6393. \begin{lstlisting}
  6394. (vector (fun-ref |$f$|))
  6395. \end{lstlisting}
  6396. \end{minipage}
  6397. \end{tabular} \\
  6398. %
  6399. The top-level function definitions need to be updated as well to take
  6400. an extra closure parameter.
  6401. \section{An Example Translation}
  6402. \label{sec:example-lambda}
  6403. Figure~\ref{fig:lexical-functions-example} shows the result of closure
  6404. conversion for the example program demonstrating lexical scoping that
  6405. we discussed at the beginning of this chapter.
  6406. \begin{figure}[h]
  6407. \begin{minipage}{0.8\textwidth}
  6408. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6409. (program
  6410. (define (f [x : Integer]) : (Integer -> Integer)
  6411. (let ([y 4])
  6412. (lambda: ([z : Integer]) : Integer
  6413. (+ x (+ y z)))))
  6414. (let ([g (f 5)])
  6415. (let ([h (f 3)])
  6416. (+ (g 11) (h 15)))))
  6417. \end{lstlisting}
  6418. $\Downarrow$
  6419. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6420. (program (type Integer)
  6421. (define (f (x : Integer)) : (Integer -> Integer)
  6422. (let ((y 4))
  6423. (lambda: ((z : Integer)) : Integer
  6424. (+ x (+ y z)))))
  6425. (let ((g (app (fun-ref f) 5)))
  6426. (let ((h (app (fun-ref f) 3)))
  6427. (+ (app g 11) (app h 15)))))
  6428. \end{lstlisting}
  6429. $\Downarrow$
  6430. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  6431. (program (type Integer)
  6432. (define (f (clos.1 : _) (x : Integer)) : (Integer -> Integer)
  6433. (let ((y 4))
  6434. (vector (fun-ref lam.1) x y)))
  6435. (define (lam.1 (clos.2 : _) (z : Integer)) : Integer
  6436. (let ((x (vector-ref clos.2 1)))
  6437. (let ((y (vector-ref clos.2 2)))
  6438. (+ x (+ y z)))))
  6439. (let ((g (let ((t.1 (vector (fun-ref f))))
  6440. (app (vector-ref t.1 0) t.1 5))))
  6441. (let ((h (let ((t.2 (vector (fun-ref f))))
  6442. (app (vector-ref t.2 0) t.2 3))))
  6443. (+ (let ((t.3 g)) (app (vector-ref t.3 0) t.3 11))
  6444. (let ((t.4 h)) (app (vector-ref t.4 0) t.4 15))))))
  6445. \end{lstlisting}
  6446. \end{minipage}
  6447. \caption{Example of closure conversion.}
  6448. \label{fig:lexical-functions-example}
  6449. \end{figure}
  6450. \begin{figure}[p]
  6451. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6452. \node (R4) at (0,2) {\large $R_4$};
  6453. \node (R4-2) at (3,2) {\large $R_4$};
  6454. \node (R4-3) at (6,2) {\large $R_4$};
  6455. \node (F1-1) at (12,0) {\large $F_1$};
  6456. \node (F1-2) at (9,0) {\large $F_1$};
  6457. \node (F1-3) at (6,0) {\large $F_1$};
  6458. \node (F1-4) at (3,0) {\large $F_1$};
  6459. \node (F1-5) at (0,0) {\large $F_1$};
  6460. \node (C3-1) at (6,-2) {\large $C_3$};
  6461. \node (C3-2) at (3,-2) {\large $C_3$};
  6462. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  6463. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  6464. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  6465. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  6466. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  6467. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  6468. \path[->,bend left=15] (R4) edge [above] node
  6469. {\ttfamily\footnotesize\color{red} typecheck} (R4-2);
  6470. \path[->,bend left=15] (R4-2) edge [above] node
  6471. {\ttfamily\footnotesize uniquify} (R4-3);
  6472. \path[->] (R4-3) edge [right] node
  6473. {\ttfamily\footnotesize reveal-functions} (F1-1);
  6474. \path[->,bend left=15] (F1-1) edge [below] node
  6475. {\ttfamily\footnotesize\color{red} convert-to-clos.} (F1-2);
  6476. \path[->,bend right=15] (F1-2) edge [above] node
  6477. {\ttfamily\footnotesize limit-functions} (F1-3);
  6478. \path[->,bend right=15] (F1-3) edge [above] node
  6479. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  6480. \path[->,bend right=15] (F1-4) edge [above] node
  6481. {\ttfamily\footnotesize remove-complex.} (F1-5);
  6482. \path[->] (F1-5) edge [left] node
  6483. {\ttfamily\footnotesize explicate-control} (C3-1);
  6484. \path[->,bend left=15] (C3-1) edge [below] node
  6485. {\ttfamily\footnotesize uncover-locals} (C3-2);
  6486. \path[->,bend right=15] (C3-2) edge [left] node
  6487. {\ttfamily\footnotesize select-instr.} (x86-2);
  6488. \path[->,bend left=15] (x86-2) edge [left] node
  6489. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6490. \path[->,bend right=15] (x86-2-1) edge [below] node
  6491. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  6492. \path[->,bend right=15] (x86-2-2) edge [left] node
  6493. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6494. \path[->,bend left=15] (x86-3) edge [above] node
  6495. {\ttfamily\footnotesize patch-instr.} (x86-4);
  6496. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  6497. \end{tikzpicture}
  6498. \caption{Diagram of the passes for $R_5$, a language with lexically-scoped
  6499. functions.}
  6500. \label{fig:R5-passes}
  6501. \end{figure}
  6502. Figure~\ref{fig:R5-passes} provides an overview of all the passes needed
  6503. for the compilation of $R_5$.
  6504. \begin{exercise}\normalfont
  6505. Expand your compiler to handle $R_5$ as outlined in this chapter.
  6506. Create 5 new programs that use \key{lambda} functions and make use of
  6507. lexical scoping. Test your compiler on these new programs and all of
  6508. your previously created test programs.
  6509. \end{exercise}
  6510. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6511. \chapter{Dynamic Typing}
  6512. \label{ch:type-dynamic}
  6513. In this chapter we discuss the compilation of a dynamically typed
  6514. language, named $R_7$, that is a subset of the Racket
  6515. language. (Recall that in the previous chapters we have studied
  6516. subsets of the \emph{Typed} Racket language.) In dynamically typed
  6517. languages, an expression may produce values of differing
  6518. type. Consider the following example with a conditional expression
  6519. that may return a Boolean or an integer depending on the input to the
  6520. program.
  6521. \begin{lstlisting}
  6522. (not (if (eq? (read) 1) #f 0))
  6523. \end{lstlisting}
  6524. Languages that allow expressions to produce different kinds of values
  6525. are called \emph{polymorphic}. There are many kinds of polymorphism,
  6526. such as subtype polymorphism and parametric
  6527. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism are
  6528. talking about here does not have a special name, but it is the usual
  6529. kind that arises in dynamically typed languages.
  6530. Another characteristic of dynamically typed languages is that
  6531. primitive operations, such as \code{not}, are often defined to operate
  6532. on many different types of values. In fact, in Racket, the \code{not}
  6533. operator produces a result for any kind of value: given \code{\#f} it
  6534. returns \code{\#t} and given anything else it returns \code{\#f}.
  6535. Furthermore, even when primitive operations restrict their inputs to
  6536. values of a certain type, this restriction is enforced at runtime
  6537. instead of during compilation. For example, the following vector
  6538. reference results in a run-time contract violation.
  6539. \begin{lstlisting}
  6540. (vector-ref (vector 42) #t)
  6541. \end{lstlisting}
  6542. \begin{figure}[tp]
  6543. \centering
  6544. \fbox{
  6545. \begin{minipage}{0.97\textwidth}
  6546. \[
  6547. \begin{array}{rcl}
  6548. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  6549. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6550. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp) \\
  6551. &\mid& \Var \mid \LET{\Var}{\Exp}{\Exp} \\
  6552. &\mid& \key{\#t} \mid \key{\#f}
  6553. \mid (\key{and}\;\Exp\;\Exp)
  6554. \mid (\key{or}\;\Exp\;\Exp)
  6555. \mid (\key{not}\;\Exp) \\
  6556. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp} \\
  6557. &\mid& (\key{vector}\;\Exp^{+}) \mid
  6558. (\key{vector-ref}\;\Exp\;\Exp) \\
  6559. &\mid& (\key{vector-set!}\;\Exp\;\Exp\;\Exp) \mid (\key{void}) \\
  6560. &\mid& (\Exp \; \Exp^{*}) \mid (\key{lambda}\; (\Var^{*}) \; \Exp) \\
  6561. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  6562. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  6563. \Def &::=& (\key{define}\; (\Var \; \Var^{*}) \; \Exp) \\
  6564. R_7 &::=& (\key{program} \; \Def^{*}\; \Exp)
  6565. \end{array}
  6566. \]
  6567. \end{minipage}
  6568. }
  6569. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  6570. \label{fig:r7-syntax}
  6571. \end{figure}
  6572. The syntax of $R_7$, our subset of Racket, is defined in
  6573. Figure~\ref{fig:r7-syntax}.
  6574. %
  6575. The definitional interpreter for $R_7$ is given in
  6576. Figure~\ref{fig:interp-R7}.
  6577. \begin{figure}[tbp]
  6578. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6579. (define (get-tagged-type v) (match v [`(tagged ,v1 ,ty) ty]))
  6580. (define (valid-op? op) (member op '(+ - and or not)))
  6581. (define (interp-r7 env)
  6582. (lambda (ast)
  6583. (define recur (interp-r7 env))
  6584. (match ast
  6585. [(? symbol?) (lookup ast env)]
  6586. [(? integer?) `(inject ,ast Integer)]
  6587. [#t `(inject #t Boolean)]
  6588. [#f `(inject #f Boolean)]
  6589. [`(read) `(inject ,(read-fixnum) Integer)]
  6590. [`(lambda (,xs ...) ,body)
  6591. `(inject (lambda ,xs ,body ,env) (,@(map (lambda (x) 'Any) xs) -> Any))]
  6592. [`(define (,f ,xs ...) ,body)
  6593. (mcons f `(lambda ,xs ,body))]
  6594. [`(program ,ds ... ,body)
  6595. (let ([top-level (for/list ([d ds]) ((interp-r7 '()) d))])
  6596. (for/list ([b top-level])
  6597. (set-mcdr! b (match (mcdr b)
  6598. [`(lambda ,xs ,body)
  6599. `(inject (lambda ,xs ,body ,top-level)
  6600. (,@(map (lambda (x) 'Any) xs) -> Any))])))
  6601. ((interp-r7 top-level) body))]
  6602. [`(vector ,(app recur elts) ...)
  6603. (define tys (map get-tagged-type elts))
  6604. `(inject ,(apply vector elts) (Vector ,@tys))]
  6605. [`(vector-set! ,(app recur v1) ,n ,(app recur v2))
  6606. (match v1
  6607. [`(inject ,vec ,ty)
  6608. (vector-set! vec n v2)
  6609. `(inject (void) Void)])]
  6610. [`(vector-ref ,(app recur v) ,n)
  6611. (match v [`(inject ,vec ,ty) (vector-ref vec n)])]
  6612. [`(let ([,x ,(app recur v)]) ,body)
  6613. ((interp-r7 (cons (cons x v) env)) body)]
  6614. [`(,op ,es ...) #:when (valid-op? op)
  6615. (interp-r7-op op (for/list ([e es]) (recur e)))]
  6616. [`(eq? ,(app recur l) ,(app recur r))
  6617. `(inject ,(equal? l r) Boolean)]
  6618. [`(if ,(app recur q) ,t ,f)
  6619. (match q
  6620. [`(inject #f Boolean) (recur f)]
  6621. [else (recur t)])]
  6622. [`(,(app recur f-val) ,(app recur vs) ...)
  6623. (match f-val
  6624. [`(inject (lambda (,xs ...) ,body ,lam-env) ,ty)
  6625. (define new-env (append (map cons xs vs) lam-env))
  6626. ((interp-r7 new-env) body)]
  6627. [else (error "interp-r7, expected function, not" f-val)])])))
  6628. \end{lstlisting}
  6629. \caption{Interpreter for the $R_7$ language. UPDATE ME -Jeremy}
  6630. \label{fig:interp-R7}
  6631. \end{figure}
  6632. Let us consider how we might compile $R_7$ to x86, thinking about the
  6633. first example above. Our bit-level representation of the Boolean
  6634. \code{\#f} is zero and similarly for the integer \code{0}. However,
  6635. \code{(not \#f)} should produce \code{\#t} whereas \code{(not 0)}
  6636. should produce \code{\#f}. Furthermore, the behavior of \code{not}, in
  6637. general, cannot be determined at compile time, but depends on the
  6638. runtime type of its input, as in the example above that depends on the
  6639. result of \code{(read)}.
  6640. The way around this problem is to include information about a value's
  6641. runtime type in the value itself, so that this information can be
  6642. inspected by operators such as \code{not}. In particular, we shall
  6643. steal the 3 right-most bits from our 64-bit values to encode the
  6644. runtime type. We shall use $001$ to identify integers, $100$ for
  6645. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  6646. void value. We shall refer to these 3 bits as the \emph{tag} and we
  6647. define the following auxiliary function.
  6648. \begin{align*}
  6649. \itm{tagof}(\key{Integer}) &= 001 \\
  6650. \itm{tagof}(\key{Boolean}) &= 100 \\
  6651. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  6652. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  6653. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  6654. \itm{tagof}(\key{Void}) &= 101
  6655. \end{align*}
  6656. (We shall say more about the new \key{Vectorof} type shortly.)
  6657. This stealing of 3 bits comes at some
  6658. price: our integers are reduced to ranging from $-2^{60}$ to
  6659. $2^{60}$. The stealing does not adversely affect vectors and
  6660. procedures because those values are addresses, and our addresses are
  6661. 8-byte aligned so the rightmost 3 bits are unused, they are always
  6662. $000$. Thus, we do not lose information by overwriting the rightmost 3
  6663. bits with the tag and we can simply zero-out the tag to recover the
  6664. original address.
  6665. In some sense, these tagged values are a new kind of value. Indeed,
  6666. we can extend our \emph{typed} language with tagged values by adding a
  6667. new type to classify them, called \key{Any}, and with operations for
  6668. creating and using tagged values, yielding the $R_6$ language that we
  6669. define in Section~\ref{sec:r6-lang}. The $R_6$ language provides the
  6670. fundamental support for polymorphism and runtime types that we need to
  6671. support dynamic typing.
  6672. There is an interesting interaction between tagged values and garbage
  6673. collection. A variable of type \code{Any} might refer to a vector and
  6674. therefore it might be a root that needs to be inspected and copied
  6675. during garbage collection. Thus, we need to treat variables of type
  6676. \code{Any} in a similar way to variables of type \code{Vector} for
  6677. purposes of register allocation, which we discuss in
  6678. Section~\ref{sec:register-allocation-r6}. One concern is that, if a
  6679. variable of type \code{Any} is spilled, it must be spilled to the root
  6680. stack. But this means that the garbage collector needs to be able to
  6681. differentiate between (1) plain old pointers to tuples, (2) a tagged
  6682. value that points to a tuple, and (3) a tagged value that is not a
  6683. tuple. We enable this differentiation by choosing not to use the tag
  6684. $000$. Instead, that bit pattern is reserved for identifying plain old
  6685. pointers to tuples. On the other hand, if one of the first three bits
  6686. is set, then we have a tagged value, and inspecting the tag can
  6687. differentiation between vectors ($010$) and the other kinds of values.
  6688. We shall implement our untyped language $R_7$ by compiling it to $R_6$
  6689. (Section~\ref{sec:compile-r7}), but first we describe the how to
  6690. extend our compiler to handle the new features of $R_6$
  6691. (Sections~\ref{sec:shrink-r6}, \ref{sec:select-r6}, and
  6692. \ref{sec:register-allocation-r6}).
  6693. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  6694. \label{sec:r6-lang}
  6695. \begin{figure}[tp]
  6696. \centering
  6697. \fbox{
  6698. \begin{minipage}{0.97\textwidth}
  6699. \[
  6700. \begin{array}{lcl}
  6701. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6702. \mid (\key{Vector}\;\Type^{+}) \mid (\key{Vectorof}\;\Type) \mid \key{Void}} \\
  6703. &\mid& \gray{(\Type^{*} \; \key{->}\; \Type)} \mid \key{Any} \\
  6704. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void} \mid (\key{Vectorof}\;\key{Any}) \mid (\key{Vector}\; \key{Any}^{*}) \\
  6705. &\mid& (\key{Any}^{*} \; \key{->}\; \key{Any})\\
  6706. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  6707. \Exp &::=& \gray{\Int \mid (\key{read}) \mid (\key{-}\;\Exp)
  6708. \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-} \; \Exp\;\Exp)} \\
  6709. &\mid& \gray{\Var \mid \LET{\Var}{\Exp}{\Exp}} \\
  6710. &\mid& \gray{\key{\#t} \mid \key{\#f}
  6711. \mid (\key{and}\;\Exp\;\Exp)
  6712. \mid (\key{or}\;\Exp\;\Exp)
  6713. \mid (\key{not}\;\Exp)} \\
  6714. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \IF{\Exp}{\Exp}{\Exp}} \\
  6715. &\mid& \gray{(\key{vector}\;\Exp^{+}) \mid
  6716. (\key{vector-ref}\;\Exp\;\Int)} \\
  6717. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})} \\
  6718. &\mid& \gray{(\Exp \; \Exp^{*})
  6719. \mid (\key{lambda:}\; ([\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6720. & \mid & (\key{inject}\; \Exp \; \FType) \mid (\key{project}\;\Exp\;\FType) \\
  6721. & \mid & (\key{boolean?}\;\Exp) \mid (\key{integer?}\;\Exp)\\
  6722. & \mid & (\key{vector?}\;\Exp) \mid (\key{procedure?}\;\Exp) \mid (\key{void?}\;\Exp) \\
  6723. \Def &::=& \gray{(\key{define}\; (\Var \; [\Var \key{:} \Type]^{*}) \key{:} \Type \; \Exp)} \\
  6724. R_6 &::=& \gray{(\key{program} \; \Def^{*} \; \Exp)}
  6725. \end{array}
  6726. \]
  6727. \end{minipage}
  6728. }
  6729. \caption{Syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax})
  6730. with \key{Any}.}
  6731. \label{fig:r6-syntax}
  6732. \end{figure}
  6733. The syntax of $R_6$ is defined in Figure~\ref{fig:r6-syntax}. The
  6734. $(\key{inject}\; e\; T)$ form converts the value produced by
  6735. expression $e$ of type $T$ into a tagged value. The
  6736. $(\key{project}\;e\;T)$ form converts the tagged value produced by
  6737. expression $e$ into a value of type $T$ or else halts the program if
  6738. the type tag is equivalent to $T$. We treat
  6739. $(\key{Vectorof}\;\key{Any})$ as equivalent to
  6740. $(\key{Vector}\;\key{Any}\;\ldots)$.
  6741. Note that in both \key{inject} and
  6742. \key{project}, the type $T$ is restricted to the flat types $\FType$,
  6743. which simplifies the implementation and corresponds with what is
  6744. needed for compiling untyped Racket. The type predicates,
  6745. $(\key{boolean?}\,e)$ etc., expect a tagged value and return \key{\#t}
  6746. if the tag corresponds to the predicate, and return \key{\#t}
  6747. otherwise.
  6748. %
  6749. Selections from the type checker for $R_6$ are shown in
  6750. Figure~\ref{fig:typecheck-R6} and the interpreter for $R_6$ is in
  6751. Figure~\ref{fig:interp-R6}.
  6752. \begin{figure}[btp]
  6753. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6754. (define (flat-ty? ty) ...)
  6755. (define (typecheck-R6 env)
  6756. (lambda (e)
  6757. (define recur (typecheck-R6 env))
  6758. (match e
  6759. [`(inject ,e ,ty)
  6760. (unless (flat-ty? ty)
  6761. (error "may only inject a value of flat type, not ~a" ty))
  6762. (define-values (new-e e-ty) (recur e))
  6763. (cond
  6764. [(equal? e-ty ty)
  6765. (values `(inject ,new-e ,ty) 'Any)]
  6766. [else
  6767. (error "inject expected ~a to have type ~a" e ty)])]
  6768. [`(project ,e ,ty)
  6769. (unless (flat-ty? ty)
  6770. (error "may only project to a flat type, not ~a" ty))
  6771. (define-values (new-e e-ty) (recur e))
  6772. (cond
  6773. [(equal? e-ty 'Any)
  6774. (values `(project ,new-e ,ty) ty)]
  6775. [else
  6776. (error "project expected ~a to have type Any" e)])]
  6777. [`(vector-ref ,e ,i)
  6778. (define-values (new-e e-ty) (recur e))
  6779. (match e-ty
  6780. [`(Vector ,ts ...) ...]
  6781. [`(Vectorof ,ty)
  6782. (unless (exact-nonnegative-integer? i)
  6783. (error 'type-check "invalid index ~a" i))
  6784. (values `(vector-ref ,new-e ,i) ty)]
  6785. [else (error "expected a vector in vector-ref, not" e-ty)])]
  6786. ...
  6787. )))
  6788. \end{lstlisting}
  6789. \caption{Type checker for parts of the $R_6$ language.}
  6790. \label{fig:typecheck-R6}
  6791. \end{figure}
  6792. % to do: add rules for vector-ref, etc. for Vectorof
  6793. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  6794. \begin{figure}[btp]
  6795. \begin{lstlisting}
  6796. (define primitives (set 'boolean? ...))
  6797. (define (interp-op op)
  6798. (match op
  6799. ['boolean? (lambda (v)
  6800. (match v
  6801. [`(tagged ,v1 Boolean) #t]
  6802. [else #f]))]
  6803. ...))
  6804. ;; Equivalence of flat types
  6805. (define (tyeq? t1 t2)
  6806. (match `(,t1 ,t2)
  6807. [`((Vectorof Any) (Vector ,t2s ...))
  6808. (for/and ([t2 t2s]) (eq? t2 'Any))]
  6809. [`((Vector ,t1s ...) (Vectorof Any))
  6810. (for/and ([t1 t1s]) (eq? t1 'Any))]
  6811. [else (equal? t1 t2)]))
  6812. (define (interp-R6 env)
  6813. (lambda (ast)
  6814. (match ast
  6815. [`(inject ,e ,t)
  6816. `(tagged ,((interp-R6 env) e) ,t)]
  6817. [`(project ,e ,t2)
  6818. (define v ((interp-R6 env) e))
  6819. (match v
  6820. [`(tagged ,v1 ,t1)
  6821. (cond [(tyeq? t1 t2)
  6822. v1]
  6823. [else
  6824. (error "in project, type mismatch" t1 t2)])]
  6825. [else
  6826. (error "in project, expected tagged value" v)])]
  6827. ...)))
  6828. \end{lstlisting}
  6829. \caption{Interpreter for $R_6$.}
  6830. \label{fig:interp-R6}
  6831. \end{figure}
  6832. %\clearpage
  6833. \section{Shrinking $R_6$}
  6834. \label{sec:shrink-r6}
  6835. In the \code{shrink} pass we recommend compiling \code{project} into
  6836. an explicit \code{if} expression that uses three new operations:
  6837. \code{tag-of-any}, \code{value-of-any}, and \code{exit}. The
  6838. \code{tag-of-any} operation retrieves the type tag from a tagged value
  6839. of type \code{Any}. The \code{value-of-any} retrieves the underlying
  6840. value from a tagged value. Finally, the \code{exit} operation ends the
  6841. execution of the program by invoking the operating system's
  6842. \code{exit} function. So the translation for \code{project} is as
  6843. follows. (We have omitted the \code{has-type} AST nodes to make this
  6844. output more readable.)
  6845. \begin{tabular}{lll}
  6846. \begin{minipage}{0.3\textwidth}
  6847. \begin{lstlisting}
  6848. (project |$e$| |$\Type$|)
  6849. \end{lstlisting}
  6850. \end{minipage}
  6851. &
  6852. $\Rightarrow$
  6853. &
  6854. \begin{minipage}{0.5\textwidth}
  6855. \begin{lstlisting}
  6856. (let ([|$\itm{tmp}$| |$e'$|])
  6857. (if (eq? (tag-of-any |$\itm{tmp}$|) |$\itm{tag}$|)
  6858. (value-of-any |$\itm{tmp}$|)
  6859. (exit)))
  6860. \end{lstlisting}
  6861. \end{minipage}
  6862. \end{tabular} \\
  6863. Similarly, we recommend translating the type predicates
  6864. (\code{boolean?}, etc.) into uses of \code{tag-of-any} and \code{eq?}.
  6865. \section{Instruction Selection for $R_6$}
  6866. \label{sec:select-r6}
  6867. \paragraph{Inject}
  6868. We recommend compiling an \key{inject} as follows if the type is
  6869. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  6870. destination to the left by the number of bits specified its source
  6871. argument (in this case $3$, the length of the tag) and it preserves
  6872. the sign of the integer. We use the \key{orq} instruction to combine
  6873. the tag and the value to form the tagged value. \\
  6874. \begin{tabular}{lll}
  6875. \begin{minipage}{0.4\textwidth}
  6876. \begin{lstlisting}
  6877. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  6878. \end{lstlisting}
  6879. \end{minipage}
  6880. &
  6881. $\Rightarrow$
  6882. &
  6883. \begin{minipage}{0.5\textwidth}
  6884. \begin{lstlisting}
  6885. (movq |$e'$| |\itm{lhs}'|)
  6886. (salq (int 3) |\itm{lhs}'|)
  6887. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  6888. \end{lstlisting}
  6889. \end{minipage}
  6890. \end{tabular} \\
  6891. The instruction selection for vectors and procedures is different
  6892. because their is no need to shift them to the left. The rightmost 3
  6893. bits are already zeros as described above. So we just combine the
  6894. value and the tag using \key{orq}. \\
  6895. \begin{tabular}{lll}
  6896. \begin{minipage}{0.4\textwidth}
  6897. \begin{lstlisting}
  6898. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  6899. \end{lstlisting}
  6900. \end{minipage}
  6901. &
  6902. $\Rightarrow$
  6903. &
  6904. \begin{minipage}{0.5\textwidth}
  6905. \begin{lstlisting}
  6906. (movq |$e'$| |\itm{lhs}'|)
  6907. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  6908. \end{lstlisting}
  6909. \end{minipage}
  6910. \end{tabular}
  6911. \paragraph{Tag of Any}
  6912. Recall that the \code{tag-of-any} operation extracts the type tag from
  6913. a value of type \code{Any}. The type tag is the bottom three bits, so
  6914. we obtain the tag by taking the bitwise-and of the value with $111$
  6915. ($7$ in decimal).
  6916. \begin{tabular}{lll}
  6917. \begin{minipage}{0.4\textwidth}
  6918. \begin{lstlisting}
  6919. (assign |\itm{lhs}| (tag-of-any |$e$|))
  6920. \end{lstlisting}
  6921. \end{minipage}
  6922. &
  6923. $\Rightarrow$
  6924. &
  6925. \begin{minipage}{0.5\textwidth}
  6926. \begin{lstlisting}
  6927. (movq |$e'$| |\itm{lhs}'|)
  6928. (andq (int 7) |\itm{lhs}'|)
  6929. \end{lstlisting}
  6930. \end{minipage}
  6931. \end{tabular}
  6932. \paragraph{Value of Any}
  6933. Like \key{inject}, the instructions for \key{value-of-any} are
  6934. different depending on whether the type $T$ is a pointer (vector or
  6935. procedure) or not (Integer or Boolean). The following shows the
  6936. instruction selection for Integer and Boolean. We produce an untagged
  6937. value by shifting it to the right by 3 bits.
  6938. %
  6939. \\
  6940. \begin{tabular}{lll}
  6941. \begin{minipage}{0.4\textwidth}
  6942. \begin{lstlisting}
  6943. (assign |\itm{lhs}| (project |$e$| |$T$|))
  6944. \end{lstlisting}
  6945. \end{minipage}
  6946. &
  6947. $\Rightarrow$
  6948. &
  6949. \begin{minipage}{0.5\textwidth}
  6950. \begin{lstlisting}
  6951. (movq |$e'$| |\itm{lhs}'|)
  6952. (sarq (int 3) |\itm{lhs}'|)
  6953. \end{lstlisting}
  6954. \end{minipage}
  6955. \end{tabular} \\
  6956. %
  6957. In the case for vectors and procedures, there is no need to
  6958. shift. Instead we just need to zero-out the rightmost 3 bits. We
  6959. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  6960. decimal) and apply \code{bitwise-not} to obtain $\ldots 1000$ which we
  6961. \code{movq} into the destination $\itm{lhs}$. We then generate
  6962. \code{andq} with the tagged value to get the desired result. \\
  6963. %
  6964. \begin{tabular}{lll}
  6965. \begin{minipage}{0.4\textwidth}
  6966. \begin{lstlisting}
  6967. (assign |\itm{lhs}| (project |$e$| |$T$|))
  6968. \end{lstlisting}
  6969. \end{minipage}
  6970. &
  6971. $\Rightarrow$
  6972. &
  6973. \begin{minipage}{0.5\textwidth}
  6974. \begin{lstlisting}
  6975. (movq (int |$\ldots 1000$|) |\itm{lhs}'|)
  6976. (andq |$e'$| |\itm{lhs}'|)
  6977. \end{lstlisting}
  6978. \end{minipage}
  6979. \end{tabular}
  6980. %% \paragraph{Type Predicates} We leave it to the reader to
  6981. %% devise a sequence of instructions to implement the type predicates
  6982. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  6983. \section{Register Allocation for $R_6$}
  6984. \label{sec:register-allocation-r6}
  6985. As mentioned above, a variable of type \code{Any} might refer to a
  6986. vector. Thus, the register allocator for $R_6$ needs to treat variable
  6987. of type \code{Any} in the same way that it treats variables of type
  6988. \code{Vector} for purposes of garbage collection. In particular,
  6989. \begin{itemize}
  6990. \item If a variable of type \code{Any} is live during a function call,
  6991. then it must be spilled. One way to accomplish this is to augment
  6992. the pass \code{build-interference} to mark all variables that are
  6993. live after a \code{callq} as interfering with all the registers.
  6994. \item If a variable of type \code{Any} is spilled, it must be spilled
  6995. to the root stack instead of the normal procedure call stack.
  6996. \end{itemize}
  6997. \begin{exercise}\normalfont
  6998. Expand your compiler to handle $R_6$ as discussed in the last few
  6999. sections. Create 5 new programs that use the \code{Any} type and the
  7000. new operations (\code{inject}, \code{project}, \code{boolean?},
  7001. etc.). Test your compiler on these new programs and all of your
  7002. previously created test programs.
  7003. \end{exercise}
  7004. \section{Compiling $R_7$ to $R_6$}
  7005. \label{sec:compile-r7}
  7006. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  7007. $R_7$ forms into $R_6$. An important invariant of this pass is that
  7008. given a subexpression $e$ of $R_7$, the pass will produce an
  7009. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  7010. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  7011. the Boolean \code{\#t}, which must be injected to produce an
  7012. expression of type \key{Any}.
  7013. %
  7014. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  7015. addition, is representative of compilation for many operations: the
  7016. arguments have type \key{Any} and must be projected to \key{Integer}
  7017. before the addition can be performed.
  7018. The compilation of \key{lambda} (third row of
  7019. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  7020. produce type annotations: we simply use \key{Any}.
  7021. %
  7022. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  7023. has to account for some differences in behavior between $R_7$ and
  7024. $R_6$. The $R_7$ language is more permissive than $R_6$ regarding what
  7025. kind of values can be used in various places. For example, the
  7026. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  7027. the arguments need not be of the same type (but in that case, the
  7028. result will be \code{\#f}).
  7029. \begin{figure}[btp]
  7030. \centering
  7031. \begin{tabular}{|lll|} \hline
  7032. \begin{minipage}{0.25\textwidth}
  7033. \begin{lstlisting}
  7034. #t
  7035. \end{lstlisting}
  7036. \end{minipage}
  7037. &
  7038. $\Rightarrow$
  7039. &
  7040. \begin{minipage}{0.6\textwidth}
  7041. \begin{lstlisting}
  7042. (inject #t Boolean)
  7043. \end{lstlisting}
  7044. \end{minipage}
  7045. \\[2ex]\hline
  7046. \begin{minipage}{0.25\textwidth}
  7047. \begin{lstlisting}
  7048. (+ |$e_1$| |$e_2$|)
  7049. \end{lstlisting}
  7050. \end{minipage}
  7051. &
  7052. $\Rightarrow$
  7053. &
  7054. \begin{minipage}{0.6\textwidth}
  7055. \begin{lstlisting}
  7056. (inject
  7057. (+ (project |$e'_1$| Integer)
  7058. (project |$e'_2$| Integer))
  7059. Integer)
  7060. \end{lstlisting}
  7061. \end{minipage}
  7062. \\[2ex]\hline
  7063. \begin{minipage}{0.25\textwidth}
  7064. \begin{lstlisting}
  7065. (lambda (|$x_1 \ldots$|) |$e$|)
  7066. \end{lstlisting}
  7067. \end{minipage}
  7068. &
  7069. $\Rightarrow$
  7070. &
  7071. \begin{minipage}{0.6\textwidth}
  7072. \begin{lstlisting}
  7073. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  7074. (Any|$\ldots$|Any -> Any))
  7075. \end{lstlisting}
  7076. \end{minipage}
  7077. \\[2ex]\hline
  7078. \begin{minipage}{0.25\textwidth}
  7079. \begin{lstlisting}
  7080. (app |$e_0$| |$e_1 \ldots e_n$|)
  7081. \end{lstlisting}
  7082. \end{minipage}
  7083. &
  7084. $\Rightarrow$
  7085. &
  7086. \begin{minipage}{0.6\textwidth}
  7087. \begin{lstlisting}
  7088. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  7089. |$e'_1 \ldots e'_n$|)
  7090. \end{lstlisting}
  7091. \end{minipage}
  7092. \\[2ex]\hline
  7093. \begin{minipage}{0.25\textwidth}
  7094. \begin{lstlisting}
  7095. (vector-ref |$e_1$| |$e_2$|)
  7096. \end{lstlisting}
  7097. \end{minipage}
  7098. &
  7099. $\Rightarrow$
  7100. &
  7101. \begin{minipage}{0.6\textwidth}
  7102. \begin{lstlisting}
  7103. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  7104. (let ([tmp2 (project |$e'_2$| Integer)])
  7105. (vector-ref tmp1 tmp2)))
  7106. \end{lstlisting}
  7107. \end{minipage}
  7108. \\[2ex]\hline
  7109. \begin{minipage}{0.25\textwidth}
  7110. \begin{lstlisting}
  7111. (if |$e_1$| |$e_2$| |$e_3$|)
  7112. \end{lstlisting}
  7113. \end{minipage}
  7114. &
  7115. $\Rightarrow$
  7116. &
  7117. \begin{minipage}{0.6\textwidth}
  7118. \begin{lstlisting}
  7119. (if (eq? |$e'_1$| (inject #f Boolean))
  7120. |$e'_3$|
  7121. |$e'_2$|)
  7122. \end{lstlisting}
  7123. \end{minipage}
  7124. \\[2ex]\hline
  7125. \begin{minipage}{0.25\textwidth}
  7126. \begin{lstlisting}
  7127. (eq? |$e_1$| |$e_2$|)
  7128. \end{lstlisting}
  7129. \end{minipage}
  7130. &
  7131. $\Rightarrow$
  7132. &
  7133. \begin{minipage}{0.6\textwidth}
  7134. \begin{lstlisting}
  7135. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  7136. \end{lstlisting}
  7137. \end{minipage}
  7138. \\[2ex]\hline
  7139. \end{tabular}
  7140. \caption{Compiling $R_7$ to $R_6$.}
  7141. \label{fig:compile-r7-r6}
  7142. \end{figure}
  7143. \begin{exercise}\normalfont
  7144. Expand your compiler to handle $R_7$ as outlined in this chapter.
  7145. Create tests for $R_7$ by adapting all of your previous test programs
  7146. by removing type annotations. Add 5 more tests programs that
  7147. specifically rely on the language being dynamically typed. That is,
  7148. they should not be legal programs in a statically typed language, but
  7149. nevertheless, they should be valid $R_7$ programs that run to
  7150. completion without error.
  7151. \end{exercise}
  7152. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7153. \chapter{Gradual Typing}
  7154. \label{ch:gradual-typing}
  7155. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  7156. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7157. \chapter{Parametric Polymorphism}
  7158. \label{ch:parametric-polymorphism}
  7159. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  7160. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  7161. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7162. \chapter{High-level Optimization}
  7163. \label{ch:high-level-optimization}
  7164. This chapter will present a procedure inlining pass based on the
  7165. algorithm of \citet{Waddell:1997fk}.
  7166. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7167. \chapter{Appendix}
  7168. \section{Interpreters}
  7169. \label{appendix:interp}
  7170. We provide several interpreters in the \key{interp.rkt} file. The
  7171. \key{interp-scheme} function takes an AST in one of the Racket-like
  7172. languages considered in this book ($R_1, R_2, \ldots$) and interprets
  7173. the program, returning the result value. The \key{interp-C} function
  7174. interprets an AST for a program in one of the C-like languages ($C_0,
  7175. C_1, \ldots$), and the \code{interp-x86} function interprets an AST
  7176. for an x86 program.
  7177. \section{Utility Functions}
  7178. \label{appendix:utilities}
  7179. The utility function described in this section can be found in the
  7180. \key{utilities.rkt} file.
  7181. The \key{read-program} function takes a file path and parses that file
  7182. (it must be a Racket program) into an abstract syntax tree with a
  7183. \key{Program} node at the top.
  7184. The \key{parse-program} function takes an S-expression representation
  7185. of an AST and converts it into the struct-based representation.
  7186. The \key{assert} function displays the error message \key{msg} if the
  7187. Boolean \key{bool} is false.
  7188. \begin{lstlisting}
  7189. (define (assert msg bool) ...)
  7190. \end{lstlisting}
  7191. The \key{lookup} function takes a key and an association list (a list
  7192. of key-value pairs), and returns the first value that is associated
  7193. with the given key, if there is one. If not, an error is triggered.
  7194. The association list may contain both immutable pairs (built with
  7195. \key{cons}) and mutable pairs (built with \key{mcons}).
  7196. The \key{map2} function ...
  7197. %% \subsection{Graphs}
  7198. %% \begin{itemize}
  7199. %% \item The \code{make-graph} function takes a list of vertices
  7200. %% (symbols) and returns a graph.
  7201. %% \item The \code{add-edge} function takes a graph and two vertices and
  7202. %% adds an edge to the graph that connects the two vertices. The graph
  7203. %% is updated in-place. There is no return value for this function.
  7204. %% \item The \code{adjacent} function takes a graph and a vertex and
  7205. %% returns the set of vertices that are adjacent to the given
  7206. %% vertex. The return value is a Racket \code{hash-set} so it can be
  7207. %% used with functions from the \code{racket/set} module.
  7208. %% \item The \code{vertices} function takes a graph and returns the list
  7209. %% of vertices in the graph.
  7210. %% \end{itemize}
  7211. \subsection{Testing}
  7212. The \key{interp-tests} function takes a compiler name (a string), a
  7213. description of the passes, an interpreter for the source language, a
  7214. test family name (a string), and a list of test numbers, and runs the
  7215. compiler passes and the interpreters to check whether the passes
  7216. correct. The description of the passes is a list with one entry per
  7217. pass. An entry is a list with three things: a string giving the name
  7218. of the pass, the function that implements the pass (a translator from
  7219. AST to AST), and a function that implements the interpreter (a
  7220. function from AST to result value) for the language of the output of
  7221. the pass. The interpreters from Appendix~\ref{appendix:interp} make a
  7222. good choice. The \key{interp-tests} function assumes that the
  7223. subdirectory \key{tests} has a collection of Scheme programs whose names
  7224. all start with the family name, followed by an underscore and then the
  7225. test number, ending in \key{.scm}. Also, for each Scheme program there
  7226. is a file with the same number except that it ends with \key{.in} that
  7227. provides the input for the Scheme program.
  7228. \begin{lstlisting}
  7229. (define (interp-tests name passes test-family test-nums) ...)
  7230. \end{lstlisting}
  7231. The compiler-tests function takes a compiler name (a string) a
  7232. description of the passes (as described above for
  7233. \code{interp-tests}), a test family name (a string), and a list of
  7234. test numbers (see the comment for interp-tests), and runs the compiler
  7235. to generate x86 (a \key{.s} file) and then runs gcc to generate
  7236. machine code. It runs the machine code and checks that the output is
  7237. 42.
  7238. \begin{lstlisting}
  7239. (define (compiler-tests name passes test-family test-nums) ...)
  7240. \end{lstlisting}
  7241. The compile-file function takes a description of the compiler passes
  7242. (see the comment for \key{interp-tests}) and returns a function that,
  7243. given a program file name (a string ending in \key{.scm}), applies all
  7244. of the passes and writes the output to a file whose name is the same
  7245. as the program file name but with \key{.scm} replaced with \key{.s}.
  7246. \begin{lstlisting}
  7247. (define (compile-file passes)
  7248. (lambda (prog-file-name) ...))
  7249. \end{lstlisting}
  7250. \section{x86 Instruction Set Quick-Reference}
  7251. \label{sec:x86-quick-reference}
  7252. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  7253. do. We write $A \to B$ to mean that the value of $A$ is written into
  7254. location $B$. Address offsets are given in bytes. The instruction
  7255. arguments $A, B, C$ can be immediate constants (such as $\$4$),
  7256. registers (such as $\%rax$), or memory references (such as
  7257. $-4(\%ebp)$). Most x86 instructions only allow at most one memory
  7258. reference per instruction. Other operands must be immediates or
  7259. registers.
  7260. \begin{table}[tbp]
  7261. \centering
  7262. \begin{tabular}{l|l}
  7263. \textbf{Instruction} & \textbf{Operation} \\ \hline
  7264. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  7265. \texttt{negq} $A$ & $- A \to A$ \\
  7266. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  7267. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  7268. \texttt{callq} *$A$ & Calls the function at the address $A$. \\
  7269. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  7270. \texttt{retq} & Pops the return address and jumps to it \\
  7271. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  7272. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  7273. \texttt{leaq} $A$,$B$ & $A \to B$ ($C$ must be a register) \\
  7274. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register \\
  7275. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  7276. matches the condition code of the instruction, otherwise go to the
  7277. next instructions. The condition codes are \key{e} for ``equal'',
  7278. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  7279. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  7280. \texttt{jl} $L$ & \\
  7281. \texttt{jle} $L$ & \\
  7282. \texttt{jg} $L$ & \\
  7283. \texttt{jge} $L$ & \\
  7284. \texttt{jmp} $L$ & Jump to label $L$ \\
  7285. \texttt{movq} $A$, $B$ & $A \to B$ \\
  7286. \texttt{movzbq} $A$, $B$ &
  7287. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  7288. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  7289. and the extra bytes of $B$ are set to zero.} \\
  7290. & \\
  7291. & \\
  7292. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  7293. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  7294. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  7295. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  7296. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  7297. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  7298. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  7299. description of the condition codes. $A$ must be a single byte register
  7300. (e.g., \texttt{al} or \texttt{cl}).} \\
  7301. \texttt{setl} $A$ & \\
  7302. \texttt{setle} $A$ & \\
  7303. \texttt{setg} $A$ & \\
  7304. \texttt{setge} $A$ &
  7305. \end{tabular}
  7306. \vspace{5pt}
  7307. \caption{Quick-reference for the x86 instructions used in this book.}
  7308. \label{tab:x86-instr}
  7309. \end{table}
  7310. \bibliographystyle{plainnat}
  7311. \bibliography{all}
  7312. \end{document}
  7313. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  7314. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  7315. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  7316. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  7317. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator
  7318. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  7319. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  7320. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  7321. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs
  7322. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  7323. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  7324. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  7325. %% LocalWords: boolean typecheck notq cmpq sete movzbq jmp al xorq
  7326. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  7327. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  7328. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  7329. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  7330. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  7331. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  7332. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  7333. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  7334. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  7335. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  7336. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  7337. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  7338. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  7339. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  7340. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  7341. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  7342. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  7343. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  7344. % LocalWords: struct symtab