book.tex 479 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504
  1. % Why direct style instead of continuation passing style?
  2. %% Student project ideas:
  3. %% * high-level optimizations like procedure inlining, etc.
  4. %% * closure optimization
  5. %% * adding letrec to the language
  6. %% (Thought: in the book and regular course, replace top-level defines
  7. %% with letrec.)
  8. %% * alternative back ends (ARM, LLVM)
  9. %% * alternative calling convention (a la Dybvig)
  10. %% * lazy evaluation
  11. %% * gradual typing
  12. %% * continuations (frames in heap a la SML or segmented stack a la Dybvig)
  13. %% * exceptions
  14. %% * self hosting
  15. %% * I/O
  16. %% * foreign function interface
  17. %% * quasi-quote and unquote
  18. %% * macros (too difficult?)
  19. %% * alternative garbage collector
  20. %% * alternative register allocator
  21. %% * parametric polymorphism
  22. %% * type classes (too difficulty?)
  23. %% * loops (too easy? combine with something else?)
  24. %% * loop optimization (fusion, etc.)
  25. %% * deforestation
  26. %% * records and subtyping
  27. %% * object-oriented features
  28. %% - objects, object types, and structural subtyping (e.g. Abadi & Cardelli)
  29. %% - class-based objects and nominal subtyping (e.g. Featherweight Java)
  30. %% * multi-threading, fork join, futures, implicit parallelism
  31. %% * dataflow analysis, type analysis and specialization
  32. \documentclass[11pt]{book}
  33. \usepackage[T1]{fontenc}
  34. \usepackage[utf8]{inputenc}
  35. \usepackage{lmodern}
  36. \usepackage{hyperref}
  37. \usepackage{graphicx}
  38. \usepackage[english]{babel}
  39. \usepackage{listings}
  40. \usepackage{amsmath}
  41. \usepackage{amsthm}
  42. \usepackage{amssymb}
  43. \usepackage{natbib}
  44. \usepackage{stmaryrd}
  45. \usepackage{xypic}
  46. \usepackage{semantic}
  47. \usepackage{wrapfig}
  48. \usepackage{tcolorbox}
  49. \usepackage{multirow}
  50. \usepackage{color}
  51. \usepackage{upquote}
  52. \usepackage{makeidx}
  53. \makeindex
  54. \definecolor{lightgray}{gray}{1}
  55. \newcommand{\black}[1]{{\color{black} #1}}
  56. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  57. \newcommand{\gray}[1]{{\color{gray} #1}}
  58. %% For pictures
  59. \usepackage{tikz}
  60. \usetikzlibrary{arrows.meta}
  61. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  62. % Computer Modern is already the default. -Jeremy
  63. %\renewcommand{\ttdefault}{cmtt}
  64. \definecolor{comment-red}{rgb}{0.8,0,0}
  65. \if01
  66. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  67. \newcommand{\margincomment}[1]{\marginpar{\color{comment-red}\tiny #1}}
  68. \else
  69. \newcommand{\rn}[1]{}
  70. \newcommand{\margincomment}[1]{}
  71. \fi
  72. \lstset{%
  73. language=Lisp,
  74. basicstyle=\ttfamily\small,
  75. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  76. deletekeywords={read,mapping,vector},
  77. escapechar=|,
  78. columns=flexible,
  79. moredelim=[is][\color{red}]{~}{~},
  80. showstringspaces=false
  81. }
  82. \newtheorem{theorem}{Theorem}
  83. \newtheorem{lemma}[theorem]{Lemma}
  84. \newtheorem{corollary}[theorem]{Corollary}
  85. \newtheorem{proposition}[theorem]{Proposition}
  86. \newtheorem{constraint}[theorem]{Constraint}
  87. \newtheorem{definition}[theorem]{Definition}
  88. \newtheorem{exercise}[theorem]{Exercise}
  89. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  90. % 'dedication' environment: To add a dedication paragraph at the start of book %
  91. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  92. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  93. \newenvironment{dedication}
  94. {
  95. \cleardoublepage
  96. \thispagestyle{empty}
  97. \vspace*{\stretch{1}}
  98. \hfill\begin{minipage}[t]{0.66\textwidth}
  99. \raggedright
  100. }
  101. {
  102. \end{minipage}
  103. \vspace*{\stretch{3}}
  104. \clearpage
  105. }
  106. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  107. % Chapter quote at the start of chapter %
  108. % Source: http://tex.stackexchange.com/a/53380 %
  109. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  110. \makeatletter
  111. \renewcommand{\@chapapp}{}% Not necessary...
  112. \newenvironment{chapquote}[2][2em]
  113. {\setlength{\@tempdima}{#1}%
  114. \def\chapquote@author{#2}%
  115. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  116. \itshape}
  117. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  118. \makeatother
  119. \input{defs}
  120. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  121. \title{\Huge \textbf{Essentials of Compilation} \\
  122. \huge The Incremental, Nano-Pass Approach}
  123. \author{\textsc{Jeremy G. Siek} \\
  124. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  125. Indiana University \\
  126. \\
  127. with contributions from: \\
  128. Carl Factora \\
  129. Andre Kuhlenschmidt \\
  130. Ryan R. Newton \\
  131. Ryan Scott \\
  132. Cameron Swords \\
  133. Michael M. Vitousek \\
  134. Michael Vollmer
  135. }
  136. \begin{document}
  137. \frontmatter
  138. \maketitle
  139. \begin{dedication}
  140. This book is dedicated to the programming language wonks at Indiana
  141. University.
  142. \end{dedication}
  143. \tableofcontents
  144. \listoffigures
  145. %\listoftables
  146. \mainmatter
  147. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  148. \chapter*{Preface}
  149. The tradition of compiler writing at Indiana University goes back to
  150. research and courses on programming languages by Professor Daniel
  151. Friedman in the 1970's and 1980's. Friedman conducted research on lazy
  152. evaluation~\citep{Friedman:1976aa} in the context of
  153. Lisp~\citep{McCarthy:1960dz} and then studied
  154. continuations~\citep{Felleisen:kx} and
  155. macros~\citep{Kohlbecker:1986dk} in the context of the
  156. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  157. of those courses, Kent Dybvig, went on to build Chez
  158. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  159. compiler for Scheme. After completing his Ph.D. at the University of
  160. North Carolina, he returned to teach at Indiana University.
  161. Throughout the 1990's and 2000's, Professor Dybvig continued
  162. development of Chez Scheme and taught the compiler course.
  163. The compiler course evolved to incorporate novel pedagogical ideas
  164. while also including elements of effective real-world compilers. One
  165. of Friedman's ideas was to split the compiler into many small
  166. ``passes'' so that the code for each pass would be easy to understood
  167. in isolation. In contrast, most compilers of the time were organized
  168. into only a few monolithic passes for reasons of compile-time
  169. efficiency. Another idea, called ``the game'', was to test the code
  170. generated by each pass on interpreters for each intermediate language,
  171. thereby helping to pinpoint errors in individual passes.
  172. %
  173. Dybvig, with later help from his students Dipanwita Sarkar and Andrew
  174. Keep, developed infrastructure to support this approach and evolved
  175. the course, first to use smaller micro-passes and then into even
  176. smaller nano-passes~\citep{Sarkar:2004fk,Keep:2012aa}. I was a student
  177. in this compiler course in the early 2000's as part of my
  178. Ph.D. studies at Indiana University. Needless to say, I enjoyed the
  179. course immensely!
  180. During that time, another graduate student named Abdulaziz Ghuloum
  181. observed that the front-to-back organization of the course made it
  182. difficult for students to understand the rationale for the compiler
  183. design. Ghuloum proposed an incremental approach in which the students
  184. build the compiler in stages; they start by implementing a complete
  185. compiler for a very small subset of the input language and in each
  186. subsequent stage they add a language feature and add or modify passes
  187. to handle the new feature~\citep{Ghuloum:2006bh}. In this way, the
  188. students see how the language features motivate aspects of the
  189. compiler design.
  190. After graduating from Indiana University in 2005, I went on to teach
  191. at the University of Colorado. I adapted the nano-pass and incremental
  192. approaches to compiling a subset of the Python
  193. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  194. on the surface but there is a large overlap in the compiler techniques
  195. required for the two languages. Thus, I was able to teach much of the
  196. same content from the Indiana compiler course. I very much enjoyed
  197. teaching the course organized in this way, and even better, many of
  198. the students learned a lot and got excited about compilers.
  199. I returned to Indiana University in 2013. In my absence the compiler
  200. course had switched from the front-to-back organization to a
  201. back-to-front organization~\cite{Dybvig:2010aa}. Seeing how well the
  202. incremental approach worked at Colorado, I started porting and
  203. adapting the structure of the Colorado course back into the land of
  204. Scheme. In the meantime Indiana University had moved on from Scheme to
  205. Racket~\citep{plt-tr}, so the course is now about compiling a subset
  206. of Racket (and Typed Racket) to the x86 assembly language.
  207. This is the textbook for the incremental version of the compiler
  208. course at Indiana University (Spring 2016 - present). With this book
  209. I hope to make the Indiana compiler course available to people that
  210. have not had the chance to study compilers at Indiana University.
  211. %% I have captured what
  212. %% I think are the most important topics from \cite{Dybvig:2010aa} but
  213. %% have omitted topics that are less interesting conceptually. I have
  214. %% also made simplifications to reduce complexity. In this way, this
  215. %% book leans more towards pedagogy than towards the efficiency of the
  216. %% generated code. Also, the book differs in places where we I the
  217. %% opportunity to make the topics more fun, such as in relating register
  218. %% allocation to Sudoku (Chapter~\ref{ch:register-allocation-r1}).
  219. \section*{Prerequisites}
  220. The material in this book is challenging but rewarding. It is meant to
  221. prepare students for a lifelong career in programming languages.
  222. The book uses the Racket language both for the implementation of the
  223. compiler and for the language that is compiled, so a student should be
  224. proficient with Racket (or Scheme) prior to reading this book. There
  225. are many excellent resources for learning Scheme and
  226. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  227. It is helpful but not necessary for the student to have prior exposure
  228. to the x86 assembly language~\citep{Intel:2015aa}, as one might obtain
  229. from a computer systems
  230. course~\citep{Bryant:2010aa}. This book introduces the
  231. parts of x86-64 assembly language that are needed.
  232. %
  233. We follow the System V calling
  234. conventions~\citep{Bryant:2005aa,Matz:2013aa}, which means that the
  235. assembly code that we generate will work properly with our runtime
  236. system (written in C) when it is compiled using the GNU C compiler
  237. (\code{gcc}) on the Linux and MacOS operating systems. (Minor
  238. adjustments are needed for MacOS which we note as they arise.)
  239. %
  240. When running on the Microsoft Windows operating system, the GNU C
  241. compiler follows the Microsoft x64 calling
  242. convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the assembly
  243. code that we generate will \emph{not} work properly with our runtime
  244. system on Windows. One option to consider for using a Windows computer
  245. is to run a virtual machine with Linux as the guest operating system.
  246. %\section*{Structure of book}
  247. % You might want to add short description about each chapter in this book.
  248. %\section*{About the companion website}
  249. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  250. %\begin{itemize}
  251. % \item A link to (freely downlodable) latest version of this document.
  252. % \item Link to download LaTeX source for this document.
  253. % \item Miscellaneous material (e.g. suggested readings etc).
  254. %\end{itemize}
  255. \section*{Acknowledgments}
  256. Many people have contributed to the ideas, techniques, and
  257. organization of this book and have taught courses based on it. Many
  258. of the compiler design decisions in this book are drawn from the
  259. assignment descriptions of \cite{Dybvig:2010aa}. We also would like
  260. to thank John Clements, Bor-Yuh Evan Chang, Daniel P. Friedman, Ronald
  261. Garcia, Abdulaziz Ghuloum, Jay McCarthy, Nate Nystrom, Dipanwita
  262. Sarkar, Oscar Waddell, and Michael Wollowski.
  263. \mbox{}\\
  264. \noindent Jeremy G. Siek \\
  265. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  266. %\noindent Spring 2016
  267. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  268. \chapter{Preliminaries}
  269. \label{ch:trees-recur}
  270. In this chapter we review the basic tools that are needed to implement
  271. a compiler. Programs are typically input by a programmer as text,
  272. i.e., a sequence of characters. The program-as-text representation is
  273. called \emph{concrete syntax}. We use concrete syntax to concisely
  274. write down and talk about programs. Inside the compiler, we use
  275. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  276. that efficiently supports the operations that the compiler needs to
  277. perform.\index{concrete syntax}\index{abstract syntax}\index{abstract
  278. syntax tree}\index{AST}\index{program}\index{parse} The translation
  279. from concrete syntax to abstract syntax is a process called
  280. \emph{parsing}~\citep{Aho:1986qf}. We do not cover the theory and
  281. implementation of parsing in this book. A parser is provided in the
  282. supporting materials for translating from concrete to abstract syntax.
  283. ASTs can be represented in many different ways inside the compiler,
  284. depending on the programming language used to write the compiler.
  285. %
  286. We use Racket's
  287. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  288. feature to represent ASTs (Section~\ref{sec:ast}). We use grammars to
  289. define the abstract syntax of programming languages
  290. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  291. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  292. recursive functions to construct and deconstruct entire ASTs
  293. (Section~\ref{sec:recursion}). This chapter provides an brief
  294. introduction to these ideas. \index{struct}
  295. \section{Abstract Syntax Trees and Racket Structures}
  296. \label{sec:ast}
  297. Compilers use abstract syntax trees to represent programs because they
  298. often need to ask questions like: for a given part of a program, what
  299. kind of language feature is it? What are its sub-parts? Consider the
  300. program on the left and its AST on the right. This program is an
  301. addition and it has two sub-parts, a read operation and a
  302. negation. The negation has another sub-part, the integer constant
  303. \code{8}. By using a tree to represent the program, we can easily
  304. follow the links to go from one part of a program to its sub-parts.
  305. \begin{center}
  306. \begin{minipage}{0.4\textwidth}
  307. \begin{lstlisting}
  308. (+ (read) (- 8))
  309. \end{lstlisting}
  310. \end{minipage}
  311. \begin{minipage}{0.4\textwidth}
  312. \begin{equation}
  313. \begin{tikzpicture}
  314. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  315. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  316. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  317. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  318. \draw[->] (plus) to (read);
  319. \draw[->] (plus) to (minus);
  320. \draw[->] (minus) to (8);
  321. \end{tikzpicture}
  322. \label{eq:arith-prog}
  323. \end{equation}
  324. \end{minipage}
  325. \end{center}
  326. We use the standard terminology for trees to describe ASTs: each
  327. circle above is called a \emph{node}. The arrows connect a node to its
  328. \emph{children} (which are also nodes). The top-most node is the
  329. \emph{root}. Every node except for the root has a \emph{parent} (the
  330. node it is the child of). If a node has no children, it is a
  331. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  332. \index{node}
  333. \index{children}
  334. \index{root}
  335. \index{parent}
  336. \index{leaf}
  337. \index{internal node}
  338. %% Recall that an \emph{symbolic expression} (S-expression) is either
  339. %% \begin{enumerate}
  340. %% \item an atom, or
  341. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  342. %% where $e_1$ and $e_2$ are each an S-expression.
  343. %% \end{enumerate}
  344. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  345. %% null value \code{'()}, etc. We can create an S-expression in Racket
  346. %% simply by writing a backquote (called a quasi-quote in Racket)
  347. %% followed by the textual representation of the S-expression. It is
  348. %% quite common to use S-expressions to represent a list, such as $a, b
  349. %% ,c$ in the following way:
  350. %% \begin{lstlisting}
  351. %% `(a . (b . (c . ())))
  352. %% \end{lstlisting}
  353. %% Each element of the list is in the first slot of a pair, and the
  354. %% second slot is either the rest of the list or the null value, to mark
  355. %% the end of the list. Such lists are so common that Racket provides
  356. %% special notation for them that removes the need for the periods
  357. %% and so many parenthesis:
  358. %% \begin{lstlisting}
  359. %% `(a b c)
  360. %% \end{lstlisting}
  361. %% The following expression creates an S-expression that represents AST
  362. %% \eqref{eq:arith-prog}.
  363. %% \begin{lstlisting}
  364. %% `(+ (read) (- 8))
  365. %% \end{lstlisting}
  366. %% When using S-expressions to represent ASTs, the convention is to
  367. %% represent each AST node as a list and to put the operation symbol at
  368. %% the front of the list. The rest of the list contains the children. So
  369. %% in the above case, the root AST node has operation \code{`+} and its
  370. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  371. %% diagram \eqref{eq:arith-prog}.
  372. %% To build larger S-expressions one often needs to splice together
  373. %% several smaller S-expressions. Racket provides the comma operator to
  374. %% splice an S-expression into a larger one. For example, instead of
  375. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  376. %% we could have first created an S-expression for AST
  377. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  378. %% S-expression.
  379. %% \begin{lstlisting}
  380. %% (define ast1.4 `(- 8))
  381. %% (define ast1.1 `(+ (read) ,ast1.4))
  382. %% \end{lstlisting}
  383. %% In general, the Racket expression that follows the comma (splice)
  384. %% can be any expression that produces an S-expression.
  385. We define a Racket \code{struct} for each kind of node. For this
  386. chapter we require just two kinds of nodes: one for integer constants
  387. and one for primitive operations. The following is the \code{struct}
  388. definition for integer constants.
  389. \begin{lstlisting}
  390. (struct Int (value))
  391. \end{lstlisting}
  392. An integer node includes just one thing: the integer value.
  393. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  394. \begin{lstlisting}
  395. (define eight (Int 8))
  396. \end{lstlisting}
  397. We say that the value created by \code{(Int 8)} is an
  398. \emph{instance} of the \code{Int} structure.
  399. The following is the \code{struct} definition for primitives operations.
  400. \begin{lstlisting}
  401. (struct Prim (op args))
  402. \end{lstlisting}
  403. A primitive operation node includes an operator symbol \code{op}
  404. and a list of children \code{args}. For example, to create
  405. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  406. \begin{lstlisting}
  407. (define neg-eight (Prim '- (list eight)))
  408. \end{lstlisting}
  409. Primitive operations may have zero or more children. The \code{read}
  410. operator has zero children:
  411. \begin{lstlisting}
  412. (define rd (Prim 'read '()))
  413. \end{lstlisting}
  414. whereas the addition operator has two children:
  415. \begin{lstlisting}
  416. (define ast1.1 (Prim '+ (list rd neg-eight)))
  417. \end{lstlisting}
  418. We have made a design choice regarding the \code{Prim} structure.
  419. Instead of using one structure for many different operations
  420. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  421. structure for each operation, as follows.
  422. \begin{lstlisting}
  423. (struct Read ())
  424. (struct Add (left right))
  425. (struct Neg (value))
  426. \end{lstlisting}
  427. The reason we choose to use just one structure is that in many parts
  428. of the compiler the code for the different primitive operators is the
  429. same, so we might as well just write that code once, which is enabled
  430. by using a single structure.
  431. When compiling a program such as \eqref{eq:arith-prog}, we need to
  432. know that the operation associated with the root node is addition and
  433. we need to be able to access its two children. Racket provides pattern
  434. matching over structures to support these kinds of queries, as we
  435. see in Section~\ref{sec:pattern-matching}.
  436. In this book, we often write down the concrete syntax of a program
  437. even when we really have in mind the AST because the concrete syntax
  438. is more concise. We recommend that, in your mind, you always think of
  439. programs as abstract syntax trees.
  440. \section{Grammars}
  441. \label{sec:grammar}
  442. \index{integer}
  443. \index{literal}
  444. \index{constant}
  445. A programming language can be thought of as a \emph{set} of programs.
  446. The set is typically infinite (one can always create larger and larger
  447. programs), so one cannot simply describe a language by listing all of
  448. the programs in the language. Instead we write down a set of rules, a
  449. \emph{grammar}, for building programs. Grammars are often used to
  450. define the concrete syntax of a language, but they can also be used to
  451. describe the abstract syntax. We write our rules in a variant of
  452. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  453. \index{Backus-Naur Form}\index{BNF}
  454. As an example, we describe a small language, named $R_0$, that consists of
  455. integers and arithmetic operations.
  456. \index{grammar}
  457. The first grammar rule for the abstract syntax of $R_0$ says that an
  458. instance of the \code{Int} structure is an expression:
  459. \begin{equation}
  460. \Exp ::= \INT{\Int} \label{eq:arith-int}
  461. \end{equation}
  462. %
  463. Each rule has a left-hand-side and a right-hand-side. The way to read
  464. a rule is that if you have an AST node that matches the
  465. right-hand-side, then you can categorize it according to the
  466. left-hand-side.
  467. %
  468. A name such as $\Exp$ that is defined by the grammar rules is a
  469. \emph{non-terminal}. \index{non-terminal}
  470. %
  471. The name $\Int$ is a also a non-terminal, but instead of defining it
  472. with a grammar rule, we define it with the following explanation. We
  473. make the simplifying design decision that all of the languages in this
  474. book only handle machine-representable integers. On most modern
  475. machines this corresponds to integers represented with 64-bits, i.e.,
  476. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  477. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  478. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  479. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  480. that the sequence of decimals represent an integer in range $-2^{62}$
  481. to $2^{62}-1$.
  482. The second grammar rule is the \texttt{read} operation that receives
  483. an input integer from the user of the program.
  484. \begin{equation}
  485. \Exp ::= \READ{} \label{eq:arith-read}
  486. \end{equation}
  487. The third rule says that, given an $\Exp$ node, you can build another
  488. $\Exp$ node by negating it.
  489. \begin{equation}
  490. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  491. \end{equation}
  492. Symbols in typewriter font such as \key{-} and \key{read} are
  493. \emph{terminal} symbols and must literally appear in the program for
  494. the rule to be applicable.
  495. \index{terminal}
  496. We can apply these rules to build ASTs in the $R_0$ language. By rule
  497. \eqref{eq:arith-int}, \texttt{(Int 8)} is an $\Exp$, then by rule
  498. \eqref{eq:arith-neg}, the following AST is an $\Exp$.
  499. \begin{center}
  500. \begin{minipage}{0.4\textwidth}
  501. \begin{lstlisting}
  502. (Prim '- (list (Int 8)))
  503. \end{lstlisting}
  504. \end{minipage}
  505. \begin{minipage}{0.25\textwidth}
  506. \begin{equation}
  507. \begin{tikzpicture}
  508. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  509. \node[draw, circle] (8) at (0, -1.2) {$8$};
  510. \draw[->] (minus) to (8);
  511. \end{tikzpicture}
  512. \label{eq:arith-neg8}
  513. \end{equation}
  514. \end{minipage}
  515. \end{center}
  516. The next grammar rule defines addition expressions:
  517. \begin{equation}
  518. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  519. \end{equation}
  520. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  521. $R_0$. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  522. \eqref{eq:arith-read} and we have already categorized \code{(Prim '-
  523. (list (Int 8)))} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  524. to show that
  525. \begin{lstlisting}
  526. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  527. \end{lstlisting}
  528. is an $\Exp$ in the $R_0$ language.
  529. If you have an AST for which the above rules do not apply, then the
  530. AST is not in $R_0$. For example, the program \code{(- (read) (+ 8))}
  531. is not in $R_0$ because there are no rules for \code{+} with only one
  532. argument, nor for \key{-} with two arguments. Whenever we define a
  533. language with a grammar, the language only includes those programs
  534. that are justified by the rules.
  535. The last grammar rule for $R_0$ states that there is a \code{Program}
  536. node to mark the top of the whole program:
  537. \[
  538. R_0 ::= \PROGRAM{\code{'()}}{\Exp}
  539. \]
  540. The \code{Program} structure is defined as follows
  541. \begin{lstlisting}
  542. (struct Program (info body))
  543. \end{lstlisting}
  544. where \code{body} is an expression. In later chapters, the \code{info}
  545. part will be used to store auxiliary information but for now it is
  546. just the empty list.
  547. It is common to have many grammar rules with the same left-hand side
  548. but different right-hand sides, such as the rules for $\Exp$ in the
  549. grammar of $R_0$. As a short-hand, a vertical bar can be used to
  550. combine several right-hand-sides into a single rule.
  551. We collect all of the grammar rules for the abstract syntax of $R_0$
  552. in Figure~\ref{fig:r0-syntax}. The concrete syntax for $R_0$ is
  553. defined in Figure~\ref{fig:r0-concrete-syntax}.
  554. The \code{read-program} function provided in \code{utilities.rkt} of
  555. the support materials reads a program in from a file (the sequence of
  556. characters in the concrete syntax of Racket) and parses it into an
  557. abstract syntax tree. See the description of \code{read-program} in
  558. Appendix~\ref{appendix:utilities} for more details.
  559. \begin{figure}[tp]
  560. \fbox{
  561. \begin{minipage}{0.96\textwidth}
  562. \[
  563. \begin{array}{rcl}
  564. \begin{array}{rcl}
  565. \Exp &::=& \Int \mid \LP\key{read}\RP \mid \LP\key{-}\;\Exp\RP \mid \LP\key{+} \; \Exp\;\Exp\RP\\
  566. R_0 &::=& \Exp
  567. \end{array}
  568. \end{array}
  569. \]
  570. \end{minipage}
  571. }
  572. \caption{The concrete syntax of $R_0$.}
  573. \label{fig:r0-concrete-syntax}
  574. \end{figure}
  575. \begin{figure}[tp]
  576. \fbox{
  577. \begin{minipage}{0.96\textwidth}
  578. \[
  579. \begin{array}{rcl}
  580. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  581. &\mid& \ADD{\Exp}{\Exp} \\
  582. R_0 &::=& \PROGRAM{\code{'()}}{\Exp}
  583. \end{array}
  584. \]
  585. \end{minipage}
  586. }
  587. \caption{The abstract syntax of $R_0$.}
  588. \label{fig:r0-syntax}
  589. \end{figure}
  590. \section{Pattern Matching}
  591. \label{sec:pattern-matching}
  592. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  593. the parts of an AST node. Racket provides the \texttt{match} form to
  594. access the parts of a structure. Consider the following example and
  595. the output on the right. \index{match} \index{pattern matching}
  596. \begin{center}
  597. \begin{minipage}{0.5\textwidth}
  598. \begin{lstlisting}
  599. (match ast1.1
  600. [(Prim op (list child1 child2))
  601. (print op)])
  602. \end{lstlisting}
  603. \end{minipage}
  604. \vrule
  605. \begin{minipage}{0.25\textwidth}
  606. \begin{lstlisting}
  607. '+
  608. \end{lstlisting}
  609. \end{minipage}
  610. \end{center}
  611. In the above example, the \texttt{match} form takes the AST
  612. \eqref{eq:arith-prog} and binds its parts to the three pattern
  613. variables \texttt{op}, \texttt{child1}, and \texttt{child2}. In
  614. general, a match clause consists of a \emph{pattern} and a
  615. \emph{body}.
  616. \index{pattern}
  617. Patterns are recursively defined to be either a pattern
  618. variable, a structure name followed by a pattern for each of the
  619. structure's arguments, or an S-expression (symbols, lists, etc.).
  620. (See Chapter 12 of The Racket
  621. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  622. and Chapter 9 of The Racket
  623. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  624. for a complete description of \code{match}.)
  625. %
  626. The body of a match clause may contain arbitrary Racket code. The
  627. pattern variables can be used in the scope of the body, such as
  628. \code{op} in \code{(print op)}.
  629. A \code{match} form may contain several clauses, as in the following
  630. function \code{leaf?} that recognizes when an $R_0$ node is a leaf in
  631. the AST. The \code{match} proceeds through the clauses in order,
  632. checking whether the pattern can match the input AST. The body of the
  633. first clause that matches is executed. The output of \code{leaf?} for
  634. several ASTs is shown on the right.
  635. \begin{center}
  636. \begin{minipage}{0.6\textwidth}
  637. \begin{lstlisting}
  638. (define (leaf? arith)
  639. (match arith
  640. [(Int n) #t]
  641. [(Prim 'read '()) #t]
  642. [(Prim '- (list e1)) #f]
  643. [(Prim '+ (list e1 e2)) #f]))
  644. (leaf? (Prim 'read '()))
  645. (leaf? (Prim '- (list (Int 8))))
  646. (leaf? (Int 8))
  647. \end{lstlisting}
  648. \end{minipage}
  649. \vrule
  650. \begin{minipage}{0.25\textwidth}
  651. \begin{lstlisting}
  652. #t
  653. #f
  654. #t
  655. \end{lstlisting}
  656. \end{minipage}
  657. \end{center}
  658. When writing a \code{match}, we refer to the grammar definition to
  659. identify which non-terminal we are expecting to match against, then we
  660. make sure that 1) we have one clause for each alternative of that
  661. non-terminal and 2) that the pattern in each clause corresponds to the
  662. corresponding right-hand side of a grammar rule. For the \code{match}
  663. in the \code{leaf?} function, we refer to the grammar for $R_0$ in
  664. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  665. alternatives, so the \code{match} has 4 clauses. The pattern in each
  666. clause corresponds to the right-hand side of a grammar rule. For
  667. example, the pattern \code{(Prim '+ (list e1 e2))} corresponds to the
  668. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  669. patterns, replace non-terminals such as $\Exp$ with pattern variables
  670. of your choice (e.g. \code{e1} and \code{e2}).
  671. \section{Recursive Functions}
  672. \label{sec:recursion}
  673. \index{recursive function}
  674. Programs are inherently recursive. For example, an $R_0$ expression is
  675. often made of smaller expressions. Thus, the natural way to process an
  676. entire program is with a recursive function. As a first example of
  677. such a recursive function, we define \texttt{exp?} below, which takes
  678. an arbitrary value and determines whether or not it is an $R_0$
  679. expression.
  680. %
  681. We say that a function is defined by \emph{structural recursion} when
  682. it is defined using a sequence of match clauses that correspond to a
  683. grammar, and the body of each clause makes a recursive call on each
  684. child node.\footnote{This principle of structuring code according to
  685. the data definition is advocated in the book \emph{How to Design
  686. Programs}\url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}.
  687. Below we also define a second function, named \code{R0?}, that
  688. determines whether an AST is an $R_0$ program. In general we can
  689. expect to write one recursive function to handle each non-terminal in
  690. a grammar.\index{structural recursion}
  691. %
  692. \begin{center}
  693. \begin{minipage}{0.7\textwidth}
  694. \begin{lstlisting}
  695. (define (exp? ast)
  696. (match ast
  697. [(Int n) #t]
  698. [(Prim 'read '()) #t]
  699. [(Prim '- (list e)) (exp? e)]
  700. [(Prim '+ (list e1 e2))
  701. (and (exp? e1) (exp? e2))]
  702. [else #f]))
  703. (define (R0? ast)
  704. (match ast
  705. [(Program '() e) (exp? e)]
  706. [else #f]))
  707. (R0? (Program '() ast1.1)
  708. (R0? (Program '()
  709. (Prim '- (list (Prim 'read '())
  710. (Prim '+ (list (Num 8)))))))
  711. \end{lstlisting}
  712. \end{minipage}
  713. \vrule
  714. \begin{minipage}{0.25\textwidth}
  715. \begin{lstlisting}
  716. #t
  717. #f
  718. \end{lstlisting}
  719. \end{minipage}
  720. \end{center}
  721. You may be tempted to merge the two functions into one, like this:
  722. \begin{center}
  723. \begin{minipage}{0.5\textwidth}
  724. \begin{lstlisting}
  725. (define (R0? ast)
  726. (match ast
  727. [(Int n) #t]
  728. [(Prim 'read '()) #t]
  729. [(Prim '- (list e)) (R0? e)]
  730. [(Prim '+ (list e1 e2)) (and (R0? e1) (R0? e2))]
  731. [(Program '() e) (R0? e)]
  732. [else #f]))
  733. \end{lstlisting}
  734. \end{minipage}
  735. \end{center}
  736. %
  737. Sometimes such a trick will save a few lines of code, especially when
  738. it comes to the \code{Program} wrapper. Yet this style is generally
  739. \emph{not} recommended because it can get you into trouble.
  740. %
  741. For example, the above function is subtly wrong:
  742. \lstinline{(R0? (Program '() (Program '() (Int 3))))}
  743. would return true, when it should return false.
  744. \section{Interpreters}
  745. \label{sec:interp-R0}
  746. \index{interpreter}
  747. In general, the intended behavior of a program is defined by the
  748. specification of the language. For example, the Scheme language is
  749. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  750. defined in its reference manual~\citep{plt-tr}. In this book we use
  751. interpreters to specify each language that we consider. An interpreter
  752. that is designated as the definition of a language is called a
  753. \emph{definitional interpreter}~\citep{reynolds72:_def_interp}.
  754. \index{definitional interpreter} We warm up by creating a definitional
  755. interpreter for the $R_0$ language, which serves as a second example
  756. of structural recursion. The \texttt{interp-R0} function is defined in
  757. Figure~\ref{fig:interp-R0}. The body of the function is a match on the
  758. input program followed by a call to the \lstinline{interp-exp} helper
  759. function, which in turn has one match clause per grammar rule for
  760. $R_0$ expressions.
  761. \begin{figure}[tp]
  762. \begin{lstlisting}
  763. (define (interp-exp e)
  764. (match e
  765. [(Int n) n]
  766. [(Prim 'read '())
  767. (define r (read))
  768. (cond [(fixnum? r) r]
  769. [else (error 'interp-R0 "expected an integer" r)])]
  770. [(Prim '- (list e))
  771. (define v (interp-exp e))
  772. (fx- 0 v)]
  773. [(Prim '+ (list e1 e2))
  774. (define v1 (interp-exp e1))
  775. (define v2 (interp-exp e2))
  776. (fx+ v1 v2)]
  777. ))
  778. (define (interp-R0 p)
  779. (match p
  780. [(Program '() e) (interp-exp e)]
  781. ))
  782. \end{lstlisting}
  783. \caption{Interpreter for the $R_0$ language.}
  784. \label{fig:interp-R0}
  785. \end{figure}
  786. Let us consider the result of interpreting a few $R_0$ programs. The
  787. following program adds two integers.
  788. \begin{lstlisting}
  789. (+ 10 32)
  790. \end{lstlisting}
  791. The result is \key{42}. We wrote the above program in concrete syntax,
  792. whereas the parsed abstract syntax is:
  793. \begin{lstlisting}
  794. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  795. \end{lstlisting}
  796. The next example demonstrates that expressions may be nested within
  797. each other, in this case nesting several additions and negations.
  798. \begin{lstlisting}
  799. (+ 10 (- (+ 12 20)))
  800. \end{lstlisting}
  801. What is the result of the above program?
  802. As mentioned previously, the $R_0$ language does not support
  803. arbitrarily-large integers, but only $63$-bit integers, so we
  804. interpret the arithmetic operations of $R_0$ using fixnum arithmetic
  805. in Racket.
  806. Suppose
  807. \[
  808. n = 999999999999999999
  809. \]
  810. which indeed fits in $63$-bits. What happens when we run the
  811. following program in our interpreter?
  812. \begin{lstlisting}
  813. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  814. \end{lstlisting}
  815. It produces an error:
  816. \begin{lstlisting}
  817. fx+: result is not a fixnum
  818. \end{lstlisting}
  819. We establish the convention that if running the definitional
  820. interpreter on a program produces an error other than
  821. \code{trapped-error}, then the meaning of that program is
  822. \emph{unspecified}\index{unspecified behavior}. That means a compiler
  823. for the language is under no obligations regarding that program; it
  824. may or may not produce an executable, and if it does, that executable
  825. can do anything. On the other hand, if the error is a
  826. \code{trapped-error}, then the compiled program is also required to
  827. report that an error occurred. To signal an error, exit with a return
  828. code of \code{255}. The interpreters in chapters
  829. \ref{ch:type-dynamic} and \ref{ch:gradual-typing} use
  830. \code{trapped-error}.
  831. %% This convention applies to the languages defined in this
  832. %% book, as a way to simplify the student's task of implementing them,
  833. %% but this convention is not applicable to all programming languages.
  834. %%
  835. Moving on to the last feature of the $R_0$ language, the \key{read}
  836. operation prompts the user of the program for an integer. Recall that
  837. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  838. \code{8}. So if we run
  839. \begin{lstlisting}
  840. (interp-R0 (Program '() ast1.1))
  841. \end{lstlisting}
  842. and if the input is \code{50}, then we get the answer to life, the
  843. universe, and everything: \code{42}!\footnote{\emph{The Hitchhiker's
  844. Guide to the Galaxy} by Douglas Adams.}
  845. We include the \key{read} operation in $R_0$ so a clever student
  846. cannot implement a compiler for $R_0$ that simply runs the interpreter
  847. during compilation to obtain the output and then generates the trivial
  848. code to produce the output. (Yes, a clever student did this in the
  849. first instance of this course.)
  850. The job of a compiler is to translate a program in one language into a
  851. program in another language so that the output program behaves the
  852. same way as the input program does according to its definitional
  853. interpreter. This idea is depicted in the following diagram. Suppose
  854. we have two languages, $\mathcal{L}_1$ and $\mathcal{L}_2$, and an
  855. interpreter for each language. Suppose that the compiler translates
  856. program $P_1$ in language $\mathcal{L}_1$ into program $P_2$ in
  857. language $\mathcal{L}_2$. Then interpreting $P_1$ and $P_2$ on their
  858. respective interpreters with input $i$ should yield the same output
  859. $o$.
  860. \begin{equation} \label{eq:compile-correct}
  861. \begin{tikzpicture}[baseline=(current bounding box.center)]
  862. \node (p1) at (0, 0) {$P_1$};
  863. \node (p2) at (3, 0) {$P_2$};
  864. \node (o) at (3, -2.5) {$o$};
  865. \path[->] (p1) edge [above] node {compile} (p2);
  866. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  867. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  868. \end{tikzpicture}
  869. \end{equation}
  870. In the next section we see our first example of a compiler.
  871. \section{Example Compiler: a Partial Evaluator}
  872. \label{sec:partial-evaluation}
  873. In this section we consider a compiler that translates $R_0$ programs
  874. into $R_0$ programs that may be more efficient, that is, this compiler
  875. is an optimizer. This optimizer eagerly computes the parts of the
  876. program that do not depend on any inputs, a process known as
  877. \emph{partial evaluation}~\cite{Jones:1993uq}.
  878. \index{partial evaluation}
  879. For example, given the following program
  880. \begin{lstlisting}
  881. (+ (read) (- (+ 5 3)))
  882. \end{lstlisting}
  883. our compiler will translate it into the program
  884. \begin{lstlisting}
  885. (+ (read) -8)
  886. \end{lstlisting}
  887. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  888. evaluator for the $R_0$ language. The output of the partial evaluator
  889. is an $R_0$ program. In Figure~\ref{fig:pe-arith}, the structural
  890. recursion over $\Exp$ is captured in the \code{pe-exp} function
  891. whereas the code for partially evaluating the negation and addition
  892. operations is factored into two separate helper functions:
  893. \code{pe-neg} and \code{pe-add}. The input to these helper
  894. functions is the output of partially evaluating the children.
  895. \begin{figure}[tp]
  896. \begin{lstlisting}
  897. (define (pe-neg r)
  898. (match r
  899. [(Int n) (Int (fx- 0 n))]
  900. [else (Prim '- (list r))]))
  901. (define (pe-add r1 r2)
  902. (match* (r1 r2)
  903. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  904. [(_ _) (Prim '+ (list r1 r2))]))
  905. (define (pe-exp e)
  906. (match e
  907. [(Int n) (Int n)]
  908. [(Prim 'read '()) (Prim 'read '())]
  909. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  910. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]
  911. ))
  912. (define (pe-R0 p)
  913. (match p
  914. [(Program '() e) (Program '() (pe-exp e))]
  915. ))
  916. \end{lstlisting}
  917. \caption{A partial evaluator for $R_0$ expressions.}
  918. \label{fig:pe-arith}
  919. \end{figure}
  920. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  921. arguments are integers and if they are, perform the appropriate
  922. arithmetic. Otherwise, they create an AST node for the operation
  923. (either negation or addition).
  924. To gain some confidence that the partial evaluator is correct, we can
  925. test whether it produces programs that get the same result as the
  926. input programs. That is, we can test whether it satisfies Diagram
  927. \eqref{eq:compile-correct}. The following code runs the partial
  928. evaluator on several examples and tests the output program. The
  929. \texttt{parse-program} and \texttt{assert} functions are defined in
  930. Appendix~\ref{appendix:utilities}.\\
  931. \begin{minipage}{1.0\textwidth}
  932. \begin{lstlisting}
  933. (define (test-pe p)
  934. (assert "testing pe-R0"
  935. (equal? (interp-R0 p) (interp-R0 (pe-R0 p)))))
  936. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  937. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  938. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  939. \end{lstlisting}
  940. \end{minipage}
  941. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  942. \chapter{Integers and Variables}
  943. \label{ch:int-exp}
  944. This chapter is about compiling the subset of Racket that includes
  945. integer arithmetic and local variable binding, which we name $R_1$, to
  946. x86-64 assembly code~\citep{Intel:2015aa}. Henceforth we refer
  947. to x86-64 simply as x86. The chapter begins with a description of the
  948. $R_1$ language (Section~\ref{sec:s0}) followed by a description of x86
  949. (Section~\ref{sec:x86}). The x86 assembly language is large, so we
  950. discuss only what is needed for compiling $R_1$. We introduce more of
  951. x86 in later chapters. Once we have introduced $R_1$ and x86, we
  952. reflect on their differences and come up with a plan to break down the
  953. translation from $R_1$ to x86 into a handful of steps
  954. (Section~\ref{sec:plan-s0-x86}). The rest of the sections in this
  955. chapter give detailed hints regarding each step
  956. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  957. to give enough hints that the well-prepared reader, together with a
  958. few friends, can implement a compiler from $R_1$ to x86 in a couple
  959. weeks while at the same time leaving room for some fun and creativity.
  960. To give the reader a feeling for the scale of this first compiler, the
  961. instructor solution for the $R_1$ compiler is less than 500 lines of
  962. code.
  963. \section{The $R_1$ Language}
  964. \label{sec:s0}
  965. \index{variable}
  966. The $R_1$ language extends the $R_0$ language with variable
  967. definitions. The concrete syntax of the $R_1$ language is defined by
  968. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  969. syntax is defined in Figure~\ref{fig:r1-syntax}. The non-terminal
  970. \Var{} may be any Racket identifier. As in $R_0$, \key{read} is a
  971. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  972. operator. Similar to $R_0$, the abstract syntax of $R_1$ includes the
  973. \key{Program} struct to mark the top of the program.
  974. %% The $\itm{info}$
  975. %% field of the \key{Program} structure contains an \emph{association
  976. %% list} (a list of key-value pairs) that is used to communicate
  977. %% auxiliary data from one compiler pass the next.
  978. Despite the simplicity of the $R_1$ language, it is rich enough to
  979. exhibit several compilation techniques.
  980. \begin{figure}[tp]
  981. \centering
  982. \fbox{
  983. \begin{minipage}{0.96\textwidth}
  984. \[
  985. \begin{array}{rcl}
  986. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp}\\
  987. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  988. R_1 &::=& \Exp
  989. \end{array}
  990. \]
  991. \end{minipage}
  992. }
  993. \caption{The concrete syntax of $R_1$.}
  994. \label{fig:r1-concrete-syntax}
  995. \end{figure}
  996. \begin{figure}[tp]
  997. \centering
  998. \fbox{
  999. \begin{minipage}{0.96\textwidth}
  1000. \[
  1001. \begin{array}{rcl}
  1002. \Exp &::=& \INT{\Int} \mid \READ{} \\
  1003. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  1004. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  1005. R_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1006. \end{array}
  1007. \]
  1008. \end{minipage}
  1009. }
  1010. \caption{The abstract syntax of $R_1$.}
  1011. \label{fig:r1-syntax}
  1012. \end{figure}
  1013. Let us dive further into the syntax and semantics of the $R_1$
  1014. language. The \key{Let} feature defines a variable for use within its
  1015. body and initializes the variable with the value of an expression.
  1016. The abstract syntax for \key{Let} is defined in Figure~\ref{fig:r1-syntax}.
  1017. The concrete syntax for \key{Let} is
  1018. \begin{lstlisting}
  1019. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1020. \end{lstlisting}
  1021. For example, the following program initializes \code{x} to $32$ and then
  1022. evaluates the body \code{(+ 10 x)}, producing $42$.
  1023. \begin{lstlisting}
  1024. (let ([x (+ 12 20)]) (+ 10 x))
  1025. \end{lstlisting}
  1026. When there are multiple \key{let}'s for the same variable, the closest
  1027. enclosing \key{let} is used. That is, variable definitions overshadow
  1028. prior definitions. Consider the following program with two \key{let}'s
  1029. that define variables named \code{x}. Can you figure out the result?
  1030. \begin{lstlisting}
  1031. (let ([x 32]) (+ (let ([x 10]) x) x))
  1032. \end{lstlisting}
  1033. For the purposes of depicting which variable uses correspond to which
  1034. definitions, the following shows the \code{x}'s annotated with
  1035. subscripts to distinguish them. Double check that your answer for the
  1036. above is the same as your answer for this annotated version of the
  1037. program.
  1038. \begin{lstlisting}
  1039. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1040. \end{lstlisting}
  1041. The initializing expression is always evaluated before the body of the
  1042. \key{let}, so in the following, the \key{read} for \code{x} is
  1043. performed before the \key{read} for \code{y}. Given the input
  1044. $52$ then $10$, the following produces $42$ (not $-42$).
  1045. \begin{lstlisting}
  1046. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1047. \end{lstlisting}
  1048. \subsection{Extensible Interpreters via Method Overriding}
  1049. To prepare for discussing the interpreter for $R_1$, we need to
  1050. explain why we choose to implement the interpreter using
  1051. object-oriented programming, that is, as a collection of methods
  1052. inside of a class. Throughout this book we define many interpreters,
  1053. one for each of the languages that we study. Because each language
  1054. builds on the prior one, there is a lot of commonality between their
  1055. interpreters. We want to write down those common parts just once
  1056. instead of many times. A naive approach would be to have, for example,
  1057. the interpreter for $R_2$ handle all of the new features in that
  1058. language and then have a default case that dispatches to the
  1059. interpreter for $R_1$. The following code sketches this idea.
  1060. \begin{center}
  1061. \begin{minipage}{0.45\textwidth}
  1062. \begin{lstlisting}
  1063. (define (interp-R1 e)
  1064. (match e
  1065. [(Prim '- (list e))
  1066. (define v (interp-R1 e))
  1067. (fx- 0 v)]
  1068. ...
  1069. ))
  1070. \end{lstlisting}
  1071. \end{minipage}
  1072. \begin{minipage}{0.45\textwidth}
  1073. \begin{lstlisting}
  1074. (define (interp-R2 e)
  1075. (match e
  1076. [(If cnd thn els)
  1077. (define b (interp-R2 cnd))
  1078. (match b
  1079. [#t (interp-R2 thn)]
  1080. [#f (interp-R2 els)])]
  1081. ...
  1082. [else (interp-R1 e)]
  1083. ))
  1084. \end{lstlisting}
  1085. \end{minipage}
  1086. \end{center}
  1087. The problem with this approach is that it does not handle situations
  1088. in which an $R_2$ feature, like \code{If}, is nested inside an $R_1$
  1089. feature, like the \code{-} operator, as in the following program.
  1090. \begin{lstlisting}
  1091. (Prim '- (list (If (Bool #t) (Int 42) (Int 0))))
  1092. \end{lstlisting}
  1093. If we invoke \code{interp-R2} on this program, it dispatches to
  1094. \code{interp-R1} to handle the \code{-} operator, but then it
  1095. recurisvely calls \code{interp-R1} again on the argument of \code{-},
  1096. which is an \code{If}. But there is no case for \code{If} in
  1097. \code{interp-R1}, so we get an error!
  1098. To make our intepreters extensible we need something called \emph{open
  1099. recursion}\index{open recursion}. That is, a recursive call should
  1100. always invoke the ``top'' interpreter, even if the recursive call is
  1101. made from interpreters that are lower down. Object-oriented languages
  1102. provide open recursion in the form of method overriding\index{method
  1103. overriding}. The following code sketches this idea for interpreting
  1104. $R_1$ and $R_2$ using the
  1105. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1106. \index{class} feature of Racket. We define one class for each
  1107. language and place a method for interpreting expressions inside each
  1108. class. The class for $R_2$ inherits from the class for $R_1$ and the
  1109. method \code{interp-exp} for $R_2$ overrides the \code{interp-exp} for
  1110. $R_1$. Note that the default case in \code{interp-exp} for $R_2$ uses
  1111. \code{super} to invoke \code{interp-exp}, and because $R_2$ inherits
  1112. from $R_1$, that dispatches to the \code{interp-exp} for $R_1$.
  1113. \begin{center}
  1114. \begin{minipage}{0.45\textwidth}
  1115. \begin{lstlisting}
  1116. (define interp-R1-class
  1117. (class object%
  1118. (define/public (interp-exp e)
  1119. (match e
  1120. [(Prim '- (list e))
  1121. (define v (interp-exp e))
  1122. (fx- 0 v)]
  1123. ...
  1124. ))
  1125. ...
  1126. ))
  1127. \end{lstlisting}
  1128. \end{minipage}
  1129. \begin{minipage}{0.45\textwidth}
  1130. \begin{lstlisting}
  1131. (define interp-R2-class
  1132. (class interp-R1-class
  1133. (define/override (interp-exp e)
  1134. (match e
  1135. [(If cnd thn els)
  1136. (define b (interp-exp cnd))
  1137. (match b
  1138. [#t (interp-exp thn)]
  1139. [#f (interp-exp els)])]
  1140. ...
  1141. [else (super interp-exp e)]
  1142. ))
  1143. ...
  1144. ))
  1145. \end{lstlisting}
  1146. \end{minipage}
  1147. \end{center}
  1148. Getting back to the troublesome example, repeated here:
  1149. \begin{lstlisting}
  1150. (define e0 (Prim '- (list (If (Bool #t) (Int 42) (Int 0)))))
  1151. \end{lstlisting}
  1152. We can invoke the \code{interp-exp} method for $R_2$ on this
  1153. expression by creating an object of the $R_2$ class and sending it the
  1154. \code{interp-exp} method with the argument \code{e0}.
  1155. \begin{lstlisting}
  1156. (send (new interp-R2-class) interp-exp e0)
  1157. \end{lstlisting}
  1158. This will again hit the default case of \code{interp-exp} in $R_2$ and
  1159. dispatch to the \code{interp-exp} method for $R_1$, which will handle
  1160. the \code{-} operator. But then for the recursive method call, it will
  1161. dispatch back to \code{interp-exp} for $R_2$, where the \code{If} will
  1162. be correctly handled. Thus, method overriding gives us the open
  1163. recursion that we need to implement our interpreters in an extensible
  1164. way.
  1165. \newpage
  1166. \subsection{Definitional Interpreter for $R_1$}
  1167. \begin{wrapfigure}[25]{r}[1.0in]{0.6\textwidth}
  1168. \small
  1169. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1170. An \emph{association list} (alist) is a list of key-value pairs.
  1171. For example, we can map people to their ages with an alist.
  1172. \index{alist}\index{association list}
  1173. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1174. (define ages
  1175. '((jane . 25) (sam . 24) (kate . 45)))
  1176. \end{lstlisting}
  1177. The \emph{dictionary} interface is for mapping keys to values.
  1178. Every alist implements this interface. \index{dictionary} The package
  1179. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1180. provides many functions for working with dictionaries. Here
  1181. are a few of them:
  1182. \begin{description}
  1183. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1184. returns the value associated with the given $\itm{key}$.
  1185. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1186. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1187. but otherwise is the same as $\itm{dict}$.
  1188. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1189. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1190. of keys and values in $\itm{dict}$. For example, the following
  1191. creates a new alist in which the ages are incremented.
  1192. \end{description}
  1193. \vspace{-10pt}
  1194. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1195. (for/list ([(k v) (in-dict ages)])
  1196. (cons k (add1 v)))
  1197. \end{lstlisting}
  1198. \end{tcolorbox}
  1199. \end{wrapfigure}
  1200. Now that we have explained why we use classes and methods to implement
  1201. interpreters, we turn to the discussion of the actual interpreter for
  1202. $R_1$. Figure~\ref{fig:interp-R1} shows the definitional interpreter
  1203. for the $R_1$ language. It is similar to the interpreter for $R_0$ but
  1204. it adds two new \key{match} clauses for variables and for \key{let}.
  1205. For \key{let}, we need a way to communicate the value of a variable to
  1206. all the uses of a variable. To accomplish this, we maintain a mapping
  1207. from variables to values. Throughout the compiler we often need to map
  1208. variables to information about them. We refer to these mappings as
  1209. \emph{environments}\index{environment}
  1210. \footnote{Another common term for environment in the compiler
  1211. literature is \emph{symbol table}\index{symbol table}.}.
  1212. For simplicity, we use an
  1213. association list (alist) to represent the environment. The sidebar to
  1214. the right gives a brief introduction to alists and the
  1215. \code{racket/dict} package. The \code{interp-R1} function takes the
  1216. current environment, \code{env}, as an extra parameter. When the
  1217. interpreter encounters a variable, it finds the corresponding value
  1218. using the \code{dict-ref} function. When the interpreter encounters a
  1219. \key{Let}, it evaluates the initializing expression, extends the
  1220. environment with the result value bound to the variable, using
  1221. \code{dict-set}, then evaluates the body of the \key{Let}.
  1222. \begin{figure}[tp]
  1223. \begin{lstlisting}
  1224. (define interp-R1-class
  1225. (class object%
  1226. (super-new)
  1227. (define/public ((interp-exp env) e)
  1228. (match e
  1229. [(Int n) n]
  1230. [(Prim 'read '())
  1231. (define r (read))
  1232. (cond [(fixnum? r) r]
  1233. [else (error 'interp-exp "expected an integer" r)])]
  1234. [(Prim '- (list e))
  1235. (define v ((interp-exp env) e))
  1236. (fx- 0 v)]
  1237. [(Prim '+ (list e1 e2))
  1238. (define v1 ((interp-exp env) e1))
  1239. (define v2 ((interp-exp env) e2))
  1240. (fx+ v1 v2)]
  1241. [(Var x) (dict-ref env x)]
  1242. [(Let x e body)
  1243. (define new-env (dict-set env x ((interp-exp env) e)))
  1244. ((interp-exp new-env) body)]
  1245. ))
  1246. (define/public (interp-program p)
  1247. (match p
  1248. [(Program '() e) ((interp-exp '()) e)]
  1249. ))
  1250. ))
  1251. (define (interp-R1 p)
  1252. (send (new interp-R1-class) interp-program p))
  1253. \end{lstlisting}
  1254. \caption{Interpreter for the $R_1$ language.}
  1255. \label{fig:interp-R1}
  1256. \end{figure}
  1257. The goal for this chapter is to implement a compiler that translates
  1258. any program $P_1$ written in the $R_1$ language into an x86 assembly
  1259. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1260. computer as the $P_1$ program interpreted by \code{interp-R1}. That
  1261. is, they both output the same integer $n$. We depict this correctness
  1262. criteria in the following diagram.
  1263. \[
  1264. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1265. \node (p1) at (0, 0) {$P_1$};
  1266. \node (p2) at (4, 0) {$P_2$};
  1267. \node (o) at (4, -2) {$n$};
  1268. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1269. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  1270. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  1271. \end{tikzpicture}
  1272. \]
  1273. In the next section we introduce enough of the x86 assembly
  1274. language to compile $R_1$.
  1275. \section{The x86$_0$ Assembly Language}
  1276. \label{sec:x86}
  1277. \index{x86}
  1278. Figure~\ref{fig:x86-0-concrete} defines the concrete syntax for the subset of
  1279. the x86 assembly language needed for this chapter, which we call x86$_0$.
  1280. %
  1281. An x86 program begins with a \code{main} label followed by a sequence
  1282. of instructions. In the grammar, ellipses such as $\ldots$ are used to
  1283. indicate a sequence of items, e.g., $\Instr \ldots$ is a sequence of
  1284. instructions.\index{instruction}
  1285. %
  1286. An x86 program is stored in the computer's memory and the computer has
  1287. a \emph{program counter} (PC)\index{program counter}\index{PC}
  1288. that points to the address of the next
  1289. instruction to be executed. For most instructions, once the
  1290. instruction is executed, the program counter is incremented to point
  1291. to the immediately following instruction in memory. Most x86
  1292. instructions take two operands, where each operand is either an
  1293. integer constant (called \emph{immediate value}\index{immediate value}),
  1294. a \emph{register}\index{register}, or a memory location.
  1295. A register is a special kind of variable. Each
  1296. one holds a 64-bit value; there are 16 registers in the computer and
  1297. their names are given in Figure~\ref{fig:x86-0-concrete}. The computer's memory
  1298. as a mapping of 64-bit addresses to 64-bit values%
  1299. \footnote{This simple story suffices for describing how sequential
  1300. programs access memory but is not sufficient for multi-threaded
  1301. programs. However, multi-threaded execution is beyond the scope of
  1302. this book.}.
  1303. %
  1304. We use the AT\&T syntax expected by the GNU assembler, which comes
  1305. with the \key{gcc} compiler that we use for compiling assembly code to
  1306. machine code.
  1307. %
  1308. Appendix~\ref{sec:x86-quick-reference} is a quick-reference for all of
  1309. the x86 instructions used in this book.
  1310. % to do: finish treatment of imulq
  1311. % it's needed for vector's in R6/R7
  1312. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1313. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1314. && \key{r8} \mid \key{r9} \mid \key{r10}
  1315. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1316. \mid \key{r14} \mid \key{r15}}
  1317. \begin{figure}[tp]
  1318. \fbox{
  1319. \begin{minipage}{0.96\textwidth}
  1320. \[
  1321. \begin{array}{lcl}
  1322. \Reg &::=& \allregisters{} \\
  1323. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1324. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1325. \key{subq} \; \Arg\key{,} \Arg \mid
  1326. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1327. && \key{callq} \; \mathit{label} \mid
  1328. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} \\
  1329. && \itm{label}\key{:}\; \Instr \\
  1330. x86_0 &::= & \key{.globl main}\\
  1331. & & \key{main:} \; \Instr\ldots
  1332. \end{array}
  1333. \]
  1334. \end{minipage}
  1335. }
  1336. \caption{The syntax of the x86$_0$ assembly language (AT\&T syntax).}
  1337. \label{fig:x86-0-concrete}
  1338. \end{figure}
  1339. An immediate value is written using the notation \key{\$}$n$ where $n$
  1340. is an integer.
  1341. %
  1342. A register is written with a \key{\%} followed by the register name,
  1343. such as \key{\%rax}.
  1344. %
  1345. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1346. which obtains the address stored in register $r$ and then adds $n$
  1347. bytes to the address. The resulting address is used to either load or
  1348. store to memory depending on whether it occurs as a source or
  1349. destination argument of an instruction.
  1350. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1351. source $s$ and destination $d$, applies the arithmetic operation, then
  1352. writes the result back to the destination $d$.
  1353. %
  1354. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1355. stores the result in $d$.
  1356. %
  1357. The $\key{callq}\,\itm{label}$ instruction executes the procedure
  1358. specified by the label and $\key{retq}$ returns from a procedure to
  1359. its caller. The abstract syntax for \code{callq} includes an extra
  1360. integer field that represents the arity (number of parameters) of the
  1361. function being called.
  1362. %
  1363. We discuss procedure calls in more detail later in this
  1364. chapter and in Chapter~\ref{ch:functions}. The
  1365. $\key{jmp}\,\itm{label}$ instruction updates the program counter to
  1366. the address of the instruction after the specified label.
  1367. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  1368. to \code{(+ 10 32)}. The \key{globl} directive says that the
  1369. \key{main} procedure is externally visible, which is necessary so
  1370. that the operating system can call it. The label \key{main:}
  1371. indicates the beginning of the \key{main} procedure which is where
  1372. the operating system starts executing this program. The instruction
  1373. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  1374. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  1375. $10$ in \key{rax} and puts the result, $42$, back into
  1376. \key{rax}.
  1377. %
  1378. The last instruction, \key{retq}, finishes the \key{main} function by
  1379. returning the integer in \key{rax} to the operating system. The
  1380. operating system interprets this integer as the program's exit
  1381. code. By convention, an exit code of 0 indicates that a program
  1382. completed successfully, and all other exit codes indicate various
  1383. errors. Nevertheless, we return the result of the program as the exit
  1384. code.
  1385. %\begin{wrapfigure}{r}{2.25in}
  1386. \begin{figure}[tbp]
  1387. \begin{lstlisting}
  1388. .globl main
  1389. main:
  1390. movq $10, %rax
  1391. addq $32, %rax
  1392. retq
  1393. \end{lstlisting}
  1394. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1395. \label{fig:p0-x86}
  1396. %\end{wrapfigure}
  1397. \end{figure}
  1398. Unfortunately, x86 varies in a couple ways depending on what operating
  1399. system it is assembled in. The code examples shown here are correct on
  1400. Linux and most Unix-like platforms, but when assembled on Mac OS X,
  1401. labels like \key{main} must be prefixed with an underscore, as in
  1402. \key{\_main}.
  1403. We exhibit the use of memory for storing intermediate results in the
  1404. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1405. equivalent to \code{(+ 52 (- 10))}. This program uses a region of
  1406. memory called the \emph{procedure call stack} (or \emph{stack} for
  1407. short). \index{stack}\index{procedure call stack} The stack consists
  1408. of a separate \emph{frame}\index{frame} for each procedure call. The
  1409. memory layout for an individual frame is shown in
  1410. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1411. \emph{stack pointer}\index{stack pointer} and points to the item at
  1412. the top of the stack. The stack grows downward in memory, so we
  1413. increase the size of the stack by subtracting from the stack pointer.
  1414. In the context of a procedure call, the \emph{return
  1415. address}\index{return address} is the instruction after the call
  1416. instruction on the caller side. The function call instruction,
  1417. \code{callq}, pushes the return address onto the stack. The register
  1418. \key{rbp} is the \emph{base pointer}\index{base pointer} and is used
  1419. to access variables associated with the current procedure call. The
  1420. base pointer of the caller is pushed onto the stack after the return
  1421. address. We number the variables from $1$ to $n$. Variable $1$ is
  1422. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  1423. $-16\key{(\%rbp)}$, etc.
  1424. \begin{figure}[tbp]
  1425. \begin{lstlisting}
  1426. start:
  1427. movq $10, -8(%rbp)
  1428. negq -8(%rbp)
  1429. movq -8(%rbp), %rax
  1430. addq $52, %rax
  1431. jmp conclusion
  1432. .globl main
  1433. main:
  1434. pushq %rbp
  1435. movq %rsp, %rbp
  1436. subq $16, %rsp
  1437. jmp start
  1438. conclusion:
  1439. addq $16, %rsp
  1440. popq %rbp
  1441. retq
  1442. \end{lstlisting}
  1443. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1444. \label{fig:p1-x86}
  1445. \end{figure}
  1446. \begin{figure}[tbp]
  1447. \centering
  1448. \begin{tabular}{|r|l|} \hline
  1449. Position & Contents \\ \hline
  1450. 8(\key{\%rbp}) & return address \\
  1451. 0(\key{\%rbp}) & old \key{rbp} \\
  1452. -8(\key{\%rbp}) & variable $1$ \\
  1453. -16(\key{\%rbp}) & variable $2$ \\
  1454. \ldots & \ldots \\
  1455. 0(\key{\%rsp}) & variable $n$\\ \hline
  1456. \end{tabular}
  1457. \caption{Memory layout of a frame.}
  1458. \label{fig:frame}
  1459. \end{figure}
  1460. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  1461. control is transferred from the operating system to the \code{main}
  1462. function. The operating system issues a \code{callq main} instruction
  1463. which pushes its return address on the stack and then jumps to
  1464. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  1465. by 16 bytes prior to the execution of any \code{callq} instruction, so
  1466. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  1467. alignment (because the \code{callq} pushed the return address). The
  1468. first three instructions are the typical \emph{prelude}\index{prelude}
  1469. for a procedure. The instruction \code{pushq \%rbp} saves the base
  1470. pointer for the caller onto the stack and subtracts $8$ from the stack
  1471. pointer. At this point the stack pointer is back to being 16-byte
  1472. aligned. The second instruction \code{movq \%rsp, \%rbp} changes the
  1473. base pointer so that it points the location of the old base
  1474. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  1475. pointer down to make enough room for storing variables. This program
  1476. needs one variable ($8$ bytes) but we round up to 16 bytes to maintain
  1477. the 16-byte alignment of the \code{rsp}. With the \code{rsp} aligned,
  1478. we are ready to make calls to other functions. The last instruction of
  1479. the prelude is \code{jmp start}, which transfers control to the
  1480. instructions that were generated from the Racket expression \code{(+
  1481. 10 32)}.
  1482. The four instructions under the label \code{start} carry out the work
  1483. of computing \code{(+ 52 (- 10)))}.
  1484. %
  1485. The first instruction \code{movq \$10, -8(\%rbp)} stores $10$ in
  1486. variable $1$.
  1487. %
  1488. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  1489. %
  1490. The following instruction moves the $-10$ from variable $1$ into the
  1491. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  1492. the value in \code{rax}, updating its contents to $42$.
  1493. The three instructions under the label \code{conclusion} are the
  1494. typical \emph{conclusion}\index{conclusion} of a procedure. The first
  1495. two instructions are necessary to get the state of the machine back to
  1496. where it was at the beginning of the procedure. The instruction
  1497. \key{addq \$16, \%rsp} moves the stack pointer back to point at the
  1498. old base pointer. The amount added here needs to match the amount that
  1499. was subtracted in the prelude of the procedure. Then \key{popq \%rbp}
  1500. returns the old base pointer to \key{rbp} and adds $8$ to the stack
  1501. pointer. The last instruction, \key{retq}, jumps back to the
  1502. procedure that called this one and adds 8 to the stack pointer, which
  1503. returns the stack pointer to where it was prior to the procedure call.
  1504. The compiler needs a convenient representation for manipulating x86
  1505. programs, so we define an abstract syntax for x86 in
  1506. Figure~\ref{fig:x86-0-ast}. We refer to this language as x86$_0$ with
  1507. a subscript $0$ because later we introduce extended versions of this
  1508. assembly language. The main difference compared to the concrete syntax
  1509. of x86 (Figure~\ref{fig:x86-0-concrete}) is that it does not allow
  1510. labeled instructions to appear anywhere, but instead organizes
  1511. instructions into a group called a
  1512. \emph{block}\index{block}\index{basic block} and associates a label
  1513. with every block, which is why the \key{CFG} struct (for control-flow
  1514. graph) includes an alist mapping labels to blocks. The reason for this
  1515. organization becomes apparent in Chapter~\ref{ch:bool-types} when we
  1516. introduce conditional branching. The \code{Block} structure includes
  1517. an $\itm{info}$ field that is not needed for this chapter, but will
  1518. become useful in Chapter~\ref{ch:register-allocation-r1}. For now,
  1519. the $\itm{info}$ field should just contain an empty list. Also,
  1520. regarding the abstract syntax for \code{callq}, the \code{Callq}
  1521. struct includes an integer for representing the arity of the function,
  1522. i.e., the number of arguments, which is helpful to know during
  1523. register allocation (Chapter~\ref{ch:register-allocation-r1}).
  1524. \begin{figure}[tp]
  1525. \fbox{
  1526. \begin{minipage}{0.96\textwidth}
  1527. \small
  1528. \[
  1529. \begin{array}{lcl}
  1530. \Reg &::=& \allregisters{} \\
  1531. \Arg &::=& \IMM{\Int} \mid \REG{\Reg}
  1532. \mid \DEREF{\Reg}{\Int} \\
  1533. \Instr &::=& \BININSTR{\code{'addq}}{\Arg}{\Arg}
  1534. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} \\
  1535. &\mid& \BININSTR{\code{'movq}}{\Arg}{\Arg}
  1536. \mid \UNIINSTR{\code{'negq}}{\Arg}\\
  1537. &\mid& \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  1538. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  1539. \Block &::= & \BLOCK{\itm{info}}{\Instr\ldots} \\
  1540. x86_0 &::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}}
  1541. \end{array}
  1542. \]
  1543. \end{minipage}
  1544. }
  1545. \caption{The abstract syntax of x86$_0$ assembly.}
  1546. \label{fig:x86-0-ast}
  1547. \end{figure}
  1548. \section{Planning the trip to x86 via the $C_0$ language}
  1549. \label{sec:plan-s0-x86}
  1550. To compile one language to another it helps to focus on the
  1551. differences between the two languages because the compiler will need
  1552. to bridge those differences. What are the differences between $R_1$
  1553. and x86 assembly? Here are some of the most important ones:
  1554. \begin{enumerate}
  1555. \item[(a)] x86 arithmetic instructions typically have two arguments
  1556. and update the second argument in place. In contrast, $R_1$
  1557. arithmetic operations take two arguments and produce a new value.
  1558. An x86 instruction may have at most one memory-accessing argument.
  1559. Furthermore, some instructions place special restrictions on their
  1560. arguments.
  1561. \item[(b)] An argument of an $R_1$ operator can be any expression,
  1562. whereas x86 instructions restrict their arguments to be integers
  1563. constants, registers, and memory locations.
  1564. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1565. sequence of instructions and jumps to labeled positions, whereas in
  1566. $R_1$ the order of evaluation is a left-to-right depth-first
  1567. traversal of the abstract syntax tree.
  1568. \item[(d)] An $R_1$ program can have any number of variables whereas
  1569. x86 has 16 registers and the procedure calls stack.
  1570. \item[(e)] Variables in $R_1$ can overshadow other variables with the
  1571. same name. The registers and memory locations of x86 all have unique
  1572. names or addresses.
  1573. \end{enumerate}
  1574. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1575. the problem into several steps, dealing with the above differences one
  1576. at a time. Each of these steps is called a \emph{pass} of the
  1577. compiler.\index{pass}\index{compiler pass}
  1578. %
  1579. This terminology comes from each step traverses (i.e. passes over) the
  1580. AST of the program.
  1581. %
  1582. We begin by sketching how we might implement each pass, and give them
  1583. names. We then figure out an ordering of the passes and the
  1584. input/output language for each pass. The very first pass has $R_1$ as
  1585. its input language and the last pass has x86 as its output
  1586. language. In between we can choose whichever language is most
  1587. convenient for expressing the output of each pass, whether that be
  1588. $R_1$, x86, or new \emph{intermediate languages} of our own design.
  1589. Finally, to implement each pass we write one recursive function per
  1590. non-terminal in the grammar of the input language of the pass.
  1591. \index{intermediate language}
  1592. \begin{description}
  1593. \item[Pass \key{select-instructions}] To handle the difference between
  1594. $R_1$ operations and x86 instructions we convert each $R_1$
  1595. operation to a short sequence of instructions that accomplishes the
  1596. same task.
  1597. \item[Pass \key{remove-complex-opera*}] To ensure that each
  1598. subexpression (i.e. operator and operand, and hence the name
  1599. \key{opera*}) is an \emph{atomic} expression (a variable or
  1600. integer), we introduce temporary variables to hold the results
  1601. of subexpressions.\index{atomic expression}
  1602. \item[Pass \key{explicate-control}] To make the execution order of the
  1603. program explicit, we convert from the abstract syntax tree
  1604. representation into a control-flow graph in which each node
  1605. contains a sequence of statements and the edges between nodes say
  1606. where to go at the end of the sequence.
  1607. \item[Pass \key{assign-homes}] To handle the difference between the
  1608. variables in $R_1$ versus the registers and stack locations in x86,
  1609. we map each variable to a register or stack location.
  1610. \item[Pass \key{uniquify}] This pass deals with the shadowing of variables
  1611. by renaming every variable to a unique name, so that shadowing no
  1612. longer occurs.
  1613. \end{description}
  1614. The next question is: in what order should we apply these passes? This
  1615. question can be challenging because it is difficult to know ahead of
  1616. time which orders will be better (easier to implement, produce more
  1617. efficient code, etc.) so oftentimes trial-and-error is
  1618. involved. Nevertheless, we can try to plan ahead and make educated
  1619. choices regarding the ordering.
  1620. Let us consider the ordering of \key{uniquify} and
  1621. \key{remove-complex-opera*}. The assignment of subexpressions to
  1622. temporary variables involves introducing new variables and moving
  1623. subexpressions, which might change the shadowing of variables and
  1624. inadvertently change the behavior of the program. But if we apply
  1625. \key{uniquify} first, this will not be an issue. Of course, this means
  1626. that in \key{remove-complex-opera*}, we need to ensure that the
  1627. temporary variables that it creates are unique.
  1628. What should be the ordering of \key{explicate-control} with respect to
  1629. \key{uniquify}? The \key{uniquify} pass should come first because
  1630. \key{explicate-control} changes all the \key{let}-bound variables to
  1631. become local variables whose scope is the entire program, which would
  1632. confuse variables with the same name.
  1633. %
  1634. Likewise, we place \key{explicate-control} after
  1635. \key{remove-complex-opera*} because \key{explicate-control} removes
  1636. the \key{let} form, but it is convenient to use \key{let} in the
  1637. output of \key{remove-complex-opera*}.
  1638. %
  1639. Regarding \key{assign-homes}, it is helpful to place
  1640. \key{explicate-control} first because \key{explicate-control} changes
  1641. \key{let}-bound variables into program-scope variables. This means
  1642. that the \key{assign-homes} pass can read off the variables from the
  1643. $\itm{info}$ of the \key{Program} AST node instead of traversing the
  1644. entire program in search of \key{let}-bound variables.
  1645. Last, we need to decide on the ordering of \key{select-instructions}
  1646. and \key{assign-homes}. These two passes are intertwined, creating a
  1647. Gordian Knot. To do a good job of assigning homes, it is helpful to
  1648. have already determined which instructions will be used, because x86
  1649. instructions have restrictions about which of their arguments can be
  1650. registers versus stack locations. One might want to give preferential
  1651. treatment to variables that occur in register-argument positions. On
  1652. the other hand, it may turn out to be impossible to make sure that all
  1653. such variables are assigned to registers, and then one must redo the
  1654. selection of instructions. Some compilers handle this problem by
  1655. iteratively repeating these two passes until a good solution is found.
  1656. We use a simpler approach in which \key{select-instructions}
  1657. comes first, followed by the \key{assign-homes}, then a third
  1658. pass named \key{patch-instructions} that uses a reserved register to
  1659. patch-up outstanding problems regarding instructions with too many
  1660. memory accesses. The disadvantage of this approach is some programs
  1661. may not execute as efficiently as they would if we used the iterative
  1662. approach and used all of the registers for variables.
  1663. \begin{figure}[tbp]
  1664. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1665. \node (R1) at (0,2) {\large $R_1$};
  1666. \node (R1-2) at (3,2) {\large $R_1$};
  1667. \node (R1-3) at (6,2) {\large $R_1^{\dagger}$};
  1668. %\node (C0-1) at (6,0) {\large $C_0$};
  1669. \node (C0-2) at (3,0) {\large $C_0$};
  1670. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_0$};
  1671. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_0$};
  1672. \node (x86-4) at (9,-2) {\large $\text{x86}_0$};
  1673. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}_0$};
  1674. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1675. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  1676. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-2);
  1677. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1678. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1679. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1680. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1681. \end{tikzpicture}
  1682. \caption{Overview of the passes for compiling $R_1$. }
  1683. \label{fig:R1-passes}
  1684. \end{figure}
  1685. Figure~\ref{fig:R1-passes} presents the ordering of the compiler
  1686. passes in the form of a graph. Each pass is an edge and the
  1687. input/output language of each pass is a node in the graph. The output
  1688. of \key{uniquify} and \key{remove-complex-opera*} are programs that
  1689. are still in the $R_1$ language, but the output of the pass
  1690. \key{explicate-control} is in a different language $C_0$ that is
  1691. designed to make the order of evaluation explicit in its syntax, which
  1692. we introduce in the next section. The \key{select-instruction} pass
  1693. translates from $C_0$ to a variant of x86. The \key{assign-homes} and
  1694. \key{patch-instructions} passes input and output variants of x86
  1695. assembly. The last pass in Figure~\ref{fig:R1-passes} is
  1696. \key{print-x86}, which converts from the abstract syntax of
  1697. $\text{x86}_0$ to the concrete syntax of x86.
  1698. In the next sections we discuss the $C_0$ language and the
  1699. $\text{x86}^{*}_0$ and $\text{x86}^{\dagger}_0$ dialects of x86. The
  1700. remainder of this chapter gives hints regarding the implementation of
  1701. each of the compiler passes in Figure~\ref{fig:R1-passes}.
  1702. \subsection{The $C_0$ Intermediate Language}
  1703. The output of \key{explicate-control} is similar to the $C$
  1704. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1705. categories for expressions and statements, so we name it $C_0$. The
  1706. abstract syntax for $C_0$ is defined in Figure~\ref{fig:c0-syntax}.
  1707. (The concrete syntax for $C_0$ is in the Appendix,
  1708. Figure~\ref{fig:c0-concrete-syntax}.)
  1709. %
  1710. The $C_0$ language supports the same operators as $R_1$ but the
  1711. arguments of operators are restricted to atomic expressions (variables
  1712. and integers), thanks to the \key{remove-complex-opera*} pass. Instead
  1713. of \key{Let} expressions, $C_0$ has assignment statements which can be
  1714. executed in sequence using the \key{Seq} form. A sequence of
  1715. statements always ends with \key{Return}, a guarantee that is baked
  1716. into the grammar rules for the \itm{tail} non-terminal. The naming of
  1717. this non-terminal comes from the term \emph{tail position}\index{tail position},
  1718. which refers to an expression that is the last one to execute within a
  1719. function. (An expression in tail position may contain subexpressions,
  1720. and those may or may not be in tail position depending on the kind of
  1721. expression.)
  1722. A $C_0$ program consists of a control-flow graph (represented as an
  1723. alist mapping labels to tails). This is more general than
  1724. necessary for the present chapter, as we do not yet need to introduce
  1725. \key{goto} for jumping to labels, but it saves us from having to
  1726. change the syntax of the program construct in
  1727. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1728. \key{start}, and the whole program is its tail.
  1729. %
  1730. The $\itm{info}$ field of the \key{Program} form, after the
  1731. \key{explicate-control} pass, contains a mapping from the symbol
  1732. \key{locals} to a list of variables, that is, a list of all the
  1733. variables used in the program. At the start of the program, these
  1734. variables are uninitialized; they become initialized on their first
  1735. assignment.
  1736. \begin{figure}[tbp]
  1737. \fbox{
  1738. \begin{minipage}{0.96\textwidth}
  1739. \[
  1740. \begin{array}{lcl}
  1741. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1742. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1743. &\mid& \ADD{\Atm}{\Atm}\\
  1744. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  1745. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1746. C_0 & ::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}\ldots}}
  1747. \end{array}
  1748. \]
  1749. \end{minipage}
  1750. }
  1751. \caption{The abstract syntax of the $C_0$ intermediate language.}
  1752. \label{fig:c0-syntax}
  1753. \end{figure}
  1754. \subsection{The dialects of x86}
  1755. The x86$^{*}_0$ language, pronounced ``pseudo x86'', is the output of
  1756. the pass \key{select-instructions}. It extends x86$_0$ with an
  1757. unbounded number of program-scope variables and has looser rules
  1758. regarding instruction arguments. The x86$^{\dagger}$ language, the
  1759. output of \key{print-x86}, is the concrete syntax for x86.
  1760. \section{Uniquify Variables}
  1761. \label{sec:uniquify-s0}
  1762. The \code{uniquify} pass compiles arbitrary $R_1$ programs into $R_1$
  1763. programs in which every \key{let} uses a unique variable name. For
  1764. example, the \code{uniquify} pass should translate the program on the
  1765. left into the program on the right. \\
  1766. \begin{tabular}{lll}
  1767. \begin{minipage}{0.4\textwidth}
  1768. \begin{lstlisting}
  1769. (let ([x 32])
  1770. (+ (let ([x 10]) x) x))
  1771. \end{lstlisting}
  1772. \end{minipage}
  1773. &
  1774. $\Rightarrow$
  1775. &
  1776. \begin{minipage}{0.4\textwidth}
  1777. \begin{lstlisting}
  1778. (let ([x.1 32])
  1779. (+ (let ([x.2 10]) x.2) x.1))
  1780. \end{lstlisting}
  1781. \end{minipage}
  1782. \end{tabular} \\
  1783. %
  1784. The following is another example translation, this time of a program
  1785. with a \key{let} nested inside the initializing expression of another
  1786. \key{let}.\\
  1787. \begin{tabular}{lll}
  1788. \begin{minipage}{0.4\textwidth}
  1789. \begin{lstlisting}
  1790. (let ([x (let ([x 4])
  1791. (+ x 1))])
  1792. (+ x 2))
  1793. \end{lstlisting}
  1794. \end{minipage}
  1795. &
  1796. $\Rightarrow$
  1797. &
  1798. \begin{minipage}{0.4\textwidth}
  1799. \begin{lstlisting}
  1800. (let ([x.2 (let ([x.1 4])
  1801. (+ x.1 1))])
  1802. (+ x.2 2))
  1803. \end{lstlisting}
  1804. \end{minipage}
  1805. \end{tabular}
  1806. We recommend implementing \code{uniquify} by creating a function named
  1807. \code{uniquify-exp} that is structurally recursive function and mostly
  1808. just copies the input program. However, when encountering a \key{let},
  1809. it should generate a unique name for the variable (the Racket function
  1810. \code{gensym} is handy for this) and associate the old name with the
  1811. new unique name in an alist. The \code{uniquify-exp}
  1812. function will need to access this alist when it gets to a
  1813. variable reference, so we add another parameter to \code{uniquify-exp}
  1814. for the alist.
  1815. The skeleton of the \code{uniquify-exp} function is shown in
  1816. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1817. convenient to partially apply it to a symbol table and then apply it
  1818. to different expressions, as in the last clause for primitive
  1819. operations in Figure~\ref{fig:uniquify-s0}. The \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  1820. form is useful for applying a function to each element of a list to produce
  1821. a new list.
  1822. \index{for/list}
  1823. \begin{exercise}
  1824. \normalfont % I don't like the italics for exercises. -Jeremy
  1825. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1826. implement the clauses for variables and for the \key{let} form.
  1827. \end{exercise}
  1828. \begin{figure}[tbp]
  1829. \begin{lstlisting}
  1830. (define (uniquify-exp symtab)
  1831. (lambda (e)
  1832. (match e
  1833. [(Var x) ___]
  1834. [(Int n) (Int n)]
  1835. [(Let x e body) ___]
  1836. [(Prim op es)
  1837. (Prim op (for/list ([e es]) ((uniquify-exp symtab) e)))]
  1838. )))
  1839. (define (uniquify p)
  1840. (match p
  1841. [(Program '() e)
  1842. (Program '() ((uniquify-exp '()) e))]
  1843. )))
  1844. \end{lstlisting}
  1845. \caption{Skeleton for the \key{uniquify} pass.}
  1846. \label{fig:uniquify-s0}
  1847. \end{figure}
  1848. \begin{exercise}
  1849. \normalfont % I don't like the italics for exercises. -Jeremy
  1850. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1851. and checking whether the output programs produce the same result as
  1852. the input programs. The $R_1$ programs should be designed to test the
  1853. most interesting parts of the \key{uniquify} pass, that is, the
  1854. programs should include \key{let} forms, variables, and variables that
  1855. overshadow each other. The five programs should be in a subdirectory
  1856. named \key{tests} and they should have the same file name except for a
  1857. different integer at the end of the name, followed by the ending
  1858. \key{.rkt}. Use the \key{interp-tests} function
  1859. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1860. your \key{uniquify} pass on the example programs. See the
  1861. \key{run-tests.rkt} script in the support code for an example of how
  1862. to use \key{interp-tests}. The support code is in a \code{github}
  1863. repository at the following URL:
  1864. \begin{center}\footnotesize
  1865. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  1866. \end{center}
  1867. \end{exercise}
  1868. \section{Remove Complex Operands}
  1869. \label{sec:remove-complex-opera-R1}
  1870. The \code{remove-complex-opera*} pass compiles $R_1$ programs into
  1871. $R_1$ programs in which the arguments of operations are atomic
  1872. expressions. Put another way, this pass removes complex
  1873. operands\index{complex operand}, such as the expression \code{(- 10)}
  1874. in the program below. This is accomplished by introducing a new
  1875. \key{let}-bound variable, binding the complex operand to the new
  1876. variable, and then using the new variable in place of the complex
  1877. operand, as shown in the output of \code{remove-complex-opera*} on the
  1878. right.\\
  1879. \begin{tabular}{lll}
  1880. \begin{minipage}{0.4\textwidth}
  1881. % s0_19.rkt
  1882. \begin{lstlisting}
  1883. (+ 52 (- 10))
  1884. \end{lstlisting}
  1885. \end{minipage}
  1886. &
  1887. $\Rightarrow$
  1888. &
  1889. \begin{minipage}{0.4\textwidth}
  1890. \begin{lstlisting}
  1891. (let ([tmp.1 (- 10)])
  1892. (+ 52 tmp.1))
  1893. \end{lstlisting}
  1894. \end{minipage}
  1895. \end{tabular}
  1896. \begin{figure}[tp]
  1897. \centering
  1898. \fbox{
  1899. \begin{minipage}{0.96\textwidth}
  1900. \[
  1901. \begin{array}{rcl}
  1902. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1903. \Exp &::=& \Atm \mid \READ{} \\
  1904. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  1905. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  1906. R^{\dagger}_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1907. \end{array}
  1908. \]
  1909. \end{minipage}
  1910. }
  1911. \caption{$R_1^{\dagger}$ is $R_1$ in administrative normal form (ANF).}
  1912. \label{fig:r1-anf-syntax}
  1913. \end{figure}
  1914. Figure~\ref{fig:r1-anf-syntax} presents the grammar for the output of
  1915. this pass, language $R_1^{\dagger}$. The main difference is that
  1916. operator arguments are required to be atomic expressions. In the
  1917. literature, this is called \emph{administrative normal form}, or ANF
  1918. for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  1919. \index{administrative normal form}
  1920. \index{ANF}
  1921. We recommend implementing this pass with two mutually recursive
  1922. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1923. \code{rco-atom} to subexpressions that are required to be atomic and
  1924. to apply \code{rco-exp} to subexpressions that can be atomic or
  1925. complex (see Figure~\ref{fig:r1-anf-syntax}). Both functions take an
  1926. $R_1$ expression as input. The \code{rco-exp} function returns an
  1927. expression. The \code{rco-atom} function returns two things: an
  1928. atomic expression and alist mapping temporary variables to complex
  1929. subexpressions. You can return multiple things from a function using
  1930. Racket's \key{values} form and you can receive multiple things from a
  1931. function call using the \key{define-values} form. If you are not
  1932. familiar with these features, review the Racket documentation. Also,
  1933. the \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  1934. form is useful for applying a function to each
  1935. element of a list, in the case where the function returns multiple
  1936. values.
  1937. \index{for/lists}
  1938. The following shows the output of \code{rco-atom} on the expression
  1939. \code{(- 10)} (using concrete syntax to be concise).
  1940. \begin{tabular}{lll}
  1941. \begin{minipage}{0.4\textwidth}
  1942. \begin{lstlisting}
  1943. (- 10)
  1944. \end{lstlisting}
  1945. \end{minipage}
  1946. &
  1947. $\Rightarrow$
  1948. &
  1949. \begin{minipage}{0.4\textwidth}
  1950. \begin{lstlisting}
  1951. tmp.1
  1952. ((tmp.1 . (- 10)))
  1953. \end{lstlisting}
  1954. \end{minipage}
  1955. \end{tabular}
  1956. Take special care of programs such as the next one that \key{let}-bind
  1957. variables with integers or other variables. You should leave them
  1958. unchanged, as shown in to the program on the right \\
  1959. \begin{tabular}{lll}
  1960. \begin{minipage}{0.4\textwidth}
  1961. % s0_20.rkt
  1962. \begin{lstlisting}
  1963. (let ([a 42])
  1964. (let ([b a])
  1965. b))
  1966. \end{lstlisting}
  1967. \end{minipage}
  1968. &
  1969. $\Rightarrow$
  1970. &
  1971. \begin{minipage}{0.4\textwidth}
  1972. \begin{lstlisting}
  1973. (let ([a 42])
  1974. (let ([b a])
  1975. b))
  1976. \end{lstlisting}
  1977. \end{minipage}
  1978. \end{tabular} \\
  1979. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  1980. produce the following output.\\
  1981. \begin{minipage}{0.4\textwidth}
  1982. \begin{lstlisting}
  1983. (let ([tmp.1 42])
  1984. (let ([a tmp.1])
  1985. (let ([tmp.2 a])
  1986. (let ([b tmp.2])
  1987. b))))
  1988. \end{lstlisting}
  1989. \end{minipage}
  1990. \begin{exercise}
  1991. \normalfont Implement the \code{remove-complex-opera*} pass.
  1992. Test the new pass on all of the example programs that you created to test the
  1993. \key{uniquify} pass and create three new example programs that are
  1994. designed to exercise the interesting code in the
  1995. \code{remove-complex-opera*} pass. Use the \key{interp-tests} function
  1996. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1997. your passes on the example programs.
  1998. \end{exercise}
  1999. \section{Explicate Control}
  2000. \label{sec:explicate-control-r1}
  2001. The \code{explicate-control} pass compiles $R_1$ programs into $C_0$
  2002. programs that make the order of execution explicit in their
  2003. syntax. For now this amounts to flattening \key{let} constructs into a
  2004. sequence of assignment statements. For example, consider the following
  2005. $R_1$ program.\\
  2006. % s0_11.rkt
  2007. \begin{minipage}{0.96\textwidth}
  2008. \begin{lstlisting}
  2009. (let ([y (let ([x 20])
  2010. (+ x (let ([x 22]) x)))])
  2011. y)
  2012. \end{lstlisting}
  2013. \end{minipage}\\
  2014. %
  2015. The output of the previous pass and of \code{explicate-control} is
  2016. shown below. Recall that the right-hand-side of a \key{let} executes
  2017. before its body, so the order of evaluation for this program is to
  2018. assign \code{20} to \code{x.1}, assign \code{22} to \code{x.2}, assign
  2019. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  2020. output of \code{explicate-control} makes this ordering explicit.\\
  2021. \begin{tabular}{lll}
  2022. \begin{minipage}{0.4\textwidth}
  2023. \begin{lstlisting}
  2024. (let ([y (let ([x.1 20])
  2025. (let ([x.2 22])
  2026. (+ x.1 x.2)))])
  2027. y)
  2028. \end{lstlisting}
  2029. \end{minipage}
  2030. &
  2031. $\Rightarrow$
  2032. &
  2033. \begin{minipage}{0.4\textwidth}
  2034. \begin{lstlisting}
  2035. start:
  2036. x.1 = 20;
  2037. x.2 = 22;
  2038. y = (+ x.1 x.2);
  2039. return y;
  2040. \end{lstlisting}
  2041. \end{minipage}
  2042. \end{tabular}
  2043. We recommend implementing \code{explicate-control} using two mutually
  2044. recursive functions: \code{explicate-tail} and
  2045. \code{explicate-assign}. The first function should be applied to
  2046. expressions in tail position whereas the second should be applied to
  2047. expressions that occur on the right-hand-side of a \key{let}.
  2048. %
  2049. The \code{explicate-tail} function takes an $R_1$ expression as input
  2050. and produces a $C_0$ $\Tail$ (see Figure~\ref{fig:c0-syntax}).
  2051. %
  2052. The \code{explicate-assign} function takes an $R_1$ expression, the
  2053. variable that it is to be assigned to, and $C_0$ code (a $\Tail$) that
  2054. should come after the assignment (e.g., the code generated for the
  2055. body of the \key{let}) and returns a $\Tail$. The
  2056. \code{explicate-assign} function is in accumulator-passing style in
  2057. that its third parameter is some $C_0$ code that it adds to and
  2058. returns. The reader might be tempted to instead organize
  2059. \code{explicate-assign} in a more direct fashion, without the third
  2060. parameter and perhaps using \code{append} to combine statements. We
  2061. warn against that alternative because the accumulator-passing style is
  2062. key to how we generate high-quality code for conditional expressions
  2063. in Chapter~\ref{ch:bool-types}.
  2064. The top-level \code{explicate-control} function should invoke
  2065. \code{explicate-tail} on the body of the \key{Program} AST node.
  2066. \section{Select Instructions}
  2067. \label{sec:select-r1}
  2068. \index{instruction selection}
  2069. In the \code{select-instructions} pass we begin the work of
  2070. translating from $C_0$ to $\text{x86}^{*}_0$. The target language of
  2071. this pass is a variant of x86 that still uses variables, so we add an
  2072. AST node of the form $\VAR{\itm{var}}$ to the $\text{x86}_0$ abstract
  2073. syntax of Figure~\ref{fig:x86-0-ast}. We recommend implementing the
  2074. \code{select-instructions} in terms of three auxiliary functions, one
  2075. for each of the non-terminals of $C_0$: $\Atm$, $\Stmt$, and $\Tail$.
  2076. The cases for $\Atm$ are straightforward, variables stay
  2077. the same and integer constants are changed to immediates:
  2078. $\INT{n}$ changes to $\IMM{n}$.
  2079. Next we consider the cases for $\Stmt$, starting with arithmetic
  2080. operations. For example, in $C_0$ an addition operation can take the
  2081. form below, to the left of the $\Rightarrow$. To translate to x86, we
  2082. need to use the \key{addq} instruction which does an in-place
  2083. update. So we must first move \code{10} to \code{x}. \\
  2084. \begin{tabular}{lll}
  2085. \begin{minipage}{0.4\textwidth}
  2086. \begin{lstlisting}
  2087. x = (+ 10 32);
  2088. \end{lstlisting}
  2089. \end{minipage}
  2090. &
  2091. $\Rightarrow$
  2092. &
  2093. \begin{minipage}{0.4\textwidth}
  2094. \begin{lstlisting}
  2095. movq $10, x
  2096. addq $32, x
  2097. \end{lstlisting}
  2098. \end{minipage}
  2099. \end{tabular} \\
  2100. %
  2101. There are cases that require special care to avoid generating
  2102. needlessly complicated code. If one of the arguments of the addition
  2103. is the same as the left-hand side of the assignment, then there is no
  2104. need for the extra move instruction. For example, the following
  2105. assignment statement can be translated into a single \key{addq}
  2106. instruction.\\
  2107. \begin{tabular}{lll}
  2108. \begin{minipage}{0.4\textwidth}
  2109. \begin{lstlisting}
  2110. x = (+ 10 x);
  2111. \end{lstlisting}
  2112. \end{minipage}
  2113. &
  2114. $\Rightarrow$
  2115. &
  2116. \begin{minipage}{0.4\textwidth}
  2117. \begin{lstlisting}
  2118. addq $10, x
  2119. \end{lstlisting}
  2120. \end{minipage}
  2121. \end{tabular} \\
  2122. The \key{read} operation does not have a direct counterpart in x86
  2123. assembly, so we have instead implemented this functionality in the C
  2124. language~\citep{Kernighan:1988nx}, with the function \code{read\_int}
  2125. in the file \code{runtime.c}. In general, we refer to all of the
  2126. functionality in this file as the \emph{runtime system}\index{runtime system},
  2127. or simply the \emph{runtime} for short. When compiling your generated x86
  2128. assembly code, you need to compile \code{runtime.c} to \code{runtime.o} (an
  2129. ``object file'', using \code{gcc} option \code{-c}) and link it into
  2130. the executable. For our purposes of code generation, all you need to
  2131. do is translate an assignment of \key{read} into some variable
  2132. $\itm{lhs}$ (for left-hand side) into a call to the \code{read\_int}
  2133. function followed by a move from \code{rax} to the left-hand side.
  2134. The move from \code{rax} is needed because the return value from
  2135. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  2136. \begin{tabular}{lll}
  2137. \begin{minipage}{0.3\textwidth}
  2138. \begin{lstlisting}
  2139. |$\itm{var}$| = (read);
  2140. \end{lstlisting}
  2141. \end{minipage}
  2142. &
  2143. $\Rightarrow$
  2144. &
  2145. \begin{minipage}{0.3\textwidth}
  2146. \begin{lstlisting}
  2147. callq read_int
  2148. movq %rax, |$\itm{var}$|
  2149. \end{lstlisting}
  2150. \end{minipage}
  2151. \end{tabular} \\
  2152. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  2153. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  2154. assignment to the \key{rax} register followed by a jump to the
  2155. conclusion of the program (so the conclusion needs to be labeled).
  2156. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  2157. recursively and append the resulting instructions.
  2158. \begin{exercise}
  2159. \normalfont
  2160. Implement the \key{select-instructions} pass and test it on all of the
  2161. example programs that you created for the previous passes and create
  2162. three new example programs that are designed to exercise all of the
  2163. interesting code in this pass. Use the \key{interp-tests} function
  2164. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2165. your passes on the example programs.
  2166. \end{exercise}
  2167. \section{Assign Homes}
  2168. \label{sec:assign-r1}
  2169. The \key{assign-homes} pass compiles $\text{x86}^{*}_0$ programs to
  2170. $\text{x86}^{*}_0$ programs that no longer use program variables.
  2171. Thus, the \key{assign-homes} pass is responsible for placing all of
  2172. the program variables in registers or on the stack. For runtime
  2173. efficiency, it is better to place variables in registers, but as there
  2174. are only 16 registers, some programs must necessarily resort to
  2175. placing some variables on the stack. In this chapter we focus on the
  2176. mechanics of placing variables on the stack. We study an algorithm for
  2177. placing variables in registers in
  2178. Chapter~\ref{ch:register-allocation-r1}.
  2179. Consider again the following $R_1$ program.
  2180. % s0_20.rkt
  2181. \begin{lstlisting}
  2182. (let ([a 42])
  2183. (let ([b a])
  2184. b))
  2185. \end{lstlisting}
  2186. For reference, we repeat the output of \code{select-instructions} on
  2187. the left and show the output of \code{assign-homes} on the right.
  2188. %
  2189. %% Recall that \key{explicate-control} associated the list of
  2190. %% variables with the \code{locals} symbol in the program's $\itm{info}$
  2191. %% field, so \code{assign-homes} has convenient access to the them.
  2192. %
  2193. In this example, we assign variable \code{a} to stack location
  2194. \code{-8(\%rbp)} and variable \code{b} to location
  2195. \code{-16(\%rbp)}.\\
  2196. \begin{tabular}{l}
  2197. \begin{minipage}{0.4\textwidth}
  2198. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2199. locals-types:
  2200. a : 'Integer, b : 'Integer
  2201. start:
  2202. movq $42, a
  2203. movq a, b
  2204. movq b, %rax
  2205. jmp conclusion
  2206. \end{lstlisting}
  2207. \end{minipage}
  2208. {$\Rightarrow$}
  2209. \begin{minipage}{0.4\textwidth}
  2210. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2211. stack-space: 16
  2212. start:
  2213. movq $42, -8(%rbp)
  2214. movq -8(%rbp), -16(%rbp)
  2215. movq -16(%rbp), %rax
  2216. jmp conclusion
  2217. \end{lstlisting}
  2218. \end{minipage}
  2219. \end{tabular} \\
  2220. In the output of \code{select-instructions}, there is a entry for
  2221. \code{locals-types} in the $\itm{info}$ of the \code{Program} node,
  2222. which is needed here so that we have the list of variables that should
  2223. be assigned to homes. The support code computes the
  2224. \code{locals-types} entry. In particular, \code{type-check-C0}
  2225. installs it in the $\itm{info}$ field of the \code{Program} node.
  2226. When using \code{interp-tests} or \code{compiler-tests} (see Appendix,
  2227. Section~\ref{appendix:utilities}), specify \code{type-check-C0} as the
  2228. type checker to use after \code{explicate-control}.
  2229. In the process of assigning variables to stack locations, it is
  2230. convenient for you to compute and store the size of the frame (in
  2231. bytes) in the $\itm{info}$ field of the \key{Program} node, with the
  2232. key \code{stack-space}, which is needed later to generate the
  2233. conclusion of the \code{main} procedure. The x86-64 standard requires
  2234. the frame size to be a multiple of 16 bytes. \index{frame}
  2235. \begin{exercise}
  2236. \normalfont Implement the \key{assign-homes} pass and test it on all
  2237. of the example programs that you created for the previous passes pass.
  2238. We recommend that \key{assign-homes} take an extra parameter that is a
  2239. mapping of variable names to homes (stack locations for now). Use the
  2240. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  2241. \key{utilities.rkt} to test your passes on the example programs.
  2242. \end{exercise}
  2243. \section{Patch Instructions}
  2244. \label{sec:patch-s0}
  2245. The \code{patch-instructions} pass compiles $\text{x86}^{*}_0$
  2246. programs to $\text{x86}_0$ programs by making sure that each
  2247. instruction adheres to the restrictions of the x86 assembly language.
  2248. In particular, at most one argument of an instruction may be a memory
  2249. reference.
  2250. We return to the following running example.
  2251. % s0_20.rkt
  2252. \begin{lstlisting}
  2253. (let ([a 42])
  2254. (let ([b a])
  2255. b))
  2256. \end{lstlisting}
  2257. After the \key{assign-homes} pass, the above program has been translated to
  2258. the following. \\
  2259. \begin{minipage}{0.5\textwidth}
  2260. \begin{lstlisting}
  2261. stack-space: 16
  2262. start:
  2263. movq $42, -8(%rbp)
  2264. movq -8(%rbp), -16(%rbp)
  2265. movq -16(%rbp), %rax
  2266. jmp conclusion
  2267. \end{lstlisting}
  2268. \end{minipage}\\
  2269. The second \key{movq} instruction is problematic because both
  2270. arguments are stack locations. We suggest fixing this problem by
  2271. moving from the source location to the register \key{rax} and then
  2272. from \key{rax} to the destination location, as follows.
  2273. \begin{lstlisting}
  2274. movq -8(%rbp), %rax
  2275. movq %rax, -16(%rbp)
  2276. \end{lstlisting}
  2277. \begin{exercise}
  2278. \normalfont
  2279. Implement the \key{patch-instructions} pass and test it on all of the
  2280. example programs that you created for the previous passes and create
  2281. three new example programs that are designed to exercise all of the
  2282. interesting code in this pass. Use the \key{interp-tests} function
  2283. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2284. your passes on the example programs.
  2285. \end{exercise}
  2286. \section{Print x86}
  2287. \label{sec:print-x86}
  2288. The last step of the compiler from $R_1$ to x86 is to convert the
  2289. $\text{x86}_0$ AST (defined in Figure~\ref{fig:x86-0-ast}) to the
  2290. string representation (defined in Figure~\ref{fig:x86-0-concrete}). The Racket
  2291. \key{format} and \key{string-append} functions are useful in this
  2292. regard. The main work that this step needs to perform is to create the
  2293. \key{main} function and the standard instructions for its prelude and
  2294. conclusion, as shown in Figure~\ref{fig:p1-x86} of
  2295. Section~\ref{sec:x86}. You need to know the number of stack-allocated
  2296. variables, so we suggest computing it in the \key{assign-homes} pass
  2297. (Section~\ref{sec:assign-r1}) and storing it in the $\itm{info}$ field
  2298. of the \key{program} node.
  2299. %% Your compiled code should print the result of the program's execution
  2300. %% by using the \code{print\_int} function provided in
  2301. %% \code{runtime.c}. If your compiler has been implemented correctly so
  2302. %% far, this final result should be stored in the \key{rax} register.
  2303. %% We'll talk more about how to perform function calls with arguments in
  2304. %% general later on, but for now, place the following after the compiled
  2305. %% code for the $R_1$ program but before the conclusion:
  2306. %% \begin{lstlisting}
  2307. %% movq %rax, %rdi
  2308. %% callq print_int
  2309. %% \end{lstlisting}
  2310. %% These lines move the value in \key{rax} into the \key{rdi} register, which
  2311. %% stores the first argument to be passed into \key{print\_int}.
  2312. If you want your program to run on Mac OS X, your code needs to
  2313. determine whether or not it is running on a Mac, and prefix
  2314. underscores to labels like \key{main}. You can determine the platform
  2315. with the Racket call \code{(system-type 'os)}, which returns
  2316. \code{'macosx}, \code{'unix}, or \code{'windows}.
  2317. %% In addition to
  2318. %% placing underscores on \key{main}, you need to put them in front of
  2319. %% \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  2320. %% \_print\_int}).
  2321. \begin{exercise}
  2322. \normalfont Implement the \key{print-x86} pass and test it on all of
  2323. the example programs that you created for the previous passes. Use the
  2324. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  2325. \key{utilities.rkt} to test your complete compiler on the example
  2326. programs. See the \key{run-tests.rkt} script in the student support
  2327. code for an example of how to use \key{compiler-tests}. Also, remember
  2328. to compile the provided \key{runtime.c} file to \key{runtime.o} using
  2329. \key{gcc}.
  2330. \end{exercise}
  2331. \section{Challenge: Partial Evaluator for $R_1$}
  2332. \label{sec:pe-R1}
  2333. \index{partial evaluation}
  2334. This section describes optional challenge exercises that involve
  2335. adapting and improving the partial evaluator for $R_0$ that was
  2336. introduced in Section~\ref{sec:partial-evaluation}.
  2337. \begin{exercise}\label{ex:pe-R1}
  2338. \normalfont
  2339. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2340. (Figure~\ref{fig:pe-arith}) so that it applies to $R_1$ programs
  2341. instead of $R_0$ programs. Recall that $R_1$ adds \key{let} binding
  2342. and variables to the $R_0$ language, so you will need to add cases for
  2343. them in the \code{pe-exp} function. Also, note that the \key{program}
  2344. form changes slightly to include an $\itm{info}$ field. Once
  2345. complete, add the partial evaluation pass to the front of your
  2346. compiler and make sure that your compiler still passes all of the
  2347. tests.
  2348. \end{exercise}
  2349. The next exercise builds on Exercise~\ref{ex:pe-R1}.
  2350. \begin{exercise}
  2351. \normalfont
  2352. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2353. \code{pe-add} auxiliary functions with functions that know more about
  2354. arithmetic. For example, your partial evaluator should translate
  2355. \begin{lstlisting}
  2356. (+ 1 (+ (read) 1))
  2357. \end{lstlisting}
  2358. into
  2359. \begin{lstlisting}
  2360. (+ 2 (read))
  2361. \end{lstlisting}
  2362. To accomplish this, the \code{pe-exp} function should produce output
  2363. in the form of the $\itm{residual}$ non-terminal of the following
  2364. grammar.
  2365. \[
  2366. \begin{array}{lcl}
  2367. \itm{inert} &::=& \Var \mid (\key{read}) \mid (\key{-} \;(\key{read}))
  2368. \mid (\key{+} \; \itm{inert} \; \itm{inert})\\
  2369. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \itm{inert}) \mid \itm{inert}
  2370. \end{array}
  2371. \]
  2372. The \code{pe-add} and \code{pe-neg} functions may therefore assume
  2373. that their inputs are $\itm{residual}$ expressions and they should
  2374. return $\itm{residual}$ expressions. Once the improvements are
  2375. complete, make sure that your compiler still passes all of the tests.
  2376. After all, fast code is useless if it produces incorrect results!
  2377. \end{exercise}
  2378. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2379. \chapter{Register Allocation}
  2380. \label{ch:register-allocation-r1}
  2381. \index{register allocation}
  2382. In Chapter~\ref{ch:int-exp} we placed all variables on the stack to
  2383. make our life easier. However, we can improve the performance of the
  2384. generated code if we instead place some variables into registers. The
  2385. CPU can access a register in a single cycle, whereas accessing the
  2386. stack takes many cycles if the relevant data is in cache or many more
  2387. to access main memory if the data is not in cache.
  2388. Figure~\ref{fig:reg-eg} shows a program with four variables that
  2389. serves as a running example. We show the source program and also the
  2390. output of instruction selection. At that point the program is almost
  2391. x86 assembly but not quite; it still contains variables instead of
  2392. stack locations or registers.
  2393. \begin{figure}
  2394. \begin{minipage}{0.45\textwidth}
  2395. Example $R_1$ program:
  2396. % s0_28.rkt
  2397. \begin{lstlisting}
  2398. (let ([v 1])
  2399. (let ([w 42])
  2400. (let ([x (+ v 7)])
  2401. (let ([y x])
  2402. (let ([z (+ x w)])
  2403. (+ z (- y)))))))
  2404. \end{lstlisting}
  2405. \end{minipage}
  2406. \begin{minipage}{0.45\textwidth}
  2407. After instruction selection:
  2408. \begin{lstlisting}
  2409. locals-types:
  2410. x : Integer, y : Integer,
  2411. z : Integer, t : Integer,
  2412. v : Integer, w : Integer
  2413. start:
  2414. movq $1, v
  2415. movq $42, w
  2416. movq v, x
  2417. addq $7, x
  2418. movq x, y
  2419. movq x, z
  2420. addq w, z
  2421. movq y, t
  2422. negq t
  2423. movq z, %rax
  2424. addq t, %rax
  2425. jmp conclusion
  2426. \end{lstlisting}
  2427. \end{minipage}
  2428. \caption{A running example program for register allocation.}
  2429. \label{fig:reg-eg}
  2430. \end{figure}
  2431. The goal of register allocation is to fit as many variables into
  2432. registers as possible. A program sometimes has more variables than
  2433. registers, so we cannot always map each variable to a different
  2434. register. Fortunately, it is common for different variables to be
  2435. needed during different periods of time during program execution, and
  2436. in such cases several variables can be mapped to the same register.
  2437. Consider variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}.
  2438. After the variable \code{x} is moved to \code{z} it is no longer
  2439. needed. Variable \code{y}, on the other hand, is used only after this
  2440. point, so \code{x} and \code{y} could share the same register. The
  2441. topic of Section~\ref{sec:liveness-analysis-r1} is how to compute
  2442. where a variable is needed. Once we have that information, we compute
  2443. which variables are needed at the same time, i.e., which ones
  2444. \emph{interfere} with each other, and represent this relation as an
  2445. undirected graph whose vertices are variables and edges indicate when
  2446. two variables interfere (Section~\ref{sec:build-interference}). We
  2447. then model register allocation as a graph coloring problem, which we
  2448. discuss in Section~\ref{sec:graph-coloring}.
  2449. If we run out of registers despite these efforts, we place the
  2450. remaining variables on the stack, similar to what we did in
  2451. Chapter~\ref{ch:int-exp}. It is common to use the verb \emph{spill}
  2452. for assigning a variable to a stack location. The decision to spill a
  2453. variable is handled as part of the graph coloring process described in
  2454. Section~\ref{sec:graph-coloring}.
  2455. We make the simplifying assumption that each variable is assigned to
  2456. one location (a register or stack address). A more sophisticated
  2457. approach is to assign a variable to one or more locations in different
  2458. regions of the program. For example, if a variable is used many times
  2459. in short sequence and then only used again after many other
  2460. instructions, it could be more efficient to assign the variable to a
  2461. register during the initial sequence and then move it to the stack for
  2462. the rest of its lifetime. We refer the interested reader to
  2463. \citet{Cooper:1998ly} and \citet{Cooper:2011aa} for more information
  2464. about that approach.
  2465. % discuss prioritizing variables based on how much they are used.
  2466. \section{Registers and Calling Conventions}
  2467. \label{sec:calling-conventions}
  2468. \index{calling conventions}
  2469. As we perform register allocation, we need to be aware of the
  2470. \emph{calling conventions} \index{calling conventions} that govern how
  2471. functions calls are performed in x86. Function calls require
  2472. coordination between the caller and the callee, which is often
  2473. assembly code written by different programmers or generated by
  2474. different compilers. Here we follow the System V calling conventions
  2475. that are used by the \code{gcc} compiler on Linux and
  2476. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  2477. %
  2478. Even though $R_1$ does not include programmer-defined functions, our
  2479. generated code will 1) include a \code{main} function that the
  2480. operating system will call to initiate execution, and 2) make calls to
  2481. the \code{read\_int} function in our runtime system.
  2482. The calling conventions include rules about how functions share the
  2483. use of registers. In particular, the caller is responsible for freeing
  2484. up some registers prior to the function call for use by the callee.
  2485. These are called the \emph{caller-saved registers}
  2486. \index{caller-saved registers}
  2487. and they are
  2488. \begin{lstlisting}
  2489. rax rcx rdx rsi rdi r8 r9 r10 r11
  2490. \end{lstlisting}
  2491. On the other hand, the callee is responsible for preserving the values
  2492. of the \emph{callee-saved registers}, \index{callee-saved registers}
  2493. which are
  2494. \begin{lstlisting}
  2495. rsp rbp rbx r12 r13 r14 r15
  2496. \end{lstlisting}
  2497. We can think about this caller/callee convention from two points of
  2498. view, the caller view and the callee view:
  2499. \begin{itemize}
  2500. \item The caller should assume that all the caller-saved registers get
  2501. overwritten with arbitrary values by the callee. On the other hand,
  2502. the caller can safely assume that all the callee-saved registers
  2503. contain the same values after the call that they did before the
  2504. call.
  2505. \item The callee can freely use any of the caller-saved registers.
  2506. However, if the callee wants to use a callee-saved register, the
  2507. callee must arrange to put the original value back in the register
  2508. prior to returning to the caller, which is usually accomplished by
  2509. saving the value to the stack in the prelude of the function and
  2510. restoring the value in the conclusion of the function.
  2511. \end{itemize}
  2512. In x86, registers are also used for passing arguments to a function
  2513. and for the return value. In particular, the first six arguments of a
  2514. function are passed in the following six registers, in the order
  2515. given.
  2516. \begin{lstlisting}
  2517. rdi rsi rdx rcx r8 r9
  2518. \end{lstlisting}
  2519. If there are more than six arguments, then the convention is to use
  2520. space on the frame of the caller for the rest of the
  2521. arguments. However, in Chapter~\ref{ch:functions} we arrange to never
  2522. need more than six arguments. For now, the only function we care about
  2523. is \code{read\_int} and it takes zero argument.
  2524. %
  2525. The register \code{rax} is for the return value of a function.
  2526. The next question is how these calling conventions impact register
  2527. allocation. Consider the $R_1$ program in
  2528. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  2529. example from the caller point of view and then from the callee point
  2530. of view.
  2531. The program makes two calls to the \code{read} function. Also, the
  2532. variable \code{x} is in-use during the second call to \code{read}, so
  2533. we need to make sure that the value in \code{x} does not get
  2534. accidentally wiped out by the call to \code{read}. One obvious
  2535. approach is to save all the values in caller-saved registers to the
  2536. stack prior to each function call, and restore them after each
  2537. call. That way, if the register allocator chooses to assign \code{x}
  2538. to a caller-saved register, its value will be preserved across the
  2539. call to \code{read}. However, the disadvantage of this approach is
  2540. that saving and restoring to the stack is relatively slow. If \code{x}
  2541. is not used many times, it may be better to assign \code{x} to a stack
  2542. location in the first place. Or better yet, if we can arrange for
  2543. \code{x} to be placed in a callee-saved register, then it won't need
  2544. to be saved and restored during function calls.
  2545. The approach that we recommend for variables that are in-use during a
  2546. function call is to either assign them to callee-saved registers or to
  2547. spill them to the stack. On the other hand, for variables that are not
  2548. in-use during a function call, we try the following alternatives in
  2549. order 1) look for an available caller-saved register (to leave room
  2550. for other variables in the callee-saved register), 2) look for a
  2551. callee-saved register, and 3) spill the variable to the stack.
  2552. It is straightforward to implement this approach in a graph coloring
  2553. register allocator. First, we know which variables are in-use during
  2554. every function call because we compute that information for every
  2555. instruction (Section~\ref{sec:liveness-analysis-r1}). Second, when we
  2556. build the interference graph (Section~\ref{sec:build-interference}),
  2557. we can place an edge between each of these variables and the
  2558. caller-saved registers in the interference graph. This will prevent
  2559. the graph coloring algorithm from assigning those variables to
  2560. caller-saved registers.
  2561. Returning to the example in
  2562. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  2563. generated x86 code on the right-hand side, focusing on the
  2564. \code{start} block. Notice that variable \code{x} is assigned to
  2565. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  2566. place during the second call to \code{read\_int}. Next, notice that
  2567. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  2568. because there are no function calls in the remainder of the block.
  2569. Next we analyze the example from the callee point of view, focusing on
  2570. the prelude and conclusion of the \code{main} function. As usual the
  2571. prelude begins with saving the \code{rbp} register to the stack and
  2572. setting the \code{rbp} to the current stack pointer. We now know why
  2573. it is necessary to save the \code{rbp}: it is a callee-saved register.
  2574. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  2575. is also a callee-saved register and 2) \code{rbx} is assigned to a
  2576. variable (\code{x}). There are several more callee-saved register that
  2577. are not saved in the prelude because they were not assigned to
  2578. variables. The prelude subtracts 8 bytes from the \code{rsp} to make
  2579. it 16-byte aligned and then jumps to the \code{start} block. Shifting
  2580. attention to the \code{conclusion}, we see that \code{rbx} is restored
  2581. from the stack with a \code{popq} instruction.
  2582. \index{prelude}\index{conclusion}
  2583. \begin{figure}[tp]
  2584. \begin{minipage}{0.45\textwidth}
  2585. Example $R_1$ program:
  2586. %s0_14.rkt
  2587. \begin{lstlisting}
  2588. (let ([x (read)])
  2589. (let ([y (read)])
  2590. (+ (+ x y) 42)))
  2591. \end{lstlisting}
  2592. \end{minipage}
  2593. \begin{minipage}{0.45\textwidth}
  2594. Generated x86 assembly:
  2595. \begin{lstlisting}
  2596. start:
  2597. callq read_int
  2598. movq %rax, %rbx
  2599. callq read_int
  2600. movq %rax, %rcx
  2601. addq %rcx, %rbx
  2602. movq %rbx, %rax
  2603. addq $42, %rax
  2604. jmp _conclusion
  2605. .globl main
  2606. main:
  2607. pushq %rbp
  2608. movq %rsp, %rbp
  2609. pushq %rbx
  2610. subq $8, %rsp
  2611. jmp start
  2612. conclusion:
  2613. addq $8, %rsp
  2614. popq %rbx
  2615. popq %rbp
  2616. retq
  2617. \end{lstlisting}
  2618. \end{minipage}
  2619. \caption{An example with function calls.}
  2620. \label{fig:example-calling-conventions}
  2621. \end{figure}
  2622. \section{Liveness Analysis}
  2623. \label{sec:liveness-analysis-r1}
  2624. \index{liveness analysis}
  2625. A variable or register is \emph{live} at a program point if its
  2626. current value is used at some later point in the program. We
  2627. refer to variables and registers collectively as \emph{locations}.
  2628. %
  2629. Consider the following code fragment in which there are two writes to
  2630. \code{b}. Are \code{a} and \code{b} both live at the same time?
  2631. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2632. movq $5, a
  2633. movq $30, b
  2634. movq a, c
  2635. movq $10, b
  2636. addq b, c
  2637. \end{lstlisting}
  2638. The answer is no because the integer \code{30} written to \code{b} on
  2639. line 2 is never used. The variable \code{b} is read on line 5 and
  2640. there is an intervening write to \code{b} on line 4, so the read on
  2641. line 5 receives the value written on line 4, not line 2.
  2642. \begin{wrapfigure}[19]{l}[1.0in]{0.6\textwidth}
  2643. \small
  2644. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  2645. A \emph{set} is an unordered collection of elements without duplicates.
  2646. \index{set}
  2647. \begin{description}
  2648. \item[$\LP\code{set}\,v\,\ldots\RP$] constructs a set containing the specified elements.
  2649. \item[$\LP\code{set-union}\,set_1\,set_2\RP$] returns the union of the two sets.
  2650. \item[$\LP\code{set-subtract}\,set_1\,set_2\RP$] returns the difference of the two sets.
  2651. \item[$\LP\code{set-member?}\,set\,v\RP$] is element $v$ in $set$?
  2652. \item[$\LP\code{set-count}\,set\RP$] how many unique elements are in $set$?
  2653. \item[$\LP\code{set->list}\,set\RP$] converts the set to a list.
  2654. \end{description}
  2655. \end{tcolorbox}
  2656. \end{wrapfigure}
  2657. The live locations can be computed by traversing the instruction
  2658. sequence back to front (i.e., backwards in execution order). Let
  2659. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2660. $L_{\mathsf{after}}(k)$ for the set of live locations after
  2661. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2662. locations before instruction $I_k$. The live locations after an
  2663. instruction are always the same as the live locations before the next
  2664. instruction. \index{live-after} \index{live-before}
  2665. \begin{equation} \label{eq:live-after-before-next}
  2666. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2667. \end{equation}
  2668. To start things off, there are no live locations after the last
  2669. instruction\footnote{Technically, the \code{rax} register is live
  2670. but we do not use it for register allocation.}, so
  2671. \begin{equation}\label{eq:live-last-empty}
  2672. L_{\mathsf{after}}(n) = \emptyset
  2673. \end{equation}
  2674. We then apply the following rule repeatedly, traversing the
  2675. instruction sequence back to front.
  2676. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2677. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2678. \end{equation}
  2679. where $W(k)$ are the locations written to by instruction $I_k$ and
  2680. $R(k)$ are the locations read by instruction $I_k$.
  2681. There is a special case for \code{jmp} instructions. The locations
  2682. that are live before a \code{jmp} should be the locations that are
  2683. live before the instruction that follows the target label. So we
  2684. recommend maintaining an alist, perhaps called \code{label->live},
  2685. that maps each label to a set of such locations. Recall that for now,
  2686. the only \code{jmp} in a pseudo-x86 program is the one at the end, to
  2687. the \code{conclusion}. (For example, see Figure~\ref{fig:reg-eg}.) So
  2688. the alist should map \code{conclusion} to the set
  2689. $\{\ttm{rax},\ttm{rsp}\}$.
  2690. Let us walk through the above example, applying these formulas
  2691. starting with the instruction on line 5. We collect the answers in the
  2692. below listing. The $L_{\mathsf{after}}$ for the \code{addq b, c}
  2693. instruction is $\emptyset$ because it is the last instruction
  2694. (formula~\ref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  2695. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  2696. variables \code{b} and \code{c}
  2697. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  2698. \[
  2699. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  2700. \]
  2701. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2702. the live-before set from line 5 to be the live-after set for this
  2703. instruction (formula~\ref{eq:live-after-before-next}).
  2704. \[
  2705. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  2706. \]
  2707. This move instruction writes to \code{b} and does not read from any
  2708. variables, so we have the following live-before set
  2709. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2710. \[
  2711. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  2712. \]
  2713. The live-before for instruction \code{movq a, c}
  2714. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  2715. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2716. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  2717. variable that is not live and does not read from a variable.
  2718. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2719. because it writes to variable \code{a}.
  2720. \begin{center}
  2721. \begin{minipage}{0.45\textwidth}
  2722. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2723. movq $5, a
  2724. movq $30, b
  2725. movq a, c
  2726. movq $10, b
  2727. addq b, c
  2728. \end{lstlisting}
  2729. \end{minipage}
  2730. \vrule\hspace{10pt}
  2731. \begin{minipage}{0.45\textwidth}
  2732. \begin{align*}
  2733. L_{\mathsf{before}}(1)= \emptyset,
  2734. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  2735. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  2736. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  2737. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  2738. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  2739. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  2740. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  2741. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  2742. L_{\mathsf{after}}(5)= \emptyset
  2743. \end{align*}
  2744. \end{minipage}
  2745. \end{center}
  2746. Figure~\ref{fig:live-eg} shows the results of liveness analysis for
  2747. the running example program, with the live-before and live-after sets
  2748. shown between each instruction to make the figure easy to read.
  2749. \begin{figure}[tp]
  2750. \hspace{20pt}
  2751. \begin{minipage}{0.45\textwidth}
  2752. \begin{lstlisting}
  2753. |$\{\ttm{rsp}\}$|
  2754. movq $1, v
  2755. |$\{\ttm{v},\ttm{rsp}\}$|
  2756. movq $42, w
  2757. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  2758. movq v, x
  2759. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  2760. addq $7, x
  2761. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  2762. movq x, y
  2763. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  2764. movq x, z
  2765. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  2766. addq w, z
  2767. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  2768. movq y, t
  2769. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  2770. negq t
  2771. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  2772. movq z, %rax
  2773. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  2774. addq t, %rax
  2775. |$\{\ttm{rax},\ttm{rsp}\}$|
  2776. jmp conclusion
  2777. \end{lstlisting}
  2778. \end{minipage}
  2779. \caption{The running example annotated with live-after sets.}
  2780. \label{fig:live-eg}
  2781. \end{figure}
  2782. \begin{exercise}\normalfont
  2783. Implement the compiler pass named \code{uncover-live} that computes
  2784. the live-after sets. We recommend storing the live-after sets (a list
  2785. of a set of variables) in the $\itm{info}$ field of the \code{Block}
  2786. structure.
  2787. %
  2788. We recommend organizing your code to use a helper function that takes
  2789. a list of instructions and an initial live-after set (typically empty)
  2790. and returns the list of live-after sets.
  2791. %
  2792. We recommend creating helper functions to 1) compute the set of
  2793. locations that appear in an argument (of an instruction), 2) compute
  2794. the locations read by an instruction which corresponds to the $R$
  2795. function discussed above, and 3) the locations written by an
  2796. instruction which corresponds to $W$. The \code{callq} instruction
  2797. should include all of the caller-saved registers in its write-set $W$
  2798. because the calling convention says that those registers may be
  2799. written to during the function call. Likewise, the \code{callq}
  2800. instruction should include the appropriate number of argument passing
  2801. registers in its read-set $R$, depending on the arity of the function
  2802. being called. (This is why the abstract syntax for \code{callq}
  2803. includes the arity.)
  2804. \end{exercise}
  2805. \section{Building the Interference Graph}
  2806. \label{sec:build-interference}
  2807. \begin{wrapfigure}[27]{r}[1.0in]{0.6\textwidth}
  2808. \small
  2809. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  2810. A \emph{graph} is a collection of vertices and edges where each
  2811. edge connects two vertices. A graph is \emph{directed} if each
  2812. edge points from a source to a target. Otherwise the graph is
  2813. \emph{undirected}.
  2814. \index{graph}\index{directed graph}\index{undirected graph}
  2815. \begin{description}
  2816. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  2817. directed graph from a list of edges. Each edge is a list
  2818. containing the source and target vertex.
  2819. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  2820. undirected graph from a list of edges. Each edge is represented by
  2821. a list containing two vertices.
  2822. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  2823. inserts a vertex into the graph.
  2824. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  2825. inserts an edge between the two vertices into the graph.
  2826. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  2827. returns a sequence of all the neighbors of the given vertex.
  2828. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  2829. returns a sequence of all the vertices in the graph.
  2830. \end{description}
  2831. \end{tcolorbox}
  2832. \end{wrapfigure}
  2833. Based on the liveness analysis, we know where each location is used
  2834. (read from). However, during register allocation, we need to answer
  2835. questions of the specific form: are locations $u$ and $v$ live at the
  2836. same time? (And therefore cannot be assigned to the same register.)
  2837. To make this question easier to answer, we create an explicit data
  2838. structure, an \emph{interference graph}\index{interference graph}. An
  2839. interference graph is an undirected graph that has an edge between two
  2840. locations if they are live at the same time, that is, if they
  2841. interfere with each other.
  2842. The most obvious way to compute the interference graph is to look at
  2843. the set of live location between each statement in the program and add
  2844. an edge to the graph for every pair of variables in the same set.
  2845. This approach is less than ideal for two reasons. First, it can be
  2846. expensive because it takes $O(n^2)$ time to look at every pair in a
  2847. set of $n$ live locations. Second, there is a special case in which
  2848. two locations that are live at the same time do not actually interfere
  2849. with each other: when they both contain the same value because we have
  2850. assigned one to the other.
  2851. A better way to compute the interference graph is to focus on the
  2852. writes~\cite{Appel:2003fk}. We do not want the writes performed by an
  2853. instruction to overwrite something in a live location. So for each
  2854. instruction, we create an edge between the locations being written to
  2855. and all the other live locations. (Except that one should not create
  2856. self edges.) Recall that for a \key{callq} instruction, we consider
  2857. all of the caller-saved registers as being written to, so an edge will
  2858. be added between every live variable and every caller-saved
  2859. register. For \key{movq}, we deal with the above-mentioned special
  2860. case by not adding an edge between a live variable $v$ and destination
  2861. $d$ if $v$ matches the source of the move. So we have the following
  2862. two rules.
  2863. \begin{enumerate}
  2864. \item If instruction $I_k$ is a move such as \key{movq} $s$\key{,}
  2865. $d$, then add the edge $(d,v)$ for every $v \in
  2866. L_{\mathsf{after}}(k)$ unless $v = d$ or $v = s$.
  2867. \item For any other instruction $I_k$, for every $d \in W(k)$
  2868. add an edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  2869. %% \item If instruction $I_k$ is an arithmetic instruction such as
  2870. %% \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2871. %% L_{\mathsf{after}}(k)$ unless $v = d$.
  2872. %% \item If instruction $I_k$ is of the form \key{callq}
  2873. %% $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2874. %% register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2875. \end{enumerate}
  2876. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  2877. the above rules to each instruction. We highlight a few of the
  2878. instructions and then refer the reader to
  2879. Figure~\ref{fig:interference-results} for all the interference
  2880. results. The first instruction is \lstinline{movq $1, v}, so rule 3
  2881. applies, and the live-after set is $\{\ttm{v}\}$. We do not add any
  2882. interference edges because the one live variable \code{v} is also the
  2883. destination of this instruction.
  2884. %
  2885. For the second instruction, \lstinline{movq $42, w}, so rule 3 applies
  2886. again, and the live-after set is $\{\ttm{v},\ttm{w}\}$. So the target
  2887. $\ttm{w}$ of \key{movq} interferes with $\ttm{v}$.
  2888. %
  2889. Next we skip forward to the instruction \lstinline{movq x, y}.
  2890. \begin{figure}[tbp]
  2891. \begin{quote}
  2892. \begin{tabular}{ll}
  2893. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  2894. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  2895. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  2896. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  2897. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  2898. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  2899. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  2900. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  2901. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  2902. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  2903. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  2904. \lstinline!jmp conclusion!& no interference.
  2905. \end{tabular}
  2906. \end{quote}
  2907. \caption{Interference results for the running example.}
  2908. \label{fig:interference-results}
  2909. \end{figure}
  2910. The resulting interference graph is shown in
  2911. Figure~\ref{fig:interfere}.
  2912. \begin{figure}[tbp]
  2913. \large
  2914. \[
  2915. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2916. \node (rax) at (0,0) {$\ttm{rax}$};
  2917. \node (rsp) at (9,2) {$\ttm{rsp}$};
  2918. \node (t1) at (0,2) {$\ttm{t}$};
  2919. \node (z) at (3,2) {$\ttm{z}$};
  2920. \node (x) at (6,2) {$\ttm{x}$};
  2921. \node (y) at (3,0) {$\ttm{y}$};
  2922. \node (w) at (6,0) {$\ttm{w}$};
  2923. \node (v) at (9,0) {$\ttm{v}$};
  2924. \draw (t1) to (rax);
  2925. \draw (t1) to (z);
  2926. \draw (z) to (y);
  2927. \draw (z) to (w);
  2928. \draw (x) to (w);
  2929. \draw (y) to (w);
  2930. \draw (v) to (w);
  2931. \draw (v) to (rsp);
  2932. \draw (w) to (rsp);
  2933. \draw (x) to (rsp);
  2934. \draw (y) to (rsp);
  2935. \path[-.,bend left=15] (z) edge node {} (rsp);
  2936. \path[-.,bend left=10] (t1) edge node {} (rsp);
  2937. \draw (rax) to (rsp);
  2938. \end{tikzpicture}
  2939. \]
  2940. \caption{The interference graph of the example program.}
  2941. \label{fig:interfere}
  2942. \end{figure}
  2943. %% Our next concern is to choose a data structure for representing the
  2944. %% interference graph. There are many choices for how to represent a
  2945. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2946. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2947. %% data structure is to study the algorithm that uses the data structure,
  2948. %% determine what operations need to be performed, and then choose the
  2949. %% data structure that provide the most efficient implementations of
  2950. %% those operations. Often times the choice of data structure can have an
  2951. %% effect on the time complexity of the algorithm, as it does here. If
  2952. %% you skim the next section, you will see that the register allocation
  2953. %% algorithm needs to ask the graph for all of its vertices and, given a
  2954. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2955. %% correct choice of graph representation is that of an adjacency
  2956. %% list. There are helper functions in \code{utilities.rkt} for
  2957. %% representing graphs using the adjacency list representation:
  2958. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2959. %% (Appendix~\ref{appendix:utilities}).
  2960. %% %
  2961. %% \margincomment{\footnotesize To do: change to use the
  2962. %% Racket graph library. \\ --Jeremy}
  2963. %% %
  2964. %% In particular, those functions use a hash table to map each vertex to
  2965. %% the set of adjacent vertices, and the sets are represented using
  2966. %% Racket's \key{set}, which is also a hash table.
  2967. \begin{exercise}\normalfont
  2968. Implement the compiler pass named \code{build-interference} according
  2969. to the algorithm suggested above. We recommend using the \code{graph}
  2970. package to create and inspect the interference graph. The output
  2971. graph of this pass should be stored in the $\itm{info}$ field of the
  2972. program, under the key \code{conflicts}.
  2973. \end{exercise}
  2974. \section{Graph Coloring via Sudoku}
  2975. \label{sec:graph-coloring}
  2976. \index{graph coloring}
  2977. \index{Sudoku}
  2978. \index{color}
  2979. We come to the main event, mapping variables to registers (or to stack
  2980. locations in the event that we run out of registers). We need to make
  2981. sure that two variables do not get mapped to the same register if the
  2982. two variables interfere with each other. Thinking about the
  2983. interference graph, this means that adjacent vertices must be mapped
  2984. to different registers. If we think of registers as colors, the
  2985. register allocation problem becomes the widely-studied graph coloring
  2986. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2987. The reader may be more familiar with the graph coloring problem than he
  2988. or she realizes; the popular game of Sudoku is an instance of the
  2989. graph coloring problem. The following describes how to build a graph
  2990. out of an initial Sudoku board.
  2991. \begin{itemize}
  2992. \item There is one vertex in the graph for each Sudoku square.
  2993. \item There is an edge between two vertices if the corresponding squares
  2994. are in the same row, in the same column, or if the squares are in
  2995. the same $3\times 3$ region.
  2996. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2997. \item Based on the initial assignment of numbers to squares in the
  2998. Sudoku board, assign the corresponding colors to the corresponding
  2999. vertices in the graph.
  3000. \end{itemize}
  3001. If you can color the remaining vertices in the graph with the nine
  3002. colors, then you have also solved the corresponding game of Sudoku.
  3003. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  3004. the corresponding graph with colored vertices. We map the Sudoku
  3005. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  3006. sampling of the vertices (the colored ones) because showing edges for
  3007. all of the vertices would make the graph unreadable.
  3008. \begin{figure}[tbp]
  3009. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  3010. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  3011. \caption{A Sudoku game board and the corresponding colored graph.}
  3012. \label{fig:sudoku-graph}
  3013. \end{figure}
  3014. Given that Sudoku is an instance of graph coloring, one can use Sudoku
  3015. strategies to come up with an algorithm for allocating registers. For
  3016. example, one of the basic techniques for Sudoku is called Pencil
  3017. Marks. The idea is to use a process of elimination to determine what
  3018. numbers no longer make sense for a square and write down those
  3019. numbers in the square (writing very small). For example, if the number
  3020. $1$ is assigned to a square, then by process of elimination, you can
  3021. write the pencil mark $1$ in all the squares in the same row, column,
  3022. and region. Many Sudoku computer games provide automatic support for
  3023. Pencil Marks.
  3024. %
  3025. The Pencil Marks technique corresponds to the notion of
  3026. \emph{saturation}\index{saturation} due to \cite{Brelaz:1979eu}.
  3027. The saturation of a
  3028. vertex, in Sudoku terms, is the set of numbers that are no longer
  3029. available. In graph terminology, we have the following definition:
  3030. \begin{equation*}
  3031. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  3032. \text{ and } \mathrm{color}(v) = c \}
  3033. \end{equation*}
  3034. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  3035. edge with $u$.
  3036. Using the Pencil Marks technique leads to a simple strategy for
  3037. filling in numbers: if there is a square with only one possible number
  3038. left, then choose that number! But what if there are no squares with
  3039. only one possibility left? One brute-force approach is to try them
  3040. all: choose the first and if it ultimately leads to a solution,
  3041. great. If not, backtrack and choose the next possibility. One good
  3042. thing about Pencil Marks is that it reduces the degree of branching in
  3043. the search tree. Nevertheless, backtracking can be horribly time
  3044. consuming. One way to reduce the amount of backtracking is to use the
  3045. most-constrained-first heuristic. That is, when choosing a square,
  3046. always choose one with the fewest possibilities left (the vertex with
  3047. the highest saturation). The idea is that choosing highly constrained
  3048. squares earlier rather than later is better because later on there may
  3049. not be any possibilities left for those squares.
  3050. However, register allocation is easier than Sudoku because the
  3051. register allocator can map variables to stack locations when the
  3052. registers run out. Thus, it makes sense to drop backtracking in favor
  3053. of greedy search, that is, make the best choice at the time and keep
  3054. going. We still wish to minimize the number of colors needed, so
  3055. keeping the most-constrained-first heuristic is a good idea.
  3056. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  3057. algorithm for register allocation based on saturation and the
  3058. most-constrained-first heuristic. It is roughly equivalent to the
  3059. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  3060. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just as in
  3061. Sudoku, the algorithm represents colors with integers. The integers
  3062. $0$ through $k-1$ correspond to the $k$ registers that we use for
  3063. register allocation. The integers $k$ and larger correspond to stack
  3064. locations. The registers that are not used for register allocation,
  3065. such as \code{rax}, are assigned to negative integers. In particular,
  3066. we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  3067. One might wonder why we include registers at all in the liveness
  3068. analysis and interference graph, for example, we never allocate a
  3069. variable to \code{rax} and \code{rsp}, so it would be harmless to
  3070. leave them out. As we see in Chapter~\ref{ch:tuples}, when we begin
  3071. to use register for passing arguments to functions, it will be
  3072. necessary for those registers to appear in the interference graph
  3073. because those registers will also be assigned to variables, and we
  3074. don't want those two uses to encroach on each other. Regarding
  3075. registers such as \code{rax} and \code{rsp} that are not used for
  3076. variables, we could omit them from the interference graph but that
  3077. would require adding special cases to our algorithm, which would
  3078. complicate the logic for little gain.
  3079. \begin{figure}[btp]
  3080. \centering
  3081. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  3082. Algorithm: DSATUR
  3083. Input: a graph |$G$|
  3084. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  3085. |$W \gets \mathrm{vertices}(G)$|
  3086. while |$W \neq \emptyset$| do
  3087. pick a vertex |$u$| from |$W$| with the highest saturation,
  3088. breaking ties randomly
  3089. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  3090. |$\mathrm{color}[u] \gets c$|
  3091. |$W \gets W - \{u\}$|
  3092. \end{lstlisting}
  3093. \caption{The saturation-based greedy graph coloring algorithm.}
  3094. \label{fig:satur-algo}
  3095. \end{figure}
  3096. With the DSATUR algorithm in hand, let us return to the running
  3097. example and consider how to color the interference graph in
  3098. Figure~\ref{fig:interfere}.
  3099. %
  3100. We color the vertices for registers with their own color. For example,
  3101. \code{rax} is assigned the color $-1$ and \code{rsp} is assigned $-2$.
  3102. The vertices for variables are not yet colored, so they annotated with
  3103. a dash. We then update the saturation for vertices that are adjacent
  3104. to a register. For example, the saturation for \code{t} is $\{-1,-2\}$
  3105. because it interferes with both \code{rax} and \code{rsp}.
  3106. \[
  3107. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3108. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  3109. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  3110. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  3111. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  3112. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3113. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3114. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3115. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3116. \draw (t1) to (rax);
  3117. \draw (t1) to (z);
  3118. \draw (z) to (y);
  3119. \draw (z) to (w);
  3120. \draw (x) to (w);
  3121. \draw (y) to (w);
  3122. \draw (v) to (w);
  3123. \draw (v) to (rsp);
  3124. \draw (w) to (rsp);
  3125. \draw (x) to (rsp);
  3126. \draw (y) to (rsp);
  3127. \path[-.,bend left=15] (z) edge node {} (rsp);
  3128. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3129. \draw (rax) to (rsp);
  3130. \end{tikzpicture}
  3131. \]
  3132. The algorithm says to select a maximally saturated vertex. So we pick
  3133. $\ttm{t}$ and color it with the first available integer, which is
  3134. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  3135. and \ttm{rsp} because they interfere with $\ttm{t}$.
  3136. \[
  3137. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3138. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3139. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  3140. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  3141. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  3142. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3143. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3144. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3145. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3146. \draw (t1) to (rax);
  3147. \draw (t1) to (z);
  3148. \draw (z) to (y);
  3149. \draw (z) to (w);
  3150. \draw (x) to (w);
  3151. \draw (y) to (w);
  3152. \draw (v) to (w);
  3153. \draw (v) to (rsp);
  3154. \draw (w) to (rsp);
  3155. \draw (x) to (rsp);
  3156. \draw (y) to (rsp);
  3157. \path[-.,bend left=15] (z) edge node {} (rsp);
  3158. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3159. \draw (rax) to (rsp);
  3160. \end{tikzpicture}
  3161. \]
  3162. We repeat the process, selecting another maximally saturated
  3163. vertex, which is \code{z}, and color it with the first available
  3164. number, which is $1$. We add $1$ to the saturation for the
  3165. neighboring vertices \code{t}, \code{y}, \code{w}, and \code{rsp}.
  3166. \[
  3167. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3168. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3169. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3170. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3171. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3172. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3173. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3174. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3175. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3176. \draw (t1) to (rax);
  3177. \draw (t1) to (z);
  3178. \draw (z) to (y);
  3179. \draw (z) to (w);
  3180. \draw (x) to (w);
  3181. \draw (y) to (w);
  3182. \draw (v) to (w);
  3183. \draw (v) to (rsp);
  3184. \draw (w) to (rsp);
  3185. \draw (x) to (rsp);
  3186. \draw (y) to (rsp);
  3187. \path[-.,bend left=15] (z) edge node {} (rsp);
  3188. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3189. \draw (rax) to (rsp);
  3190. \end{tikzpicture}
  3191. \]
  3192. The most saturated vertices are now \code{w} and \code{y}. We color
  3193. \code{w} with the first available color, which is $0$.
  3194. \[
  3195. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3196. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3197. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3198. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3199. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3200. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3201. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  3202. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  3203. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  3204. \draw (t1) to (rax);
  3205. \draw (t1) to (z);
  3206. \draw (z) to (y);
  3207. \draw (z) to (w);
  3208. \draw (x) to (w);
  3209. \draw (y) to (w);
  3210. \draw (v) to (w);
  3211. \draw (v) to (rsp);
  3212. \draw (w) to (rsp);
  3213. \draw (x) to (rsp);
  3214. \draw (y) to (rsp);
  3215. \path[-.,bend left=15] (z) edge node {} (rsp);
  3216. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3217. \draw (rax) to (rsp);
  3218. \end{tikzpicture}
  3219. \]
  3220. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  3221. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  3222. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  3223. and \code{z}, whose colors are $0$ and $1$ respectively.
  3224. \[
  3225. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3226. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3227. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3228. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3229. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3230. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3231. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3232. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3233. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  3234. \draw (t1) to (rax);
  3235. \draw (t1) to (z);
  3236. \draw (z) to (y);
  3237. \draw (z) to (w);
  3238. \draw (x) to (w);
  3239. \draw (y) to (w);
  3240. \draw (v) to (w);
  3241. \draw (v) to (rsp);
  3242. \draw (w) to (rsp);
  3243. \draw (x) to (rsp);
  3244. \draw (y) to (rsp);
  3245. \path[-.,bend left=15] (z) edge node {} (rsp);
  3246. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3247. \draw (rax) to (rsp);
  3248. \end{tikzpicture}
  3249. \]
  3250. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  3251. \[
  3252. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3253. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3254. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3255. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3256. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3257. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3258. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3259. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3260. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3261. \draw (t1) to (rax);
  3262. \draw (t1) to (z);
  3263. \draw (z) to (y);
  3264. \draw (z) to (w);
  3265. \draw (x) to (w);
  3266. \draw (y) to (w);
  3267. \draw (v) to (w);
  3268. \draw (v) to (rsp);
  3269. \draw (w) to (rsp);
  3270. \draw (x) to (rsp);
  3271. \draw (y) to (rsp);
  3272. \path[-.,bend left=15] (z) edge node {} (rsp);
  3273. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3274. \draw (rax) to (rsp);
  3275. \end{tikzpicture}
  3276. \]
  3277. In the last step of the algorithm, we color \code{x} with $1$.
  3278. \[
  3279. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3280. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3281. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3282. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3283. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3284. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  3285. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3286. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3287. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3288. \draw (t1) to (rax);
  3289. \draw (t1) to (z);
  3290. \draw (z) to (y);
  3291. \draw (z) to (w);
  3292. \draw (x) to (w);
  3293. \draw (y) to (w);
  3294. \draw (v) to (w);
  3295. \draw (v) to (rsp);
  3296. \draw (w) to (rsp);
  3297. \draw (x) to (rsp);
  3298. \draw (y) to (rsp);
  3299. \path[-.,bend left=15] (z) edge node {} (rsp);
  3300. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3301. \draw (rax) to (rsp);
  3302. \end{tikzpicture}
  3303. \]
  3304. With the coloring complete, we finalize the assignment of variables to
  3305. registers and stack locations. Recall that if we have $k$ registers to
  3306. use for allocation, we map the first $k$ colors to registers and the
  3307. rest to stack locations. Suppose for the moment that we have just one
  3308. register to use for register allocation, \key{rcx}. Then the following
  3309. maps of colors to registers and stack allocations.
  3310. \[
  3311. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  3312. \]
  3313. Putting this mapping together with the above coloring of the
  3314. variables, we arrive at the following assignment.
  3315. \begin{gather*}
  3316. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  3317. \ttm{w} \mapsto \key{\%rcx}, \,
  3318. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  3319. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  3320. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  3321. \ttm{t} \mapsto \key{\%rcx} \}
  3322. \end{gather*}
  3323. Applying this assignment to our running example, on the left, yields
  3324. the program on the right.
  3325. % why frame size of 32? -JGS
  3326. \begin{center}
  3327. \begin{minipage}{0.3\textwidth}
  3328. \begin{lstlisting}
  3329. movq $1, v
  3330. movq $42, w
  3331. movq v, x
  3332. addq $7, x
  3333. movq x, y
  3334. movq x, z
  3335. addq w, z
  3336. movq y, t
  3337. negq t
  3338. movq z, %rax
  3339. addq t, %rax
  3340. jmp conclusion
  3341. \end{lstlisting}
  3342. \end{minipage}
  3343. $\Rightarrow\qquad$
  3344. \begin{minipage}{0.45\textwidth}
  3345. \begin{lstlisting}
  3346. movq $1, %rcx
  3347. movq $42, %rcx
  3348. movq %rcx, -8(%rbp)
  3349. addq $7, -8(%rbp)
  3350. movq -8(%rbp), -16(%rbp)
  3351. movq -8(%rbp), -8(%rbp)
  3352. addq %rcx, -8(%rbp)
  3353. movq -16(%rbp), %rcx
  3354. negq %rcx
  3355. movq -8(%rbp), %rax
  3356. addq %rcx, %rax
  3357. jmp conclusion
  3358. \end{lstlisting}
  3359. \end{minipage}
  3360. \end{center}
  3361. The resulting program is almost an x86 program. The remaining step is
  3362. the patch instructions pass. In this example, the trivial move of
  3363. \code{-8(\%rbp)} to itself is deleted and the addition of
  3364. \code{-8(\%rbp)} to \key{-16(\%rbp)} is fixed by going through
  3365. \code{rax} as follows.
  3366. \begin{lstlisting}
  3367. movq -8(%rbp), %rax
  3368. addq %rax, -16(%rbp)
  3369. \end{lstlisting}
  3370. We recommend creating a helper function named \code{color-graph} that
  3371. takes an interference graph and a list of all the variables in the
  3372. program. This function should return a mapping of variables to their
  3373. colors (represented as natural numbers). By creating this helper
  3374. function, you will be able to reuse it in Chapter~\ref{ch:functions}
  3375. when you add support for functions. To prioritize the processing of
  3376. highly saturated nodes inside your \code{color-graph} function, we
  3377. recommend using the priority queue data structure (see the side bar on
  3378. the right). Note that you will also need to maintain a mapping from
  3379. variables to their ``handles'' in the priority queue so that you can
  3380. notify the priority queue when their saturation changes.
  3381. \begin{wrapfigure}[23]{r}[1.0in]{0.6\textwidth}
  3382. \small
  3383. \begin{tcolorbox}[title=Priority Queue]
  3384. A \emph{priority queue} is a collection of items in which the
  3385. removal of items is governed by priority. In a ``min'' queue,
  3386. lower priority items are removed first. An implementation is in
  3387. \code{priority\_queue.rkt} of the support code. \index{priority
  3388. queue} \index{minimum priority queue}
  3389. \begin{description}
  3390. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  3391. priority queue that uses the $\itm{cmp}$ predicate to determine
  3392. whether its first argument has lower or equal priority to its
  3393. second argument.
  3394. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  3395. items in the queue.
  3396. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  3397. the item into the queue and returns a handle for the item in the
  3398. queue.
  3399. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  3400. the lowest priority.
  3401. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  3402. notifies the queue that the priority has decreased for the item
  3403. associated with the given handle.
  3404. \end{description}
  3405. \end{tcolorbox}
  3406. \end{wrapfigure}
  3407. Once you have obtained the coloring from \code{color-graph}, you can
  3408. assign the variables to registers or stack locations and then reuse
  3409. code from the \code{assign-homes} pass from
  3410. Section~\ref{sec:assign-r1} to replace the variables with their
  3411. assigned location.
  3412. \begin{exercise}\normalfont
  3413. Implement the compiler pass \code{allocate-registers}, which should
  3414. come after the \code{build-interference} pass. The three new passes
  3415. described in this chapter replace the \code{assign-homes} pass of
  3416. Section~\ref{sec:assign-r1}.
  3417. %
  3418. Test your updated compiler by creating new example programs that
  3419. exercise all of the register allocation algorithm, such as forcing
  3420. variables to be spilled to the stack.
  3421. \end{exercise}
  3422. \section{Print x86}
  3423. \label{sec:print-x86-reg-alloc}
  3424. \index{calling conventions}
  3425. \index{prelude}\index{conclusion}
  3426. Recall that the \code{print-x86} pass generates the prelude and
  3427. conclusion instructions for the \code{main} function.
  3428. %
  3429. The prelude saved the values in \code{rbp} and \code{rsp} and the
  3430. conclusion returned those values to \code{rbp} and \code{rsp}. The
  3431. reason for this is that our \code{main} function must adhere to the
  3432. x86 calling conventions that we described in
  3433. Section~\ref{sec:calling-conventions}. Furthermore, if your register
  3434. allocator assigned variables to other callee-saved registers
  3435. (e.g. \code{rbx}, \code{r12}, etc.), then those variables must also be
  3436. saved to the stack in the prelude and restored in the conclusion. The
  3437. simplest approach is to save and restore all of the callee-saved
  3438. registers. The more efficient approach is to keep track of which
  3439. callee-saved registers were used and only save and restore
  3440. them. Either way, make sure to take this use of stack space into
  3441. account when you are calculating the size of the frame and adjusting
  3442. the \code{rsp} in the prelude. Also, don't forget that the size of the
  3443. frame needs to be a multiple of 16 bytes!
  3444. An overview of all of the passes involved in register allocation is
  3445. shown in Figure~\ref{fig:reg-alloc-passes}.
  3446. \begin{figure}[tbp]
  3447. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3448. \node (R1) at (0,2) {\large $R_1$};
  3449. \node (R1-2) at (3,2) {\large $R_1$};
  3450. \node (R1-3) at (6,2) {\large $R_1$};
  3451. \node (C0-1) at (3,0) {\large $C_0$};
  3452. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  3453. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  3454. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  3455. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}$};
  3456. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  3457. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  3458. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  3459. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  3460. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  3461. \path[->,bend right=15] (C0-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  3462. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  3463. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  3464. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  3465. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  3466. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  3467. \end{tikzpicture}
  3468. \caption{Diagram of the passes for $R_1$ with register allocation.}
  3469. \label{fig:reg-alloc-passes}
  3470. \end{figure}
  3471. \section{Challenge: Move Biasing}
  3472. \label{sec:move-biasing}
  3473. \index{move biasing}
  3474. This section describes an optional enhancement to register allocation
  3475. for those students who are looking for an extra challenge or who have
  3476. a deeper interest in register allocation.
  3477. We return to the running example, but we remove the supposition that
  3478. we only have one register to use. So we have the following mapping of
  3479. color numbers to registers.
  3480. \[
  3481. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx} \}
  3482. \]
  3483. Using the same assignment of variables to color numbers that was
  3484. produced by the register allocator described in the last section, we
  3485. get the following program.
  3486. \begin{minipage}{0.3\textwidth}
  3487. \begin{lstlisting}
  3488. movq $1, v
  3489. movq $42, w
  3490. movq v, x
  3491. addq $7, x
  3492. movq x, y
  3493. movq x, z
  3494. addq w, z
  3495. movq y, t
  3496. negq t
  3497. movq z, %rax
  3498. addq t, %rax
  3499. jmp conclusion
  3500. \end{lstlisting}
  3501. \end{minipage}
  3502. $\Rightarrow\qquad$
  3503. \begin{minipage}{0.45\textwidth}
  3504. \begin{lstlisting}
  3505. movq $1, %rcx
  3506. movq $42, $rbx
  3507. movq %rcx, %rcx
  3508. addq $7, %rcx
  3509. movq %rcx, %rdx
  3510. movq %rcx, %rcx
  3511. addq %rbx, %rcx
  3512. movq %rdx, %rbx
  3513. negq %rbx
  3514. movq %rcx, %rax
  3515. addq %rbx, %rax
  3516. jmp conclusion
  3517. \end{lstlisting}
  3518. \end{minipage}
  3519. In the above output code there are two \key{movq} instructions that
  3520. can be removed because their source and target are the same. However,
  3521. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  3522. register, we could instead remove three \key{movq} instructions. We
  3523. can accomplish this by taking into account which variables appear in
  3524. \key{movq} instructions with which other variables.
  3525. We say that two variables $p$ and $q$ are \emph{move
  3526. related}\index{move related} if they participate together in a
  3527. \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  3528. \key{movq} $q$\key{,} $p$. When the register allocator chooses a color
  3529. for a variable, it should prefer a color that has already been used
  3530. for a move-related variable (assuming that they do not interfere). Of
  3531. course, this preference should not override the preference for
  3532. registers over stack locations. This preference should be used as a
  3533. tie breaker when choosing between registers or when choosing between
  3534. stack locations.
  3535. We recommend representing the move relationships in a graph, similar
  3536. to how we represented interference. The following is the \emph{move
  3537. graph} for our running example.
  3538. \[
  3539. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3540. \node (rax) at (0,0) {$\ttm{rax}$};
  3541. \node (rsp) at (9,2) {$\ttm{rsp}$};
  3542. \node (t) at (0,2) {$\ttm{t}$};
  3543. \node (z) at (3,2) {$\ttm{z}$};
  3544. \node (x) at (6,2) {$\ttm{x}$};
  3545. \node (y) at (3,0) {$\ttm{y}$};
  3546. \node (w) at (6,0) {$\ttm{w}$};
  3547. \node (v) at (9,0) {$\ttm{v}$};
  3548. \draw (v) to (x);
  3549. \draw (x) to (y);
  3550. \draw (x) to (z);
  3551. \draw (y) to (t);
  3552. \end{tikzpicture}
  3553. \]
  3554. Now we replay the graph coloring, pausing to see the coloring of
  3555. \code{y}. Recall the following configuration. The most saturated vertices
  3556. were \code{w} and \code{y}.
  3557. \[
  3558. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3559. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3560. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3561. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3562. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3563. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3564. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3565. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3566. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  3567. \draw (t1) to (rax);
  3568. \draw (t1) to (z);
  3569. \draw (z) to (y);
  3570. \draw (z) to (w);
  3571. \draw (x) to (w);
  3572. \draw (y) to (w);
  3573. \draw (v) to (w);
  3574. \draw (v) to (rsp);
  3575. \draw (w) to (rsp);
  3576. \draw (x) to (rsp);
  3577. \draw (y) to (rsp);
  3578. \path[-.,bend left=15] (z) edge node {} (rsp);
  3579. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3580. \draw (rax) to (rsp);
  3581. \end{tikzpicture}
  3582. \]
  3583. %
  3584. Last time we chose to color \code{w} with $0$. But this time we see
  3585. that \code{w} is not move related to any vertex, but \code{y} is move
  3586. related to \code{t}. So we choose to color \code{y} the same color as
  3587. \code{t}, $0$.
  3588. \[
  3589. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3590. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3591. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3592. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3593. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3594. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3595. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  3596. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  3597. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  3598. \draw (t1) to (rax);
  3599. \draw (t1) to (z);
  3600. \draw (z) to (y);
  3601. \draw (z) to (w);
  3602. \draw (x) to (w);
  3603. \draw (y) to (w);
  3604. \draw (v) to (w);
  3605. \draw (v) to (rsp);
  3606. \draw (w) to (rsp);
  3607. \draw (x) to (rsp);
  3608. \draw (y) to (rsp);
  3609. \path[-.,bend left=15] (z) edge node {} (rsp);
  3610. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3611. \draw (rax) to (rsp);
  3612. \end{tikzpicture}
  3613. \]
  3614. Now \code{w} is the most saturated, so we color it $2$.
  3615. \[
  3616. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3617. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3618. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3619. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3620. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3621. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  3622. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  3623. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  3624. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  3625. \draw (t1) to (rax);
  3626. \draw (t1) to (z);
  3627. \draw (z) to (y);
  3628. \draw (z) to (w);
  3629. \draw (x) to (w);
  3630. \draw (y) to (w);
  3631. \draw (v) to (w);
  3632. \draw (v) to (rsp);
  3633. \draw (w) to (rsp);
  3634. \draw (x) to (rsp);
  3635. \draw (y) to (rsp);
  3636. \path[-.,bend left=15] (z) edge node {} (rsp);
  3637. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3638. \draw (rax) to (rsp);
  3639. \end{tikzpicture}
  3640. \]
  3641. At this point, vertices \code{x} and \code{v} are most saturated, but
  3642. \code{x} is move related to \code{y} and \code{z}, so we color
  3643. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  3644. \[
  3645. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3646. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3647. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3648. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3649. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3650. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  3651. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  3652. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  3653. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  3654. \draw (t1) to (rax);
  3655. \draw (t) to (z);
  3656. \draw (z) to (y);
  3657. \draw (z) to (w);
  3658. \draw (x) to (w);
  3659. \draw (y) to (w);
  3660. \draw (v) to (w);
  3661. \draw (v) to (rsp);
  3662. \draw (w) to (rsp);
  3663. \draw (x) to (rsp);
  3664. \draw (y) to (rsp);
  3665. \path[-.,bend left=15] (z) edge node {} (rsp);
  3666. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3667. \draw (rax) to (rsp);
  3668. \end{tikzpicture}
  3669. \]
  3670. So we have the following assignment of variables to registers.
  3671. \begin{gather*}
  3672. \{ \ttm{v} \mapsto \key{\%rbx}, \,
  3673. \ttm{w} \mapsto \key{\%rdx}, \,
  3674. \ttm{x} \mapsto \key{\%rbx}, \,
  3675. \ttm{y} \mapsto \key{\%rbx}, \,
  3676. \ttm{z} \mapsto \key{\%rcx}, \,
  3677. \ttm{t} \mapsto \key{\%rbx} \}
  3678. \end{gather*}
  3679. We apply this register assignment to the running example, on the left,
  3680. to obtain the code in the middle. The \code{patch-instructions} then
  3681. removes the three trivial moves from \key{rbx} to \key{rbx} to obtain
  3682. the code on the right.
  3683. \begin{minipage}{0.25\textwidth}
  3684. \begin{lstlisting}
  3685. movq $1, v
  3686. movq $42, w
  3687. movq v, x
  3688. addq $7, x
  3689. movq x, y
  3690. movq x, z
  3691. addq w, z
  3692. movq y, t
  3693. negq t
  3694. movq z, %rax
  3695. addq t, %rax
  3696. jmp conclusion
  3697. \end{lstlisting}
  3698. \end{minipage}
  3699. $\Rightarrow\qquad$
  3700. \begin{minipage}{0.25\textwidth}
  3701. \begin{lstlisting}
  3702. movq $1, %rbx
  3703. movq $42, %rdx
  3704. movq %rbx, %rbx
  3705. addq $7, %rbx
  3706. movq %rbx, %rbx
  3707. movq %rbx, %rcx
  3708. addq %rdx, %rcx
  3709. movq %rbx, %rbx
  3710. negq %rbx
  3711. movq %rcx, %rax
  3712. addq %rbx, %rax
  3713. jmp conclusion
  3714. \end{lstlisting}
  3715. \end{minipage}
  3716. $\Rightarrow\qquad$
  3717. \begin{minipage}{0.25\textwidth}
  3718. \begin{lstlisting}
  3719. movq $1, %rbx
  3720. movq $42, %rdx
  3721. addq $7, %rbx
  3722. movq %rbx, %rcx
  3723. addq %rdx, %rcx
  3724. negq %rbx
  3725. movq %rcx, %rax
  3726. addq %rbx, %rax
  3727. jmp conclusion
  3728. \end{lstlisting}
  3729. \end{minipage}
  3730. \begin{exercise}\normalfont
  3731. Change your implementation of \code{allocate-registers} to take move
  3732. biasing into account. Make sure that your compiler still passes all of
  3733. the previous tests. Create two new tests that include at least one
  3734. opportunity for move biasing and visually inspect the output x86
  3735. programs to make sure that your move biasing is working properly.
  3736. \end{exercise}
  3737. \margincomment{\footnotesize To do: another neat challenge would be to do
  3738. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3739. \section{Output of the Running Example}
  3740. \label{sec:reg-alloc-output}
  3741. \index{prelude}\index{conclusion}
  3742. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  3743. the running example (Figure~\ref{fig:reg-eg}) with register allocation
  3744. and move biasing. To demonstrate both the use of registers and the
  3745. stack, we have limited the register allocator to use just two
  3746. registers: \code{rbx} and \code{rcx}. In the prelude of the
  3747. \code{main} function, we push \code{rbx} onto the stack because it is
  3748. a callee-saved register and it was assigned to variable by the
  3749. register allocator. We subtract \code{8} from the \code{rsp} at the
  3750. end of the prelude to reserve space for the one spilled variable.
  3751. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  3752. Moving on the the \code{start} block, we see how the registers were
  3753. allocated. Variables \code{v}, \code{x}, and \code{y} were assigned to
  3754. \code{rbx} and variable \code{z} was assigned to \code{rcx}. Variable
  3755. \code{w} was spilled to the stack location \code{-16(\%rbp)}. Recall
  3756. that the prelude saved the callee-save register \code{rbx} onto the
  3757. stack. The spilled variables must be placed lower on the stack than
  3758. the saved callee-save registers, so in this case \code{w} is placed at
  3759. \code{-16(\%rbp)}.
  3760. In the \code{conclusion}, we undo the work that was done in the
  3761. prelude. We move the stack pointer up by \code{8} bytes (the room for
  3762. spilled variables), then we pop the old values of \code{rbx} and
  3763. \code{rbp} (callee-saved registers), and finish with \code{retq} to
  3764. return control to the operating system.
  3765. \begin{figure}[tbp]
  3766. % s0_28.rkt
  3767. % (use-minimal-set-of-registers! #t)
  3768. % and only rbx rcx
  3769. % tmp 0 rbx
  3770. % z 1 rcx
  3771. % y 0 rbx
  3772. % w 2 16(%rbp)
  3773. % v 0 rbx
  3774. % x 0 rbx
  3775. \begin{lstlisting}
  3776. start:
  3777. movq $1, %rbx
  3778. movq $42, -16(%rbp)
  3779. addq $7, %rbx
  3780. movq %rbx, %rcx
  3781. addq -16(%rbp), %rcx
  3782. negq %rbx
  3783. movq %rcx, %rax
  3784. addq %rbx, %rax
  3785. jmp conclusion
  3786. .globl main
  3787. main:
  3788. pushq %rbp
  3789. movq %rsp, %rbp
  3790. pushq %rbx
  3791. subq $8, %rsp
  3792. jmp start
  3793. conclusion:
  3794. addq $8, %rsp
  3795. popq %rbx
  3796. popq %rbp
  3797. retq
  3798. \end{lstlisting}
  3799. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  3800. \label{fig:running-example-x86}
  3801. \end{figure}
  3802. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3803. \chapter{Booleans and Control Flow}
  3804. \label{ch:bool-types}
  3805. \index{Boolean}
  3806. \index{control flow}
  3807. \index{conditional expression}
  3808. The $R_0$ and $R_1$ languages only have a single kind of value, the
  3809. integers. In this chapter we add a second kind of value, the Booleans,
  3810. to create the $R_2$ language. The Boolean values \emph{true} and
  3811. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  3812. Racket. The $R_2$ language includes several operations that involve
  3813. Booleans (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the
  3814. conditional \key{if} expression. With the addition of \key{if}
  3815. expressions, programs can have non-trivial control flow which which
  3816. significantly impacts the \code{explicate-control} and the liveness
  3817. analysis for register allocation. Also, because we now have two kinds
  3818. of values, we need to handle programs that apply an operation to the
  3819. wrong kind of value, such as \code{(not 1)}.
  3820. There are two language design options for such situations. One option
  3821. is to signal an error and the other is to provide a wider
  3822. interpretation of the operation. The Racket language uses a mixture of
  3823. these two options, depending on the operation and the kind of
  3824. value. For example, the result of \code{(not 1)} in Racket is
  3825. \code{\#f} because Racket treats non-zero integers as if they were
  3826. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  3827. error in Racket stating that \code{car} expects a pair.
  3828. The Typed Racket language makes similar design choices as Racket,
  3829. except much of the error detection happens at compile time instead of
  3830. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  3831. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  3832. reports a compile-time error because Typed Racket expects the type of
  3833. the argument to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  3834. For the $R_2$ language we choose to be more like Typed Racket in that
  3835. we perform type checking during compilation. In
  3836. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  3837. is, how to compile a dynamically typed language like Racket. The
  3838. $R_2$ language is a subset of Typed Racket but by no means includes
  3839. all of Typed Racket. For many operations we take a narrower
  3840. interpretation than Typed Racket, for example, rejecting \code{(not 1)}.
  3841. This chapter is organized as follows. We begin by defining the syntax
  3842. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  3843. then introduce the idea of type checking and build a type checker for
  3844. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  3845. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  3846. Section~\ref{sec:c1}. The remaining sections of this chapter discuss
  3847. how our compiler passes need to change to accommodate Booleans and
  3848. conditional control flow.
  3849. \section{The $R_2$ Language}
  3850. \label{sec:r2-lang}
  3851. The concrete syntax of the $R_2$ language is defined in
  3852. Figure~\ref{fig:r2-concrete-syntax} and the abstract syntax is defined
  3853. in Figure~\ref{fig:r2-syntax}. The $R_2$ language includes all of
  3854. $R_1$ (shown in gray), the Boolean literals \code{\#t} and \code{\#f},
  3855. and the conditional \code{if} expression. Also, we expand the
  3856. operators to include
  3857. \begin{enumerate}
  3858. \item subtraction on integers,
  3859. \item the logical operators \key{and}, \key{or} and \key{not},
  3860. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  3861. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  3862. comparing integers.
  3863. \end{enumerate}
  3864. We reorganize the abstract syntax for the primitive operations in
  3865. Figure~\ref{fig:r2-syntax}, using only one grammar rule for all of
  3866. them. This means that the grammar no longer checks whether the arity
  3867. of an operators matches the number of arguments. That responsibility
  3868. is moved to the type checker for $R_2$, which we introduce in
  3869. Section~\ref{sec:type-check-r2}.
  3870. \begin{figure}[tp]
  3871. \centering
  3872. \fbox{
  3873. \begin{minipage}{0.96\textwidth}
  3874. \[
  3875. \begin{array}{lcl}
  3876. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3877. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3878. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} } \mid \CSUB{\Exp}{\Exp} \\
  3879. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} } \\
  3880. &\mid& \itm{bool}
  3881. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  3882. \mid (\key{not}\;\Exp) \\
  3883. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} \\
  3884. R_2 &::=& \Exp
  3885. \end{array}
  3886. \]
  3887. \end{minipage}
  3888. }
  3889. \caption{The concrete syntax of $R_2$, extending $R_1$
  3890. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  3891. \label{fig:r2-concrete-syntax}
  3892. \end{figure}
  3893. \begin{figure}[tp]
  3894. \centering
  3895. \fbox{
  3896. \begin{minipage}{0.96\textwidth}
  3897. \[
  3898. \begin{array}{lcl}
  3899. \itm{bool} &::=& \code{\#t} \mid \code{\#f} \\
  3900. \itm{cmp} &::= & \code{eq?} \mid \code{<} \mid \code{<=} \mid \code{>} \mid \code{>=} \\
  3901. \itm{op} &::= & \itm{cmp} \mid \code{read} \mid \code{+} \mid \code{-}
  3902. \mid \code{and} \mid \code{or} \mid \code{not} \\
  3903. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  3904. &\mid& \PRIM{\itm{op}}{\Exp\ldots}\\
  3905. &\mid& \BOOL{\itm{bool}} \mid \IF{\Exp}{\Exp}{\Exp} \\
  3906. R_2 &::=& \PROGRAM{\code{'()}}{\Exp}
  3907. \end{array}
  3908. \]
  3909. \end{minipage}
  3910. }
  3911. \caption{The abstract syntax of $R_2$.}
  3912. \label{fig:r2-syntax}
  3913. \end{figure}
  3914. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$,
  3915. inheriting from the interpreter for $R_1$
  3916. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  3917. evaluate to the corresponding Boolean values. The conditional
  3918. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  3919. the Boolean expression \itm{cnd} and then either evaluates \itm{thn}
  3920. or \itm{els} depending on whether \itm{cnd} produced \code{\#t} or
  3921. \code{\#f}. The logical operations \code{not} and \code{and} behave as
  3922. you might expect, but note that the \code{and} operation is
  3923. short-circuiting. That is, given the expression
  3924. $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not evaluated if
  3925. $e_1$ evaluates to \code{\#f}.
  3926. With the increase in the number of primitive operations, the
  3927. interpreter code for them could become repetitive without some
  3928. care. We factor out the different parts of the code for primitive
  3929. operations into the \code{interp-op} method shown in in
  3930. Figure~\ref{fig:interp-op-R2}. The match clause for \code{Prim} makes
  3931. the recursive calls to interpret the arguments and then passes the
  3932. resulting values to \code{interp-op}. We do not use \code{interp-op}
  3933. for the \code{and} operation because of its short-circuiting behavior.
  3934. \begin{figure}[tbp]
  3935. \begin{lstlisting}
  3936. (define interp-R2-class
  3937. (class interp-R1-class
  3938. (super-new)
  3939. (define/public (interp-op op) ...)
  3940. (define/override ((interp-exp env) e)
  3941. (define recur (interp-exp env))
  3942. (match e
  3943. [(Bool b) b]
  3944. [(If cnd thn els)
  3945. (define b (recur cnd))
  3946. (match b
  3947. [#t (recur thn)]
  3948. [#f (recur els)])]
  3949. [(Prim 'and (list e1 e2))
  3950. (define v1 (recur e1))
  3951. (match v1
  3952. [#t (match (recur e2) [#t #t] [#f #f])]
  3953. [#f #f])]
  3954. [(Prim op args)
  3955. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  3956. [else ((super interp-exp env) e)]
  3957. ))
  3958. ))
  3959. (define (interp-R2 p)
  3960. (send (new interp-R2-class) interp-program p))
  3961. \end{lstlisting}
  3962. \caption{Interpreter for the $R_2$ language. (See
  3963. Figure~\ref{fig:interp-op-R2} for \code{interp-op}.)}
  3964. \label{fig:interp-R2}
  3965. \end{figure}
  3966. \begin{figure}[tbp]
  3967. \begin{lstlisting}
  3968. (define/public (interp-op op)
  3969. (match op
  3970. ['+ fx+]
  3971. ['- fx-]
  3972. ['read read-fixnum]
  3973. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  3974. ['or (lambda (v1 v2)
  3975. (cond [(and (boolean? v1) (boolean? v2))
  3976. (or v1 v2)]))]
  3977. ['eq? (lambda (v1 v2)
  3978. (cond [(or (and (fixnum? v1) (fixnum? v2))
  3979. (and (boolean? v1) (boolean? v2))
  3980. (and (vector? v1) (vector? v2)))
  3981. (eq? v1 v2)]))]
  3982. ['< (lambda (v1 v2)
  3983. (cond [(and (fixnum? v1) (fixnum? v2))
  3984. (< v1 v2)]))]
  3985. ['<= (lambda (v1 v2)
  3986. (cond [(and (fixnum? v1) (fixnum? v2))
  3987. (<= v1 v2)]))]
  3988. ['> (lambda (v1 v2)
  3989. (cond [(and (fixnum? v1) (fixnum? v2))
  3990. (> v1 v2)]))]
  3991. ['>= (lambda (v1 v2)
  3992. (cond [(and (fixnum? v1) (fixnum? v2))
  3993. (>= v1 v2)]))]
  3994. [else (error 'interp-op "unknown operator")]
  3995. ))
  3996. \end{lstlisting}
  3997. \caption{Interpreter for the primitive operators in the $R_2$ language.}
  3998. \label{fig:interp-op-R2}
  3999. \end{figure}
  4000. \section{Type Checking $R_2$ Programs}
  4001. \label{sec:type-check-r2}
  4002. \index{type checking}
  4003. \index{semantic analysis}
  4004. It is helpful to think about type checking in two complementary
  4005. ways. A type checker predicts the type of value that will be produced
  4006. by each expression in the program. For $R_2$, we have just two types,
  4007. \key{Integer} and \key{Boolean}. So a type checker should predict that
  4008. \begin{lstlisting}
  4009. (+ 10 (- (+ 12 20)))
  4010. \end{lstlisting}
  4011. produces an \key{Integer} while
  4012. \begin{lstlisting}
  4013. (and (not #f) #t)
  4014. \end{lstlisting}
  4015. produces a \key{Boolean}.
  4016. Another way to think about type checking is that it enforces a set of
  4017. rules about which operators can be applied to which kinds of
  4018. values. For example, our type checker for $R_2$ will signal an error
  4019. for the below expression because, as we have seen above, the
  4020. expression \code{(+ 10 ...)} has type \key{Integer} but the type
  4021. checker enforces the rule that the argument of \code{not} must be a
  4022. \key{Boolean}.
  4023. \begin{lstlisting}
  4024. (not (+ 10 (- (+ 12 20))))
  4025. \end{lstlisting}
  4026. We implement type checking using classes and method overriding for the
  4027. same reason that we use them to implement the interpreters. We
  4028. separate the type checker for the $R_1$ fragment into its own class,
  4029. shown in Figure~\ref{fig:type-check-R1}. The type checker for $R_2$ is
  4030. shown in Figure~\ref{fig:type-check-R2}; inherits from the one for
  4031. $R_1$. The code for these type checkers are in the files
  4032. \code{type-check-R1.rkt} and \code{type-check-R2.rkt} of the support
  4033. code.
  4034. %
  4035. Each type checker is a structurally recursive function over the AST.
  4036. Given an input expression \code{e}, the type checker either signals an
  4037. error or returns an expression and its type (\key{Integer} or
  4038. \key{Boolean}). There are situations in which we want to change or
  4039. update the expression.
  4040. %
  4041. The type of an integer literal is \code{Integer} and
  4042. the type of a Boolean literal is \code{Boolean}. To handle variables,
  4043. the type checker uses the environment \code{env} to map variables to
  4044. types. Consider the clause for \key{let}. We type check the
  4045. initializing expression to obtain its type \key{T} and then associate
  4046. type \code{T} with the variable \code{x} in the environment used to
  4047. type check the body of the \key{let}. Thus, when the type checker
  4048. encounters a use of variable \code{x}, it can find its type in the
  4049. environment.
  4050. \begin{figure}[tbp]
  4051. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4052. (define type-check-R1-class
  4053. (class object%
  4054. (super-new)
  4055. (define/public (operator-types)
  4056. '((+ . ((Integer Integer) . Integer))
  4057. (- . ((Integer) . Integer))
  4058. (read . (() . Integer))))
  4059. (define/public (type-equal? t1 t2) (equal? t1 t2))
  4060. (define/public (check-type-equal? t1 t2 e)
  4061. (unless (type-equal? t1 t2)
  4062. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  4063. (define/public (type-check-op op arg-types e)
  4064. (match (dict-ref (operator-types) op)
  4065. [`(,param-types . ,return-type)
  4066. (for ([at arg-types] [pt param-types])
  4067. (check-type-equal? at pt e))
  4068. return-type]
  4069. [else (error 'type-check-op "unrecognized ~a" op)]))
  4070. (define/public (type-check-exp env)
  4071. (lambda (e)
  4072. (debug 'type-check-exp "R1" e)
  4073. (match e
  4074. [(Var x) (values (Var x) (dict-ref env x))]
  4075. [(Int n) (values (Int n) 'Integer)]
  4076. [(Let x e body)
  4077. (define-values (e^ Te) ((type-check-exp env) e))
  4078. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  4079. (values (Let x e^ b) Tb)]
  4080. [(Prim op es)
  4081. (define-values (new-es ts)
  4082. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  4083. (values (Prim op new-es) (type-check-op op ts e))]
  4084. [else (error 'type-check-exp "couldn't match" e)])))
  4085. (define/public (type-check-program e)
  4086. (match e
  4087. [(Program info body)
  4088. (define-values (body^ Tb) ((type-check-exp '()) body))
  4089. (check-type-equal? Tb 'Integer body)
  4090. (Program info body^)]
  4091. [else (error 'type-check-R1 "couldn't match ~a" e)]))
  4092. ))
  4093. (define (type-check-R1 p)
  4094. (send (new type-check-R1-class) type-check-program p))
  4095. \end{lstlisting}
  4096. \caption{Type checker for the $R_1$ fragment of $R_2$.}
  4097. \label{fig:type-check-R1}
  4098. \end{figure}
  4099. \begin{figure}[tbp]
  4100. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4101. (define type-check-R2-class
  4102. (class type-check-R1-class
  4103. (super-new)
  4104. (inherit check-type-equal?)
  4105. (define/override (operator-types)
  4106. (append '((- . ((Integer Integer) . Integer))
  4107. (and . ((Boolean Boolean) . Boolean))
  4108. (or . ((Boolean Boolean) . Boolean))
  4109. (< . ((Integer Integer) . Boolean))
  4110. (<= . ((Integer Integer) . Boolean))
  4111. (> . ((Integer Integer) . Boolean))
  4112. (>= . ((Integer Integer) . Boolean))
  4113. (not . ((Boolean) . Boolean))
  4114. )
  4115. (super operator-types)))
  4116. (define/override (type-check-exp env)
  4117. (lambda (e)
  4118. (match e
  4119. [(Bool b) (values (Bool b) 'Boolean)]
  4120. [(If cnd thn els)
  4121. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  4122. (define-values (thn^ Tt) ((type-check-exp env) thn))
  4123. (define-values (els^ Te) ((type-check-exp env) els))
  4124. (check-type-equal? Tc 'Boolean e)
  4125. (check-type-equal? Tt Te e)
  4126. (values (If cnd^ thn^ els^) Te)]
  4127. [(Prim 'eq? (list e1 e2))
  4128. (define-values (e1^ T1) ((type-check-exp env) e1))
  4129. (define-values (e2^ T2) ((type-check-exp env) e2))
  4130. (check-type-equal? T1 T2 e)
  4131. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  4132. [else ((super type-check-exp env) e)])))
  4133. ))
  4134. (define (type-check-R2 p)
  4135. (send (new type-check-R2-class) type-check-program p))
  4136. \end{lstlisting}
  4137. \caption{Type checker for the $R_2$ language.}
  4138. \label{fig:type-check-R2}
  4139. \end{figure}
  4140. Three auxiliary methods are used in the type checker. The method
  4141. \code{operator-types} defines a dictionary that maps the operator
  4142. names to their parameter and return types. The \code{type-equal?}
  4143. method determines whether two types are equal, which for now simply
  4144. dispatches to \code{equal?} (deep equality). The \code{type-check-op}
  4145. method looks up the operator in the \code{operator-types} dictionary
  4146. and then checks whether the argument types are equal to the parameter
  4147. types. The result is the return type of the operator.
  4148. \begin{exercise}\normalfont
  4149. Create 10 new example programs in $R_2$. Half of the example programs
  4150. should have a type error. For those programs, to signal that a type
  4151. error is expected, create an empty file with the same base name but
  4152. with file extension \code{.tyerr}. For example, if the test
  4153. \code{r2\_14.rkt} is expected to error, then create an empty file
  4154. named \code{r2\_14.tyerr}. The other half of the example programs
  4155. should not have type errors. Note that if the type checker does not
  4156. signal an error for a program, then interpreting that program should
  4157. not encounter an error.
  4158. \end{exercise}
  4159. \section{Shrink the $R_2$ Language}
  4160. \label{sec:shrink-r2}
  4161. The $R_2$ language includes several operators that are easily
  4162. expressible in terms of other operators. For example, subtraction is
  4163. expressible in terms of addition and negation.
  4164. \[
  4165. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  4166. \]
  4167. Several of the comparison operations are expressible in terms of
  4168. less-than and logical negation.
  4169. \[
  4170. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  4171. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  4172. \]
  4173. The \key{let} is needed in the above translation to ensure that
  4174. expression $e_1$ is evaluated before $e_2$.
  4175. By performing these translations near the front-end of the compiler,
  4176. the later passes of the compiler do not need to deal with these
  4177. constructs, making those passes shorter. On the other hand, sometimes
  4178. these translations make it more difficult to generate the most
  4179. efficient code with respect to the number of instructions. However,
  4180. these differences typically do not affect the number of accesses to
  4181. memory, which is the primary factor that determines execution time on
  4182. modern computer architectures.
  4183. \begin{exercise}\normalfont
  4184. Implement the pass \code{shrink} that removes subtraction,
  4185. \key{and}, \key{or}, \key{<=}, \key{>}, and \key{>=} from the language
  4186. by translating them to other constructs in $R_2$. Create tests to
  4187. make sure that the behavior of all of these constructs stays the
  4188. same after translation.
  4189. \end{exercise}
  4190. \section{The x86$_1$ Language}
  4191. \label{sec:x86-1}
  4192. \index{x86}
  4193. To implement the new logical operations, the comparison operations,
  4194. and the \key{if} expression, we need to delve further into the x86
  4195. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} define
  4196. the concrete and abstract syntax for a larger subset of x86 that
  4197. includes instructions for logical operations, comparisons, and
  4198. conditional jumps.
  4199. One small challenge is that x86 does not provide an instruction that
  4200. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  4201. However, the \code{xorq} instruction can be used to encode \code{not}.
  4202. The \key{xorq} instruction takes two arguments, performs a pairwise
  4203. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  4204. and writes the results into its second argument. Recall the truth
  4205. table for exclusive-or:
  4206. \begin{center}
  4207. \begin{tabular}{l|cc}
  4208. & 0 & 1 \\ \hline
  4209. 0 & 0 & 1 \\
  4210. 1 & 1 & 0
  4211. \end{tabular}
  4212. \end{center}
  4213. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  4214. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  4215. for the bit $1$, the result is the opposite of the second bit. Thus,
  4216. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  4217. the first argument:
  4218. \[
  4219. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  4220. \qquad\Rightarrow\qquad
  4221. \begin{array}{l}
  4222. \key{movq}~ \Arg\key{,} \Var\\
  4223. \key{xorq}~ \key{\$1,} \Var
  4224. \end{array}
  4225. \]
  4226. \begin{figure}[tp]
  4227. \fbox{
  4228. \begin{minipage}{0.96\textwidth}
  4229. \[
  4230. \begin{array}{lcl}
  4231. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  4232. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4233. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} } \mid \key{\%}\itm{bytereg}\\
  4234. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4235. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \mid
  4236. \key{subq} \; \Arg\key{,} \Arg \mid
  4237. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid } \\
  4238. && \gray{ \key{callq} \; \itm{label} \mid
  4239. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} } \\
  4240. && \gray{ \itm{label}\key{:}\; \Instr }
  4241. \mid \key{xorq}~\Arg\key{,}~\Arg
  4242. \mid \key{cmpq}~\Arg\key{,}~\Arg \mid \\
  4243. && \key{set}cc~\Arg
  4244. \mid \key{movzbq}~\Arg\key{,}~\Arg
  4245. \mid \key{j}cc~\itm{label}
  4246. \\
  4247. x86_1 &::= & \gray{ \key{.globl main} }\\
  4248. & & \gray{ \key{main:} \; \Instr\ldots }
  4249. \end{array}
  4250. \]
  4251. \end{minipage}
  4252. }
  4253. \caption{The concrete syntax of x86$_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-concrete}).}
  4254. \label{fig:x86-1-concrete}
  4255. \end{figure}
  4256. \begin{figure}[tp]
  4257. \fbox{
  4258. \begin{minipage}{0.96\textwidth}
  4259. \small
  4260. \[
  4261. \begin{array}{lcl}
  4262. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  4263. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4264. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}}
  4265. \mid \BYTEREG{\itm{bytereg}} \\
  4266. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4267. \Instr &::=& \gray{ \BININSTR{\code{'addq}}{\Arg}{\Arg}
  4268. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} } \\
  4269. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  4270. \mid \UNIINSTR{\code{'negq}}{\Arg} } \\
  4271. &\mid& \gray{ \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  4272. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  4273. &\mid& \BININSTR{\code{'xorq}}{\Arg}{\Arg}
  4274. \mid \BININSTR{\code{'cmpq}}{\Arg}{\Arg}\\
  4275. &\mid& \BININSTR{\code{'set}}{\itm{cc}}{\Arg}
  4276. \mid \BININSTR{\code{'movzbq}}{\Arg}{\Arg}\\
  4277. &\mid& \JMPIF{\itm{cc}}{\itm{label}} \\
  4278. \Block &::= & \gray{\BLOCK{\itm{info}}{\Instr\ldots}} \\
  4279. x86_1 &::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}}}
  4280. \end{array}
  4281. \]
  4282. \end{minipage}
  4283. }
  4284. \caption{The abstract syntax of x86$_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-ast}).}
  4285. \label{fig:x86-1}
  4286. \end{figure}
  4287. Next we consider the x86 instructions that are relevant for compiling
  4288. the comparison operations. The \key{cmpq} instruction compares its two
  4289. arguments to determine whether one argument is less than, equal, or
  4290. greater than the other argument. The \key{cmpq} instruction is unusual
  4291. regarding the order of its arguments and where the result is
  4292. placed. The argument order is backwards: if you want to test whether
  4293. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  4294. \key{cmpq} is placed in the special EFLAGS register. This register
  4295. cannot be accessed directly but it can be queried by a number of
  4296. instructions, including the \key{set} instruction. The \key{set}
  4297. instruction puts a \key{1} or \key{0} into its destination depending
  4298. on whether the comparison came out according to the condition code
  4299. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  4300. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  4301. The \key{set} instruction has an annoying quirk in that its
  4302. destination argument must be single byte register, such as \code{al}
  4303. (L for lower bits) or \code{ah} (H for higher bits), which are part of
  4304. the \code{rax} register. Thankfully, the \key{movzbq} instruction can
  4305. then be used to move from a single byte register to a normal 64-bit
  4306. register.
  4307. The x86 instruction for conditional jump are relevant to the
  4308. compilation of \key{if} expressions. The \key{JmpIf} instruction
  4309. updates the program counter to point to the instruction after the
  4310. indicated label depending on whether the result in the EFLAGS register
  4311. matches the condition code \itm{cc}, otherwise the \key{JmpIf}
  4312. instruction falls through to the next instruction. The abstract
  4313. syntax for \key{JmpIf} differs from the concrete syntax for x86 in
  4314. that it separates the instruction name from the condition code. For
  4315. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  4316. the \key{JmpIf} instruction relies on the EFLAGS register, it is
  4317. common for the \key{JmpIf} to be immediately preceded by a \key{cmpq}
  4318. instruction to set the EFLAGS register.
  4319. \section{The $C_1$ Intermediate Language}
  4320. \label{sec:c1}
  4321. As with $R_1$, we compile $R_2$ to a C-like intermediate language, but
  4322. we need to grow that intermediate language to handle the new features
  4323. in $R_2$: Booleans and conditional expressions.
  4324. Figure~\ref{fig:c1-syntax} defines the abstract syntax of $C_1$. (The
  4325. concrete syntax is in the Appendix,
  4326. Figure~\ref{fig:c1-concrete-syntax}.) The $C_1$ language adds logical
  4327. and comparison operators to the $\Exp$ non-terminal and the literals
  4328. \key{\#t} and \key{\#f} to the $\Arg$ non-terminal. Regarding control
  4329. flow, $C_1$ differs considerably from $R_2$. Instead of \key{if}
  4330. expressions, $C_1$ has \key{goto} and conditional \key{goto} in the
  4331. grammar for $\Tail$. This means that a sequence of statements may now
  4332. end with a \code{goto} or a conditional \code{goto}. The conditional
  4333. \code{goto} jumps to one of two labels depending on the outcome of the
  4334. comparison. In Section~\ref{sec:explicate-control-r2} we discuss how
  4335. to translate from $R_2$ to $C_1$, bridging this gap between \key{if}
  4336. expressions and \key{goto}'s.
  4337. \begin{figure}[tp]
  4338. \fbox{
  4339. \begin{minipage}{0.96\textwidth}
  4340. \small
  4341. \[
  4342. \begin{array}{lcl}
  4343. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  4344. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  4345. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  4346. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4347. &\mid& \UNIOP{\key{'not}}{\Atm}
  4348. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  4349. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  4350. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  4351. \mid \GOTO{\itm{label}} \\
  4352. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  4353. C_1 & ::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}\ldots}}}
  4354. \end{array}
  4355. \]
  4356. \end{minipage}
  4357. }
  4358. \caption{The abstract syntax of $C_1$, an extension of $C_0$
  4359. (Figure~\ref{fig:c0-syntax}).}
  4360. \label{fig:c1-syntax}
  4361. \end{figure}
  4362. \clearpage
  4363. \section{Remove Complex Operands}
  4364. \label{sec:remove-complex-opera-R2}
  4365. Add cases for \code{Bool} and \code{If} to the \code{rco-exp} and
  4366. \code{rco-atom} functions according to the definition of the output
  4367. language for this pass, $R_2^{\dagger}$, the administrative normal
  4368. form of $R_2$, which is defined in Figure~\ref{fig:r2-anf-syntax}. The
  4369. \code{Bool} form is an atomic expressions but \code{If} is not. All
  4370. three sub-expressions of an \code{If} are allowed to be complex
  4371. expressions in the output of \code{remove-complex-opera*}, but the
  4372. operands of \code{not} and the comparisons must be atoms. Regarding
  4373. the \code{If} form, it is particularly important to \textbf{not}
  4374. replace its condition with a temporary variable because that would
  4375. interfere with the generation of high-quality output in the
  4376. \code{explicate-control} pass.
  4377. \begin{figure}[tp]
  4378. \centering
  4379. \fbox{
  4380. \begin{minipage}{0.96\textwidth}
  4381. \[
  4382. \begin{array}{rcl}
  4383. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} } \mid \BOOL{\itm{bool}}\\
  4384. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  4385. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4386. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  4387. &\mid& \UNIOP{\key{'not}}{\Atm} \\
  4388. &\mid& \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4389. R^{\dagger}_2 &::=& \PROGRAM{\code{'()}}{\Exp}
  4390. \end{array}
  4391. \]
  4392. \end{minipage}
  4393. }
  4394. \caption{$R_2^{\dagger}$ is $R_2$ in administrative normal form (ANF).}
  4395. \label{fig:r2-anf-syntax}
  4396. \end{figure}
  4397. \section{Explicate Control}
  4398. \label{sec:explicate-control-r2}
  4399. Recall that the purpose of \code{explicate-control} is to make the
  4400. order of evaluation explicit in the syntax of the program. With the
  4401. addition of \key{if} in $R_2$ this get more interesting.
  4402. As a motivating example, consider the following program that has an
  4403. \key{if} expression nested in the predicate of another \key{if}.
  4404. % s1_41.rkt
  4405. \begin{center}
  4406. \begin{minipage}{0.96\textwidth}
  4407. \begin{lstlisting}
  4408. (let ([x (read)])
  4409. (let ([y (read)])
  4410. (if (if (< x 1) (eq? x 0) (eq? x 2))
  4411. (+ y 2)
  4412. (+ y 10))))
  4413. \end{lstlisting}
  4414. \end{minipage}
  4415. \end{center}
  4416. %
  4417. The naive way to compile \key{if} and the comparison would be to
  4418. handle each of them in isolation, regardless of their context. Each
  4419. comparison would be translated into a \key{cmpq} instruction followed
  4420. by a couple instructions to move the result from the EFLAGS register
  4421. into a general purpose register or stack location. Each \key{if} would
  4422. be translated into the combination of a \key{cmpq} and a conditional
  4423. jump. The generated code for the inner \key{if} in the above example
  4424. would be as follows.
  4425. \begin{center}
  4426. \begin{minipage}{0.96\textwidth}
  4427. \begin{lstlisting}
  4428. ...
  4429. cmpq $1, x ;; (< x 1)
  4430. setl %al
  4431. movzbq %al, tmp
  4432. cmpq $1, tmp ;; (if (< x 1) ...)
  4433. je then_branch_1
  4434. jmp else_branch_1
  4435. ...
  4436. \end{lstlisting}
  4437. \end{minipage}
  4438. \end{center}
  4439. However, if we take context into account we can do better and reduce
  4440. the use of \key{cmpq} and EFLAG-accessing instructions.
  4441. One idea is to try and reorganize the code at the level of $R_2$,
  4442. pushing the outer \key{if} inside the inner one. This would yield the
  4443. following code.
  4444. \begin{center}
  4445. \begin{minipage}{0.96\textwidth}
  4446. \begin{lstlisting}
  4447. (let ([x (read)])
  4448. (let ([y (read)])
  4449. (if (< x 1)
  4450. (if (eq? x 0)
  4451. (+ y 2)
  4452. (+ y 10))
  4453. (if (eq? x 2)
  4454. (+ y 2)
  4455. (+ y 10)))))
  4456. \end{lstlisting}
  4457. \end{minipage}
  4458. \end{center}
  4459. Unfortunately, this approach duplicates the two branches, and a
  4460. compiler must never duplicate code!
  4461. We need a way to perform the above transformation, but without
  4462. duplicating code. That is, we need a way for different parts of a
  4463. program to refer to the same piece of code, that is, to \emph{share}
  4464. code. At the level of x86 assembly this is straightforward because we
  4465. can label the code for each of the branches and insert jumps in all
  4466. the places that need to execute the branches. At the higher level of
  4467. our intermediate languages, we need to move away from abstract syntax
  4468. \emph{trees} and instead use \emph{graphs}. In particular, we use a
  4469. standard program representation called a \emph{control flow graph}
  4470. (CFG), due to Frances Elizabeth \citet{Allen:1970uq}.
  4471. \index{control-flow graph} Each vertex is a labeled sequence of code,
  4472. called a \emph{basic block}, and each edge represents a jump to
  4473. another block. The \key{Program} construct of $C_0$ and $C_1$ contains
  4474. a control flow graph represented as an alist mapping labels to basic
  4475. blocks. Each basic block is represented by the $\Tail$ non-terminal.
  4476. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  4477. \code{remove-complex-opera*} pass and then the
  4478. \code{explicate-control} pass on the example program. We walk through
  4479. the output program and then discuss the algorithm.
  4480. %
  4481. Following the order of evaluation in the output of
  4482. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  4483. and then the less-than-comparison to \code{1} in the predicate of the
  4484. inner \key{if}. In the output of \code{explicate-control}, in the
  4485. block labeled \code{start}, this becomes two assignment statements
  4486. followed by a conditional \key{goto} to label \code{block40} or
  4487. \code{block41}. The blocks associated with those labels contain the
  4488. translations of the code \code{(eq? x 0)} and \code{(eq? x 2)},
  4489. respectively. Regarding the block labeled with \code{block40}, we
  4490. start with the comparison to \code{0} and then have a conditional
  4491. goto, either to label \code{block38} or label \code{block39}, which
  4492. are the two branches of the outer \key{if}, i.e., \code{(+ y 2)} and
  4493. \code{(+ y 10)}. The story for the block labeled \code{block41} is
  4494. similar.
  4495. \begin{figure}[tbp]
  4496. \begin{tabular}{lll}
  4497. \begin{minipage}{0.4\textwidth}
  4498. % s1_41.rkt
  4499. \begin{lstlisting}
  4500. (let ([x (read)])
  4501. (let ([y (read)])
  4502. (if (if (< x 1)
  4503. (eq? x 0)
  4504. (eq? x 2))
  4505. (+ y 2)
  4506. (+ y 10))))
  4507. \end{lstlisting}
  4508. \hspace{40pt}$\Downarrow$
  4509. \begin{lstlisting}
  4510. (let ([x (read)])
  4511. (let ([y (read)])
  4512. (if (if (< x 1)
  4513. (eq? x 0)
  4514. (eq? x 2))
  4515. (+ y 2)
  4516. (+ y 10))))
  4517. \end{lstlisting}
  4518. \end{minipage}
  4519. &
  4520. $\Rightarrow$
  4521. &
  4522. \begin{minipage}{0.55\textwidth}
  4523. \begin{lstlisting}
  4524. start:
  4525. x = (read);
  4526. y = (read);
  4527. if (< x 1)
  4528. goto block40;
  4529. else
  4530. goto block41;
  4531. block40:
  4532. if (eq? x 0)
  4533. goto block38;
  4534. else
  4535. goto block39;
  4536. block41:
  4537. if (eq? x 2)
  4538. goto block38;
  4539. else
  4540. goto block39;
  4541. block38:
  4542. return (+ y 2);
  4543. block39:
  4544. return (+ y 10);
  4545. \end{lstlisting}
  4546. \end{minipage}
  4547. \end{tabular}
  4548. \caption{Translation from $R_2$ to $C_1$
  4549. via the \code{explicate-control}.}
  4550. \label{fig:explicate-control-s1-38}
  4551. \end{figure}
  4552. %% The nice thing about the output of \code{explicate-control} is that
  4553. %% there are no unnecessary comparisons and every comparison is part of a
  4554. %% conditional jump.
  4555. %% The down-side of this output is that it includes
  4556. %% trivial blocks, such as the blocks labeled \code{block92} through
  4557. %% \code{block95}, that only jump to another block. We discuss a solution
  4558. %% to this problem in Section~\ref{sec:opt-jumps}.
  4559. Recall that in Section~\ref{sec:explicate-control-r1} we implement
  4560. \code{explicate-control} for $R_1$ using two mutually recursive
  4561. functions, \code{explicate-tail} and \code{explicate-assign}. The
  4562. former function translates expressions in tail position whereas the
  4563. later function translates expressions on the right-hand-side of a
  4564. \key{let}. With the addition of \key{if} expression in $R_2$ we have a
  4565. new kind of context to deal with: the predicate position of the
  4566. \key{if}. We need another function, \code{explicate-pred}, that takes
  4567. an $R_2$ expression and two blocks for the then-branch and
  4568. else-branch. The output of \code{explicate-pred} is a block.
  4569. %
  4570. %% Note that the three explicate functions need to construct a
  4571. %% control-flow graph, which we recommend they do via updates to a global
  4572. %% variable.
  4573. %
  4574. In the following paragraphs we discuss specific cases in the
  4575. \code{explicate-pred} function as well as the additions to the
  4576. \code{explicate-tail} and \code{explicate-assign} functions.
  4577. The function \code{explicate-pred} will need a case for every
  4578. expression that can have type \code{Boolean}. We detail a few cases
  4579. here and leave the rest for the reader. The input to this function is
  4580. an expression and two blocks, $B_1$ and $B_2$, for the two branches of
  4581. the enclosing \key{if}, though some care will be needed regarding how
  4582. we represent the blocks. Suppose the expression is the Boolean
  4583. \code{\#t}. Then we can perform a kind of partial evaluation
  4584. \index{partial evaluation} and translate it to the ``then'' branch
  4585. $B_1$. Likewise, we translate \code{\#f} to the ``else`` branch $B_2$.
  4586. \[
  4587. \key{\#t} \quad\Rightarrow\quad B_1,
  4588. \qquad\qquad\qquad
  4589. \key{\#f} \quad\Rightarrow\quad B_2
  4590. \]
  4591. These two cases demonstrate that we sometimes discard one of the
  4592. blocks that are input to \code{explicate-pred}. We will need to
  4593. arrange for the blocks that we actually use to appear in the resulting
  4594. control-flow graph, but not the discarded blocks.
  4595. The case for \key{if} in \code{explicate-pred} is particularly
  4596. illuminating as it deals with the challenges that we discussed above
  4597. regarding the example of the nested \key{if} expressions. The
  4598. ``then'' and ``else'' branches of the current \key{if} inherit their
  4599. context from the current one, that is, predicate context. So we
  4600. recursively apply \code{explicate-pred} to the ``then'' and ``else''
  4601. branches. For both of those recursive calls, we shall pass the blocks
  4602. $B_1$ and $B_2$. Thus, $B_1$ may get used twice, once inside each
  4603. recursive call, and likewise for $B_2$. As discussed above, to avoid
  4604. duplicating code, we need to add these blocks to the control-flow
  4605. graph so that we can instead refer to them by name and execute them
  4606. with a \key{goto}. However, as we saw in the cases above for \key{\#t}
  4607. and \key{\#f}, the blocks $B_1$ or $B_2$ may not get used at all and
  4608. we don't want to prematurely add them to the control-flow graph if
  4609. they end up being discarded.
  4610. The solution to this conundrum is to use \emph{lazy evaluation} to
  4611. delay adding the blocks to the control-flow graph until the points
  4612. where we know they will be used~\citep{Friedman:1976aa}.\index{lazy
  4613. evaluation} Racket provides support for lazy evaluation with the
  4614. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  4615. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  4616. \index{delay} creates a \emph{promise}\index{promise} in which the
  4617. evaluation of the expressions is postponed. When \key{(force}
  4618. $p$\key{)}\index{force} is applied to a promise $p$ for the first
  4619. time, the expressions $e_1 \ldots e_n$ are evaluated and the result of
  4620. $e_n$ is cached in the promise and returned. If \code{force} is
  4621. applied again to the same promise, then the cached result is returned.
  4622. We use lazy evaluation for the input and output blocks of the
  4623. functions \code{explicate-pred} and \code{explicate-assign} and for
  4624. the output block of \code{explicate-tail}. So instead of taking and
  4625. returning blocks, they take and return promised blocks. Furthermore,
  4626. when we come to a situation in which we a block might be used more
  4627. than once, as in the case for \code{if} above, we transform the
  4628. promise into a new promise that will add the block to the control-flow
  4629. graph and return a \code{goto}. The following auxiliary function
  4630. accomplishes this task. It begins with \code{delay} to create a
  4631. promise. When forced, this promise will force the input block. If that
  4632. block is already a \code{goto} (because it was already added to the
  4633. control-flow graph), then we return that \code{goto}. Otherwise we add
  4634. the block to the control-flow graph with another auxiliary function
  4635. named \code{add-node} that returns the new label, and then return the
  4636. \code{goto}.
  4637. \begin{lstlisting}
  4638. (define (block->goto block)
  4639. (delay
  4640. (define b (force block))
  4641. (match b
  4642. [(Goto label) (Goto label)]
  4643. [else (Goto (add-node b))]
  4644. )))
  4645. \end{lstlisting}
  4646. Getting back to the case for \code{if} in \code{explicate-pred}, we
  4647. make the recursive calls to \code{explicate-pred} on the ``then'' and
  4648. ``else'' branches with the arguments \code{(block->goto} $B_1$\code{)}
  4649. and \code{(block->goto} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  4650. results from the two recursive calls. We complete the case for
  4651. \code{if} by recursively apply \code{explicate-pred} to the condition
  4652. of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  4653. the result $B_5$.
  4654. \[
  4655. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  4656. \quad\Rightarrow\quad
  4657. B_5
  4658. \]
  4659. Next, consider the case for a less-than comparison in
  4660. \code{explicate-pred}. We translate it to an \code{if} statement,
  4661. whose two branches are required to be \code{goto}'s. So we apply
  4662. \code{block->goto} to $B_1$ and $B_2$ to obtain two promised goto's,
  4663. which we can \code{force} to obtain the two actual goto's $G_1$ and
  4664. $G_2$. The translation of the less-than comparison is as follows.
  4665. \[
  4666. (\key{<}~e_1~e_2) \quad\Rightarrow\quad
  4667. \begin{array}{l}
  4668. \key{if}~(\key{<}~e_1~e_2) \; G_1\\
  4669. \key{else} \; G_2
  4670. \end{array}
  4671. \]
  4672. The \code{explicate-tail} function needs to be updated to use lazy
  4673. evaluation and it needs an additional case for \key{if}. Each of the
  4674. cases that return an AST node need use \code{delay} to instead return
  4675. a promise of an AST node. Recall that \code{explicate-tail} has an
  4676. accumulator parameter that is a block, which now becomes a promise of
  4677. a block, which we refer to as $B_0$.
  4678. In the case for \code{if} in \code{explicate-tail}, the two branches
  4679. inherit the current context, so they are in tail position. Thus, the
  4680. recursive calls on the ``then'' and ``else'' branch should be calls to
  4681. \code{explicate-tail}.
  4682. %
  4683. We need to pass $B_0$ as the accumulator argument for both of these
  4684. recursive calls, but we need to be careful not to duplicate $B_0$.
  4685. Thus, we first apply \code{block->goto} to $B_0$ so that it gets added
  4686. to the control-flow graph and obtain a promised goto $G_0$.
  4687. %
  4688. Let $B_1$ be the result of \code{explicate-tail} on the ``then''
  4689. branch and $G_0$ and let $B_2$ be the result of \code{explicate-tail}
  4690. on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  4691. \code{explicate-pred} to the condition of the \key{if}, $B_1$, and
  4692. $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  4693. \[
  4694. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  4695. \]
  4696. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  4697. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  4698. %% should not be confused with the labels for the blocks that appear in
  4699. %% the generated code. We initially construct unlabeled blocks; we only
  4700. %% attach labels to blocks when we add them to the control-flow graph, as
  4701. %% we see in the next case.
  4702. Next consider the case for \key{if} in the \code{explicate-assign}
  4703. function. The context of the \key{if} is an assignment to some
  4704. variable $x$ and then the control continues to some promised block
  4705. $B_1$. The code that we generate for both the ``then'' and ``else''
  4706. branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  4707. apply \code{block->goto} to it and obtain a promised goto $G_1$. The
  4708. branches of the \key{if} inherit the current context, so they are in
  4709. assignment positions. Let $B_2$ be the result of applying
  4710. \code{explicate-assign} to the ``then'' branch, variable $x$, and
  4711. $G_1$. Let $B_3$ be the result of applying \code{explicate-assign} to
  4712. the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  4713. the result of applying \code{explicate-pred} to the predicate
  4714. $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  4715. translates to the promise $B_4$.
  4716. \[
  4717. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  4718. \]
  4719. This completes the description of \code{explicate-control} for $R_2$.
  4720. The way in which the \code{shrink} pass transforms logical operations
  4721. such as \code{and} and \code{or} can impact the quality of code
  4722. generated by \code{explicate-control}. For example, consider the
  4723. following program.
  4724. % s1_21.rkt
  4725. \begin{lstlisting}
  4726. (if (and (eq? (read) 0) (eq? (read) 1))
  4727. 0
  4728. 42)
  4729. \end{lstlisting}
  4730. The \code{and} operation should transform into something that the
  4731. \code{explicate-pred} function can still analyze and descend through to
  4732. reach the underlying \code{eq?} conditions. Ideally, your
  4733. \code{explicate-control} pass should generate code similar to the
  4734. following for the above program.
  4735. \begin{center}
  4736. \begin{lstlisting}
  4737. start:
  4738. tmp1 = (read);
  4739. if (eq? tmp1 0)
  4740. goto block40;
  4741. else
  4742. goto block39;
  4743. block40:
  4744. tmp2 = (read);
  4745. if (eq? tmp2 1)
  4746. goto block38;
  4747. else
  4748. goto block39;
  4749. block38:
  4750. return 0;
  4751. block39:
  4752. return 42;
  4753. \end{lstlisting}
  4754. \end{center}
  4755. \begin{exercise}\normalfont
  4756. Implement the pass \code{explicate-control} by adding the cases for
  4757. \key{if} to the functions for tail and assignment contexts, and
  4758. implement \code{explicate-pred} for predicate contexts. Create test
  4759. cases that exercise all of the new cases in the code for this pass.
  4760. \end{exercise}
  4761. \section{Select Instructions}
  4762. \label{sec:select-r2}
  4763. \index{instruction selection}
  4764. Recall that the \code{select-instructions} pass lowers from our
  4765. $C$-like intermediate representation to the pseudo-x86 language, which
  4766. is suitable for conducting register allocation. The pass is
  4767. implemented using three auxiliary functions, one for each of the
  4768. non-terminals $\Atm$, $\Stmt$, and $\Tail$.
  4769. For $\Atm$, we have new cases for the Booleans. We take the usual
  4770. approach of encoding them as integers, with true as 1 and false as 0.
  4771. \[
  4772. \key{\#t} \Rightarrow \key{1}
  4773. \qquad
  4774. \key{\#f} \Rightarrow \key{0}
  4775. \]
  4776. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  4777. be implemented in terms of \code{xorq} as we discussed at the
  4778. beginning of this section. Given an assignment
  4779. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  4780. if the left-hand side $\itm{var}$ is
  4781. the same as $\Atm$, then just the \code{xorq} suffices.
  4782. \[
  4783. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  4784. \quad\Rightarrow\quad
  4785. \key{xorq}~\key{\$}1\key{,}~\Var
  4786. \]
  4787. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  4788. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  4789. x86. Then we have
  4790. \[
  4791. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  4792. \quad\Rightarrow\quad
  4793. \begin{array}{l}
  4794. \key{movq}~\Arg\key{,}~\Var\\
  4795. \key{xorq}~\key{\$}1\key{,}~\Var
  4796. \end{array}
  4797. \]
  4798. Next consider the cases for \code{eq?} and less-than comparison.
  4799. Translating these operations to x86 is slightly involved due to the
  4800. unusual nature of the \key{cmpq} instruction discussed above. We
  4801. recommend translating an assignment from \code{eq?} into the following
  4802. sequence of three instructions. \\
  4803. \begin{tabular}{lll}
  4804. \begin{minipage}{0.4\textwidth}
  4805. \begin{lstlisting}
  4806. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  4807. \end{lstlisting}
  4808. \end{minipage}
  4809. &
  4810. $\Rightarrow$
  4811. &
  4812. \begin{minipage}{0.4\textwidth}
  4813. \begin{lstlisting}
  4814. cmpq |$\Arg_2$|, |$\Arg_1$|
  4815. sete %al
  4816. movzbq %al, |$\Var$|
  4817. \end{lstlisting}
  4818. \end{minipage}
  4819. \end{tabular} \\
  4820. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  4821. and conditional \key{goto}. Both are straightforward to handle. A
  4822. \key{goto} becomes a jump instruction.
  4823. \[
  4824. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  4825. \]
  4826. A conditional \key{goto} becomes a compare instruction followed
  4827. by a conditional jump (for ``then'') and the fall-through is
  4828. to a regular jump (for ``else'').\\
  4829. \begin{tabular}{lll}
  4830. \begin{minipage}{0.4\textwidth}
  4831. \begin{lstlisting}
  4832. if (eq? |$\Atm_1$| |$\Atm_2$|)
  4833. goto |$\ell_1$|;
  4834. else
  4835. goto |$\ell_2$|;
  4836. \end{lstlisting}
  4837. \end{minipage}
  4838. &
  4839. $\Rightarrow$
  4840. &
  4841. \begin{minipage}{0.4\textwidth}
  4842. \begin{lstlisting}
  4843. cmpq |$\Arg_2$|, |$\Arg_1$|
  4844. je |$\ell_1$|
  4845. jmp |$\ell_2$|
  4846. \end{lstlisting}
  4847. \end{minipage}
  4848. \end{tabular} \\
  4849. \begin{exercise}\normalfont
  4850. Expand your \code{select-instructions} pass to handle the new features
  4851. of the $R_2$ language. Test the pass on all the examples you have
  4852. created and make sure that you have some test programs that use the
  4853. \code{eq?} and \code{<} operators, creating some if necessary. Test
  4854. the output using the \code{interp-x86} interpreter
  4855. (Appendix~\ref{appendix:interp}).
  4856. \end{exercise}
  4857. \section{Register Allocation}
  4858. \label{sec:register-allocation-r2}
  4859. \index{register allocation}
  4860. The changes required for $R_2$ affect liveness analysis, building the
  4861. interference graph, and assigning homes, but the graph coloring
  4862. algorithm itself does not change.
  4863. \subsection{Liveness Analysis}
  4864. \label{sec:liveness-analysis-r2}
  4865. \index{liveness analysis}
  4866. Recall that for $R_1$ we implemented liveness analysis for a single
  4867. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  4868. addition of \key{if} expressions to $R_2$, \code{explicate-control}
  4869. produces many basic blocks arranged in a control-flow graph. We
  4870. recommend that you create a new auxiliary function named
  4871. \code{uncover-live-CFG} that applies liveness analysis to a
  4872. control-flow graph.
  4873. The first question we need to consider is: what order should we
  4874. process the basic blocks in the control-flow graph? To perform
  4875. liveness analysis on a basic block, we need to know its live-after
  4876. set. If a basic block has no successor blocks (i.e. no out-edges in
  4877. the control flow graph), then it has an empty live-after set and we
  4878. can immediately apply liveness analysis to it. If a basic block has
  4879. some successors, then we need to complete liveness analysis on those
  4880. blocks first. Thankfully, the control flow graph does not contain any
  4881. cycles because $R_2$ does not include loops. (In
  4882. Chapter~\ref{ch:loop} we add loops and study how to handle cycles in
  4883. the control-flow graph.)
  4884. %
  4885. Returning to the question of what order should we process the basic
  4886. blocks, the answer is reverse topological order. We recommend using
  4887. the \code{tsort} (topological sort) and \code{transpose} functions of
  4888. the Racket \code{graph} package to obtain this ordering.
  4889. \index{topological order}
  4890. \index{topological sort}
  4891. The next question is how to analyze the jump instructions. In
  4892. Section~\ref{sec:liveness-analysis-r1} we recommended that you
  4893. maintain an alist named \code{label->live} that maps each label to the
  4894. set of live locations at the beginning of the associated block. Now
  4895. that we have many basic blocks, the alist needs to be extended as we
  4896. process the blocks. In particular, after performing liveness analysis
  4897. on a block, we can take the live-before set for its first instruction
  4898. and associate that with the block's label in the alist.
  4899. %
  4900. As discussed in Section~\ref{sec:liveness-analysis-r1}, the
  4901. live-before set for a $\JMP{\itm{label}}$ instruction is given by the
  4902. mapping for $\itm{label}$ in \code{label->live}.
  4903. Now for $x86_1$ we also have the conditional jump
  4904. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. This one is
  4905. particularly interesting because during compilation we do not know, in
  4906. general, which way a conditional jump will go, so we do not know
  4907. whether to use the live-before set for the following instruction or
  4908. the live-before set for $\itm{label}$. The solution to this challenge
  4909. is based on the observation that there is no harm to the correctness
  4910. of the compiler if we classify more locations as live than the ones
  4911. that are truly live during a particular execution of the
  4912. instruction. Thus, we can take the union of the live-before sets from
  4913. the following instruction and from the mapping fro $\itm{label}$ in
  4914. \code{label->live}.
  4915. The helper functions for computing the variables in an instruction's
  4916. argument and for computing the variables read-from ($R$) or written-to
  4917. ($W$) by an instruction need to be updated to handle the new kinds of
  4918. arguments and instructions in x86$_1$.
  4919. \subsection{Build Interference}
  4920. \label{sec:build-interference-r2}
  4921. Many of the new instructions in x86$_1$ can be handled in the same way
  4922. as the instructions in x86$_0$. Thus, if your code was already quite
  4923. general, it will not need to be changed to handle the new
  4924. instructions. If you code is not general enough, I recommend that you
  4925. change your code to be more general. For example, you can factor out
  4926. the computing of the the read and write sets for each kind of
  4927. instruction into two auxiliary functions.
  4928. Note that the \key{movzbq} instruction requires some special care,
  4929. just like the \key{movq} instruction. See rule number 3 in
  4930. Section~\ref{sec:build-interference}.
  4931. %% \subsection{Assign Homes}
  4932. %% \label{sec:assign-homes-r2}
  4933. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  4934. %% to be updated to handle the \key{if} statement, simply by recursively
  4935. %% processing the child nodes. Hopefully your code already handles the
  4936. %% other new instructions, but if not, you can generalize your code.
  4937. \begin{exercise}\normalfont
  4938. Update the \code{register-allocation} pass so that it works for $R_2$
  4939. and test your compiler using your previously created programs on the
  4940. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4941. \end{exercise}
  4942. \section{Patch Instructions}
  4943. The second argument of the \key{cmpq} instruction must not be an
  4944. immediate value (such as an integer). So if you are comparing two
  4945. immediates, we recommend inserting a \key{movq} instruction to put the
  4946. second argument in \key{rax}. Also, recall that instructions may have
  4947. at most one memory reference.
  4948. %
  4949. The second argument of the \key{movzbq} must be a register.
  4950. %
  4951. There are no special restrictions on the x86 instructions \key{JmpIf}
  4952. and \key{Jmp}.
  4953. \begin{exercise}\normalfont
  4954. Update \code{patch-instructions} to handle the new x86 instructions.
  4955. Test your compiler using your previously created programs on the
  4956. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4957. \end{exercise}
  4958. \begin{figure}[tbp]
  4959. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4960. \node (R2) at (0,2) {\large $R_2$};
  4961. \node (R2-2) at (3,2) {\large $R_2$};
  4962. \node (R2-3) at (6,2) {\large $R_2$};
  4963. \node (R2-4) at (9,2) {\large $R_2$};
  4964. \node (R2-5) at (12,2) {\large $R_2$};
  4965. \node (C1-1) at (3,0) {\large $C_1$};
  4966. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_1$};
  4967. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_1$};
  4968. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}_1$};
  4969. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}_1$};
  4970. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}_1$};
  4971. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}_1$};
  4972. \path[->,bend left=15] (R2) edge [above] node {\ttfamily\footnotesize type-check} (R2-2);
  4973. \path[->,bend left=15] (R2-2) edge [above] node {\ttfamily\footnotesize shrink} (R2-3);
  4974. \path[->,bend left=15] (R2-3) edge [above] node {\ttfamily\footnotesize uniquify} (R2-4);
  4975. \path[->,bend left=15] (R2-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R2-5);
  4976. \path[->,bend left=15] (R2-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C1-1);
  4977. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select-instructions} (x86-2);
  4978. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  4979. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  4980. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4981. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  4982. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86 } (x86-5);
  4983. \end{tikzpicture}
  4984. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  4985. \label{fig:R2-passes}
  4986. \end{figure}
  4987. Figure~\ref{fig:R2-passes} lists all the passes needed for the
  4988. compilation of $R_2$.
  4989. \section{An Example Translation}
  4990. Figure~\ref{fig:if-example-x86} shows a simple example program in
  4991. $R_2$ translated to x86, showing the results of
  4992. \code{explicate-control}, \code{select-instructions}, and the final
  4993. x86 assembly code.
  4994. \begin{figure}[tbp]
  4995. \begin{tabular}{lll}
  4996. \begin{minipage}{0.5\textwidth}
  4997. % s1_20.rkt
  4998. \begin{lstlisting}
  4999. (if (eq? (read) 1) 42 0)
  5000. \end{lstlisting}
  5001. $\Downarrow$
  5002. \begin{lstlisting}
  5003. start:
  5004. tmp7951 = (read);
  5005. if (eq? tmp7951 1) then
  5006. goto block7952;
  5007. else
  5008. goto block7953;
  5009. block7952:
  5010. return 42;
  5011. block7953:
  5012. return 0;
  5013. \end{lstlisting}
  5014. $\Downarrow$
  5015. \begin{lstlisting}
  5016. start:
  5017. callq read_int
  5018. movq %rax, tmp7951
  5019. cmpq $1, tmp7951
  5020. je block7952
  5021. jmp block7953
  5022. block7953:
  5023. movq $0, %rax
  5024. jmp conclusion
  5025. block7952:
  5026. movq $42, %rax
  5027. jmp conclusion
  5028. \end{lstlisting}
  5029. \end{minipage}
  5030. &
  5031. $\Rightarrow\qquad$
  5032. \begin{minipage}{0.4\textwidth}
  5033. \begin{lstlisting}
  5034. start:
  5035. callq read_int
  5036. movq %rax, %rcx
  5037. cmpq $1, %rcx
  5038. je block7952
  5039. jmp block7953
  5040. block7953:
  5041. movq $0, %rax
  5042. jmp conclusion
  5043. block7952:
  5044. movq $42, %rax
  5045. jmp conclusion
  5046. .globl main
  5047. main:
  5048. pushq %rbp
  5049. movq %rsp, %rbp
  5050. pushq %r13
  5051. pushq %r12
  5052. pushq %rbx
  5053. pushq %r14
  5054. subq $0, %rsp
  5055. jmp start
  5056. conclusion:
  5057. addq $0, %rsp
  5058. popq %r14
  5059. popq %rbx
  5060. popq %r12
  5061. popq %r13
  5062. popq %rbp
  5063. retq
  5064. \end{lstlisting}
  5065. \end{minipage}
  5066. \end{tabular}
  5067. \caption{Example compilation of an \key{if} expression to x86.}
  5068. \label{fig:if-example-x86}
  5069. \end{figure}
  5070. \section{Challenge: Remove Jumps}
  5071. \label{sec:opt-jumps}
  5072. %% Recall that in the example output of \code{explicate-control} in
  5073. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  5074. %% \code{block60} are trivial blocks, they do nothing but jump to another
  5075. %% block. The first goal of this challenge assignment is to remove those
  5076. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  5077. %% \code{explicate-control} on the left and shows the result of bypassing
  5078. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  5079. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  5080. %% \code{block55}. The optimized code on the right of
  5081. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  5082. %% \code{then} branch jumping directly to \code{block55}. The story is
  5083. %% similar for the \code{else} branch, as well as for the two branches in
  5084. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  5085. %% have been optimized in this way, there are no longer any jumps to
  5086. %% blocks \code{block57} through \code{block60}, so they can be removed.
  5087. %% \begin{figure}[tbp]
  5088. %% \begin{tabular}{lll}
  5089. %% \begin{minipage}{0.4\textwidth}
  5090. %% \begin{lstlisting}
  5091. %% block62:
  5092. %% tmp54 = (read);
  5093. %% if (eq? tmp54 2) then
  5094. %% goto block59;
  5095. %% else
  5096. %% goto block60;
  5097. %% block61:
  5098. %% tmp53 = (read);
  5099. %% if (eq? tmp53 0) then
  5100. %% goto block57;
  5101. %% else
  5102. %% goto block58;
  5103. %% block60:
  5104. %% goto block56;
  5105. %% block59:
  5106. %% goto block55;
  5107. %% block58:
  5108. %% goto block56;
  5109. %% block57:
  5110. %% goto block55;
  5111. %% block56:
  5112. %% return (+ 700 77);
  5113. %% block55:
  5114. %% return (+ 10 32);
  5115. %% start:
  5116. %% tmp52 = (read);
  5117. %% if (eq? tmp52 1) then
  5118. %% goto block61;
  5119. %% else
  5120. %% goto block62;
  5121. %% \end{lstlisting}
  5122. %% \end{minipage}
  5123. %% &
  5124. %% $\Rightarrow$
  5125. %% &
  5126. %% \begin{minipage}{0.55\textwidth}
  5127. %% \begin{lstlisting}
  5128. %% block62:
  5129. %% tmp54 = (read);
  5130. %% if (eq? tmp54 2) then
  5131. %% goto block55;
  5132. %% else
  5133. %% goto block56;
  5134. %% block61:
  5135. %% tmp53 = (read);
  5136. %% if (eq? tmp53 0) then
  5137. %% goto block55;
  5138. %% else
  5139. %% goto block56;
  5140. %% block56:
  5141. %% return (+ 700 77);
  5142. %% block55:
  5143. %% return (+ 10 32);
  5144. %% start:
  5145. %% tmp52 = (read);
  5146. %% if (eq? tmp52 1) then
  5147. %% goto block61;
  5148. %% else
  5149. %% goto block62;
  5150. %% \end{lstlisting}
  5151. %% \end{minipage}
  5152. %% \end{tabular}
  5153. %% \caption{Optimize jumps by removing trivial blocks.}
  5154. %% \label{fig:optimize-jumps}
  5155. %% \end{figure}
  5156. %% The name of this pass is \code{optimize-jumps}. We recommend
  5157. %% implementing this pass in two phases. The first phrase builds a hash
  5158. %% table that maps labels to possibly improved labels. The second phase
  5159. %% changes the target of each \code{goto} to use the improved label. If
  5160. %% the label is for a trivial block, then the hash table should map the
  5161. %% label to the first non-trivial block that can be reached from this
  5162. %% label by jumping through trivial blocks. If the label is for a
  5163. %% non-trivial block, then the hash table should map the label to itself;
  5164. %% we do not want to change jumps to non-trivial blocks.
  5165. %% The first phase can be accomplished by constructing an empty hash
  5166. %% table, call it \code{short-cut}, and then iterating over the control
  5167. %% flow graph. Each time you encouter a block that is just a \code{goto},
  5168. %% then update the hash table, mapping the block's source to the target
  5169. %% of the \code{goto}. Also, the hash table may already have mapped some
  5170. %% labels to the block's source, to you must iterate through the hash
  5171. %% table and update all of those so that they instead map to the target
  5172. %% of the \code{goto}.
  5173. %% For the second phase, we recommend iterating through the $\Tail$ of
  5174. %% each block in the program, updating the target of every \code{goto}
  5175. %% according to the mapping in \code{short-cut}.
  5176. %% \begin{exercise}\normalfont
  5177. %% Implement the \code{optimize-jumps} pass as a transformation from
  5178. %% $C_1$ to $C_1$, coming after the \code{explicate-control} pass.
  5179. %% Check that \code{optimize-jumps} removes trivial blocks in a few
  5180. %% example programs. Then check that your compiler still passes all of
  5181. %% your tests.
  5182. %% \end{exercise}
  5183. There is an opportunity for optimizing jumps that is apparent in the
  5184. example of Figure~\ref{fig:if-example-x86}. The \code{start} block end
  5185. with a jump to \code{block7953} and there are no other jumps to
  5186. \code{block7953} in the rest of the program. In this situation we can
  5187. avoid the runtime overhead of this jump by merging \code{block7953}
  5188. into the preceding block, in this case the \code{start} block.
  5189. Figure~\ref{fig:remove-jumps} shows the output of
  5190. \code{select-instructions} on the left and the result of this
  5191. optimization on the right.
  5192. \begin{figure}[tbp]
  5193. \begin{tabular}{lll}
  5194. \begin{minipage}{0.5\textwidth}
  5195. % s1_20.rkt
  5196. \begin{lstlisting}
  5197. start:
  5198. callq read_int
  5199. movq %rax, tmp7951
  5200. cmpq $1, tmp7951
  5201. je block7952
  5202. jmp block7953
  5203. block7953:
  5204. movq $0, %rax
  5205. jmp conclusion
  5206. block7952:
  5207. movq $42, %rax
  5208. jmp conclusion
  5209. \end{lstlisting}
  5210. \end{minipage}
  5211. &
  5212. $\Rightarrow\qquad$
  5213. \begin{minipage}{0.4\textwidth}
  5214. \begin{lstlisting}
  5215. start:
  5216. callq read_int
  5217. movq %rax, tmp7951
  5218. cmpq $1, tmp7951
  5219. je block7952
  5220. movq $0, %rax
  5221. jmp conclusion
  5222. block7952:
  5223. movq $42, %rax
  5224. jmp conclusion
  5225. \end{lstlisting}
  5226. \end{minipage}
  5227. \end{tabular}
  5228. \caption{Merging basic blocks by removing unnecessary jumps.}
  5229. \label{fig:remove-jumps}
  5230. \end{figure}
  5231. \begin{exercise}\normalfont
  5232. Implement a pass named \code{remove-jumps} that merges basic blocks
  5233. into their preceding basic block, when there is only one preceding
  5234. block. The pass should translate from pseudo $x86_1$ to pseudo
  5235. $x86_1$ and it should come immediately after
  5236. \code{select-instructions}. Check that \code{remove-jumps}
  5237. accomplishes the goal of merging basic blocks on several test
  5238. programs and check that your compiler passes all of your tests.
  5239. \end{exercise}
  5240. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5241. \chapter{Tuples and Garbage Collection}
  5242. \label{ch:tuples}
  5243. \index{tuple}
  5244. \index{vector}
  5245. \margincomment{\scriptsize To do: challenge assignments: mark-and-sweep,
  5246. add simple structures. \\ --Jeremy}
  5247. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  5248. things to discuss in this chapter. \\ --Jeremy}
  5249. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  5250. all the IR grammars are spelled out! \\ --Jeremy}
  5251. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  5252. but keep type annotations on vector creation and local variables, function
  5253. parameters, etc. \\ --Jeremy}
  5254. \margincomment{\scriptsize Be more explicit about how to deal with
  5255. the root stack. \\ --Jeremy}
  5256. In this chapter we study the implementation of mutable tuples (called
  5257. ``vectors'' in Racket). This language feature is the first to use the
  5258. computer's \emph{heap}\index{heap} because the lifetime of a Racket tuple is
  5259. indefinite, that is, a tuple lives forever from the programmer's
  5260. viewpoint. Of course, from an implementer's viewpoint, it is important
  5261. to reclaim the space associated with a tuple when it is no longer
  5262. needed, which is why we also study \emph{garbage collection}
  5263. \emph{garbage collection}
  5264. techniques in this chapter.
  5265. Section~\ref{sec:r3} introduces the $R_3$ language including its
  5266. interpreter and type checker. The $R_3$ language extends the $R_2$
  5267. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  5268. \code{void} value. The reason for including the later is that the
  5269. \code{vector-set!} operation returns a value of type
  5270. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  5271. called the \code{Unit} type in the programming languages
  5272. literature. Racket's \code{Void} type is inhabited by a single value
  5273. \code{void} which corresponds to \code{unit} or \code{()} in the
  5274. literature~\citep{Pierce:2002hj}.}.
  5275. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  5276. copying live objects back and forth between two halves of the
  5277. heap. The garbage collector requires coordination with the compiler so
  5278. that it can see all of the \emph{root} pointers, that is, pointers in
  5279. registers or on the procedure call stack.
  5280. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  5281. discuss all the necessary changes and additions to the compiler
  5282. passes, including a new compiler pass named \code{expose-allocation}.
  5283. \section{The $R_3$ Language}
  5284. \label{sec:r3}
  5285. Figure~\ref{fig:r3-concrete-syntax} defines the concrete syntax for
  5286. $R_3$ and Figure~\ref{fig:r3-syntax} defines the abstract syntax. The
  5287. $R_3$ language includes three new forms: \code{vector} for creating a
  5288. tuple, \code{vector-ref} for reading an element of a tuple, and
  5289. \code{vector-set!} for writing to an element of a tuple. The program
  5290. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  5291. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  5292. the 3-tuple, demonstrating that tuples are first-class values. The
  5293. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  5294. of the \key{if} is taken. The element at index $0$ of \code{t} is
  5295. \code{40}, to which we add \code{2}, the element at index $0$ of the
  5296. 1-tuple. So the result of the program is \code{42}.
  5297. \begin{figure}[tbp]
  5298. \centering
  5299. \fbox{
  5300. \begin{minipage}{0.96\textwidth}
  5301. \[
  5302. \begin{array}{lcl}
  5303. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  5304. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \key{Void}\\
  5305. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  5306. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  5307. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5308. \mid \LP\key{and}\;\Exp\;\Exp\RP
  5309. \mid \LP\key{or}\;\Exp\;\Exp\RP
  5310. \mid \LP\key{not}\;\Exp\RP } \\
  5311. &\mid& \gray{ \LP\itm{cmp}\;\Exp\;\Exp\RP
  5312. \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  5313. &\mid& \LP\key{vector}\;\Exp\ldots\RP
  5314. \mid \LP\key{vector-length}\;\Exp\RP \\
  5315. &\mid& \LP\key{vector-ref}\;\Exp\;\Int\RP
  5316. \mid \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP \\
  5317. &\mid& \LP\key{void}\RP \mid \LP\key{has-type}~\Exp~\Type\RP\\
  5318. R_3 &::=& \Exp
  5319. \end{array}
  5320. \]
  5321. \end{minipage}
  5322. }
  5323. \caption{The concrete syntax of $R_3$, extending $R_2$
  5324. (Figure~\ref{fig:r2-concrete-syntax}).}
  5325. \label{fig:r3-concrete-syntax}
  5326. \end{figure}
  5327. \begin{figure}[tbp]
  5328. \begin{lstlisting}
  5329. (let ([t (vector 40 #t (vector 2))])
  5330. (if (vector-ref t 1)
  5331. (+ (vector-ref t 0)
  5332. (vector-ref (vector-ref t 2) 0))
  5333. 44))
  5334. \end{lstlisting}
  5335. \caption{Example program that creates tuples and reads from them.}
  5336. \label{fig:vector-eg}
  5337. \end{figure}
  5338. \begin{figure}[tp]
  5339. \centering
  5340. \fbox{
  5341. \begin{minipage}{0.96\textwidth}
  5342. \[
  5343. \begin{array}{lcl}
  5344. \itm{op} &::=& \ldots \mid \code{vector} \mid \code{vector-length} \\
  5345. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  5346. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots}
  5347. \mid \BOOL{\itm{bool}}
  5348. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  5349. &\mid& \VECREF{\Exp}{\INT{\Int}}\\
  5350. &\mid& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  5351. &\mid& \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP \\
  5352. R_3 &::=& \PROGRAM{\key{'()}}{\Exp}
  5353. \end{array}
  5354. \]
  5355. \end{minipage}
  5356. }
  5357. \caption{The abstract syntax of $R_3$.}
  5358. \label{fig:r3-syntax}
  5359. \end{figure}
  5360. \index{allocate}
  5361. \index{heap allocate}
  5362. Tuples are our first encounter with heap-allocated data, which raises
  5363. several interesting issues. First, variable binding performs a
  5364. shallow-copy when dealing with tuples, which means that different
  5365. variables can refer to the same tuple, that is, different variables
  5366. can be \emph{aliases} for the same entity. Consider the following
  5367. example in which both \code{t1} and \code{t2} refer to the same tuple.
  5368. Thus, the mutation through \code{t2} is visible when referencing the
  5369. tuple from \code{t1}, so the result of this program is \code{42}.
  5370. \index{alias}\index{mutation}
  5371. \begin{center}
  5372. \begin{minipage}{0.96\textwidth}
  5373. \begin{lstlisting}
  5374. (let ([t1 (vector 3 7)])
  5375. (let ([t2 t1])
  5376. (let ([_ (vector-set! t2 0 42)])
  5377. (vector-ref t1 0))))
  5378. \end{lstlisting}
  5379. \end{minipage}
  5380. \end{center}
  5381. The next issue concerns the lifetime of tuples. Of course, they are
  5382. created by the \code{vector} form, but when does their lifetime end?
  5383. Notice that $R_3$ does not include an operation for deleting
  5384. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  5385. of static scoping. For example, the following program returns
  5386. \code{42} even though the variable \code{w} goes out of scope prior to
  5387. the \code{vector-ref} that reads from the vector it was bound to.
  5388. \begin{center}
  5389. \begin{minipage}{0.96\textwidth}
  5390. \begin{lstlisting}
  5391. (let ([v (vector (vector 44))])
  5392. (let ([x (let ([w (vector 42)])
  5393. (let ([_ (vector-set! v 0 w)])
  5394. 0))])
  5395. (+ x (vector-ref (vector-ref v 0) 0))))
  5396. \end{lstlisting}
  5397. \end{minipage}
  5398. \end{center}
  5399. From the perspective of programmer-observable behavior, tuples live
  5400. forever. Of course, if they really lived forever, then many programs
  5401. would run out of memory.\footnote{The $R_3$ language does not have
  5402. looping or recursive functions, so it is nigh impossible to write a
  5403. program in $R_3$ that will run out of memory. However, we add
  5404. recursive functions in the next Chapter!} A Racket implementation
  5405. must therefore perform automatic garbage collection.
  5406. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  5407. $R_3$ language. We define the \code{vector}, \code{vector-length},
  5408. \code{vector-ref}, and \code{vector-set!} operations for $R_3$ in
  5409. terms of the corresponding operations in Racket. One subtle point is
  5410. that the \code{vector-set!} operation returns the \code{\#<void>}
  5411. value. The \code{\#<void>} value can be passed around just like other
  5412. values inside an $R_3$ program and a \code{\#<void>} value can be
  5413. compared for equality with another \code{\#<void>} value. However,
  5414. there are no other operations specific to the the \code{\#<void>}
  5415. value in $R_3$. In contrast, Racket defines the \code{void?} predicate
  5416. that returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  5417. otherwise.
  5418. \begin{figure}[tbp]
  5419. \begin{lstlisting}
  5420. (define interp-R3-class
  5421. (class interp-R2-class
  5422. (super-new)
  5423. (define/override (interp-op op)
  5424. (match op
  5425. ['eq? (lambda (v1 v2)
  5426. (cond [(or (and (fixnum? v1) (fixnum? v2))
  5427. (and (boolean? v1) (boolean? v2))
  5428. (and (vector? v1) (vector? v2))
  5429. (and (void? v1) (void? v2)))
  5430. (eq? v1 v2)]))]
  5431. ['vector vector]
  5432. ['vector-length vector-length]
  5433. ['vector-ref vector-ref]
  5434. ['vector-set! vector-set!]
  5435. [else (super interp-op op)]
  5436. ))
  5437. (define/override ((interp-exp env) e)
  5438. (define recur (interp-exp env))
  5439. (match e
  5440. [(HasType e t) (recur e)]
  5441. [(Void) (void)]
  5442. [else ((super interp-exp env) e)]
  5443. ))
  5444. ))
  5445. (define (interp-R3 p)
  5446. (send (new interp-R3-class) interp-program p))
  5447. \end{lstlisting}
  5448. \caption{Interpreter for the $R_3$ language.}
  5449. \label{fig:interp-R3}
  5450. \end{figure}
  5451. Figure~\ref{fig:type-check-R3} shows the type checker for $R_3$, which
  5452. deserves some explanation. When allocating a vector, we need to know
  5453. which elements of the vector are pointers (i.e. are also vectors). We
  5454. can obtain this information during type checking. The type checker in
  5455. Figure~\ref{fig:type-check-R3} not only computes the type of an
  5456. expression, it also wraps every \key{vector} creation with the form
  5457. $(\key{HasType}~e~T)$, where $T$ is the vector's type.
  5458. %
  5459. To create the s-expression for the \code{Vector} type in
  5460. Figure~\ref{fig:type-check-R3}, we use the
  5461. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  5462. operator} \code{,@} to insert the list \code{t*} without its usual
  5463. start and end parentheses. \index{unquote-slicing}
  5464. \begin{figure}[tp]
  5465. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5466. (define type-check-R3-class
  5467. (class type-check-R2-class
  5468. (super-new)
  5469. (inherit check-type-equal?)
  5470. (define/override (type-check-exp env)
  5471. (lambda (e)
  5472. (define recur (type-check-exp env))
  5473. (match e
  5474. [(Void) (values (Void) 'Void)]
  5475. [(Prim 'vector es)
  5476. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  5477. (define t `(Vector ,@t*))
  5478. (values (HasType (Prim 'vector e*) t) t)]
  5479. [(Prim 'vector-ref (list e1 (Int i)))
  5480. (define-values (e1^ t) (recur e1))
  5481. (match t
  5482. [`(Vector ,ts ...)
  5483. (unless (and (0 . <= . i) (i . < . (length ts)))
  5484. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  5485. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  5486. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  5487. [(Prim 'vector-set! (list e1 (Int i) arg) )
  5488. (define-values (e-vec t-vec) (recur e1))
  5489. (define-values (e-arg^ t-arg) (recur arg))
  5490. (match t-vec
  5491. [`(Vector ,ts ...)
  5492. (unless (and (0 . <= . i) (i . < . (length ts)))
  5493. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  5494. (check-type-equal? (list-ref ts i) t-arg e)
  5495. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  5496. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  5497. [(Prim 'vector-length (list e))
  5498. (define-values (e^ t) (recur e))
  5499. (match t
  5500. [`(Vector ,ts ...)
  5501. (values (Prim 'vector-length (list e^)) 'Integer)]
  5502. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  5503. [(Prim 'eq? (list arg1 arg2))
  5504. (define-values (e1 t1) (recur arg1))
  5505. (define-values (e2 t2) (recur arg2))
  5506. (match* (t1 t2)
  5507. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  5508. [(other wise) (check-type-equal? t1 t2 e)])
  5509. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  5510. [(HasType (Prim 'vector es) t)
  5511. ((type-check-exp env) (Prim 'vector es))]
  5512. [(HasType e1 t)
  5513. (define-values (e1^ t^) (recur e1))
  5514. (check-type-equal? t t^ e)
  5515. (values (HasType e1^ t) t)]
  5516. [else ((super type-check-exp env) e)]
  5517. )))
  5518. ))
  5519. (define (type-check-R3 p)
  5520. (send (new type-check-R3-class) type-check-program p))
  5521. \end{lstlisting}
  5522. \caption{Type checker for the $R_3$ language.}
  5523. \label{fig:type-check-R3}
  5524. \end{figure}
  5525. \section{Garbage Collection}
  5526. \label{sec:GC}
  5527. Here we study a relatively simple algorithm for garbage collection
  5528. that is the basis of state-of-the-art garbage
  5529. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  5530. particular, we describe a two-space copying
  5531. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  5532. perform the
  5533. copy~\citep{Cheney:1970aa}.
  5534. \index{copying collector}
  5535. \index{two-space copying collector}
  5536. Figure~\ref{fig:copying-collector} gives a
  5537. coarse-grained depiction of what happens in a two-space collector,
  5538. showing two time steps, prior to garbage collection (on the top) and
  5539. after garbage collection (on the bottom). In a two-space collector,
  5540. the heap is divided into two parts named the FromSpace and the
  5541. ToSpace. Initially, all allocations go to the FromSpace until there is
  5542. not enough room for the next allocation request. At that point, the
  5543. garbage collector goes to work to make more room.
  5544. \index{ToSpace}
  5545. \index{FromSpace}
  5546. The garbage collector must be careful not to reclaim tuples that will
  5547. be used by the program in the future. Of course, it is impossible in
  5548. general to predict what a program will do, but we can over approximate
  5549. the will-be-used tuples by preserving all tuples that could be
  5550. accessed by \emph{any} program given the current computer state. A
  5551. program could access any tuple whose address is in a register or on
  5552. the procedure call stack. These addresses are called the \emph{root
  5553. set}\index{root set}. In addition, a program could access any tuple that is
  5554. transitively reachable from the root set. Thus, it is safe for the
  5555. garbage collector to reclaim the tuples that are not reachable in this
  5556. way.
  5557. So the goal of the garbage collector is twofold:
  5558. \begin{enumerate}
  5559. \item preserve all tuple that are reachable from the root set via a
  5560. path of pointers, that is, the \emph{live} tuples, and
  5561. \item reclaim the memory of everything else, that is, the
  5562. \emph{garbage}.
  5563. \end{enumerate}
  5564. A copying collector accomplishes this by copying all of the live
  5565. objects from the FromSpace into the ToSpace and then performs a slight
  5566. of hand, treating the ToSpace as the new FromSpace and the old
  5567. FromSpace as the new ToSpace. In the example of
  5568. Figure~\ref{fig:copying-collector}, there are three pointers in the
  5569. root set, one in a register and two on the stack. All of the live
  5570. objects have been copied to the ToSpace (the right-hand side of
  5571. Figure~\ref{fig:copying-collector}) in a way that preserves the
  5572. pointer relationships. For example, the pointer in the register still
  5573. points to a 2-tuple whose first element is a 3-tuple and whose second
  5574. element is a 2-tuple. There are four tuples that are not reachable
  5575. from the root set and therefore do not get copied into the ToSpace.
  5576. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  5577. created by a well-typed program in $R_3$ because it contains a
  5578. cycle. However, creating cycles will be possible once we get to $R_6$.
  5579. We design the garbage collector to deal with cycles to begin with so
  5580. we will not need to revisit this issue.
  5581. \begin{figure}[tbp]
  5582. \centering
  5583. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  5584. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  5585. \caption{A copying collector in action.}
  5586. \label{fig:copying-collector}
  5587. \end{figure}
  5588. There are many alternatives to copying collectors (and their bigger
  5589. siblings, the generational collectors) when its comes to garbage
  5590. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  5591. reference counting~\citep{Collins:1960aa}. The strengths of copying
  5592. collectors are that allocation is fast (just a comparison and pointer
  5593. increment), there is no fragmentation, cyclic garbage is collected,
  5594. and the time complexity of collection only depends on the amount of
  5595. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  5596. main disadvantages of a two-space copying collector is that it uses a
  5597. lot of space and takes a long time to perform the copy, though these
  5598. problems are ameliorated in generational collectors. Racket and
  5599. Scheme programs tend to allocate many small objects and generate a lot
  5600. of garbage, so copying and generational collectors are a good fit.
  5601. Garbage collection is an active research topic, especially concurrent
  5602. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  5603. developing new techniques and revisiting old
  5604. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  5605. meet every year at the International Symposium on Memory Management to
  5606. present these findings.
  5607. \subsection{Graph Copying via Cheney's Algorithm}
  5608. \label{sec:cheney}
  5609. \index{Cheney's algorithm}
  5610. Let us take a closer look at the copying of the live objects. The
  5611. allocated objects and pointers can be viewed as a graph and we need to
  5612. copy the part of the graph that is reachable from the root set. To
  5613. make sure we copy all of the reachable vertices in the graph, we need
  5614. an exhaustive graph traversal algorithm, such as depth-first search or
  5615. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  5616. such algorithms take into account the possibility of cycles by marking
  5617. which vertices have already been visited, so as to ensure termination
  5618. of the algorithm. These search algorithms also use a data structure
  5619. such as a stack or queue as a to-do list to keep track of the vertices
  5620. that need to be visited. We use breadth-first search and a trick
  5621. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  5622. and copying tuples into the ToSpace.
  5623. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  5624. copy progresses. The queue is represented by a chunk of contiguous
  5625. memory at the beginning of the ToSpace, using two pointers to track
  5626. the front and the back of the queue. The algorithm starts by copying
  5627. all tuples that are immediately reachable from the root set into the
  5628. ToSpace to form the initial queue. When we copy a tuple, we mark the
  5629. old tuple to indicate that it has been visited. We discuss how this
  5630. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  5631. pointers inside the copied tuples in the queue still point back to the
  5632. FromSpace. Once the initial queue has been created, the algorithm
  5633. enters a loop in which it repeatedly processes the tuple at the front
  5634. of the queue and pops it off the queue. To process a tuple, the
  5635. algorithm copies all the tuple that are directly reachable from it to
  5636. the ToSpace, placing them at the back of the queue. The algorithm then
  5637. updates the pointers in the popped tuple so they point to the newly
  5638. copied tuples.
  5639. \begin{figure}[tbp]
  5640. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  5641. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  5642. \label{fig:cheney}
  5643. \end{figure}
  5644. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  5645. tuple whose second element is $42$ to the back of the queue. The other
  5646. pointer goes to a tuple that has already been copied, so we do not
  5647. need to copy it again, but we do need to update the pointer to the new
  5648. location. This can be accomplished by storing a \emph{forwarding
  5649. pointer} to the new location in the old tuple, back when we initially
  5650. copied the tuple into the ToSpace. This completes one step of the
  5651. algorithm. The algorithm continues in this way until the front of the
  5652. queue is empty, that is, until the front catches up with the back.
  5653. \subsection{Data Representation}
  5654. \label{sec:data-rep-gc}
  5655. The garbage collector places some requirements on the data
  5656. representations used by our compiler. First, the garbage collector
  5657. needs to distinguish between pointers and other kinds of data. There
  5658. are several ways to accomplish this.
  5659. \begin{enumerate}
  5660. \item Attached a tag to each object that identifies what type of
  5661. object it is~\citep{McCarthy:1960dz}.
  5662. \item Store different types of objects in different
  5663. regions~\citep{Steele:1977ab}.
  5664. \item Use type information from the program to either generate
  5665. type-specific code for collecting or to generate tables that can
  5666. guide the
  5667. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  5668. \end{enumerate}
  5669. Dynamically typed languages, such as Lisp, need to tag objects
  5670. anyways, so option 1 is a natural choice for those languages.
  5671. However, $R_3$ is a statically typed language, so it would be
  5672. unfortunate to require tags on every object, especially small and
  5673. pervasive objects like integers and Booleans. Option 3 is the
  5674. best-performing choice for statically typed languages, but comes with
  5675. a relatively high implementation complexity. To keep this chapter
  5676. within a 2-week time budget, we recommend a combination of options 1
  5677. and 2, using separate strategies for the stack and the heap.
  5678. Regarding the stack, we recommend using a separate stack for pointers,
  5679. which we call a \emph{root stack}\index{root stack} (a.k.a. ``shadow
  5680. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  5681. is, when a local variable needs to be spilled and is of type
  5682. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  5683. stack instead of the normal procedure call stack. Furthermore, we
  5684. always spill vector-typed variables if they are live during a call to
  5685. the collector, thereby ensuring that no pointers are in registers
  5686. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  5687. example from Figure~\ref{fig:copying-collector} and contrasts it with
  5688. the data layout using a root stack. The root stack contains the two
  5689. pointers from the regular stack and also the pointer in the second
  5690. register.
  5691. \begin{figure}[tbp]
  5692. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  5693. \caption{Maintaining a root stack to facilitate garbage collection.}
  5694. \label{fig:shadow-stack}
  5695. \end{figure}
  5696. The problem of distinguishing between pointers and other kinds of data
  5697. also arises inside of each tuple on the heap. We solve this problem by
  5698. attaching a tag, an extra 64-bits, to each
  5699. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  5700. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  5701. that we have drawn the bits in a big-endian way, from right-to-left,
  5702. with bit location 0 (the least significant bit) on the far right,
  5703. which corresponds to the direction of the x86 shifting instructions
  5704. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  5705. is dedicated to specifying which elements of the tuple are pointers,
  5706. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  5707. indicates there is a pointer and a 0 bit indicates some other kind of
  5708. data. The pointer mask starts at bit location 7. We have limited
  5709. tuples to a maximum size of 50 elements, so we just need 50 bits for
  5710. the pointer mask. The tag also contains two other pieces of
  5711. information. The length of the tuple (number of elements) is stored in
  5712. bits location 1 through 6. Finally, the bit at location 0 indicates
  5713. whether the tuple has yet to be copied to the ToSpace. If the bit has
  5714. value 1, then this tuple has not yet been copied. If the bit has
  5715. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  5716. of a pointer are always zero anyways because our tuples are 8-byte
  5717. aligned.)
  5718. \begin{figure}[tbp]
  5719. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  5720. \caption{Representation of tuples in the heap.}
  5721. \label{fig:tuple-rep}
  5722. \end{figure}
  5723. \subsection{Implementation of the Garbage Collector}
  5724. \label{sec:organize-gz}
  5725. \index{prelude}
  5726. An implementation of the copying collector is provided in the
  5727. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  5728. interface to the garbage collector that is used by the compiler. The
  5729. \code{initialize} function creates the FromSpace, ToSpace, and root
  5730. stack and should be called in the prelude of the \code{main}
  5731. function. The arguments of \code{initialize} are the root stack size
  5732. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  5733. good choice for both. The \code{initialize} function puts the address
  5734. of the beginning of the FromSpace into the global variable
  5735. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  5736. the address that is 1-past the last element of the FromSpace. (We use
  5737. half-open intervals to represent chunks of
  5738. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  5739. points to the first element of the root stack.
  5740. As long as there is room left in the FromSpace, your generated code
  5741. can allocate tuples simply by moving the \code{free\_ptr} forward.
  5742. %
  5743. The amount of room left in FromSpace is the difference between the
  5744. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  5745. function should be called when there is not enough room left in the
  5746. FromSpace for the next allocation. The \code{collect} function takes
  5747. a pointer to the current top of the root stack (one past the last item
  5748. that was pushed) and the number of bytes that need to be
  5749. allocated. The \code{collect} function performs the copying collection
  5750. and leaves the heap in a state such that the next allocation will
  5751. succeed.
  5752. \begin{figure}[tbp]
  5753. \begin{lstlisting}
  5754. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  5755. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  5756. int64_t* free_ptr;
  5757. int64_t* fromspace_begin;
  5758. int64_t* fromspace_end;
  5759. int64_t** rootstack_begin;
  5760. \end{lstlisting}
  5761. \caption{The compiler's interface to the garbage collector.}
  5762. \label{fig:gc-header}
  5763. \end{figure}
  5764. %% \begin{exercise}
  5765. %% In the file \code{runtime.c} you will find the implementation of
  5766. %% \code{initialize} and a partial implementation of \code{collect}.
  5767. %% The \code{collect} function calls another function, \code{cheney},
  5768. %% to perform the actual copy, and that function is left to the reader
  5769. %% to implement. The following is the prototype for \code{cheney}.
  5770. %% \begin{lstlisting}
  5771. %% static void cheney(int64_t** rootstack_ptr);
  5772. %% \end{lstlisting}
  5773. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  5774. %% rootstack (which is an array of pointers). The \code{cheney} function
  5775. %% also communicates with \code{collect} through the global
  5776. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  5777. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  5778. %% the ToSpace:
  5779. %% \begin{lstlisting}
  5780. %% static int64_t* tospace_begin;
  5781. %% static int64_t* tospace_end;
  5782. %% \end{lstlisting}
  5783. %% The job of the \code{cheney} function is to copy all the live
  5784. %% objects (reachable from the root stack) into the ToSpace, update
  5785. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  5786. %% update the root stack so that it points to the objects in the
  5787. %% ToSpace, and finally to swap the global pointers for the FromSpace
  5788. %% and ToSpace.
  5789. %% \end{exercise}
  5790. %% \section{Compiler Passes}
  5791. %% \label{sec:code-generation-gc}
  5792. The introduction of garbage collection has a non-trivial impact on our
  5793. compiler passes. We introduce a new compiler pass named
  5794. \code{expose-allocation}. We make
  5795. significant changes to \code{select-instructions},
  5796. \code{build-interference}, \code{allocate-registers}, and
  5797. \code{print-x86} and make minor changes in several more passes. The
  5798. following program will serve as our running example. It creates two
  5799. tuples, one nested inside the other. Both tuples have length one. The
  5800. program accesses the element in the inner tuple tuple via two vector
  5801. references.
  5802. % tests/s2_17.rkt
  5803. \begin{lstlisting}
  5804. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  5805. \end{lstlisting}
  5806. \section{Shrink}
  5807. \label{sec:shrink-R3}
  5808. Recall that the \code{shrink} pass translates the primitives operators
  5809. into a smaller set of primitives. Because this pass comes after type
  5810. checking, but before the passes that require the type information in
  5811. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  5812. to wrap \code{HasType} around each AST node that it generates.
  5813. \section{Expose Allocation}
  5814. \label{sec:expose-allocation}
  5815. The pass \code{expose-allocation} lowers the \code{vector} creation
  5816. form into a conditional call to the collector followed by the
  5817. allocation. We choose to place the \code{expose-allocation} pass
  5818. before \code{remove-complex-opera*} because the code generated by
  5819. \code{expose-allocation} contains complex operands. We also place
  5820. \code{expose-allocation} before \code{explicate-control} because
  5821. \code{expose-allocation} introduces new variables using \code{let},
  5822. but \code{let} is gone after \code{explicate-control}.
  5823. The output of \code{expose-allocation} is a language $R'_3$ that
  5824. extends $R_3$ with the three new forms that we use in the translation
  5825. of the \code{vector} form.
  5826. \[
  5827. \begin{array}{lcl}
  5828. \Exp &::=& \cdots
  5829. \mid (\key{collect} \,\itm{int})
  5830. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  5831. \mid (\key{global-value} \,\itm{name})
  5832. \end{array}
  5833. \]
  5834. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  5835. $n$ bytes. It will become a call to the \code{collect} function in
  5836. \code{runtime.c} in \code{select-instructions}. The
  5837. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  5838. \index{allocate}
  5839. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  5840. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  5841. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  5842. a global variable, such as \code{free\_ptr}.
  5843. In the following, we show the transformation for the \code{vector}
  5844. form into 1) a sequence of let-bindings for the initializing
  5845. expressions, 2) a conditional call to \code{collect}, 3) a call to
  5846. \code{allocate}, and 4) the initialization of the vector. In the
  5847. following, \itm{len} refers to the length of the vector and
  5848. \itm{bytes} is how many total bytes need to be allocated for the
  5849. vector, which is 8 for the tag plus \itm{len} times 8.
  5850. \begin{lstlisting}
  5851. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  5852. |$\Longrightarrow$|
  5853. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  5854. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  5855. (global-value fromspace_end))
  5856. (void)
  5857. (collect |\itm{bytes}|))])
  5858. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  5859. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  5860. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  5861. |$v$|) ... )))) ...)
  5862. \end{lstlisting}
  5863. In the above, we suppressed all of the \code{has-type} forms in the
  5864. output for the sake of readability. The placement of the initializing
  5865. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  5866. sequence of \code{vector-set!} is important, as those expressions may
  5867. trigger garbage collection and we cannot have an allocated but
  5868. uninitialized tuple on the heap during a collection.
  5869. Figure~\ref{fig:expose-alloc-output} shows the output of the
  5870. \code{expose-allocation} pass on our running example.
  5871. \begin{figure}[tbp]
  5872. % tests/s2_17.rkt
  5873. \begin{lstlisting}
  5874. (vector-ref
  5875. (vector-ref
  5876. (let ([vecinit7976
  5877. (let ([vecinit7972 42])
  5878. (let ([collectret7974
  5879. (if (< (+ (global-value free_ptr) 16)
  5880. (global-value fromspace_end))
  5881. (void)
  5882. (collect 16)
  5883. )])
  5884. (let ([alloc7971 (allocate 1 (Vector Integer))])
  5885. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  5886. alloc7971)
  5887. )
  5888. )
  5889. )
  5890. ])
  5891. (let ([collectret7978
  5892. (if (< (+ (global-value free_ptr) 16)
  5893. (global-value fromspace_end))
  5894. (void)
  5895. (collect 16)
  5896. )])
  5897. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  5898. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  5899. alloc7975)
  5900. )
  5901. )
  5902. )
  5903. 0)
  5904. 0)
  5905. \end{lstlisting}
  5906. \caption{Output of the \code{expose-allocation} pass, minus
  5907. all of the \code{has-type} forms.}
  5908. \label{fig:expose-alloc-output}
  5909. \end{figure}
  5910. \section{Remove Complex Operands}
  5911. \label{sec:remove-complex-opera-R3}
  5912. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  5913. should all be treated as complex operands.
  5914. %% A new case for
  5915. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  5916. %% handled carefully to prevent the \code{Prim} node from being separated
  5917. %% from its enclosing \code{HasType}.
  5918. Figure~\ref{fig:r3-anf-syntax}
  5919. shows the grammar for the output language $R_3^{\dagger}$ of this
  5920. pass, which is $R_3$ in administrative normal form.
  5921. \begin{figure}[tp]
  5922. \centering
  5923. \fbox{
  5924. \begin{minipage}{0.96\textwidth}
  5925. \small
  5926. \[
  5927. \begin{array}{rcl}
  5928. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }
  5929. \mid \VOID{} \\
  5930. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  5931. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  5932. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  5933. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  5934. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  5935. &\mid& \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  5936. \mid \LP\key{GlobalValue}~\Var\RP\\
  5937. % &\mid& \LP\key{HasType}~\Exp~\Type\RP \\
  5938. R^{\dagger}_3 &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  5939. \end{array}
  5940. \]
  5941. \end{minipage}
  5942. }
  5943. \caption{$R_3^{\dagger}$ is $R_3$ in administrative normal form (ANF).}
  5944. \label{fig:r3-anf-syntax}
  5945. \end{figure}
  5946. \section{Explicate Control and the $C_2$ language}
  5947. \label{sec:explicate-control-r3}
  5948. \begin{figure}[tp]
  5949. \fbox{
  5950. \begin{minipage}{0.96\textwidth}
  5951. \small
  5952. \[
  5953. \begin{array}{lcl}
  5954. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  5955. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5956. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  5957. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  5958. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  5959. &\mid& (\key{Allocate} \,\itm{int}\,\itm{type}) \\
  5960. &\mid& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  5961. &\mid& (\key{Prim}~\key{'vector-set!}\,(\key{list}\,\Atm\,\INT{\Int}\,\Atm))\\
  5962. &\mid& (\key{GlobalValue} \,\Var) \mid (\key{Void})\\
  5963. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  5964. \mid (\key{Collect} \,\itm{int}) \\
  5965. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  5966. \mid \GOTO{\itm{label}} } \\
  5967. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  5968. C_2 & ::= & \gray{ \PROGRAM{\itm{info}}{\CFG{(\itm{label}\,\key{.}\,\Tail)\ldots}} }
  5969. \end{array}
  5970. \]
  5971. \end{minipage}
  5972. }
  5973. \caption{The abstract syntax of $C_2$, extending $C_1$
  5974. (Figure~\ref{fig:c1-syntax}).}
  5975. \label{fig:c2-syntax}
  5976. \end{figure}
  5977. The output of \code{explicate-control} is a program in the
  5978. intermediate language $C_2$, whose abstract syntax is defined in
  5979. Figure~\ref{fig:c2-syntax}. (The concrete syntax is defined in
  5980. Figure~\ref{fig:c2-concrete-syntax} of the Appendix.) The new forms
  5981. of $C_2$ include the \key{allocate}, \key{vector-ref}, and
  5982. \key{vector-set!}, and \key{global-value} expressions and the
  5983. \code{collect} statement. The \code{explicate-control} pass can treat
  5984. these new forms much like the other expression forms that we've
  5985. already encoutered.
  5986. \section{Select Instructions and the x86$_2$ Language}
  5987. \label{sec:select-instructions-gc}
  5988. \index{instruction selection}
  5989. %% void (rep as zero)
  5990. %% allocate
  5991. %% collect (callq collect)
  5992. %% vector-ref
  5993. %% vector-set!
  5994. %% global (postpone)
  5995. In this pass we generate x86 code for most of the new operations that
  5996. were needed to compile tuples, including \code{Allocate},
  5997. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  5998. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  5999. the later has a different concrete syntax (see
  6000. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  6001. \index{x86}
  6002. The \code{vector-ref} and \code{vector-set!} forms translate into
  6003. \code{movq} instructions. (The plus one in the offset is to get past
  6004. the tag at the beginning of the tuple representation.)
  6005. \begin{lstlisting}
  6006. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  6007. |$\Longrightarrow$|
  6008. movq |$\itm{vec}'$|, %r11
  6009. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  6010. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  6011. |$\Longrightarrow$|
  6012. movq |$\itm{vec}'$|, %r11
  6013. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  6014. movq $0, |$\itm{lhs'}$|
  6015. \end{lstlisting}
  6016. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  6017. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  6018. register \code{r11} ensures that offset expression
  6019. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  6020. removing \code{r11} from consideration by the register allocating.
  6021. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  6022. \code{rax}. Then the generated code for \code{vector-set!} would be
  6023. \begin{lstlisting}
  6024. movq |$\itm{vec}'$|, %rax
  6025. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  6026. movq $0, |$\itm{lhs}'$|
  6027. \end{lstlisting}
  6028. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  6029. \code{patch-instructions} would insert a move through \code{rax}
  6030. as follows.
  6031. \begin{lstlisting}
  6032. movq |$\itm{vec}'$|, %rax
  6033. movq |$\itm{arg}'$|, %rax
  6034. movq %rax, |$8(n+1)$|(%rax)
  6035. movq $0, |$\itm{lhs}'$|
  6036. \end{lstlisting}
  6037. But the above sequence of instructions does not work because we're
  6038. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  6039. $\itm{arg}'$) at the same time!
  6040. We compile the \code{allocate} form to operations on the
  6041. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  6042. is the next free address in the FromSpace, so we copy it into
  6043. \code{r11} and then move it forward by enough space for the tuple
  6044. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  6045. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  6046. initialize the \itm{tag} and finally copy the address in \code{r11} to
  6047. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  6048. tag is organized. We recommend using the Racket operations
  6049. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  6050. during compilation. The type annotation in the \code{vector} form is
  6051. used to determine the pointer mask region of the tag.
  6052. \begin{lstlisting}
  6053. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  6054. |$\Longrightarrow$|
  6055. movq free_ptr(%rip), %r11
  6056. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  6057. movq $|$\itm{tag}$|, 0(%r11)
  6058. movq %r11, |$\itm{lhs}'$|
  6059. \end{lstlisting}
  6060. The \code{collect} form is compiled to a call to the \code{collect}
  6061. function in the runtime. The arguments to \code{collect} are 1) the
  6062. top of the root stack and 2) the number of bytes that need to be
  6063. allocated. We use another dedicated register, \code{r15}, to
  6064. store the pointer to the top of the root stack. So \code{r15} is not
  6065. available for use by the register allocator.
  6066. \begin{lstlisting}
  6067. (collect |$\itm{bytes}$|)
  6068. |$\Longrightarrow$|
  6069. movq %r15, %rdi
  6070. movq $|\itm{bytes}|, %rsi
  6071. callq collect
  6072. \end{lstlisting}
  6073. \begin{figure}[tp]
  6074. \fbox{
  6075. \begin{minipage}{0.96\textwidth}
  6076. \[
  6077. \begin{array}{lcl}
  6078. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)} \\
  6079. x86_1 &::= & \gray{ \key{.globl main} }\\
  6080. & & \gray{ \key{main:} \; \Instr\ldots }
  6081. \end{array}
  6082. \]
  6083. \end{minipage}
  6084. }
  6085. \caption{The concrete syntax of x86$_2$ (extends x86$_1$ of Figure~\ref{fig:x86-1-concrete}).}
  6086. \label{fig:x86-2-concrete}
  6087. \end{figure}
  6088. \begin{figure}[tp]
  6089. \fbox{
  6090. \begin{minipage}{0.96\textwidth}
  6091. \small
  6092. \[
  6093. \begin{array}{lcl}
  6094. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  6095. \mid \BYTEREG{\Reg}} \\
  6096. &\mid& (\key{Global}~\Var) \\
  6097. x86_2 &::= & \gray{ \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}} }
  6098. \end{array}
  6099. \]
  6100. \end{minipage}
  6101. }
  6102. \caption{The abstract syntax of x86$_2$ (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  6103. \label{fig:x86-2}
  6104. \end{figure}
  6105. The concrete and abstract syntax of the $x86_2$ language is defined in
  6106. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It differs from
  6107. x86$_1$ just in the addition of the form for global variables.
  6108. %
  6109. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  6110. \code{select-instructions} pass on the running example.
  6111. \begin{figure}[tbp]
  6112. \centering
  6113. % tests/s2_17.rkt
  6114. \begin{minipage}[t]{0.5\textwidth}
  6115. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6116. block35:
  6117. movq free_ptr(%rip), alloc9024
  6118. addq $16, free_ptr(%rip)
  6119. movq alloc9024, %r11
  6120. movq $131, 0(%r11)
  6121. movq alloc9024, %r11
  6122. movq vecinit9025, 8(%r11)
  6123. movq $0, initret9026
  6124. movq alloc9024, %r11
  6125. movq 8(%r11), tmp9034
  6126. movq tmp9034, %r11
  6127. movq 8(%r11), %rax
  6128. jmp conclusion
  6129. block36:
  6130. movq $0, collectret9027
  6131. jmp block35
  6132. block38:
  6133. movq free_ptr(%rip), alloc9020
  6134. addq $16, free_ptr(%rip)
  6135. movq alloc9020, %r11
  6136. movq $3, 0(%r11)
  6137. movq alloc9020, %r11
  6138. movq vecinit9021, 8(%r11)
  6139. movq $0, initret9022
  6140. movq alloc9020, vecinit9025
  6141. movq free_ptr(%rip), tmp9031
  6142. movq tmp9031, tmp9032
  6143. addq $16, tmp9032
  6144. movq fromspace_end(%rip), tmp9033
  6145. cmpq tmp9033, tmp9032
  6146. jl block36
  6147. jmp block37
  6148. block37:
  6149. movq %r15, %rdi
  6150. movq $16, %rsi
  6151. callq 'collect
  6152. jmp block35
  6153. block39:
  6154. movq $0, collectret9023
  6155. jmp block38
  6156. \end{lstlisting}
  6157. \end{minipage}
  6158. \begin{minipage}[t]{0.45\textwidth}
  6159. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6160. start:
  6161. movq $42, vecinit9021
  6162. movq free_ptr(%rip), tmp9028
  6163. movq tmp9028, tmp9029
  6164. addq $16, tmp9029
  6165. movq fromspace_end(%rip), tmp9030
  6166. cmpq tmp9030, tmp9029
  6167. jl block39
  6168. jmp block40
  6169. block40:
  6170. movq %r15, %rdi
  6171. movq $16, %rsi
  6172. callq 'collect
  6173. jmp block38
  6174. \end{lstlisting}
  6175. \end{minipage}
  6176. \caption{Output of the \code{select-instructions} pass.}
  6177. \label{fig:select-instr-output-gc}
  6178. \end{figure}
  6179. \clearpage
  6180. \section{Register Allocation}
  6181. \label{sec:reg-alloc-gc}
  6182. \index{register allocation}
  6183. As discussed earlier in this chapter, the garbage collector needs to
  6184. access all the pointers in the root set, that is, all variables that
  6185. are vectors. It will be the responsibility of the register allocator
  6186. to make sure that:
  6187. \begin{enumerate}
  6188. \item the root stack is used for spilling vector-typed variables, and
  6189. \item if a vector-typed variable is live during a call to the
  6190. collector, it must be spilled to ensure it is visible to the
  6191. collector.
  6192. \end{enumerate}
  6193. The later responsibility can be handled during construction of the
  6194. interference graph, by adding interference edges between the call-live
  6195. vector-typed variables and all the callee-saved registers. (They
  6196. already interfere with the caller-saved registers.) The type
  6197. information for variables is in the \code{Program} form, so we
  6198. recommend adding another parameter to the \code{build-interference}
  6199. function to communicate this alist.
  6200. The spilling of vector-typed variables to the root stack can be
  6201. handled after graph coloring, when choosing how to assign the colors
  6202. (integers) to registers and stack locations. The \code{Program} output
  6203. of this pass changes to also record the number of spills to the root
  6204. stack.
  6205. % build-interference
  6206. %
  6207. % callq
  6208. % extra parameter for var->type assoc. list
  6209. % update 'program' and 'if'
  6210. % allocate-registers
  6211. % allocate spilled vectors to the rootstack
  6212. % don't change color-graph
  6213. \section{Print x86}
  6214. \label{sec:print-x86-gc}
  6215. \index{prelude}\index{conclusion}
  6216. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  6217. \code{print-x86} pass on the running example. In the prelude and
  6218. conclusion of the \code{main} function, we treat the root stack very
  6219. much like the regular stack in that we move the root stack pointer
  6220. (\code{r15}) to make room for the spills to the root stack, except
  6221. that the root stack grows up instead of down. For the running
  6222. example, there was just one spill so we increment \code{r15} by 8
  6223. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  6224. One issue that deserves special care is that there may be a call to
  6225. \code{collect} prior to the initializing assignments for all the
  6226. variables in the root stack. We do not want the garbage collector to
  6227. accidentally think that some uninitialized variable is a pointer that
  6228. needs to be followed. Thus, we zero-out all locations on the root
  6229. stack in the prelude of \code{main}. In
  6230. Figure~\ref{fig:print-x86-output-gc}, the instruction
  6231. %
  6232. \lstinline{movq $0, (%r15)}
  6233. %
  6234. accomplishes this task. The garbage collector tests each root to see
  6235. if it is null prior to dereferencing it.
  6236. \begin{figure}[htbp]
  6237. \begin{minipage}[t]{0.5\textwidth}
  6238. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6239. block35:
  6240. movq free_ptr(%rip), %rcx
  6241. addq $16, free_ptr(%rip)
  6242. movq %rcx, %r11
  6243. movq $131, 0(%r11)
  6244. movq %rcx, %r11
  6245. movq -8(%r15), %rax
  6246. movq %rax, 8(%r11)
  6247. movq $0, %rdx
  6248. movq %rcx, %r11
  6249. movq 8(%r11), %rcx
  6250. movq %rcx, %r11
  6251. movq 8(%r11), %rax
  6252. jmp conclusion
  6253. block36:
  6254. movq $0, %rcx
  6255. jmp block35
  6256. block38:
  6257. movq free_ptr(%rip), %rcx
  6258. addq $16, free_ptr(%rip)
  6259. movq %rcx, %r11
  6260. movq $3, 0(%r11)
  6261. movq %rcx, %r11
  6262. movq %rbx, 8(%r11)
  6263. movq $0, %rdx
  6264. movq %rcx, -8(%r15)
  6265. movq free_ptr(%rip), %rcx
  6266. addq $16, %rcx
  6267. movq fromspace_end(%rip), %rdx
  6268. cmpq %rdx, %rcx
  6269. jl block36
  6270. movq %r15, %rdi
  6271. movq $16, %rsi
  6272. callq collect
  6273. jmp block35
  6274. block39:
  6275. movq $0, %rcx
  6276. jmp block38
  6277. \end{lstlisting}
  6278. \end{minipage}
  6279. \begin{minipage}[t]{0.45\textwidth}
  6280. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6281. start:
  6282. movq $42, %rbx
  6283. movq free_ptr(%rip), %rdx
  6284. addq $16, %rdx
  6285. movq fromspace_end(%rip), %rcx
  6286. cmpq %rcx, %rdx
  6287. jl block39
  6288. movq %r15, %rdi
  6289. movq $16, %rsi
  6290. callq collect
  6291. jmp block38
  6292. .globl main
  6293. main:
  6294. pushq %rbp
  6295. movq %rsp, %rbp
  6296. pushq %r13
  6297. pushq %r12
  6298. pushq %rbx
  6299. pushq %r14
  6300. subq $0, %rsp
  6301. movq $16384, %rdi
  6302. movq $16384, %rsi
  6303. callq initialize
  6304. movq rootstack_begin(%rip), %r15
  6305. movq $0, (%r15)
  6306. addq $8, %r15
  6307. jmp start
  6308. conclusion:
  6309. subq $8, %r15
  6310. addq $0, %rsp
  6311. popq %r14
  6312. popq %rbx
  6313. popq %r12
  6314. popq %r13
  6315. popq %rbp
  6316. retq
  6317. \end{lstlisting}
  6318. \end{minipage}
  6319. \caption{Output of the \code{print-x86} pass.}
  6320. \label{fig:print-x86-output-gc}
  6321. \end{figure}
  6322. \begin{figure}[p]
  6323. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6324. \node (R3) at (0,2) {\large $R_3$};
  6325. \node (R3-2) at (3,2) {\large $R_3$};
  6326. \node (R3-3) at (6,2) {\large $R_3$};
  6327. \node (R3-4) at (9,2) {\large $R_3$};
  6328. \node (R3-5) at (12,2) {\large $R'_3$};
  6329. \node (C2-4) at (3,0) {\large $C_2$};
  6330. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_2$};
  6331. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_2$};
  6332. \node (x86-4) at (9,-2) {\large $\text{x86}^{*}_2$};
  6333. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}_2$};
  6334. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}_2$};
  6335. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}_2$};
  6336. %\path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize type-check} (R3-2);
  6337. \path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize shrink} (R3-2);
  6338. \path[->,bend left=15] (R3-2) edge [above] node {\ttfamily\footnotesize uniquify} (R3-3);
  6339. \path[->,bend left=15] (R3-3) edge [above] node {\ttfamily\footnotesize expose-alloc.} (R3-4);
  6340. \path[->,bend left=15] (R3-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (R3-5);
  6341. \path[->,bend left=20] (R3-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-4);
  6342. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select-instr.} (x86-2);
  6343. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6344. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  6345. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6346. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  6347. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  6348. \end{tikzpicture}
  6349. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  6350. \label{fig:R3-passes}
  6351. \end{figure}
  6352. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  6353. for the compilation of $R_3$.
  6354. \section{Challenge: Simple Structures}
  6355. \label{sec:simple-structures}
  6356. \index{struct}
  6357. \index{structure}
  6358. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  6359. $R^s_3$, which extends $R^3$ with support for simple structures.
  6360. Recall that a \code{struct} in Typed Racket is a user-defined data
  6361. type that contains named fields and that is heap allocated, similar to
  6362. a vector. The following is an example of a structure definition, in
  6363. this case the definition of a \code{point} type.
  6364. \begin{lstlisting}
  6365. (struct point ([x : Integer] [y : Integer]) #:mutable)
  6366. \end{lstlisting}
  6367. \begin{figure}[tbp]
  6368. \centering
  6369. \fbox{
  6370. \begin{minipage}{0.96\textwidth}
  6371. \[
  6372. \begin{array}{lcl}
  6373. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6374. \mid (\key{Vector}\;\Type \ldots) \mid \key{Void} } \mid \Var \\
  6375. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6376. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  6377. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  6378. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6379. \mid (\key{and}\;\Exp\;\Exp)
  6380. \mid (\key{or}\;\Exp\;\Exp)
  6381. \mid (\key{not}\;\Exp) } \\
  6382. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  6383. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  6384. &\mid& \gray{ (\key{vector}\;\Exp \ldots)
  6385. \mid (\key{vector-ref}\;\Exp\;\Int) } \\
  6386. &\mid& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  6387. &\mid& \gray{ (\key{void}) } \mid (\Var\;\Exp \ldots)\\
  6388. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  6389. R_3 &::=& \Def \ldots \; \Exp
  6390. \end{array}
  6391. \]
  6392. \end{minipage}
  6393. }
  6394. \caption{The concrete syntax of $R^s_3$, extending $R_3$
  6395. (Figure~\ref{fig:r3-concrete-syntax}).}
  6396. \label{fig:r3s-concrete-syntax}
  6397. \end{figure}
  6398. An instance of a structure is created using function call syntax, with
  6399. the name of the structure in the function position:
  6400. \begin{lstlisting}
  6401. (point 7 12)
  6402. \end{lstlisting}
  6403. Function-call syntax is also used to read the value in a field of a
  6404. structure. The function name is formed by the structure name, a dash,
  6405. and the field name. The following example uses \code{point-x} and
  6406. \code{point-y} to access the \code{x} and \code{y} fields of two point
  6407. instances.
  6408. \begin{center}
  6409. \begin{lstlisting}
  6410. (let ([pt1 (point 7 12)])
  6411. (let ([pt2 (point 4 3)])
  6412. (+ (- (point-x pt1) (point-x pt2))
  6413. (- (point-y pt1) (point-y pt2)))))
  6414. \end{lstlisting}
  6415. \end{center}
  6416. Similarly, to write to a field of a structure, use its set function,
  6417. whose name starts with \code{set-}, followed by the structure name,
  6418. then a dash, then the field name, and concluded with an exclamation
  6419. mark. The following example uses \code{set-point-x!} to change the
  6420. \code{x} field from \code{7} to \code{42}.
  6421. \begin{center}
  6422. \begin{lstlisting}
  6423. (let ([pt (point 7 12)])
  6424. (let ([_ (set-point-x! pt 42)])
  6425. (point-x pt)))
  6426. \end{lstlisting}
  6427. \end{center}
  6428. \begin{exercise}\normalfont
  6429. Extend your compiler with support for simple structures, compiling
  6430. $R^s_3$ to x86 assembly code. Create five new test cases that use
  6431. structures and test your compiler.
  6432. \end{exercise}
  6433. \section{Challenge: Generational Collection}
  6434. The copying collector described in Section~\ref{sec:GC} can incur
  6435. significant runtime overhead because the call to \code{collect} takes
  6436. time proportional to all of the live data. One way to reduce this
  6437. overhead is to reduce how much data is inspected in each call to
  6438. \code{collect}. In particular, researchers have observed that recently
  6439. allocated data is more likely to become garbage then data that has
  6440. survived one or more previous calls to \code{collect}. This insight
  6441. motivated the creation of \emph{generational garbage collectors}
  6442. \index{generational garbage collector} that
  6443. 1) segregates data according to its age into two or more generations,
  6444. 2) allocates less space for younger generations, so collecting them is
  6445. faster, and more space for the older generations, and 3) performs
  6446. collection on the younger generations more frequently then for older
  6447. generations~\citep{Wilson:1992fk}.
  6448. For this challenge assignment, the goal is to adapt the copying
  6449. collector implemented in \code{runtime.c} to use two generations, one
  6450. for young data and one for old data. Each generation consists of a
  6451. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  6452. \code{collect} function to use the two generations.
  6453. \begin{enumerate}
  6454. \item Copy the young generation's FromSpace to its ToSpace then switch
  6455. the role of the ToSpace and FromSpace
  6456. \item If there is enough space for the requested number of bytes in
  6457. the young FromSpace, then return from \code{collect}.
  6458. \item If there is not enough space in the young FromSpace for the
  6459. requested bytes, then move the data from the young generation to the
  6460. old one with the following steps:
  6461. \begin{enumerate}
  6462. \item If there is enough room in the old FromSpace, copy the young
  6463. FromSpace to the old FromSpace and then return.
  6464. \item If there is not enough room in the old FromSpace, then collect
  6465. the old generation by copying the old FromSpace to the old ToSpace
  6466. and swap the roles of the old FromSpace and ToSpace.
  6467. \item If there is enough room now, copy the young FromSpace to the
  6468. old FromSpace and return. Otherwise, allocate a larger FromSpace
  6469. and ToSpace for the old generation. Copy the young FromSpace and
  6470. the old FromSpace into the larger FromSpace for the old
  6471. generation and then return.
  6472. \end{enumerate}
  6473. \end{enumerate}
  6474. We recommend that you generalize the \code{cheney} function so that it
  6475. can be used for all the copies mentioned above: between the young
  6476. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  6477. between the young FromSpace and old FromSpace. This can be
  6478. accomplished by adding parameters to \code{cheney} that replace its
  6479. use of the global variables \code{fromspace\_begin},
  6480. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  6481. Note that the collection of the young generation does not traverse the
  6482. old generation. This introduces a potential problem: there may be
  6483. young data that is only reachable through pointers in the old
  6484. generation. If these pointers are not taken into account, the
  6485. collector could throw away young data that is live! One solution,
  6486. called \emph{pointer recording}, is to maintain a set of all the
  6487. pointers from the old generation into the new generation and consider
  6488. this set as part of the root set. To maintain this set, the compiler
  6489. must insert extra instructions around every \code{vector-set!}. If the
  6490. vector being modified is in the old generation, and if the value being
  6491. written is a pointer into the new generation, than that pointer must
  6492. be added to the set. Also, if the value being overwritten was a
  6493. pointer into the new generation, then that pointer should be removed
  6494. from the set.
  6495. \begin{exercise}\normalfont
  6496. Adapt the \code{collect} function in \code{runtime.c} to implement
  6497. generational garbage collection, as outlined in this section.
  6498. Update the code generation for \code{vector-set!} to implement
  6499. pointer recording. Make sure that your new compiler and runtime
  6500. passes your test suite.
  6501. \end{exercise}
  6502. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6503. \chapter{Functions}
  6504. \label{ch:functions}
  6505. \index{function}
  6506. This chapter studies the compilation of functions similar to those
  6507. found in the C language. This corresponds to a subset of Typed Racket
  6508. in which only top-level function definitions are allowed. This kind of
  6509. function is an important stepping stone to implementing
  6510. lexically-scoped functions, that is, \key{lambda} abstractions, which
  6511. is the topic of Chapter~\ref{ch:lambdas}.
  6512. \section{The $R_4$ Language}
  6513. The concrete and abstract syntax for function definitions and function
  6514. application is shown in Figures~\ref{fig:r4-concrete-syntax} and
  6515. \ref{fig:r4-syntax}, where we define the $R_4$ language. Programs in
  6516. $R_4$ begin with zero or more function definitions. The function
  6517. names from these definitions are in-scope for the entire program,
  6518. including all other function definitions (so the ordering of function
  6519. definitions does not matter). The concrete syntax for function
  6520. application\index{function application} is $(\Exp \; \Exp \ldots)$
  6521. where the first expression must
  6522. evaluate to a function and the rest are the arguments.
  6523. The abstract syntax for function application is
  6524. $\APPLY{\Exp}{\Exp\ldots}$.
  6525. %% The syntax for function application does not include an explicit
  6526. %% keyword, which is error prone when using \code{match}. To alleviate
  6527. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  6528. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  6529. Functions are first-class in the sense that a function pointer
  6530. \index{function pointer} is data and can be stored in memory or passed
  6531. as a parameter to another function. Thus, we introduce a function
  6532. type, written
  6533. \begin{lstlisting}
  6534. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  6535. \end{lstlisting}
  6536. for a function whose $n$ parameters have the types $\Type_1$ through
  6537. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  6538. these functions (with respect to Racket functions) is that they are
  6539. not lexically scoped. That is, the only external entities that can be
  6540. referenced from inside a function body are other globally-defined
  6541. functions. The syntax of $R_4$ prevents functions from being nested
  6542. inside each other.
  6543. \begin{figure}[tp]
  6544. \centering
  6545. \fbox{
  6546. \begin{minipage}{0.96\textwidth}
  6547. \small
  6548. \[
  6549. \begin{array}{lcl}
  6550. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  6551. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void} } \mid (\Type \ldots \; \key{->}\; \Type) \\
  6552. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6553. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  6554. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  6555. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6556. \mid (\key{and}\;\Exp\;\Exp)
  6557. \mid (\key{or}\;\Exp\;\Exp)
  6558. \mid (\key{not}\;\Exp)} \\
  6559. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  6560. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  6561. (\key{vector-ref}\;\Exp\;\Int)} \\
  6562. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  6563. \mid \LP\key{has-type}~\Exp~\Type\RP } \\
  6564. &\mid& \LP\Exp \; \Exp \ldots\RP \\
  6565. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  6566. R_4 &::=& \Def \ldots \; \Exp
  6567. \end{array}
  6568. \]
  6569. \end{minipage}
  6570. }
  6571. \caption{The concrete syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-concrete-syntax}).}
  6572. \label{fig:r4-concrete-syntax}
  6573. \end{figure}
  6574. \begin{figure}[tp]
  6575. \centering
  6576. \fbox{
  6577. \begin{minipage}{0.96\textwidth}
  6578. \small
  6579. \[
  6580. \begin{array}{lcl}
  6581. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6582. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  6583. &\mid& \gray{ \BOOL{\itm{bool}}
  6584. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6585. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP }
  6586. \mid \APPLY{\Exp}{\Exp\ldots}\\
  6587. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}\\
  6588. R_4 &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  6589. \end{array}
  6590. \]
  6591. \end{minipage}
  6592. }
  6593. \caption{The abstract syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-syntax}).}
  6594. \label{fig:r4-syntax}
  6595. \end{figure}
  6596. The program in Figure~\ref{fig:r4-function-example} is a
  6597. representative example of defining and using functions in $R_4$. We
  6598. define a function \code{map-vec} that applies some other function
  6599. \code{f} to both elements of a vector and returns a new
  6600. vector containing the results. We also define a function \code{add1}.
  6601. The program applies
  6602. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  6603. \code{(vector 1 42)}, from which we return the \code{42}.
  6604. \begin{figure}[tbp]
  6605. \begin{lstlisting}
  6606. (define (map-vec [f : (Integer -> Integer)]
  6607. [v : (Vector Integer Integer)])
  6608. : (Vector Integer Integer)
  6609. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  6610. (define (add1 [x : Integer]) : Integer
  6611. (+ x 1))
  6612. (vector-ref (map-vec add1 (vector 0 41)) 1)
  6613. \end{lstlisting}
  6614. \caption{Example of using functions in $R_4$.}
  6615. \label{fig:r4-function-example}
  6616. \end{figure}
  6617. The definitional interpreter for $R_4$ is in
  6618. Figure~\ref{fig:interp-R4}. The case for the \code{ProgramDefsExp} form is
  6619. responsible for setting up the mutual recursion between the top-level
  6620. function definitions. We use the classic back-patching \index{back-patching}
  6621. approach that uses mutable variables and makes two passes over the function
  6622. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  6623. top-level environment using a mutable cons cell for each function
  6624. definition. Note that the \code{lambda} value for each function is
  6625. incomplete; it does not yet include the environment. Once the
  6626. top-level environment is constructed, we then iterate over it and
  6627. update the \code{lambda} values to use the top-level environment.
  6628. \begin{figure}[tp]
  6629. \begin{lstlisting}
  6630. (define interp-R4-class
  6631. (class interp-R3-class
  6632. (super-new)
  6633. (define/override ((interp-exp env) e)
  6634. (define recur (interp-exp env))
  6635. (match e
  6636. [(Var x) (unbox (dict-ref env x))]
  6637. [(Let x e body)
  6638. (define new-env (dict-set env x (box (recur e))))
  6639. ((interp-exp new-env) body)]
  6640. [(Apply fun args)
  6641. (define fun-val (recur fun))
  6642. (define arg-vals (for/list ([e args]) (recur e)))
  6643. (match fun-val
  6644. [`(function (,xs ...) ,body ,fun-env)
  6645. (define params-args (for/list ([x xs] [arg arg-vals])
  6646. (cons x (box arg))))
  6647. (define new-env (append params-args fun-env))
  6648. ((interp-exp new-env) body)]
  6649. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  6650. [else ((super interp-exp env) e)]
  6651. ))
  6652. (define/public (interp-def d)
  6653. (match d
  6654. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  6655. (cons f (box `(function ,xs ,body ())))]))
  6656. (define/override (interp-program p)
  6657. (match p
  6658. [(ProgramDefsExp info ds body)
  6659. (let ([top-level (for/list ([d ds]) (interp-def d))])
  6660. (for/list ([f (in-dict-values top-level)])
  6661. (set-box! f (match (unbox f)
  6662. [`(function ,xs ,body ())
  6663. `(function ,xs ,body ,top-level)])))
  6664. ((interp-exp top-level) body))]))
  6665. ))
  6666. (define (interp-R4 p)
  6667. (send (new interp-R4-class) interp-program p))
  6668. \end{lstlisting}
  6669. \caption{Interpreter for the $R_4$ language.}
  6670. \label{fig:interp-R4}
  6671. \end{figure}
  6672. \margincomment{TODO: explain type checker}
  6673. The type checker for $R_4$ is is in Figure~\ref{fig:type-check-R4}.
  6674. \begin{figure}[tp]
  6675. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6676. (define type-check-R4-class
  6677. (class type-check-R3-class
  6678. (super-new)
  6679. (inherit check-type-equal?)
  6680. (define/public (type-check-apply env e es)
  6681. (define-values (e^ ty) ((type-check-exp env) e))
  6682. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  6683. ((type-check-exp env) e)))
  6684. (match ty
  6685. [`(,ty^* ... -> ,rt)
  6686. (for ([arg-ty ty*] [param-ty ty^*])
  6687. (check-type-equal? arg-ty param-ty (Apply e es)))
  6688. (values e^ e* rt)]))
  6689. (define/override (type-check-exp env)
  6690. (lambda (e)
  6691. (match e
  6692. [(FunRef f)
  6693. (values (FunRef f) (dict-ref env f))]
  6694. [(Apply e es)
  6695. (define-values (e^ es^ rt) (type-check-apply env e es))
  6696. (values (Apply e^ es^) rt)]
  6697. [(Call e es)
  6698. (define-values (e^ es^ rt) (type-check-apply env e es))
  6699. (values (Call e^ es^) rt)]
  6700. [else ((super type-check-exp env) e)])))
  6701. (define/public (type-check-def env)
  6702. (lambda (e)
  6703. (match e
  6704. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  6705. (define new-env (append (map cons xs ps) env))
  6706. (define-values (body^ ty^) ((type-check-exp new-env) body))
  6707. (check-type-equal? ty^ rt body)
  6708. (Def f p:t* rt info body^)])))
  6709. (define/public (fun-def-type d)
  6710. (match d
  6711. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  6712. (define/override (type-check-program e)
  6713. (match e
  6714. [(ProgramDefsExp info ds body)
  6715. (define new-env (for/list ([d ds])
  6716. (cons (Def-name d) (fun-def-type d))))
  6717. (define ds^ (for/list ([d ds]) ((type-check-def new-env) d)))
  6718. (define-values (body^ ty) ((type-check-exp new-env) body))
  6719. (check-type-equal? ty 'Integer body)
  6720. (ProgramDefsExp info ds^ body^)]))))
  6721. (define (type-check-R4 p)
  6722. (send (new type-check-R4-class) type-check-program p))
  6723. \end{lstlisting}
  6724. \caption{Type checker for the $R_4$ language.}
  6725. \label{fig:type-check-R4}
  6726. \end{figure}
  6727. \section{Functions in x86}
  6728. \label{sec:fun-x86}
  6729. \margincomment{\tiny Make sure callee-saved registers are discussed
  6730. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  6731. \margincomment{\tiny Talk about the return address on the
  6732. stack and what callq and retq does.\\ --Jeremy }
  6733. The x86 architecture provides a few features to support the
  6734. implementation of functions. We have already seen that x86 provides
  6735. labels so that one can refer to the location of an instruction, as is
  6736. needed for jump instructions. Labels can also be used to mark the
  6737. beginning of the instructions for a function. Going further, we can
  6738. obtain the address of a label by using the \key{leaq} instruction and
  6739. PC-relative addressing. For example, the following puts the
  6740. address of the \code{add1} label into the \code{rbx} register.
  6741. \begin{lstlisting}
  6742. leaq add1(%rip), %rbx
  6743. \end{lstlisting}
  6744. The instruction pointer register \key{rip} (aka. the program counter
  6745. \index{program counter}) always points to the next instruction to be
  6746. executed. When combined with an label, as in \code{add1(\%rip)}, the
  6747. linker computes the distance $d$ between the address of \code{add1}
  6748. and where the \code{rip} would be at that moment and then changes
  6749. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  6750. the address of \code{add1}.
  6751. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  6752. jump to a function whose location is given by a label. To support
  6753. function calls in this chapter we instead will be jumping to a
  6754. function whose location is given by an address in a register, that is,
  6755. we need to make an \emph{indirect function call}. The x86 syntax for
  6756. this is a \code{callq} instruction but with an asterisk before the
  6757. register name.\index{indirect function call}
  6758. \begin{lstlisting}
  6759. callq *%rbx
  6760. \end{lstlisting}
  6761. \subsection{Calling Conventions}
  6762. \index{calling conventions}
  6763. The \code{callq} instruction provides partial support for implementing
  6764. functions: it pushes the return address on the stack and it jumps to
  6765. the target. However, \code{callq} does not handle
  6766. \begin{enumerate}
  6767. \item parameter passing,
  6768. \item pushing frames on the procedure call stack and popping them off,
  6769. or
  6770. \item determining how registers are shared by different functions.
  6771. \end{enumerate}
  6772. Regarding (1) parameter passing, recall that the following six
  6773. registers are used to pass arguments to a function, in this order.
  6774. \begin{lstlisting}
  6775. rdi rsi rdx rcx r8 r9
  6776. \end{lstlisting}
  6777. If there are
  6778. more than six arguments, then the convention is to use space on the
  6779. frame of the caller for the rest of the arguments. However, to ease
  6780. the implementation of efficient tail calls
  6781. (Section~\ref{sec:tail-call}), we arrange to never need more than six
  6782. arguments.
  6783. %
  6784. Also recall that the register \code{rax} is for the return value of
  6785. the function.
  6786. \index{prelude}\index{conclusion}
  6787. Regarding (2) frames \index{frame} and the procedure call stack,
  6788. \index{procedure call stack} recall from Section~\ref{sec:x86} that
  6789. the stack grows down, with each function call using a chunk of space
  6790. called a frame. The caller sets the stack pointer, register
  6791. \code{rsp}, to the last data item in its frame. The callee must not
  6792. change anything in the caller's frame, that is, anything that is at or
  6793. above the stack pointer. The callee is free to use locations that are
  6794. below the stack pointer.
  6795. Recall that we are storing variables of vector type on the root stack.
  6796. So the prelude needs to move the root stack pointer \code{r15} up and
  6797. the conclusion needs to move the root stack pointer back down. Also,
  6798. the prelude must initialize to \code{0} this frame's slots in the root
  6799. stack to signal to the garbage collector that those slots do not yet
  6800. contain a pointer to a vector. Otherwise the garbage collector will
  6801. interpret the garbage bits in those slots as memory addresses and try
  6802. to traverse them, causing serious mayhem!
  6803. Regarding (3) the sharing of registers between different functions,
  6804. recall from Section~\ref{sec:calling-conventions} that the registers
  6805. are divided into two groups, the caller-saved registers and the
  6806. callee-saved registers. The caller should assume that all the
  6807. caller-saved registers get overwritten with arbitrary values by the
  6808. callee. That is why we recommend in
  6809. Section~\ref{sec:calling-conventions} that variables that are live
  6810. during a function call should not be assigned to caller-saved
  6811. registers.
  6812. On the flip side, if the callee wants to use a callee-saved register,
  6813. the callee must save the contents of those registers on their stack
  6814. frame and then put them back prior to returning to the caller. That
  6815. is why we recommended in Section~\ref{sec:calling-conventions} that if
  6816. the register allocator assigns a variable to a callee-saved register,
  6817. then the prelude of the \code{main} function must save that register
  6818. to the stack and the conclusion of \code{main} must restore it. This
  6819. recommendation now generalizes to all functions.
  6820. Also recall that the base pointer, register \code{rbp}, is used as a
  6821. point-of-reference within a frame, so that each local variable can be
  6822. accessed at a fixed offset from the base pointer
  6823. (Section~\ref{sec:x86}).
  6824. %
  6825. Figure~\ref{fig:call-frames} shows the general layout of the caller
  6826. and callee frames.
  6827. \begin{figure}[tbp]
  6828. \centering
  6829. \begin{tabular}{r|r|l|l} \hline
  6830. Caller View & Callee View & Contents & Frame \\ \hline
  6831. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  6832. 0(\key{\%rbp}) & & old \key{rbp} \\
  6833. -8(\key{\%rbp}) & & callee-saved $1$ \\
  6834. \ldots & & \ldots \\
  6835. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  6836. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  6837. \ldots & & \ldots \\
  6838. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  6839. %% & & \\
  6840. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  6841. %% & \ldots & \ldots \\
  6842. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  6843. \hline
  6844. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  6845. & 0(\key{\%rbp}) & old \key{rbp} \\
  6846. & -8(\key{\%rbp}) & callee-saved $1$ \\
  6847. & \ldots & \ldots \\
  6848. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  6849. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  6850. & \ldots & \ldots \\
  6851. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  6852. \end{tabular}
  6853. \caption{Memory layout of caller and callee frames.}
  6854. \label{fig:call-frames}
  6855. \end{figure}
  6856. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  6857. %% local variables and for storing the values of callee-saved registers
  6858. %% (we shall refer to all of these collectively as ``locals''), and that
  6859. %% at the beginning of a function we move the stack pointer \code{rsp}
  6860. %% down to make room for them.
  6861. %% We recommend storing the local variables
  6862. %% first and then the callee-saved registers, so that the local variables
  6863. %% can be accessed using \code{rbp} the same as before the addition of
  6864. %% functions.
  6865. %% To make additional room for passing arguments, we shall
  6866. %% move the stack pointer even further down. We count how many stack
  6867. %% arguments are needed for each function call that occurs inside the
  6868. %% body of the function and find their maximum. Adding this number to the
  6869. %% number of locals gives us how much the \code{rsp} should be moved at
  6870. %% the beginning of the function. In preparation for a function call, we
  6871. %% offset from \code{rsp} to set up the stack arguments. We put the first
  6872. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  6873. %% so on.
  6874. %% Upon calling the function, the stack arguments are retrieved by the
  6875. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  6876. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  6877. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  6878. %% the layout of the caller and callee frames. Notice how important it is
  6879. %% that we correctly compute the maximum number of arguments needed for
  6880. %% function calls; if that number is too small then the arguments and
  6881. %% local variables will smash into each other!
  6882. \subsection{Efficient Tail Calls}
  6883. \label{sec:tail-call}
  6884. In general, the amount of stack space used by a program is determined
  6885. by the longest chain of nested function calls. That is, if function
  6886. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  6887. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  6888. $n$ can grow quite large in the case of recursive or mutually
  6889. recursive functions. However, in some cases we can arrange to use only
  6890. constant space, i.e. $O(1)$, instead of $O(n)$.
  6891. If a function call is the last action in a function body, then that
  6892. call is said to be a \emph{tail call}\index{tail call}.
  6893. For example, in the following
  6894. program, the recursive call to \code{tail-sum} is a tail call.
  6895. \begin{center}
  6896. \begin{lstlisting}
  6897. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  6898. (if (eq? n 0)
  6899. r
  6900. (tail-sum (- n 1) (+ n r))))
  6901. (+ (tail-sum 5 0) 27)
  6902. \end{lstlisting}
  6903. \end{center}
  6904. At a tail call, the frame of the caller is no longer needed, so we
  6905. can pop the caller's frame before making the tail call. With this
  6906. approach, a recursive function that only makes tail calls will only
  6907. use $O(1)$ stack space. Functional languages like Racket typically
  6908. rely heavily on recursive functions, so they typically guarantee that
  6909. all tail calls will be optimized in this way.
  6910. \index{frame}
  6911. However, some care is needed with regards to argument passing in tail
  6912. calls. As mentioned above, for arguments beyond the sixth, the
  6913. convention is to use space in the caller's frame for passing
  6914. arguments. But for a tail call we pop the caller's frame and can no
  6915. longer use it. Another alternative is to use space in the callee's
  6916. frame for passing arguments. However, this option is also problematic
  6917. because the caller and callee's frame overlap in memory. As we begin
  6918. to copy the arguments from their sources in the caller's frame, the
  6919. target locations in the callee's frame might overlap with the sources
  6920. for later arguments! We solve this problem by not using the stack for
  6921. passing more than six arguments but instead using the heap, as we
  6922. describe in the Section~\ref{sec:limit-functions-r4}.
  6923. As mentioned above, for a tail call we pop the caller's frame prior to
  6924. making the tail call. The instructions for popping a frame are the
  6925. instructions that we usually place in the conclusion of a
  6926. function. Thus, we also need to place such code immediately before
  6927. each tail call. These instructions include restoring the callee-saved
  6928. registers, so it is good that the argument passing registers are all
  6929. caller-saved registers.
  6930. One last note regarding which instruction to use to make the tail
  6931. call. When the callee is finished, it should not return to the current
  6932. function, but it should return to the function that called the current
  6933. one. Thus, the return address that is already on the stack is the
  6934. right one, and we should not use \key{callq} to make the tail call, as
  6935. that would unnecessarily overwrite the return address. Instead we can
  6936. simply use the \key{jmp} instruction. Like the indirect function call,
  6937. we write an \emph{indirect jump}\index{indirect jump} with a register
  6938. prefixed with an asterisk. We recommend using \code{rax} to hold the
  6939. jump target because the preceding conclusion overwrites just about
  6940. everything else.
  6941. \begin{lstlisting}
  6942. jmp *%rax
  6943. \end{lstlisting}
  6944. \section{Shrink $R_4$}
  6945. \label{sec:shrink-r4}
  6946. The \code{shrink} pass performs a minor modification to ease the
  6947. later passes. This pass introduces an explicit \code{main} function
  6948. and changes the top \code{ProgramDefsExp} form to
  6949. \code{ProgramDefs} as follows.
  6950. \begin{lstlisting}
  6951. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  6952. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  6953. \end{lstlisting}
  6954. where $\itm{mainDef}$ is
  6955. \begin{lstlisting}
  6956. (Def 'main '() 'Integer '() |$\Exp'$|)
  6957. \end{lstlisting}
  6958. \section{Reveal Functions and the $F_1$ language}
  6959. \label{sec:reveal-functions-r4}
  6960. The syntax of $R_4$ is inconvenient for purposes of compilation in one
  6961. respect: it conflates the use of function names and local
  6962. variables. This is a problem because we need to compile the use of a
  6963. function name differently than the use of a local variable; we need to
  6964. use \code{leaq} to convert the function name (a label in x86) to an
  6965. address in a register. Thus, it is a good idea to create a new pass
  6966. that changes function references from just a symbol $f$ to
  6967. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  6968. output language, $F_1$, is defined in Figure~\ref{fig:f1-syntax}.
  6969. The concrete syntax for a function reference is $\CFUNREF{f}$.
  6970. \begin{figure}[tp]
  6971. \centering
  6972. \fbox{
  6973. \begin{minipage}{0.96\textwidth}
  6974. \[
  6975. \begin{array}{lcl}
  6976. \Exp &::=& \ldots \mid \FUNREF{\Var}\\
  6977. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  6978. F_1 &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  6979. \end{array}
  6980. \]
  6981. \end{minipage}
  6982. }
  6983. \caption{The abstract syntax $F_1$, an extension of $R_4$
  6984. (Figure~\ref{fig:r4-syntax}).}
  6985. \label{fig:f1-syntax}
  6986. \end{figure}
  6987. % TODO: rename $F_1$ to $R'_4$
  6988. %% Distinguishing between calls in tail position and non-tail position
  6989. %% requires the pass to have some notion of context. We recommend using
  6990. %% two mutually recursive functions, one for processing expressions in
  6991. %% tail position and another for the rest.
  6992. Placing this pass after \code{uniquify} will make sure that there are
  6993. no local variables and functions that share the same name. On the
  6994. other hand, \code{reveal-functions} needs to come before the
  6995. \code{explicate-control} pass because that pass helps us compile
  6996. \code{FunRef} forms into assignment statements.
  6997. \section{Limit Functions}
  6998. \label{sec:limit-functions-r4}
  6999. Recall that we wish to limit the number of function parameters to six
  7000. so that we do not need to use the stack for argument passing, which
  7001. makes it easier to implement efficient tail calls. However, because
  7002. the input language $R_4$ supports arbitrary numbers of function
  7003. arguments, we have some work to do!
  7004. This pass transforms functions and function calls that involve more
  7005. than six arguments to pass the first five arguments as usual, but it
  7006. packs the rest of the arguments into a vector and passes it as the
  7007. sixth argument.
  7008. Each function definition with too many parameters is transformed as
  7009. follows.
  7010. \begin{lstlisting}
  7011. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  7012. |$\Rightarrow$|
  7013. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  7014. \end{lstlisting}
  7015. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  7016. the occurrences of the later parameters with vector references.
  7017. \begin{lstlisting}
  7018. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  7019. \end{lstlisting}
  7020. For function calls with too many arguments, the \code{limit-functions}
  7021. pass transforms them in the following way.
  7022. \begin{tabular}{lll}
  7023. \begin{minipage}{0.2\textwidth}
  7024. \begin{lstlisting}
  7025. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  7026. \end{lstlisting}
  7027. \end{minipage}
  7028. &
  7029. $\Rightarrow$
  7030. &
  7031. \begin{minipage}{0.4\textwidth}
  7032. \begin{lstlisting}
  7033. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  7034. \end{lstlisting}
  7035. \end{minipage}
  7036. \end{tabular}
  7037. \section{Remove Complex Operands}
  7038. \label{sec:rco-r4}
  7039. The primary decisions to make for this pass is whether to classify
  7040. \code{FunRef} and \code{Apply} as either atomic or complex
  7041. expressions. Recall that a simple expression will eventually end up as
  7042. just an immediate argument of an x86 instruction. Function
  7043. application will be translated to a sequence of instructions, so
  7044. \code{Apply} must be classified as complex expression.
  7045. On the other hand, the arguments of \code{Apply} should be
  7046. atomic expressions.
  7047. %
  7048. Regarding \code{FunRef}, as discussed above, the function label needs
  7049. to be converted to an address using the \code{leaq} instruction. Thus,
  7050. even though \code{FunRef} seems rather simple, it needs to be
  7051. classified as a complex expression so that we generate an assignment
  7052. statement with a left-hand side that can serve as the target of the
  7053. \code{leaq}. Figure~\ref{fig:r4-anf-syntax} defines the
  7054. output language $R_4^{\dagger}$ of this pass.
  7055. \begin{figure}[tp]
  7056. \centering
  7057. \fbox{
  7058. \begin{minipage}{0.96\textwidth}
  7059. \small
  7060. \[
  7061. \begin{array}{rcl}
  7062. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  7063. \mid \VOID{} } \\
  7064. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  7065. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  7066. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  7067. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  7068. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  7069. &\mid& \gray{ \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  7070. \mid \LP\key{GlobalValue}~\Var\RP }\\
  7071. &\mid& \FUNREF{\Var} \mid \APPLY{\Atm}{\Atm\ldots}\\
  7072. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7073. R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  7074. \end{array}
  7075. \]
  7076. \end{minipage}
  7077. }
  7078. \caption{$R_4^{\dagger}$ is $R_4$ in administrative normal form (ANF).}
  7079. \label{fig:r4-anf-syntax}
  7080. \end{figure}
  7081. \section{Explicate Control and the $C_3$ language}
  7082. \label{sec:explicate-control-r4}
  7083. Figure~\ref{fig:c3-syntax} defines the abstract syntax for $C_3$, the
  7084. output of \key{explicate-control}. (The concrete syntax is given in
  7085. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.) The auxiliary
  7086. functions for assignment and tail contexts should be updated with
  7087. cases for \code{Apply} and \code{FunRef} and the function for
  7088. predicate context should be updated for \code{Apply} but not
  7089. \code{FunRef}. (A \code{FunRef} can't be a Boolean.) In assignment
  7090. and predicate contexts, \code{Apply} becomes \code{Call}, whereas in
  7091. tail position \code{Apply} becomes \code{TailCall}. We recommend
  7092. defining a new auxiliary function for processing function definitions.
  7093. This code is similar to the case for \code{Program} in $R_3$. The
  7094. top-level \code{explicate-control} function that handles the
  7095. \code{ProgramDefs} form of $R_4$ can then apply this new function to
  7096. all the function definitions.
  7097. \begin{figure}[tp]
  7098. \fbox{
  7099. \begin{minipage}{0.96\textwidth}
  7100. \small
  7101. \[
  7102. \begin{array}{lcl}
  7103. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  7104. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  7105. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  7106. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  7107. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  7108. &\mid& \gray{ \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP } \\
  7109. &\mid& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  7110. &\mid& \gray{ \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP }\\
  7111. &\mid& \gray{ \LP\key{GlobalValue} \,\Var\RP \mid \LP\key{Void}\RP }\\
  7112. &\mid& \FUNREF{\itm{label}} \mid \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  7113. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  7114. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  7115. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  7116. \mid \GOTO{\itm{label}} } \\
  7117. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  7118. &\mid& \TAILCALL{\Atm}{\Atm\ldots} \\
  7119. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  7120. C_3 & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  7121. \end{array}
  7122. \]
  7123. \end{minipage}
  7124. }
  7125. \caption{The abstract syntax of $C_3$, extending $C_2$ (Figure~\ref{fig:c2-syntax}).}
  7126. \label{fig:c3-syntax}
  7127. \end{figure}
  7128. \section{Select Instructions and the x86$_3$ Language}
  7129. \label{sec:select-r4}
  7130. \index{instruction selection}
  7131. The output of select instructions is a program in the x86$_3$
  7132. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  7133. \index{x86}
  7134. \begin{figure}[tp]
  7135. \fbox{
  7136. \begin{minipage}{0.96\textwidth}
  7137. \small
  7138. \[
  7139. \begin{array}{lcl}
  7140. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)}
  7141. \mid \LP\key{fun-ref}\; \itm{label}\RP\\
  7142. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  7143. \Instr &::=& \ldots
  7144. \mid \key{callq}\;\key{*}\Arg \mid \key{tailjmp}\;\Arg
  7145. \mid \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  7146. \Block &::= & \Instr\ldots \\
  7147. \Def &::= & \LP\key{define} \; \LP\itm{label}\RP \;\LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\RP\\
  7148. x86_3 &::= & \Def\ldots
  7149. \end{array}
  7150. \]
  7151. \end{minipage}
  7152. }
  7153. \caption{The concrete syntax of x86$_3$ (extends x86$_2$ of Figure~\ref{fig:x86-2-concrete}).}
  7154. \label{fig:x86-3-concrete}
  7155. \end{figure}
  7156. \begin{figure}[tp]
  7157. \fbox{
  7158. \begin{minipage}{0.96\textwidth}
  7159. \small
  7160. \[
  7161. \begin{array}{lcl}
  7162. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  7163. \mid \BYTEREG{\Reg} } \\
  7164. &\mid& \gray{ (\key{Global}~\Var) } \mid \FUNREF{\itm{label}} \\
  7165. \Instr &::=& \ldots \mid \INDCALLQ{\Arg}{\itm{int}}
  7166. \mid \TAILJMP{\Arg}{\itm{int}}\\
  7167. &\mid& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  7168. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  7169. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  7170. x86_3 &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  7171. \end{array}
  7172. \]
  7173. \end{minipage}
  7174. }
  7175. \caption{The abstract syntax of x86$_3$ (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  7176. \label{fig:x86-3}
  7177. \end{figure}
  7178. An assignment of a function reference to a variable becomes a
  7179. load-effective-address instruction as follows: \\
  7180. \begin{tabular}{lcl}
  7181. \begin{minipage}{0.35\textwidth}
  7182. \begin{lstlisting}
  7183. |$\itm{lhs}$| = (fun-ref |$f$|);
  7184. \end{lstlisting}
  7185. \end{minipage}
  7186. &
  7187. $\Rightarrow$\qquad\qquad
  7188. &
  7189. \begin{minipage}{0.3\textwidth}
  7190. \begin{lstlisting}
  7191. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  7192. \end{lstlisting}
  7193. \end{minipage}
  7194. \end{tabular} \\
  7195. Regarding function definitions, we need to remove the parameters and
  7196. instead perform parameter passing using the conventions discussed in
  7197. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  7198. registers. We recommend turning the parameters into local variables
  7199. and generating instructions at the beginning of the function to move
  7200. from the argument passing registers to these local variables.
  7201. \begin{lstlisting}
  7202. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  7203. |$\Rightarrow$|
  7204. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  7205. \end{lstlisting}
  7206. The $G'$ control-flow graph is the same as $G$ except that the
  7207. \code{start} block is modified to add the instructions for moving from
  7208. the argument registers to the parameter variables. So the \code{start}
  7209. block of $G$ shown on the left is changed to the code on the right.
  7210. \begin{center}
  7211. \begin{minipage}{0.3\textwidth}
  7212. \begin{lstlisting}
  7213. start:
  7214. |$\itm{instr}_1$|
  7215. |$\vdots$|
  7216. |$\itm{instr}_n$|
  7217. \end{lstlisting}
  7218. \end{minipage}
  7219. $\Rightarrow$
  7220. \begin{minipage}{0.3\textwidth}
  7221. \begin{lstlisting}
  7222. start:
  7223. movq %rdi, |$x_1$|
  7224. movq %rsi, |$x_2$|
  7225. |$\vdots$|
  7226. |$\itm{instr}_1$|
  7227. |$\vdots$|
  7228. |$\itm{instr}_n$|
  7229. \end{lstlisting}
  7230. \end{minipage}
  7231. \end{center}
  7232. By changing the parameters to local variables, we are giving the
  7233. register allocator control over which registers or stack locations to
  7234. use for them. If you implemented the move-biasing challenge
  7235. (Section~\ref{sec:move-biasing}), the register allocator will try to
  7236. assign the parameter variables to the corresponding argument register,
  7237. in which case the \code{patch-instructions} pass will remove the
  7238. \code{movq} instruction. This happens in the example translation in
  7239. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  7240. the \code{add} function.
  7241. %
  7242. Also, note that the register allocator will perform liveness analysis
  7243. on this sequence of move instructions and build the interference
  7244. graph. So, for example, $x_1$ will be marked as interfering with
  7245. \code{rsi} and that will prevent the assignment of $x_1$ to
  7246. \code{rsi}, which is good, because that would overwrite the argument
  7247. that needs to move into $x_2$.
  7248. Next, consider the compilation of function calls. In the mirror image
  7249. of handling the parameters of function definitions, the arguments need
  7250. to be moved to the argument passing registers. The function call
  7251. itself is performed with an indirect function call. The return value
  7252. from the function is stored in \code{rax}, so it needs to be moved
  7253. into the \itm{lhs}.
  7254. \begin{lstlisting}
  7255. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  7256. |$\Rightarrow$|
  7257. movq |$\itm{arg}_1$|, %rdi
  7258. movq |$\itm{arg}_2$|, %rsi
  7259. |$\vdots$|
  7260. callq *|\itm{fun}|
  7261. movq %rax, |\itm{lhs}|
  7262. \end{lstlisting}
  7263. The \code{IndirectCallq} AST node includes an integer for the arity of
  7264. the function, i.e., the number of parameters. That information is
  7265. useful in the \code{uncover-live} pass for determining which
  7266. argument-passing registers are potentially read during the call.
  7267. For tail calls, the parameter passing is the same as non-tail calls:
  7268. generate instructions to move the arguments into to the argument
  7269. passing registers. After that we need to pop the frame from the
  7270. procedure call stack. However, we do not yet know how big the frame
  7271. is; that gets determined during register allocation. So instead of
  7272. generating those instructions here, we invent a new instruction that
  7273. means ``pop the frame and then do an indirect jump'', which we name
  7274. \code{TailJmp}. The abstract syntax for this instruction includes an
  7275. argument that specifies where to jump and an integer that represents
  7276. the arity of the function being called.
  7277. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  7278. using the label \code{start} for the initial block of a program, and
  7279. in Section~\ref{sec:select-r1} we recommended labeling the conclusion
  7280. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  7281. can be compiled to an assignment to \code{rax} followed by a jump to
  7282. \code{conclusion}. With the addition of function definitions, we will
  7283. have a starting block and conclusion for each function, but their
  7284. labels need to be unique. We recommend prepending the function's name
  7285. to \code{start} and \code{conclusion}, respectively, to obtain unique
  7286. labels. (Alternatively, one could \code{gensym} labels for the start
  7287. and conclusion and store them in the $\itm{info}$ field of the
  7288. function definition.)
  7289. \section{Register Allocation}
  7290. \label{sec:register-allocation-r4}
  7291. \subsection{Liveness Analysis}
  7292. \label{sec:liveness-analysis-r4}
  7293. \index{liveness analysis}
  7294. %% The rest of the passes need only minor modifications to handle the new
  7295. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  7296. %% \code{leaq}.
  7297. The \code{IndirectCallq} instruction should be treated like
  7298. \code{Callq} regarding its written locations $W$, in that they should
  7299. include all the caller-saved registers. Recall that the reason for
  7300. that is to force call-live variables to be assigned to callee-saved
  7301. registers or to be spilled to the stack.
  7302. Regarding the set of read locations $R$ the arity field of
  7303. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  7304. argument-passing registers should be considered as read by those
  7305. instructions.
  7306. \subsection{Build Interference Graph}
  7307. \label{sec:build-interference-r4}
  7308. With the addition of function definitions, we compute an interference
  7309. graph for each function (not just one for the whole program).
  7310. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  7311. spill vector-typed variables that are live during a call to the
  7312. \code{collect}. With the addition of functions to our language, we
  7313. need to revisit this issue. Many functions perform allocation and
  7314. therefore have calls to the collector inside of them. Thus, we should
  7315. not only spill a vector-typed variable when it is live during a call
  7316. to \code{collect}, but we should spill the variable if it is live
  7317. during any function call. Thus, in the \code{build-interference} pass,
  7318. we recommend adding interference edges between call-live vector-typed
  7319. variables and the callee-saved registers (in addition to the usual
  7320. addition of edges between call-live variables and the caller-saved
  7321. registers).
  7322. \subsection{Allocate Registers}
  7323. The primary change to the \code{allocate-registers} pass is adding an
  7324. auxiliary function for handling definitions (the \Def{} non-terminal
  7325. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  7326. logic is the same as described in
  7327. Chapter~\ref{ch:register-allocation-r1}, except now register
  7328. allocation is performed many times, once for each function definition,
  7329. instead of just once for the whole program.
  7330. \section{Patch Instructions}
  7331. In \code{patch-instructions}, you should deal with the x86
  7332. idiosyncrasy that the destination argument of \code{leaq} must be a
  7333. register. Additionally, you should ensure that the argument of
  7334. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  7335. code generation more convenient, because we trample many registers
  7336. before the tail call (as explained in the next section).
  7337. \section{Print x86}
  7338. For the \code{print-x86} pass, the cases for \code{FunRef} and
  7339. \code{IndirectCallq} are straightforward: output their concrete
  7340. syntax.
  7341. \begin{lstlisting}
  7342. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  7343. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  7344. \end{lstlisting}
  7345. The \code{TailJmp} node requires a bit work. A straightforward
  7346. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  7347. before the jump we need to pop the current frame. This sequence of
  7348. instructions is the same as the code for the conclusion of a function,
  7349. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  7350. Regarding function definitions, you will need to generate a prelude
  7351. and conclusion for each one. This code is similar to the prelude and
  7352. conclusion that you generated for the \code{main} function in
  7353. Chapter~\ref{ch:tuples}. To review, the prelude of every function
  7354. should carry out the following steps.
  7355. \begin{enumerate}
  7356. \item Start with \code{.global} and \code{.align} directives followed
  7357. by the label for the function. (See Figure~\ref{fig:add-fun} for an
  7358. example.)
  7359. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  7360. pointer.
  7361. \item Push to the stack all of the callee-saved registers that were
  7362. used for register allocation.
  7363. \item Move the stack pointer \code{rsp} down by the size of the stack
  7364. frame for this function, which depends on the number of regular
  7365. spills. (Aligned to 16 bytes.)
  7366. \item Move the root stack pointer \code{r15} up by the size of the
  7367. root-stack frame for this function, which depends on the number of
  7368. spilled vectors. \label{root-stack-init}
  7369. \item Initialize to zero all of the entries in the root-stack frame.
  7370. \item Jump to the start block.
  7371. \end{enumerate}
  7372. The prelude of the \code{main} function has one additional task: call
  7373. the \code{initialize} function to set up the garbage collector and
  7374. move the value of the global \code{rootstack\_begin} in
  7375. \code{r15}. This should happen before step \ref{root-stack-init}
  7376. above, which depends on \code{r15}.
  7377. The conclusion of every function should do the following.
  7378. \begin{enumerate}
  7379. \item Move the stack pointer back up by the size of the stack frame
  7380. for this function.
  7381. \item Restore the callee-saved registers by popping them from the
  7382. stack.
  7383. \item Move the root stack pointer back down by the size of the
  7384. root-stack frame for this function.
  7385. \item Restore \code{rbp} by popping it from the stack.
  7386. \item Return to the caller with the \code{retq} instruction.
  7387. \end{enumerate}
  7388. \begin{exercise}\normalfont
  7389. Expand your compiler to handle $R_4$ as outlined in this chapter.
  7390. Create 5 new programs that use functions, including examples that pass
  7391. functions and return functions from other functions, recursive
  7392. functions, functions that create vectors, and functions that make tail
  7393. calls. Test your compiler on these new programs and all of your
  7394. previously created test programs.
  7395. \end{exercise}
  7396. \begin{figure}[tbp]
  7397. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7398. \node (R4) at (0,2) {\large $R_4$};
  7399. \node (R4-1) at (3,2) {\large $R_4$};
  7400. \node (R4-2) at (6,2) {\large $R_4$};
  7401. \node (F1-1) at (12,0) {\large $F_1$};
  7402. \node (F1-2) at (9,0) {\large $F_1$};
  7403. \node (F1-3) at (6,0) {\large $F_1$};
  7404. \node (F1-4) at (3,0) {\large $F_1$};
  7405. \node (C3-2) at (3,-2) {\large $C_3$};
  7406. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  7407. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  7408. \node (x86-4) at (9,-4) {\large $\text{x86}_3$};
  7409. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  7410. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  7411. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  7412. \path[->,bend left=15] (R4) edge [above] node
  7413. {\ttfamily\footnotesize shrink} (R4-1);
  7414. \path[->,bend left=15] (R4-1) edge [above] node
  7415. {\ttfamily\footnotesize uniquify} (R4-2);
  7416. \path[->,bend left=15] (R4-2) edge [right] node
  7417. {\ttfamily\footnotesize ~~reveal-functions} (F1-1);
  7418. \path[->,bend left=15] (F1-1) edge [below] node
  7419. {\ttfamily\footnotesize limit-functions} (F1-2);
  7420. \path[->,bend right=15] (F1-2) edge [above] node
  7421. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  7422. \path[->,bend right=15] (F1-3) edge [above] node
  7423. {\ttfamily\footnotesize remove-complex.} (F1-4);
  7424. \path[->,bend left=15] (F1-4) edge [right] node
  7425. {\ttfamily\footnotesize explicate-control} (C3-2);
  7426. \path[->,bend right=15] (C3-2) edge [left] node
  7427. {\ttfamily\footnotesize select-instr.} (x86-2);
  7428. \path[->,bend left=15] (x86-2) edge [left] node
  7429. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  7430. \path[->,bend right=15] (x86-2-1) edge [below] node
  7431. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  7432. \path[->,bend right=15] (x86-2-2) edge [left] node
  7433. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7434. \path[->,bend left=15] (x86-3) edge [above] node
  7435. {\ttfamily\footnotesize patch-instr.} (x86-4);
  7436. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  7437. \end{tikzpicture}
  7438. \caption{Diagram of the passes for $R_4$, a language with functions.}
  7439. \label{fig:R4-passes}
  7440. \end{figure}
  7441. Figure~\ref{fig:R4-passes} gives an overview of the passes for
  7442. compiling $R_4$ to x86.
  7443. \section{An Example Translation}
  7444. \label{sec:functions-example}
  7445. Figure~\ref{fig:add-fun} shows an example translation of a simple
  7446. function in $R_4$ to x86. The figure also includes the results of the
  7447. \code{explicate-control} and \code{select-instructions} passes.
  7448. \begin{figure}[htbp]
  7449. \begin{tabular}{ll}
  7450. \begin{minipage}{0.5\textwidth}
  7451. % s3_2.rkt
  7452. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7453. (define (add [x : Integer] [y : Integer])
  7454. : Integer
  7455. (+ x y))
  7456. (add 40 2)
  7457. \end{lstlisting}
  7458. $\Downarrow$
  7459. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7460. (define (add86 [x87 : Integer]
  7461. [y88 : Integer]) : Integer
  7462. add86start:
  7463. return (+ x87 y88);
  7464. )
  7465. (define (main) : Integer ()
  7466. mainstart:
  7467. tmp89 = (fun-ref add86);
  7468. (tail-call tmp89 40 2)
  7469. )
  7470. \end{lstlisting}
  7471. \end{minipage}
  7472. &
  7473. $\Rightarrow$
  7474. \begin{minipage}{0.5\textwidth}
  7475. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7476. (define (add86) : Integer
  7477. add86start:
  7478. movq %rdi, x87
  7479. movq %rsi, y88
  7480. movq x87, %rax
  7481. addq y88, %rax
  7482. jmp add11389conclusion
  7483. )
  7484. (define (main) : Integer
  7485. mainstart:
  7486. leaq (fun-ref add86), tmp89
  7487. movq $40, %rdi
  7488. movq $2, %rsi
  7489. tail-jmp tmp89
  7490. )
  7491. \end{lstlisting}
  7492. $\Downarrow$
  7493. \end{minipage}
  7494. \end{tabular}
  7495. \begin{tabular}{ll}
  7496. \begin{minipage}{0.3\textwidth}
  7497. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7498. .globl add86
  7499. .align 16
  7500. add86:
  7501. pushq %rbp
  7502. movq %rsp, %rbp
  7503. jmp add86start
  7504. add86start:
  7505. movq %rdi, %rax
  7506. addq %rsi, %rax
  7507. jmp add86conclusion
  7508. add86conclusion:
  7509. popq %rbp
  7510. retq
  7511. \end{lstlisting}
  7512. \end{minipage}
  7513. &
  7514. \begin{minipage}{0.5\textwidth}
  7515. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7516. .globl main
  7517. .align 16
  7518. main:
  7519. pushq %rbp
  7520. movq %rsp, %rbp
  7521. movq $16384, %rdi
  7522. movq $16384, %rsi
  7523. callq initialize
  7524. movq rootstack_begin(%rip), %r15
  7525. jmp mainstart
  7526. mainstart:
  7527. leaq add86(%rip), %rcx
  7528. movq $40, %rdi
  7529. movq $2, %rsi
  7530. movq %rcx, %rax
  7531. popq %rbp
  7532. jmp *%rax
  7533. mainconclusion:
  7534. popq %rbp
  7535. retq
  7536. \end{lstlisting}
  7537. \end{minipage}
  7538. \end{tabular}
  7539. \caption{Example compilation of a simple function to x86.}
  7540. \label{fig:add-fun}
  7541. \end{figure}
  7542. % Challenge idea: inlining! (simple version)
  7543. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7544. \chapter{Lexically Scoped Functions}
  7545. \label{ch:lambdas}
  7546. \index{lambda}
  7547. \index{lexical scoping}
  7548. This chapter studies lexically scoped functions as they appear in
  7549. functional languages such as Racket. By lexical scoping we mean that a
  7550. function's body may refer to variables whose binding site is outside
  7551. of the function, in an enclosing scope.
  7552. %
  7553. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  7554. $R_5$, which extends $R_4$ with anonymous functions using the
  7555. \key{lambda} form. The body of the \key{lambda}, refers to three
  7556. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  7557. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  7558. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  7559. parameter of function \code{f}. The \key{lambda} is returned from the
  7560. function \code{f}. The main expression of the program includes two
  7561. calls to \code{f} with different arguments for \code{x}, first
  7562. \code{5} then \code{3}. The functions returned from \code{f} are bound
  7563. to variables \code{g} and \code{h}. Even though these two functions
  7564. were created by the same \code{lambda}, they are really different
  7565. functions because they use different values for \code{x}. Applying
  7566. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  7567. \code{15} produces \code{22}. The result of this program is \code{42}.
  7568. \begin{figure}[btp]
  7569. % s4_6.rkt
  7570. \begin{lstlisting}
  7571. (define (f [x : Integer]) : (Integer -> Integer)
  7572. (let ([y 4])
  7573. (lambda: ([z : Integer]) : Integer
  7574. (+ x (+ y z)))))
  7575. (let ([g (f 5)])
  7576. (let ([h (f 3)])
  7577. (+ (g 11) (h 15))))
  7578. \end{lstlisting}
  7579. \caption{Example of a lexically scoped function.}
  7580. \label{fig:lexical-scoping}
  7581. \end{figure}
  7582. The approach that we take for implementing lexically scoped
  7583. functions is to compile them into top-level function definitions,
  7584. translating from $R_5$ into $R_4$. However, the compiler will need to
  7585. provide special treatment for variable occurrences such as \code{x}
  7586. and \code{y} in the body of the \code{lambda} of
  7587. Figure~\ref{fig:lexical-scoping}. After all, an $R_4$ function may not
  7588. refer to variables defined outside of it. To identify such variable
  7589. occurrences, we review the standard notion of free variable.
  7590. \begin{definition}
  7591. A variable is \emph{free in expression} $e$ if the variable occurs
  7592. inside $e$ but does not have an enclosing binding in $e$.\index{free
  7593. variable}
  7594. \end{definition}
  7595. For example, in the expression \code{(+ x (+ y z))} the variables
  7596. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  7597. only \code{x} and \code{y} are free in the following expression
  7598. because \code{z} is bound by the \code{lambda}.
  7599. \begin{lstlisting}
  7600. (lambda: ([z : Integer]) : Integer
  7601. (+ x (+ y z)))
  7602. \end{lstlisting}
  7603. So the free variables of a \code{lambda} are the ones that will need
  7604. special treatment. We need to arrange for some way to transport, at
  7605. runtime, the values of those variables from the point where the
  7606. \code{lambda} was created to the point where the \code{lambda} is
  7607. applied. An efficient solution to the problem, due to
  7608. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  7609. free variables together with the function pointer for the lambda's
  7610. code, an arrangement called a \emph{flat closure} (which we shorten to
  7611. just ``closure''). \index{closure}\index{flat closure} Fortunately,
  7612. we have all the ingredients to make closures, Chapter~\ref{ch:tuples}
  7613. gave us vectors and Chapter~\ref{ch:functions} gave us function
  7614. pointers. The function pointer resides at index $0$ and the
  7615. values for the free variables will fill in the rest of the vector.
  7616. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  7617. how closures work. It's a three-step dance. The program first calls
  7618. function \code{f}, which creates a closure for the \code{lambda}. The
  7619. closure is a vector whose first element is a pointer to the top-level
  7620. function that we will generate for the \code{lambda}, the second
  7621. element is the value of \code{x}, which is \code{5}, and the third
  7622. element is \code{4}, the value of \code{y}. The closure does not
  7623. contain an element for \code{z} because \code{z} is not a free
  7624. variable of the \code{lambda}. Creating the closure is step 1 of the
  7625. dance. The closure is returned from \code{f} and bound to \code{g}, as
  7626. shown in Figure~\ref{fig:closures}.
  7627. %
  7628. The second call to \code{f} creates another closure, this time with
  7629. \code{3} in the second slot (for \code{x}). This closure is also
  7630. returned from \code{f} but bound to \code{h}, which is also shown in
  7631. Figure~\ref{fig:closures}.
  7632. \begin{figure}[tbp]
  7633. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  7634. \caption{Example closure representation for the \key{lambda}'s
  7635. in Figure~\ref{fig:lexical-scoping}.}
  7636. \label{fig:closures}
  7637. \end{figure}
  7638. Continuing with the example, consider the application of \code{g} to
  7639. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  7640. obtain the function pointer in the first element of the closure and
  7641. call it, passing in the closure itself and then the regular arguments,
  7642. in this case \code{11}. This technique for applying a closure is step
  7643. 2 of the dance.
  7644. %
  7645. But doesn't this \code{lambda} only take 1 argument, for parameter
  7646. \code{z}? The third and final step of the dance is generating a
  7647. top-level function for a \code{lambda}. We add an additional
  7648. parameter for the closure and we insert a \code{let} at the beginning
  7649. of the function for each free variable, to bind those variables to the
  7650. appropriate elements from the closure parameter.
  7651. %
  7652. This three-step dance is known as \emph{closure conversion}. We
  7653. discuss the details of closure conversion in
  7654. Section~\ref{sec:closure-conversion} and the code generated from the
  7655. example in Section~\ref{sec:example-lambda}. But first we define the
  7656. syntax and semantics of $R_5$ in Section~\ref{sec:r5}.
  7657. \section{The $R_5$ Language}
  7658. \label{sec:r5}
  7659. The concrete and abstract syntax for $R_5$, a language with anonymous
  7660. functions and lexical scoping, is defined in
  7661. Figures~\ref{fig:r5-concrete-syntax} and ~\ref{fig:r5-syntax}. It adds
  7662. the \key{lambda} form to the grammar for $R_4$, which already has
  7663. syntax for function application.
  7664. \begin{figure}[tp]
  7665. \centering
  7666. \fbox{
  7667. \begin{minipage}{0.96\textwidth}
  7668. \small
  7669. \[
  7670. \begin{array}{lcl}
  7671. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7672. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}
  7673. \mid (\Type\ldots \; \key{->}\; \Type)} \\
  7674. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  7675. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  7676. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  7677. &\mid& \gray{\key{\#t} \mid \key{\#f}
  7678. \mid (\key{and}\;\Exp\;\Exp)
  7679. \mid (\key{or}\;\Exp\;\Exp)
  7680. \mid (\key{not}\;\Exp) } \\
  7681. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  7682. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  7683. (\key{vector-ref}\;\Exp\;\Int)} \\
  7684. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  7685. \mid (\Exp \; \Exp\ldots) } \\
  7686. &\mid& \LP \key{procedure-arity}~\Exp\RP \\
  7687. &\mid& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  7688. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  7689. R_5 &::=& \gray{\Def\ldots \; \Exp}
  7690. \end{array}
  7691. \]
  7692. \end{minipage}
  7693. }
  7694. \caption{The concrete syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-concrete-syntax})
  7695. with \key{lambda}.}
  7696. \label{fig:r5-concrete-syntax}
  7697. \end{figure}
  7698. \begin{figure}[tp]
  7699. \centering
  7700. \fbox{
  7701. \begin{minipage}{0.96\textwidth}
  7702. \small
  7703. \[
  7704. \begin{array}{lcl}
  7705. \itm{op} &::=& \ldots \mid \code{procedure-arity} \\
  7706. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  7707. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  7708. &\mid& \gray{ \BOOL{\itm{bool}}
  7709. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  7710. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  7711. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  7712. &\mid& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  7713. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  7714. R_5 &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  7715. \end{array}
  7716. \]
  7717. \end{minipage}
  7718. }
  7719. \caption{The abstract syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax}).}
  7720. \label{fig:r5-syntax}
  7721. \end{figure}
  7722. \index{interpreter}
  7723. \label{sec:interp-R5}
  7724. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  7725. $R_5$. The clause for \key{lambda} saves the current environment
  7726. inside the returned \key{lambda}. Then the clause for \key{Apply} uses
  7727. the environment from the \key{lambda}, the \code{lam-env}, when
  7728. interpreting the body of the \key{lambda}. The \code{lam-env}
  7729. environment is extended with the mapping of parameters to argument
  7730. values.
  7731. \begin{figure}[tbp]
  7732. \begin{lstlisting}
  7733. (define interp-R5-class
  7734. (class interp-R4-class
  7735. (super-new)
  7736. (define/override (interp-op op)
  7737. (match op
  7738. ['procedure-arity
  7739. (lambda (v)
  7740. (match v
  7741. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  7742. [else (error 'interp-op "expected a function, not ~a" v)]))]
  7743. [else (super interp-op op)]))
  7744. (define/override ((interp-exp env) e)
  7745. (define recur (interp-exp env))
  7746. (match e
  7747. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  7748. `(function ,xs ,body ,env)]
  7749. [else ((super interp-exp env) e)]))
  7750. ))
  7751. (define (interp-R5 p)
  7752. (send (new interp-R5-class) interp-program p))
  7753. \end{lstlisting}
  7754. \caption{Interpreter for $R_5$.}
  7755. \label{fig:interp-R5}
  7756. \end{figure}
  7757. \label{sec:type-check-r5}
  7758. \index{type checking}
  7759. Figure~\ref{fig:type-check-R5} shows how to type check the new
  7760. \key{lambda} form. The body of the \key{lambda} is checked in an
  7761. environment that includes the current environment (because it is
  7762. lexically scoped) and also includes the \key{lambda}'s parameters. We
  7763. require the body's type to match the declared return type.
  7764. \begin{figure}[tbp]
  7765. \begin{lstlisting}
  7766. (define (type-check-R5 env)
  7767. (lambda (e)
  7768. (match e
  7769. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  7770. (define-values (new-body bodyT)
  7771. ((type-check-exp (append (map cons xs Ts) env)) body))
  7772. (define ty `(,@Ts -> ,rT))
  7773. (cond
  7774. [(equal? rT bodyT)
  7775. (values (HasType (Lambda params rT new-body) ty) ty)]
  7776. [else
  7777. (error "mismatch in return type" bodyT rT)])]
  7778. ...
  7779. )))
  7780. \end{lstlisting}
  7781. \caption{Type checking the \key{lambda}'s in $R_5$.}
  7782. \label{fig:type-check-R5}
  7783. \end{figure}
  7784. \section{Reveal Functions and the $F_2$ language}
  7785. \label{sec:reveal-functions-r5}
  7786. To support the \code{procedure-arity} operator we need to communicate
  7787. the arity of a function to the point of closure creation. We can
  7788. accomplish this by replacing the $\FUNREF{\Var}$ struct with one that
  7789. has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$. The
  7790. output of this pass is the language $F_2$, whose syntax is defined in
  7791. Figure~\ref{fig:f2-syntax}.
  7792. \begin{figure}[tp]
  7793. \centering
  7794. \fbox{
  7795. \begin{minipage}{0.96\textwidth}
  7796. \[
  7797. \begin{array}{lcl}
  7798. \Exp &::=& \ldots \mid \FUNREFARITY{\Var}{\Int}\\
  7799. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7800. F_2 &::=& \gray{\PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}}
  7801. \end{array}
  7802. \]
  7803. \end{minipage}
  7804. }
  7805. \caption{The abstract syntax $F_2$, an extension of $R_5$
  7806. (Figure~\ref{fig:r5-syntax}).}
  7807. \label{fig:f2-syntax}
  7808. \end{figure}
  7809. \section{Closure Conversion}
  7810. \label{sec:closure-conversion}
  7811. \index{closure conversion}
  7812. The compiling of lexically-scoped functions into top-level function
  7813. definitions is accomplished in the pass \code{convert-to-closures}
  7814. that comes after \code{reveal-functions} and before
  7815. \code{limit-functions}.
  7816. As usual, we implement the pass as a recursive function over the
  7817. AST. All of the action is in the clauses for \key{Lambda} and
  7818. \key{Apply}. We transform a \key{Lambda} expression into an expression
  7819. that creates a closure, that is, a vector whose first element is a
  7820. function pointer and the rest of the elements are the free variables
  7821. of the \key{Lambda}. We use the struct \code{Closure} here instead of
  7822. using \code{vector} so that we can distinguish closures from vectors
  7823. in Section~\ref{sec:optimize-closures} and to record the arity. In
  7824. the generated code below, the \itm{name} is a unique symbol generated
  7825. to identify the function and the \itm{arity} is the number of
  7826. parameters (the length of \itm{ps}).
  7827. \begin{lstlisting}
  7828. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  7829. |$\Rightarrow$|
  7830. (Closure |\itm{arity}| (cons (FunRef |\itm{name}|) |\itm{fvs}|))
  7831. \end{lstlisting}
  7832. In addition to transforming each \key{Lambda} into a \key{Closure}, we
  7833. create a top-level function definition for each \key{Lambda}, as
  7834. shown below.\\
  7835. \begin{minipage}{0.8\textwidth}
  7836. \begin{lstlisting}
  7837. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  7838. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  7839. ...
  7840. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  7841. |\itm{body'}|)...))
  7842. \end{lstlisting}
  7843. \end{minipage}\\
  7844. The \code{clos} parameter refers to the closure. Translate the type
  7845. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  7846. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The types
  7847. $\itm{fvts}$ are the types of the free variables in the lambda and the
  7848. underscore \code{\_} is a dummy type that we use because it is rather
  7849. difficult to give a type to the function in the closure's
  7850. type.\footnote{To give an accurate type to a closure, we would need to
  7851. add existential types to the type checker~\citep{Minamide:1996ys}.}
  7852. The dummy type is considered to be equal to any other type during type
  7853. checking. The sequence of \key{Let} forms bind the free variables to
  7854. their values obtained from the closure.
  7855. Closure conversion turns functions into vectors, so the type
  7856. annotations in the program must also be translated. We recommend
  7857. defining a auxiliary recursive function for this purpose. Function
  7858. types should be translated as follows.
  7859. \begin{lstlisting}
  7860. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  7861. |$\Rightarrow$|
  7862. (Vector ((Vector _) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  7863. \end{lstlisting}
  7864. The above type says that the first thing in the vector is a function
  7865. pointer. The first parameter of the function pointer is a vector (a
  7866. closure) and the rest of the parameters are the ones from the original
  7867. function, with types $T'_1, \ldots, T'_n$. The \code{Vector} type for
  7868. the closure omits the types of the free variables because 1) those
  7869. types are not available in this context and 2) we do not need them in
  7870. the code that is generated for function application.
  7871. We transform function application into code that retrieves the
  7872. function pointer from the closure and then calls the function, passing
  7873. in the closure as the first argument. We bind $e'$ to a temporary
  7874. variable to avoid code duplication.
  7875. \begin{lstlisting}
  7876. (Apply |$e$| |\itm{es}|)
  7877. |$\Rightarrow$|
  7878. (Let |\itm{tmp}| |$e'$|
  7879. (Apply (Prim 'vector-ref (list (Var |\itm{tmp}|) (Int 0))) (cons |\itm{tmp}| |\itm{es'}|)))
  7880. \end{lstlisting}
  7881. There is also the question of what to do with references top-level
  7882. function definitions. To maintain a uniform translation of function
  7883. application, we turn function references into closures.
  7884. \begin{tabular}{lll}
  7885. \begin{minipage}{0.3\textwidth}
  7886. \begin{lstlisting}
  7887. (FunRefArity |$f$| |$n$|)
  7888. \end{lstlisting}
  7889. \end{minipage}
  7890. &
  7891. $\Rightarrow$
  7892. &
  7893. \begin{minipage}{0.5\textwidth}
  7894. \begin{lstlisting}
  7895. (Closure |$n$| (FunRef |$f$|) '())
  7896. \end{lstlisting}
  7897. \end{minipage}
  7898. \end{tabular} \\
  7899. %
  7900. The top-level function definitions need to be updated as well to take
  7901. an extra closure parameter.
  7902. \section{An Example Translation}
  7903. \label{sec:example-lambda}
  7904. Figure~\ref{fig:lexical-functions-example} shows the result of
  7905. \code{reveal-functions} and \code{convert-to-closures} for the example
  7906. program demonstrating lexical scoping that we discussed at the
  7907. beginning of this chapter.
  7908. \begin{figure}[tbp]
  7909. \begin{minipage}{0.8\textwidth}
  7910. % tests/lambda_test_6.rkt
  7911. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7912. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  7913. (let ([y8 4])
  7914. (lambda: ([z9 : Integer]) : Integer
  7915. (+ x7 (+ y8 z9)))))
  7916. (define (main) : Integer
  7917. (let ([g0 ((fun-ref-arity f6 1) 5)])
  7918. (let ([h1 ((fun-ref-arity f6 1) 3)])
  7919. (+ (g0 11) (h1 15)))))
  7920. \end{lstlisting}
  7921. $\Rightarrow$
  7922. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7923. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  7924. (let ([y8 4])
  7925. (closure 1 (list (fun-ref lambda2) x7 y8))))
  7926. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  7927. (let ([x7 (vector-ref fvs3 1)])
  7928. (let ([y8 (vector-ref fvs3 2)])
  7929. (+ x7 (+ y8 z9)))))
  7930. (define (main) : Integer
  7931. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6)))])
  7932. ((vector-ref clos5 0) clos5 5))])
  7933. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6)))])
  7934. ((vector-ref clos6 0) clos6 3))])
  7935. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  7936. \end{lstlisting}
  7937. \end{minipage}
  7938. \caption{Example of closure conversion.}
  7939. \label{fig:lexical-functions-example}
  7940. \end{figure}
  7941. \begin{exercise}\normalfont
  7942. Expand your compiler to handle $R_5$ as outlined in this chapter.
  7943. Create 5 new programs that use \key{lambda} functions and make use of
  7944. lexical scoping. Test your compiler on these new programs and all of
  7945. your previously created test programs.
  7946. \end{exercise}
  7947. \section{Expose Allocation}
  7948. \label{sec:expose-allocation-r5}
  7949. Compile the $\CLOSURE{\itm{arity}}{\LP\Exp\ldots\RP}$ form into code
  7950. that allocates and initializes a vector, similar to the translation of
  7951. the \code{vector} operator in Section~\ref{sec:expose-allocation}.
  7952. The only difference is replacing the use of
  7953. \ALLOC{\itm{len}}{\itm{type}} with
  7954. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  7955. \section{Explicate Control and $C_4$}
  7956. \label{sec:explicate-r5}
  7957. The output language of \code{explicate-control} is $C_4$ whose
  7958. abstract syntax is defined in Figure~\ref{fig:c4-syntax}. The only
  7959. difference with respect to $C_3$ is the addition of the
  7960. \code{AllocateClosure} form to the grammar for $\Exp$. The handling
  7961. of \code{AllocateClosure} in the \code{explicate-control} pass is
  7962. similar to the handling of other expressions such as primitive
  7963. operators.
  7964. \begin{figure}[tp]
  7965. \fbox{
  7966. \begin{minipage}{0.96\textwidth}
  7967. \small
  7968. \[
  7969. \begin{array}{lcl}
  7970. \Exp &::= & \ldots
  7971. \mid \ALLOCCLOS{\Int}{\Type}{\Int} \\
  7972. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  7973. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  7974. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  7975. \mid \GOTO{\itm{label}} } \\
  7976. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  7977. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  7978. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  7979. C_4 & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  7980. \end{array}
  7981. \]
  7982. \end{minipage}
  7983. }
  7984. \caption{The abstract syntax of $C_4$, extending $C_3$ (Figure~\ref{fig:c3-syntax}).}
  7985. \label{fig:c4-syntax}
  7986. \end{figure}
  7987. \section{Select Instructions}
  7988. \label{sec:select-instructions-R5}
  7989. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  7990. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  7991. (Section~\ref{sec:select-instructions-gc}). The only difference is
  7992. that you should place the \itm{arity} in the tag that is stored at
  7993. position $0$ of the vector. Recall that in
  7994. Section~\ref{sec:select-instructions-gc} we used the first $56$ bits
  7995. of the 64-bit tag, but that the rest were unused. So the arity goes
  7996. into the tag in bit positions $57$ through $63$.
  7997. Compile the \code{procedure-arity} operator into a sequence of
  7998. instructions that access the tag from position $0$ of the vector and
  7999. shift it by $57$ bits to the right.
  8000. \begin{figure}[p]
  8001. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8002. \node (R4) at (0,2) {\large $R_4$};
  8003. \node (R4-2) at (3,2) {\large $R_4$};
  8004. \node (R4-3) at (6,2) {\large $R_4$};
  8005. \node (F1-1) at (12,0) {\large $F_1$};
  8006. \node (F1-2) at (9,0) {\large $F_1$};
  8007. \node (F1-3) at (6,0) {\large $F_1$};
  8008. \node (F1-4) at (3,0) {\large $F_1$};
  8009. \node (F1-5) at (0,0) {\large $F_1$};
  8010. \node (C3-2) at (3,-2) {\large $C_3$};
  8011. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  8012. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  8013. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  8014. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  8015. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  8016. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  8017. \path[->,bend left=15] (R4) edge [above] node
  8018. {\ttfamily\footnotesize shrink} (R4-2);
  8019. \path[->,bend left=15] (R4-2) edge [above] node
  8020. {\ttfamily\footnotesize uniquify} (R4-3);
  8021. \path[->,bend left=15] (R4-3) edge [right] node
  8022. {\ttfamily\footnotesize reveal-functions} (F1-1);
  8023. \path[->,bend left=15] (F1-1) edge [below] node
  8024. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  8025. \path[->,bend right=15] (F1-2) edge [above] node
  8026. {\ttfamily\footnotesize limit-fun.} (F1-3);
  8027. \path[->,bend right=15] (F1-3) edge [above] node
  8028. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  8029. \path[->,bend right=15] (F1-4) edge [above] node
  8030. {\ttfamily\footnotesize remove-complex.} (F1-5);
  8031. \path[->,bend right=15] (F1-5) edge [right] node
  8032. {\ttfamily\footnotesize explicate-control} (C3-2);
  8033. \path[->,bend left=15] (C3-2) edge [left] node
  8034. {\ttfamily\footnotesize select-instr.} (x86-2);
  8035. \path[->,bend right=15] (x86-2) edge [left] node
  8036. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  8037. \path[->,bend right=15] (x86-2-1) edge [below] node
  8038. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  8039. \path[->,bend right=15] (x86-2-2) edge [left] node
  8040. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  8041. \path[->,bend left=15] (x86-3) edge [above] node
  8042. {\ttfamily\footnotesize patch-instr.} (x86-4);
  8043. \path[->,bend left=15] (x86-4) edge [right] node
  8044. {\ttfamily\footnotesize print-x86} (x86-5);
  8045. \end{tikzpicture}
  8046. \caption{Diagram of the passes for $R_5$, a language with lexically-scoped
  8047. functions.}
  8048. \label{fig:R5-passes}
  8049. \end{figure}
  8050. Figure~\ref{fig:R5-passes} provides an overview of all the passes needed
  8051. for the compilation of $R_5$.
  8052. \clearpage
  8053. \section{Challenge: Optimize Closures}
  8054. \label{sec:optimize-closures}
  8055. In this chapter we compiled lexically-scoped functions into a
  8056. relatively efficient representation: flat closures. However, even this
  8057. representation comes with some overhead. For example, consider the
  8058. following program with a function \code{tail-sum} that does not have
  8059. any free variables and where all the uses of \code{tail-sum} are in
  8060. applications where we know that only \code{tail-sum} is being applied
  8061. (and not any other functions).
  8062. \begin{center}
  8063. \begin{minipage}{0.95\textwidth}
  8064. \begin{lstlisting}
  8065. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  8066. (if (eq? n 0)
  8067. r
  8068. (tail-sum (- n 1) (+ n r))))
  8069. (+ (tail-sum 5 0) 27)
  8070. \end{lstlisting}
  8071. \end{minipage}
  8072. \end{center}
  8073. As described in this chapter, we uniformly apply closure conversion to
  8074. all functions, obtaining the following output for this program.
  8075. \begin{center}
  8076. \begin{minipage}{0.95\textwidth}
  8077. \begin{lstlisting}
  8078. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [r3 : Integer]) : Integer
  8079. (if (eq? n2 0)
  8080. r3
  8081. (let ([clos4 (closure (list (fun-ref tail_sum1)))])
  8082. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 r3)))))
  8083. (define (main) : Integer
  8084. (+ (let ([clos6 (closure (list (fun-ref tail_sum1)))])
  8085. ((vector-ref clos6 0) clos6 5 0)) 27))
  8086. \end{lstlisting}
  8087. \end{minipage}
  8088. \end{center}
  8089. In the previous Chapter, there would be no allocation in the program
  8090. and the calls to \code{tail-sum} would be direct calls. In contrast,
  8091. the above program allocates memory for each \code{closure} and the
  8092. calls to \code{tail-sum} are indirect. These two differences incur
  8093. considerable overhead in a program such as this one, where the
  8094. allocations and indirect calls occur inside a tight loop.
  8095. One might think that this problem is trivial to solve: can't we just
  8096. recognize calls of the form \code{((fun-ref $f$) $e_1 \ldots e_n$)}
  8097. and compile them to direct calls \code{((fun-ref $f$) $e'_1 \ldots
  8098. e'_n$)} instead of treating it like a call to a closure? We would
  8099. also drop the \code{fvs5} parameter of \code{tail\_sum1}.
  8100. %
  8101. However, this problem is not so trivial because a global function may
  8102. ``escape'' and become involved in applications that also involve
  8103. closures. Consider the following example in which the application
  8104. \code{(f 41)} needs to be compiled into a closure application, because
  8105. the \code{lambda} may get bound to \code{f}, but the \code{add1}
  8106. function might also get bound to \code{f}.
  8107. \begin{lstlisting}
  8108. (define (add1 [x : Integer]) : Integer
  8109. (+ x 1))
  8110. (let ([y (read)])
  8111. (let ([f (if (eq? (read) 0)
  8112. add1
  8113. (lambda: ([x : Integer]) : Integer (- x y)))])
  8114. (f 41)))
  8115. \end{lstlisting}
  8116. If a global function name is used in any way other than as the
  8117. operator in a direct call, then we say that the function
  8118. \emph{escapes}. If a global function does not escape, then we do not
  8119. need to perform closure conversion on the function.
  8120. \begin{exercise}\normalfont
  8121. Implement an auxiliary function for detecting which global
  8122. functions escape. Using that function, implement an improved version
  8123. of closure conversion that does not apply closure conversion to
  8124. global functions that do not escape but instead compiles them as
  8125. regular functions. Create several new test cases that check whether
  8126. you properly detect whether global functions escape or not.
  8127. \end{exercise}
  8128. So far we have reduced the overhead of calling global functions, but
  8129. it would also be nice to reduce the overhead of calling a
  8130. \code{lambda} when we can determine at compile time which
  8131. \code{lambda} will be called. We refer to such calls as \emph{known
  8132. calls}. Consider the following example in which a \code{lambda} is
  8133. bound to \code{f} and then applied.
  8134. \begin{lstlisting}
  8135. (let ([y (read)])
  8136. (let ([f (lambda: ([x : Integer]) : Integer
  8137. (+ x y))])
  8138. (f 21)))
  8139. \end{lstlisting}
  8140. Closure conversion compiles \code{(f 21)} into an indirect call:
  8141. \begin{lstlisting}
  8142. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  8143. (let ([y2 (vector-ref fvs6 1)])
  8144. (+ x3 y2)))
  8145. (define (main) : Integer
  8146. (let ([y2 (read)])
  8147. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  8148. ((vector-ref f4 0) f4 21))))
  8149. \end{lstlisting}
  8150. but we can instead compile the application \code{(f 21)} into a direct call
  8151. to \code{lambda5}:
  8152. \begin{lstlisting}
  8153. (define (main) : Integer
  8154. (let ([y2 (read)])
  8155. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  8156. ((fun-ref lambda5) f4 21))))
  8157. \end{lstlisting}
  8158. The problem of determining which lambda will be called from a
  8159. particular application is quite challenging in general and the topic
  8160. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  8161. following exercise we recommend that you compile an application to a
  8162. direct call when the operator is a variable and the variable is
  8163. \code{let}-bound to a closure. This can be accomplished by maintaining
  8164. an environment mapping \code{let}-bound variables to function names.
  8165. Extend the environment whenever you encounter a closure on the
  8166. right-hand side of a \code{let}, mapping the \code{let}-bound variable
  8167. to the name of the global function for the closure. This pass should
  8168. come after closure conversion.
  8169. \begin{exercise}\normalfont
  8170. Implement a compiler pass, named \code{optimize-known-calls}, that
  8171. compiles known calls into direct calls. Verify that your compiler is
  8172. successful in this regard on several example programs.
  8173. \end{exercise}
  8174. These exercises only scratches the surface of optimizing of
  8175. closures. A good next step for the interested reader is to look at the
  8176. work of \citet{Keep:2012ab}.
  8177. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8178. \chapter{Dynamic Typing}
  8179. \label{ch:type-dynamic}
  8180. \index{dynamic typing}
  8181. In this chapter we discuss the compilation of $R_7$, a dynamically
  8182. typed language that is a subset of Racket. This is in contrast to the
  8183. previous chapters, which have studied the compilation of Typed
  8184. Racket. In dynamically typed languages such as $R_7$, a given
  8185. expression may produce a value of a different type each time it is
  8186. executed. Consider the following example with a conditional \code{if}
  8187. expression that may return a Boolean or an integer depending on the
  8188. input to the program.
  8189. % part of dynamic_test_25.rkt
  8190. \begin{lstlisting}
  8191. (not (if (eq? (read) 1) #f 0))
  8192. \end{lstlisting}
  8193. Languages that allow expressions to produce different kinds of values
  8194. are called \emph{polymorphic}, a word composed of the Greek roots
  8195. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  8196. are several kinds of polymorphism in programming languages, such as
  8197. subtype polymorphism and parametric
  8198. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  8199. study in this chapter does not have a special name but it is the kind
  8200. that arises in dynamically typed languages.
  8201. Another characteristic of dynamically typed languages is that
  8202. primitive operations, such as \code{not}, are often defined to operate
  8203. on many different types of values. In fact, in Racket, the \code{not}
  8204. operator produces a result for any kind of value: given \code{\#f} it
  8205. returns \code{\#t} and given anything else it returns \code{\#f}.
  8206. Furthermore, even when primitive operations restrict their inputs to
  8207. values of a certain type, this restriction is enforced at runtime
  8208. instead of during compilation. For example, the following vector
  8209. reference results in a run-time contract violation because the index
  8210. must be in integer, not a Boolean such as \code{\#t}.
  8211. \begin{lstlisting}
  8212. (vector-ref (vector 42) #t)
  8213. \end{lstlisting}
  8214. \begin{figure}[tp]
  8215. \centering
  8216. \fbox{
  8217. \begin{minipage}{0.97\textwidth}
  8218. \[
  8219. \begin{array}{rcl}
  8220. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  8221. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp}
  8222. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} \\
  8223. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  8224. &\mid& \key{\#t} \mid \key{\#f}
  8225. \mid \CBINOP{\key{and}}{\Exp}{\Exp}
  8226. \mid \CBINOP{\key{or}}{\Exp}{\Exp}
  8227. \mid \CUNIOP{\key{not}}{\Exp} \\
  8228. &\mid& \LP\itm{cmp}\;\Exp\;\Exp\RP \mid \CIF{\Exp}{\Exp}{\Exp} \\
  8229. &\mid& \LP\key{vector}\;\Exp\ldots\RP \mid
  8230. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  8231. &\mid& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \mid \LP\key{void}\RP \\
  8232. &\mid& \LP\Exp \; \Exp\ldots\RP
  8233. \mid \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  8234. & \mid & \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP\\
  8235. & \mid & \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \mid \LP\key{void?}\;\Exp\RP \\
  8236. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  8237. R_7 &::=& \Def\ldots\; \Exp
  8238. \end{array}
  8239. \]
  8240. \end{minipage}
  8241. }
  8242. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  8243. \label{fig:r7-concrete-syntax}
  8244. \end{figure}
  8245. \begin{figure}[tp]
  8246. \centering
  8247. \fbox{
  8248. \begin{minipage}{0.96\textwidth}
  8249. \small
  8250. \[
  8251. \begin{array}{lcl}
  8252. \Exp &::=& \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  8253. &\mid& \PRIM{\itm{op}}{\Exp\ldots} \\
  8254. &\mid& \BOOL{\itm{bool}}
  8255. \mid \IF{\Exp}{\Exp}{\Exp} \\
  8256. &\mid& \VOID{} \mid \APPLY{\Exp}{\Exp\ldots} \\
  8257. &\mid& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  8258. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  8259. R_7 &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  8260. \end{array}
  8261. \]
  8262. \end{minipage}
  8263. }
  8264. \caption{The abstract syntax of $R_7$.}
  8265. \label{fig:r7-syntax}
  8266. \end{figure}
  8267. The concrete and abstract syntax of $R_7$, our subset of Racket, is
  8268. defined in Figures~\ref{fig:r7-concrete-syntax} and
  8269. \ref{fig:r7-syntax}.
  8270. %
  8271. There is no type checker for $R_7$ because it is not a statically
  8272. typed language (it's dynamically typed!).
  8273. The definitional interpreter for $R_7$ is presented in
  8274. Figure~\ref{fig:interp-R7} and its auxiliary functions are defined in
  8275. Figure~\ref{fig:interp-R7-aux}. Consider the match clause for
  8276. \code{(Int n)}. Instead of simply returning the integer \code{n} (as
  8277. in the interpreter for $R_1$ in Figure~\ref{fig:interp-R1}), the
  8278. interpreter for $R_7$ creates a \emph{tagged value}\index{tagged
  8279. value} that combines an underlying value with a tag that identifies
  8280. what kind of value it is. We define the following struct
  8281. to represented tagged values.
  8282. \begin{lstlisting}
  8283. (struct Tagged (value tag) #:transparent)
  8284. \end{lstlisting}
  8285. The tags are \code{Integer}, \code{Boolean}, \code{Void},
  8286. \code{Vector}, and \code{Procedure}. Tags are closely related to types
  8287. but don't always capture all the information that a type does. For
  8288. example, a vector of type \code{(Vector Any Any)} is tagged with
  8289. \code{Vector} and a procedure of type \code{(Any Any -> Any)}
  8290. is tagged with \code{Procedure}.
  8291. Next consider the match clause for \code{vector-ref}. The
  8292. \code{check-tag} auxiliary function (Figure~\ref{fig:interp-R7-aux})
  8293. is used to ensure that the first argument is a vector and the second
  8294. is an integer. If they are not, a \code{trapped-error} is raised.
  8295. Recall from Section~\ref{sec:interp-R0} that when a definition
  8296. interpreter raises a \code{trapped-error} error, the compiled code
  8297. must also signal an error by exiting with return code \code{255}. A
  8298. \code{trapped-error} is also raised if the index is not less than
  8299. length of the vector.
  8300. \begin{figure}[tbp]
  8301. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8302. (define ((interp-R7-exp env) ast)
  8303. (define recur (interp-R7-exp env))
  8304. (match ast
  8305. [(Var x) (lookup x env)]
  8306. [(Int n) (Tagged n 'Integer)]
  8307. [(Bool b) (Tagged b 'Boolean)]
  8308. [(Lambda xs rt body)
  8309. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  8310. [(Prim 'vector es)
  8311. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  8312. [(Prim 'vector-ref (list e1 e2))
  8313. (define vec (recur e1)) (define i (recur e2))
  8314. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  8315. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  8316. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  8317. (vector-ref (Tagged-value vec) (Tagged-value i))]
  8318. [(Prim 'vector-set! (list e1 e2 e3))
  8319. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  8320. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  8321. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  8322. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  8323. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  8324. (Tagged (void) 'Void)]
  8325. [(Let x e body) ((interp-R7-exp (cons (cons x (recur e)) env)) body)]
  8326. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  8327. [(Prim 'or (list e1 e2))
  8328. (define v1 (recur e1))
  8329. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  8330. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  8331. [(Prim op (list e1))
  8332. #:when (set-member? type-predicates op)
  8333. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  8334. [(Prim op es)
  8335. (define args (map recur es))
  8336. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  8337. (unless (for/or ([expected-tags (op-tags op)])
  8338. (equal? expected-tags tags))
  8339. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  8340. (tag-value
  8341. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  8342. [(If q t f)
  8343. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  8344. [(Apply f es)
  8345. (define new-f (recur f)) (define args (map recur es))
  8346. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  8347. (match f-val
  8348. [`(function ,xs ,body ,lam-env)
  8349. (unless (eq? (length xs) (length args))
  8350. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  8351. (define new-env (append (map cons xs args) lam-env))
  8352. ((interp-R7-exp new-env) body)]
  8353. [else (error "interp-R7-exp, expected function, not" f-val)])]))
  8354. \end{lstlisting}
  8355. \caption{Interpreter for the $R_7$ language.}
  8356. \label{fig:interp-R7}
  8357. \end{figure}
  8358. \begin{figure}[tbp]
  8359. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8360. (define (interp-op op)
  8361. (match op
  8362. ['+ fx+]
  8363. ['- fx-]
  8364. ['read read-fixnum]
  8365. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  8366. ['< (lambda (v1 v2)
  8367. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  8368. ['<= (lambda (v1 v2)
  8369. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  8370. ['> (lambda (v1 v2)
  8371. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  8372. ['>= (lambda (v1 v2)
  8373. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  8374. ['boolean? boolean?]
  8375. ['integer? fixnum?]
  8376. ['void? void?]
  8377. ['vector? vector?]
  8378. ['vector-length vector-length]
  8379. ['procedure? (match-lambda
  8380. [`(functions ,xs ,body ,env) #t] [else #f])]
  8381. [else (error 'interp-op "unknown operator" op)]))
  8382. (define (op-tags op)
  8383. (match op
  8384. ['+ '((Integer Integer))]
  8385. ['- '((Integer Integer) (Integer))]
  8386. ['read '(())]
  8387. ['not '((Boolean))]
  8388. ['< '((Integer Integer))]
  8389. ['<= '((Integer Integer))]
  8390. ['> '((Integer Integer))]
  8391. ['>= '((Integer Integer))]
  8392. ['vector-length '((Vector))]))
  8393. (define type-predicates
  8394. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  8395. (define (tag-value v)
  8396. (cond [(boolean? v) (Tagged v 'Boolean)]
  8397. [(fixnum? v) (Tagged v 'Integer)]
  8398. [(procedure? v) (Tagged v 'Procedure)]
  8399. [(vector? v) (Tagged v 'Vector)]
  8400. [(void? v) (Tagged v 'Void)]
  8401. [else (error 'tag-value "unidentified value ~a" v)]))
  8402. (define (check-tag val expected ast)
  8403. (define tag (Tagged-tag val))
  8404. (unless (eq? tag expected)
  8405. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  8406. \end{lstlisting}
  8407. \caption{Auxiliary functions for the $R_7$ interpreter.}
  8408. \label{fig:interp-R7-aux}
  8409. \end{figure}
  8410. \clearpage
  8411. \section{Representation of Tagged Values}
  8412. The interpreter for $R_7$ introduced a new kind of value, a tagged
  8413. value. To compile $R_7$ to x86 we must decide how to represent tagged
  8414. values at the bit level. Because almost every operation in $R_7$
  8415. involves manipulating tagged values, the representation must be
  8416. efficient. Recall that all of our values are 64 bits. We shall steal
  8417. the 3 right-most bits to encode the tag. We use $001$ to identify
  8418. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  8419. and $101$ for the void value. We define the following auxiliary
  8420. function for mapping types to tag codes.
  8421. \begin{align*}
  8422. \itm{tagof}(\key{Integer}) &= 001 \\
  8423. \itm{tagof}(\key{Boolean}) &= 100 \\
  8424. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  8425. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  8426. \itm{tagof}(\key{Void}) &= 101
  8427. \end{align*}
  8428. This stealing of 3 bits comes at some price: our integers are reduced
  8429. to ranging from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  8430. affect vectors and procedures because those values are addresses, and
  8431. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  8432. they are always $000$. Thus, we do not lose information by overwriting
  8433. the rightmost 3 bits with the tag and we can simply zero-out the tag
  8434. to recover the original address.
  8435. To make tagged values into first-class entities, we can give them a
  8436. type, called \code{Any}, and define operations such as \code{Inject}
  8437. and \code{Project} for creating and using them, yielding the $R_6$
  8438. intermediate language. We describe how to compile $R_7$ to $R_6$ in
  8439. Section~\ref{sec:compile-r7} but first we describe the $R_6$ language
  8440. in greater detail.
  8441. \section{The $R_6$ Language}
  8442. \label{sec:r6-lang}
  8443. \begin{figure}[tp]
  8444. \centering
  8445. \fbox{
  8446. \begin{minipage}{0.96\textwidth}
  8447. \small
  8448. \[
  8449. \begin{array}{lcl}
  8450. \itm{op} &::= & \ldots \mid \code{any-vector-length}
  8451. \mid \code{any-vector-ref} \mid \code{any-vector-set!}\\
  8452. &\mid& \code{boolean?} \mid \code{integer?} \mid \code{vector?}
  8453. \mid \code{procedure?} \mid \code{void?} \\
  8454. \Exp &::=& \ldots
  8455. \mid \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  8456. &\mid& \INJECT{\Exp}{\FType} \mid \PROJECT{\Exp}{\FType} \\
  8457. \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  8458. R_6 &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  8459. \end{array}
  8460. \]
  8461. \end{minipage}
  8462. }
  8463. \caption{The abstract syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax}).}
  8464. \label{fig:r6-syntax}
  8465. \end{figure}
  8466. The abstract syntax of $R_6$ is defined in Figure~\ref{fig:r6-syntax}.
  8467. (The concrete syntax of $R_6$ is in the Appendix,
  8468. Figure~\ref{fig:r6-concrete-syntax}.) The $\INJECT{e}{T}$ form
  8469. converts the value produced by expression $e$ of type $T$ into a
  8470. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  8471. produced by expression $e$ into a value of type $T$ or else halts the
  8472. program if the type tag is not equivalent to $T$.
  8473. %
  8474. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  8475. restricted to a flat type $\FType$, which simplifies the
  8476. implementation and corresponds with what is needed for compiling $R_7$.
  8477. The \code{any-vector} operators adapt the vector operations so that
  8478. they can be applied to a value of type \code{Any}. They also
  8479. generalize the vector operations in that the index is not restricted
  8480. to be a literal integer in the grammar but is allowed to be any
  8481. expression.
  8482. The type predicates such as \key{boolean?} expect their argument to
  8483. produce a tagged value; they return \key{\#t} if the tag corresponds
  8484. to the predicate and they return \key{\#f} otherwise.
  8485. The type checker for $R_6$ is shown in
  8486. Figures~\ref{fig:type-check-R6-part-1} and
  8487. \ref{fig:type-check-R6-part-2} and uses the auxiliary functions in
  8488. Figure~\ref{fig:type-check-R6-aux}.
  8489. %
  8490. The interpreter for $R_6$ is in Figure~\ref{fig:interp-R6} and the
  8491. auxiliary functions \code{apply-inject} and \code{apply-project} are
  8492. in Figure~\ref{fig:apply-project}.
  8493. \begin{figure}[btp]
  8494. \begin{lstlisting}[basicstyle=\ttfamily\small]
  8495. (define type-check-R6-class
  8496. (class type-check-R5-class
  8497. (super-new)
  8498. (inherit check-type-equal?)
  8499. (define/override (type-check-exp env)
  8500. (lambda (e)
  8501. (define recur (type-check-exp env))
  8502. (match e
  8503. [(Inject e1 ty)
  8504. (unless (flat-ty? ty)
  8505. (error 'type-check "may only inject from flat type, not ~a" ty))
  8506. (define-values (new-e1 e-ty) (recur e1))
  8507. (check-type-equal? e-ty ty e)
  8508. (values (Inject new-e1 ty) 'Any)]
  8509. [(Project e1 ty)
  8510. (unless (flat-ty? ty)
  8511. (error 'type-check "may only project to flat type, not ~a" ty))
  8512. (define-values (new-e1 e-ty) (recur e1))
  8513. (check-type-equal? e-ty 'Any e)
  8514. (values (Project new-e1 ty) ty)]
  8515. [(Prim 'any-vector-length (list e1))
  8516. (define-values (e1^ t1) (recur e1))
  8517. (check-type-equal? t1 'Any e)
  8518. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  8519. [(Prim 'any-vector-ref (list e1 e2))
  8520. (define-values (e1^ t1) (recur e1))
  8521. (define-values (e2^ t2) (recur e2))
  8522. (check-type-equal? t1 'Any e)
  8523. (check-type-equal? t2 'Integer e)
  8524. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  8525. [(Prim 'any-vector-set! (list e1 e2 e3))
  8526. (define-values (e1^ t1) (recur e1))
  8527. (define-values (e2^ t2) (recur e2))
  8528. (define-values (e3^ t3) (recur e3))
  8529. (check-type-equal? t1 'Any e)
  8530. (check-type-equal? t2 'Integer e)
  8531. (check-type-equal? t3 'Any e)
  8532. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  8533. \end{lstlisting}
  8534. \caption{Type checker for the $R_6$ language, part 1.}
  8535. \label{fig:type-check-R6-part-1}
  8536. \end{figure}
  8537. \begin{figure}[btp]
  8538. \begin{lstlisting}[basicstyle=\ttfamily\small]
  8539. [(ValueOf e ty)
  8540. (define-values (new-e e-ty) (recur e))
  8541. (values (ValueOf new-e ty) ty)]
  8542. [(Prim pred (list e1))
  8543. #:when (set-member? (type-predicates) pred)
  8544. (define-values (new-e1 e-ty) (recur e1))
  8545. (check-type-equal? e-ty 'Any e)
  8546. (values (Prim pred (list new-e1)) 'Boolean)]
  8547. [(If cnd thn els)
  8548. (define-values (cnd^ Tc) (recur cnd))
  8549. (define-values (thn^ Tt) (recur thn))
  8550. (define-values (els^ Te) (recur els))
  8551. (check-type-equal? Tc 'Boolean cnd)
  8552. (check-type-equal? Tt Te e)
  8553. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  8554. [(Exit) (values (Exit) '_)]
  8555. [(Prim 'eq? (list arg1 arg2))
  8556. (define-values (e1 t1) (recur arg1))
  8557. (define-values (e2 t2) (recur arg2))
  8558. (match* (t1 t2)
  8559. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  8560. [(other wise) (check-type-equal? t1 t2 e)])
  8561. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  8562. [else ((super type-check-exp env) e)])))
  8563. ))
  8564. \end{lstlisting}
  8565. \caption{Type checker for the $R_6$ language, part 2.}
  8566. \label{fig:type-check-R6-part-2}
  8567. \end{figure}
  8568. \begin{figure}[tbp]
  8569. \begin{lstlisting}
  8570. (define/override (operator-types)
  8571. (append
  8572. '((integer? . ((Any) . Boolean))
  8573. (vector? . ((Any) . Boolean))
  8574. (procedure? . ((Any) . Boolean))
  8575. (void? . ((Any) . Boolean))
  8576. (tag-of-any . ((Any) . Integer))
  8577. (make-any . ((_ Integer) . Any))
  8578. )
  8579. (super operator-types)))
  8580. (define/public (type-predicates)
  8581. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  8582. (define/public (combine-types t1 t2)
  8583. (match (list t1 t2)
  8584. [(list '_ t2) t2]
  8585. [(list t1 '_) t1]
  8586. [(list `(Vector ,ts1 ...)
  8587. `(Vector ,ts2 ...))
  8588. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  8589. (combine-types t1 t2)))]
  8590. [(list `(,ts1 ... -> ,rt1)
  8591. `(,ts2 ... -> ,rt2))
  8592. `(,@(for/list ([t1 ts1] [t2 ts2])
  8593. (combine-types t1 t2))
  8594. -> ,(combine-types rt1 rt2))]
  8595. [else t1]))
  8596. (define/public (flat-ty? ty)
  8597. (match ty
  8598. [(or `Integer `Boolean '_ `Void) #t]
  8599. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  8600. [`(,ts ... -> ,rt)
  8601. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  8602. [else #f]))
  8603. \end{lstlisting}
  8604. \caption{Auxiliary methods for type checking $R_6$.}
  8605. \label{fig:type-check-R6-aux}
  8606. \end{figure}
  8607. \begin{figure}[btp]
  8608. \begin{lstlisting}
  8609. (define interp-R6-class
  8610. (class interp-R5-class
  8611. (super-new)
  8612. (define/override (interp-op op)
  8613. (match op
  8614. ['boolean? (match-lambda
  8615. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  8616. [else #f])]
  8617. ['integer? (match-lambda
  8618. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  8619. [else #f])]
  8620. ['vector? (match-lambda
  8621. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  8622. [else #f])]
  8623. ['procedure? (match-lambda
  8624. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  8625. [else #f])]
  8626. ['eq? (match-lambda*
  8627. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  8628. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  8629. [ls (apply (super interp-op op) ls)])]
  8630. ['any-vector-ref (lambda (v i)
  8631. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  8632. ['any-vector-set! (lambda (v i a)
  8633. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  8634. ['any-vector-length (lambda (v)
  8635. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  8636. [else (super interp-op op)]))
  8637. (define/override ((interp-exp env) e)
  8638. (define recur (interp-exp env))
  8639. (match e
  8640. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  8641. [(Project e ty2) (apply-project (recur e) ty2)]
  8642. [else ((super interp-exp env) e)]))
  8643. ))
  8644. (define (interp-R6 p)
  8645. (send (new interp-R6-class) interp-program p))
  8646. \end{lstlisting}
  8647. \caption{Interpreter for $R_6$.}
  8648. \label{fig:interp-R6}
  8649. \end{figure}
  8650. \begin{figure}[tbp]
  8651. \begin{lstlisting}
  8652. (define/public (apply-inject v tg) (Tagged v tg))
  8653. (define/public (apply-project v ty2)
  8654. (define tag2 (any-tag ty2))
  8655. (match v
  8656. [(Tagged v1 tag1)
  8657. (cond
  8658. [(eq? tag1 tag2)
  8659. (match ty2
  8660. [`(Vector ,ts ...)
  8661. (define l1 ((interp-op 'vector-length) v1))
  8662. (cond
  8663. [(eq? l1 (length ts)) v1]
  8664. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  8665. l1 (length ts))])]
  8666. [`(,ts ... -> ,rt)
  8667. (match v1
  8668. [`(function ,xs ,body ,env)
  8669. (cond [(eq? (length xs) (length ts)) v1]
  8670. [else
  8671. (error 'apply-project "arity mismatch ~a != ~a"
  8672. (length xs) (length ts))])]
  8673. [else (error 'apply-project "expected function not ~a" v1)])]
  8674. [else v1])]
  8675. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  8676. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  8677. \end{lstlisting}
  8678. \caption{Auxiliary functions for injection and projection.}
  8679. \label{fig:apply-project}
  8680. \end{figure}
  8681. \clearpage
  8682. \section{Cast Insertion: Compiling $R_7$ to $R_6$}
  8683. \label{sec:compile-r7}
  8684. The \code{cast-insert} pass compiles from $R_7$ to $R_6$.
  8685. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  8686. $R_7$ forms into $R_6$. An important invariant of this pass is that
  8687. given a subexpression $e$ in the $R_7$ program, the pass will produce
  8688. an expression $e'$ in $R_6$ that has type \key{Any}. For example, the
  8689. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  8690. the Boolean \code{\#t}, which must be injected to produce an
  8691. expression of type \key{Any}.
  8692. %
  8693. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  8694. addition, is representative of compilation for many primitive
  8695. operations: the arguments have type \key{Any} and must be projected to
  8696. \key{Integer} before the addition can be performed.
  8697. The compilation of \key{lambda} (third row of
  8698. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  8699. produce type annotations: we simply use \key{Any}.
  8700. %
  8701. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  8702. has to account for some differences in behavior between $R_7$ and
  8703. $R_6$. The $R_7$ language is more permissive than $R_6$ regarding what
  8704. kind of values can be used in various places. For example, the
  8705. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  8706. the arguments need not be of the same type (in that case the
  8707. result is \code{\#f}).
  8708. \begin{figure}[btp]
  8709. \centering
  8710. \begin{tabular}{|lll|} \hline
  8711. \begin{minipage}{0.27\textwidth}
  8712. \begin{lstlisting}
  8713. #t
  8714. \end{lstlisting}
  8715. \end{minipage}
  8716. &
  8717. $\Rightarrow$
  8718. &
  8719. \begin{minipage}{0.65\textwidth}
  8720. \begin{lstlisting}
  8721. (inject #t Boolean)
  8722. \end{lstlisting}
  8723. \end{minipage}
  8724. \\[2ex]\hline
  8725. \begin{minipage}{0.27\textwidth}
  8726. \begin{lstlisting}
  8727. (+ |$e_1$| |$e_2$|)
  8728. \end{lstlisting}
  8729. \end{minipage}
  8730. &
  8731. $\Rightarrow$
  8732. &
  8733. \begin{minipage}{0.65\textwidth}
  8734. \begin{lstlisting}
  8735. (inject
  8736. (+ (project |$e'_1$| Integer)
  8737. (project |$e'_2$| Integer))
  8738. Integer)
  8739. \end{lstlisting}
  8740. \end{minipage}
  8741. \\[2ex]\hline
  8742. \begin{minipage}{0.27\textwidth}
  8743. \begin{lstlisting}
  8744. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  8745. \end{lstlisting}
  8746. \end{minipage}
  8747. &
  8748. $\Rightarrow$
  8749. &
  8750. \begin{minipage}{0.65\textwidth}
  8751. \begin{lstlisting}
  8752. (inject
  8753. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  8754. (Any|$\ldots$|Any -> Any))
  8755. \end{lstlisting}
  8756. \end{minipage}
  8757. \\[2ex]\hline
  8758. \begin{minipage}{0.27\textwidth}
  8759. \begin{lstlisting}
  8760. (|$e_0$| |$e_1 \ldots e_n$|)
  8761. \end{lstlisting}
  8762. \end{minipage}
  8763. &
  8764. $\Rightarrow$
  8765. &
  8766. \begin{minipage}{0.65\textwidth}
  8767. \begin{lstlisting}
  8768. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  8769. \end{lstlisting}
  8770. \end{minipage}
  8771. \\[2ex]\hline
  8772. \begin{minipage}{0.27\textwidth}
  8773. \begin{lstlisting}
  8774. (vector-ref |$e_1$| |$e_2$|)
  8775. \end{lstlisting}
  8776. \end{minipage}
  8777. &
  8778. $\Rightarrow$
  8779. &
  8780. \begin{minipage}{0.65\textwidth}
  8781. \begin{lstlisting}
  8782. (any-vector-ref |$e_1'$| |$e_2'$|)
  8783. \end{lstlisting}
  8784. \end{minipage}
  8785. \\[2ex]\hline
  8786. \begin{minipage}{0.27\textwidth}
  8787. \begin{lstlisting}
  8788. (if |$e_1$| |$e_2$| |$e_3$|)
  8789. \end{lstlisting}
  8790. \end{minipage}
  8791. &
  8792. $\Rightarrow$
  8793. &
  8794. \begin{minipage}{0.65\textwidth}
  8795. \begin{lstlisting}
  8796. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  8797. \end{lstlisting}
  8798. \end{minipage}
  8799. \\[2ex]\hline
  8800. \begin{minipage}{0.27\textwidth}
  8801. \begin{lstlisting}
  8802. (eq? |$e_1$| |$e_2$|)
  8803. \end{lstlisting}
  8804. \end{minipage}
  8805. &
  8806. $\Rightarrow$
  8807. &
  8808. \begin{minipage}{0.65\textwidth}
  8809. \begin{lstlisting}
  8810. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  8811. \end{lstlisting}
  8812. \end{minipage}
  8813. \\[2ex]\hline
  8814. \begin{minipage}{0.27\textwidth}
  8815. \begin{lstlisting}
  8816. (not |$e_1$|)
  8817. \end{lstlisting}
  8818. \end{minipage}
  8819. &
  8820. $\Rightarrow$
  8821. &
  8822. \begin{minipage}{0.65\textwidth}
  8823. \begin{lstlisting}
  8824. (if (eq? |$e'_1$| (inject #f Boolean))
  8825. (inject #t Boolean) (inject #f Boolean))
  8826. \end{lstlisting}
  8827. \end{minipage}
  8828. \\[2ex]\hline
  8829. \end{tabular}
  8830. \caption{Cast Insertion}
  8831. \label{fig:compile-r7-r6}
  8832. \end{figure}
  8833. \section{Reveal Casts}
  8834. \label{sec:reveal-casts-r6}
  8835. % TODO: define R'_6
  8836. In the \code{reveal-casts} pass we recommend compiling \code{project}
  8837. into an \code{if} expression that checks whether the value's tag
  8838. matches the target type; if it does, the value is converted to a value
  8839. of the target type by removing the tag; if it does not, the program
  8840. exits. To perform these actions we need a new primitive operation,
  8841. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  8842. The \code{tag-of-any} operation retrieves the type tag from a tagged
  8843. value of type \code{Any}. The \code{ValueOf} form retrieves the
  8844. underlying value from a tagged value. The \code{ValueOf} form
  8845. includes the type for the underlying value which is used by the type
  8846. checker. Finally, the \code{Exit} form ends the execution of the
  8847. program.
  8848. If the target type of the projection is \code{Boolean} or
  8849. \code{Integer}, then \code{Project} can be translated as follows.
  8850. \begin{center}
  8851. \begin{minipage}{1.0\textwidth}
  8852. \begin{lstlisting}
  8853. (Project |$e$| |$\FType$|)
  8854. |$\Rightarrow$|
  8855. (Let |$\itm{tmp}$| |$e'$|
  8856. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  8857. (Int |$\itm{tagof}(\FType)$|)))
  8858. (ValueOf |$\itm{tmp}$| |$\FType$|)
  8859. (Exit)))
  8860. \end{lstlisting}
  8861. \end{minipage}
  8862. \end{center}
  8863. If the target type of the projection is a vector or function type,
  8864. then there is a bit more work to do. For vectors, check that the
  8865. length of the vector type matches the length of the vector (using the
  8866. \code{vector-length} primitive). For functions, check that the number
  8867. of parameters in the function type matches the function's arity (using
  8868. \code{procedure-arity}).
  8869. Regarding \code{inject}, we recommend compiling it to a slightly
  8870. lower-level primitive operation named \code{make-any}. This operation
  8871. takes a tag instead of a type.
  8872. \begin{center}
  8873. \begin{minipage}{1.0\textwidth}
  8874. \begin{lstlisting}
  8875. (Inject |$e$| |$\FType$|)
  8876. |$\Rightarrow$|
  8877. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  8878. \end{lstlisting}
  8879. \end{minipage}
  8880. \end{center}
  8881. The type predicates (\code{boolean?}, etc.) can be translated into
  8882. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  8883. translation of \code{Project}.
  8884. The \code{any-vector-ref} and \code{any-vector-set!} operations
  8885. combine the projection action with the vector operation. Also, the
  8886. read and write operations allow arbitrary expressions for the index so
  8887. the type checker for $R_6$ (Figure~\ref{fig:type-check-R6-part-1})
  8888. cannot guarantee that the index is within bounds. Thus, we insert code
  8889. to perform bounds checking at runtime. The translation for
  8890. \code{any-vector-ref} is as follows and the other two operations are
  8891. translated in a similar way.
  8892. \begin{lstlisting}
  8893. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  8894. |$\Rightarrow$|
  8895. (Let |$v$| |$e'_1$|
  8896. (Let |$i$| |$e'_2$|
  8897. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  8898. (If (Prim '< (list (Var |$i$|)
  8899. (Prim 'any-vector-length (list (Var |$v$|)))))
  8900. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  8901. (Exit))))
  8902. \end{lstlisting}
  8903. \section{Remove Complex Operands}
  8904. \label{sec:rco-r6}
  8905. The \code{ValueOf} and \code{Exit} forms are both complex expressions.
  8906. The subexpression of \code{ValueOf} must be atomic.
  8907. \section{Explicate Control and $C_5$}
  8908. \label{sec:explicate-r6}
  8909. The output of \code{explicate-control} is the $C_5$ language whose
  8910. syntax is defined in Figure~\ref{fig:c5-syntax}. The \code{ValueOf}
  8911. form that we added to $R_6$ remains an expression and the \code{Exit}
  8912. expression becomes a $\Tail$. Also, note that the index argument of
  8913. \code{vector-ref} and \code{vector-set!} is an $\Atm$ instead
  8914. of an integer, as in $C_2$ (Figure~\ref{fig:c2-syntax}).
  8915. \begin{figure}[tp]
  8916. \fbox{
  8917. \begin{minipage}{0.96\textwidth}
  8918. \small
  8919. \[
  8920. \begin{array}{lcl}
  8921. \Exp &::= & \ldots
  8922. \mid \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  8923. &\mid& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  8924. &\mid& \VALUEOF{\Exp}{\FType} \\
  8925. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  8926. \mid \LP\key{Collect} \,\itm{int}\RP }\\
  8927. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  8928. \mid \GOTO{\itm{label}} } \\
  8929. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  8930. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  8931. \mid \LP\key{Exit}\RP \\
  8932. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  8933. C_4 & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  8934. \end{array}
  8935. \]
  8936. \end{minipage}
  8937. }
  8938. \caption{The abstract syntax of $C_5$, extending $C_4$ (Figure~\ref{fig:c4-syntax}).}
  8939. \label{fig:c5-syntax}
  8940. \end{figure}
  8941. \section{Select Instructions}
  8942. \label{sec:select-r6}
  8943. In the \code{select-instructions} pass we translate the primitive
  8944. operations on the \code{Any} type to x86 instructions that involve
  8945. manipulating the 3 tag bits of the tagged value.
  8946. \paragraph{Make-any}
  8947. We recommend compiling the \key{make-any} primitive as follows if the
  8948. tag is for \key{Integer} or \key{Boolean}. The \key{salq} instruction
  8949. shifts the destination to the left by the number of bits specified its
  8950. source argument (in this case $3$, the length of the tag) and it
  8951. preserves the sign of the integer. We use the \key{orq} instruction to
  8952. combine the tag and the value to form the tagged value. \\
  8953. \begin{lstlisting}
  8954. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  8955. |$\Rightarrow$|
  8956. movq |$e'$|, |\itm{lhs'}|
  8957. salq $3, |\itm{lhs'}|
  8958. orq $|$\itm{tag}$|, |\itm{lhs'}|
  8959. \end{lstlisting}
  8960. The instruction selection for vectors and procedures is different
  8961. because their is no need to shift them to the left. The rightmost 3
  8962. bits are already zeros as described at the beginning of this
  8963. chapter. So we just combine the value and the tag using \key{orq}. \\
  8964. \begin{lstlisting}
  8965. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  8966. |$\Rightarrow$|
  8967. movq |$e'$|, |\itm{lhs'}|
  8968. orq $|$\itm{tag}$|, |\itm{lhs'}|
  8969. \end{lstlisting}
  8970. \paragraph{Tag-of-any}
  8971. Recall that the \code{tag-of-any} operation extracts the type tag from
  8972. a value of type \code{Any}. The type tag is the bottom three bits, so
  8973. we obtain the tag by taking the bitwise-and of the value with $111$
  8974. ($7$ in decimal).
  8975. \begin{lstlisting}
  8976. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  8977. |$\Rightarrow$|
  8978. movq |$e'$|, |\itm{lhs'}|
  8979. andq $7, |\itm{lhs'}|
  8980. \end{lstlisting}
  8981. \paragraph{ValueOf}
  8982. Like \key{make-any}, the instructions for \key{ValueOf} are different
  8983. depending on whether the type $T$ is a pointer (vector or procedure)
  8984. or not (Integer or Boolean). The following shows the instruction
  8985. selection for Integer and Boolean. We produce an untagged value by
  8986. shifting it to the right by 3 bits.
  8987. \begin{lstlisting}
  8988. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  8989. |$\Rightarrow$|
  8990. movq |$e'$|, |\itm{lhs'}|
  8991. sarq $3, |\itm{lhs'}|
  8992. \end{lstlisting}
  8993. %
  8994. In the case for vectors and procedures, there is no need to
  8995. shift. Instead we just need to zero-out the rightmost 3 bits. We
  8996. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  8997. decimal) and apply \code{bitwise-not} to obtain $\ldots 11111000$ (-8
  8998. in decimal) which we \code{movq} into the destination $\itm{lhs}$. We
  8999. then apply \code{andq} with the tagged value to get the desired
  9000. result. \\
  9001. \begin{lstlisting}
  9002. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  9003. |$\Rightarrow$|
  9004. movq $|$-8$|, |\itm{lhs'}|
  9005. andq |$e'$|, |\itm{lhs'}|
  9006. \end{lstlisting}
  9007. %% \paragraph{Type Predicates} We leave it to the reader to
  9008. %% devise a sequence of instructions to implement the type predicates
  9009. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  9010. \paragraph{Any-vector-length}
  9011. \begin{lstlisting}
  9012. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$a_1$|)))
  9013. |$\Longrightarrow$|
  9014. movq |$\neg 111$|, %r11
  9015. andq |$a_1'$|, %r11
  9016. movq 0(%r11), %r11
  9017. andq $126, %r11
  9018. sarq $1, %r11
  9019. movq %r11, |$\itm{lhs'}$|
  9020. \end{lstlisting}
  9021. \paragraph{Any-vector-ref}
  9022. The index may be an arbitrary atom so instead of computing the offset
  9023. at compile time, instructions need to be generated to compute the
  9024. offset at runtime as follows. Note the use of the new instruction
  9025. \code{imulq}.
  9026. \begin{center}
  9027. \begin{minipage}{0.96\textwidth}
  9028. \begin{lstlisting}
  9029. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$a_1$| |$a_2$|)))
  9030. |$\Longrightarrow$|
  9031. movq |$\neg 111$|, %r11
  9032. andq |$a_1'$|, %r11
  9033. movq |$a_2'$|, %rax
  9034. addq $1, %rax
  9035. imulq $8, %rax
  9036. addq %rax, %r11
  9037. movq 0(%r11) |$\itm{lhs'}$|
  9038. \end{lstlisting}
  9039. \end{minipage}
  9040. \end{center}
  9041. \paragraph{Any-vector-set!}
  9042. The code generation for \code{any-vector-set!} is similar to the other
  9043. \code{any-vector} operations.
  9044. \section{Register Allocation for $R_6$}
  9045. \label{sec:register-allocation-r6}
  9046. \index{register allocation}
  9047. There is an interesting interaction between tagged values and garbage
  9048. collection that has an impact on register allocation. A variable of
  9049. type \code{Any} might refer to a vector and therefore it might be a
  9050. root that needs to be inspected and copied during garbage
  9051. collection. Thus, we need to treat variables of type \code{Any} in a
  9052. similar way to variables of type \code{Vector} for purposes of
  9053. register allocation. In particular,
  9054. \begin{itemize}
  9055. \item If a variable of type \code{Any} is live during a function call,
  9056. then it must be spilled. This can be accomplished by changing
  9057. \code{build-interference} to mark all variables of type \code{Any}
  9058. that are live after a \code{callq} as interfering with all the
  9059. registers.
  9060. \item If a variable of type \code{Any} is spilled, it must be spilled
  9061. to the root stack instead of the normal procedure call stack.
  9062. \end{itemize}
  9063. Another concern regarding the root stack is that the garbage collector
  9064. needs to differentiate between (1) plain old pointers to tuples, (2) a
  9065. tagged value that points to a tuple, and (3) a tagged value that is
  9066. not a tuple. We enable this differentiation by choosing not to use the
  9067. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  9068. reserved for identifying plain old pointers to tuples. That way, if
  9069. one of the first three bits is set, then we have a tagged value and
  9070. inspecting the tag can differentiation between vectors ($010$) and the
  9071. other kinds of values.
  9072. \begin{exercise}\normalfont
  9073. Expand your compiler to handle $R_6$ as discussed in the last few
  9074. sections. Create 5 new programs that use the \code{Any} type and the
  9075. new operations (\code{inject}, \code{project}, \code{boolean?},
  9076. etc.). Test your compiler on these new programs and all of your
  9077. previously created test programs.
  9078. \end{exercise}
  9079. \begin{exercise}\normalfont
  9080. Expand your compiler to handle $R_7$ as outlined in this chapter.
  9081. Create tests for $R_7$ by adapting ten of your previous test programs
  9082. by removing type annotations. Add 5 more tests programs that
  9083. specifically rely on the language being dynamically typed. That is,
  9084. they should not be legal programs in a statically typed language, but
  9085. nevertheless, they should be valid $R_7$ programs that run to
  9086. completion without error.
  9087. \end{exercise}
  9088. \begin{figure}[p]
  9089. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9090. \node (R4) at (0,4) {\large $R_7$};
  9091. \node (R4-2) at (3,4) {\large $R_7$};
  9092. \node (R4-3) at (6,4) {\large $R_7$};
  9093. \node (R4-4) at (9,4) {\large $R'_7$};
  9094. \node (R4-5) at (9,2) {\large $R'_6$};
  9095. \node (R4-6) at (12,2) {\large $R'_6$};
  9096. \node (R4-7) at (12,0) {\large $R'_6$};
  9097. \node (F1-2) at (9,0) {\large $R'_6$};
  9098. \node (F1-3) at (6,0) {\large $R'_6$};
  9099. \node (F1-4) at (3,0) {\large $R'_6$};
  9100. \node (F1-5) at (0,0) {\large $R'_6$};
  9101. \node (C3-2) at (3,-2) {\large $C_3$};
  9102. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  9103. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  9104. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  9105. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  9106. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  9107. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  9108. \path[->,bend left=15] (R4) edge [above] node
  9109. {\ttfamily\footnotesize shrink} (R4-2);
  9110. \path[->,bend left=15] (R4-2) edge [above] node
  9111. {\ttfamily\footnotesize uniquify} (R4-3);
  9112. \path[->,bend left=15] (R4-3) edge [above] node
  9113. {\ttfamily\footnotesize reveal-functions} (R4-4);
  9114. \path[->,bend right=15] (R4-4) edge [left] node
  9115. {\ttfamily\footnotesize cast-insert} (R4-5);
  9116. \path[->,bend left=15] (R4-5) edge [above] node
  9117. {\ttfamily\footnotesize check-bounds} (R4-6);
  9118. \path[->,bend left=15] (R4-6) edge [left] node
  9119. {\ttfamily\footnotesize reveal-casts} (R4-7);
  9120. \path[->,bend left=15] (R4-7) edge [below] node
  9121. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  9122. \path[->,bend right=15] (F1-2) edge [above] node
  9123. {\ttfamily\footnotesize limit-fun.} (F1-3);
  9124. \path[->,bend right=15] (F1-3) edge [above] node
  9125. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9126. \path[->,bend right=15] (F1-4) edge [above] node
  9127. {\ttfamily\footnotesize remove-complex.} (F1-5);
  9128. \path[->,bend right=15] (F1-5) edge [right] node
  9129. {\ttfamily\footnotesize explicate-control} (C3-2);
  9130. \path[->,bend left=15] (C3-2) edge [left] node
  9131. {\ttfamily\footnotesize select-instr.} (x86-2);
  9132. \path[->,bend right=15] (x86-2) edge [left] node
  9133. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  9134. \path[->,bend right=15] (x86-2-1) edge [below] node
  9135. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  9136. \path[->,bend right=15] (x86-2-2) edge [left] node
  9137. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  9138. \path[->,bend left=15] (x86-3) edge [above] node
  9139. {\ttfamily\footnotesize patch-instr.} (x86-4);
  9140. \path[->,bend left=15] (x86-4) edge [right] node
  9141. {\ttfamily\footnotesize print-x86} (x86-5);
  9142. \end{tikzpicture}
  9143. \caption{Diagram of the passes for $R_7$, a dynamically typed language.}
  9144. \label{fig:R7-passes}
  9145. \end{figure}
  9146. Figure~\ref{fig:R7-passes} provides an overview of all the passes needed
  9147. for the compilation of $R_7$.
  9148. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9149. \chapter{Loops and Assignment}
  9150. \label{ch:loop}
  9151. % todo: define R'_8
  9152. In this chapter we study two features that are the hallmarks of
  9153. imperative programming languages: loops and assignments to local
  9154. variables. The following example demonstrates these new features by
  9155. computing the sum of the first five positive integers.
  9156. % similar to loop_test_1.rkt
  9157. \begin{lstlisting}
  9158. (let ([sum 0])
  9159. (let ([i 5])
  9160. (begin
  9161. (while (> i 0)
  9162. (begin
  9163. (set! sum (+ sum i))
  9164. (set! i (- i 1))))
  9165. sum)))
  9166. \end{lstlisting}
  9167. The \code{while} loop consists of a condition and a body.
  9168. %
  9169. The \code{set!} consists of a variable and a right-hand-side expression.
  9170. %
  9171. The primary purpose of both the \code{while} loop and \code{set!} is
  9172. to cause side effects, so it is convenient to also include in a
  9173. language feature for sequencing side effects: the \code{begin}
  9174. expression. It consists of one or more subexpressions that are
  9175. evaluated left-to-right.
  9176. \section{The $R_8$ Language}
  9177. \begin{figure}[tp]
  9178. \centering
  9179. \fbox{
  9180. \begin{minipage}{0.96\textwidth}
  9181. \small
  9182. \[
  9183. \begin{array}{lcl}
  9184. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  9185. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  9186. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  9187. &\mid& \gray{\key{\#t} \mid \key{\#f}
  9188. \mid (\key{and}\;\Exp\;\Exp)
  9189. \mid (\key{or}\;\Exp\;\Exp)
  9190. \mid (\key{not}\;\Exp) } \\
  9191. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  9192. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  9193. (\key{vector-ref}\;\Exp\;\Int)} \\
  9194. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  9195. \mid (\Exp \; \Exp\ldots) } \\
  9196. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP
  9197. \mid \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  9198. &\mid& \CSETBANG{\Var}{\Exp}
  9199. \mid \CBEGIN{\Exp\ldots}{\Exp}
  9200. \mid \CWHILE{\Exp}{\Exp} \\
  9201. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  9202. R_8 &::=& \gray{\Def\ldots \; \Exp}
  9203. \end{array}
  9204. \]
  9205. \end{minipage}
  9206. }
  9207. \caption{The concrete syntax of $R_8$, extending $R_6$ (Figure~\ref{fig:r6-concrete-syntax}).}
  9208. \label{fig:r8-concrete-syntax}
  9209. \end{figure}
  9210. \begin{figure}[tp]
  9211. \centering
  9212. \fbox{
  9213. \begin{minipage}{0.96\textwidth}
  9214. \small
  9215. \[
  9216. \begin{array}{lcl}
  9217. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  9218. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  9219. &\mid& \gray{ \BOOL{\itm{bool}}
  9220. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  9221. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  9222. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  9223. &\mid& \gray{ \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp} }\\
  9224. &\mid& \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  9225. \mid \WHILE{\Exp}{\Exp} \\
  9226. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  9227. R_8 &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  9228. \end{array}
  9229. \]
  9230. \end{minipage}
  9231. }
  9232. \caption{The abstract syntax of $R_8$, extending $R_6$ (Figure~\ref{fig:r6-syntax}).}
  9233. \label{fig:r8-syntax}
  9234. \end{figure}
  9235. The concrete syntax of $R_8$ is defined in
  9236. Figure~\ref{fig:r8-concrete-syntax} and its abstract syntax is defined
  9237. in Figure~\ref{fig:r8-syntax}.
  9238. %
  9239. The definitional interpreter for $R_8$ is shown in
  9240. Figure~\ref{fig:interp-R8}. We add three new cases for \code{SetBang},
  9241. \code{WhileLoop}, and \code{Begin} and we make changes to the cases
  9242. for \code{Var}, \code{Let}, and \code{Apply} regarding variables. To
  9243. support assignment to variables and to make their lifetimes indefinite
  9244. (see the second example in Section~\ref{sec:assignment-scoping}), we
  9245. box the value that is bound to each variable (in \code{Let}) and
  9246. function parameter (in \code{Apply}). The case for \code{Var} unboxes
  9247. the value.
  9248. %
  9249. Now to discuss the new cases. For \code{SetBang}, we lookup the
  9250. variable in the environment to obtain a boxed value and then we change
  9251. it using \code{set-box!} to the result of evaluating the right-hand
  9252. side. The result value of a \code{SetBang} is \code{void}.
  9253. %
  9254. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  9255. if the result is true, 2) evaluate the body.
  9256. The result value of a \code{while} loop is also \code{void}.
  9257. %
  9258. Finally, the $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  9259. subexpressions \itm{es} for their effects and then evaluates
  9260. and returns the result from \itm{body}.
  9261. \begin{figure}[tbp]
  9262. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9263. (define interp-R8-class
  9264. (class interp-R6-class
  9265. (super-new)
  9266. (define/override ((interp-exp env) e)
  9267. (define recur (interp-exp env))
  9268. (match e
  9269. [(SetBang x rhs)
  9270. (set-box! (lookup x env) (recur rhs))]
  9271. [(WhileLoop cnd body)
  9272. (define (loop)
  9273. (cond [(recur cnd) (recur body) (loop)]
  9274. [else (void)]))
  9275. (loop)]
  9276. [(Begin es body)
  9277. (for ([e es]) (recur e))
  9278. (recur body)]
  9279. [else ((super interp-exp env) e)]))
  9280. ))
  9281. (define (interp-R8 p)
  9282. (send (new interp-R8-class) interp-program p))
  9283. \end{lstlisting}
  9284. \caption{Interpreter for $R_8$.}
  9285. \label{fig:interp-R8}
  9286. \end{figure}
  9287. The type checker for $R_8$ is define in
  9288. Figure~\ref{fig:type-check-R8}. For \code{SetBang}, the type of the
  9289. variable and the right-hand-side must agree. The result type is
  9290. \code{Void}. For the \code{WhileLoop}, the condition must be a
  9291. \code{Boolean}. The result type is also \code{Void}. For
  9292. \code{Begin}, the result type is the type of its last subexpression.
  9293. \begin{figure}[tbp]
  9294. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9295. (define type-check-R8-class
  9296. (class type-check-R6-class
  9297. (super-new)
  9298. (inherit check-type-equal?)
  9299. (define/override (type-check-exp env)
  9300. (lambda (e)
  9301. (define recur (type-check-exp env))
  9302. (match e
  9303. [(SetBang x rhs)
  9304. (define-values (rhs^ rhsT) (recur rhs))
  9305. (define varT (dict-ref env x))
  9306. (check-type-equal? rhsT varT e)
  9307. (values (SetBang x rhs^) 'Void)]
  9308. [(WhileLoop cnd body)
  9309. (define-values (cnd^ Tc) (recur cnd))
  9310. (check-type-equal? Tc 'Boolean e)
  9311. (define-values (body^ Tbody) ((type-check-exp env) body))
  9312. (values (WhileLoop cnd^ body^) 'Void)]
  9313. [(Begin es body)
  9314. (define-values (es^ ts)
  9315. (for/lists (l1 l2) ([e es]) (recur e)))
  9316. (define-values (body^ Tbody) (recur body))
  9317. (values (Begin es^ body^) Tbody)]
  9318. [else ((super type-check-exp env) e)])))
  9319. ))
  9320. (define (type-check-R8 p)
  9321. (send (new type-check-R8-class) type-check-program p))
  9322. \end{lstlisting}
  9323. \caption{Type checking \key{SetBang}, \key{WhileLoop},
  9324. and \code{Begin} in $R_8$.}
  9325. \label{fig:type-check-R8}
  9326. \end{figure}
  9327. At first glance, the translation of these language features to x86
  9328. seems straightforward because the $C_3$ intermediate language already
  9329. supports all of the ingredients that we need: assignment, \code{goto},
  9330. conditional branching, and sequencing. However, there are two
  9331. complications that arise which we discuss in the next two
  9332. sections. After that we introduce one new compiler pass and the
  9333. changes necessary to the existing passes.
  9334. \section{Assignment and Lexically Scoped Functions}
  9335. \label{sec:assignment-scoping}
  9336. The addition of assignment raises a problem with our approach to
  9337. implementing lexically-scoped functions. Consider the following
  9338. example in which function \code{f} has a free variable \code{x} that
  9339. is changed after \code{f} is created but before the call to \code{f}.
  9340. % loop_test_11.rkt
  9341. \begin{lstlisting}
  9342. (let ([x 0])
  9343. (let ([y 0])
  9344. (let ([z 20])
  9345. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  9346. (begin
  9347. (set! x 10)
  9348. (set! y 12)
  9349. (f y))))))
  9350. \end{lstlisting}
  9351. The correct output for this example is \code{42} because the call to
  9352. \code{f} is required to use the current value of \code{x} (which is
  9353. \code{10}). Unfortunately, the closure conversion pass
  9354. (Section~\ref{sec:closure-conversion}) generates code for the
  9355. \code{lambda} that copies the old value of \code{x} into a
  9356. closure. Thus, if we naively add support for assignment to our current
  9357. compiler, the output of this program would be \code{32}.
  9358. A first attempt at solving this problem would be to save a pointer to
  9359. \code{x} in the closure and change the occurrences of \code{x} inside
  9360. the lambda to dereference the pointer. Of course, this would require
  9361. assigning \code{x} to the stack and not to a register. However, the
  9362. problem goes a bit deeper. Consider the following example in which we
  9363. create a counter abstraction by creating a pair of functions that
  9364. share the free variable \code{x}.
  9365. % similar to loop_test_10.rkt
  9366. \begin{lstlisting}
  9367. (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  9368. (vector
  9369. (lambda: () : Integer x)
  9370. (lambda: () : Void (set! x (+ 1 x)))))
  9371. (let ([counter (f 0)])
  9372. (let ([get (vector-ref counter 0)])
  9373. (let ([inc (vector-ref counter 1)])
  9374. (begin
  9375. (inc)
  9376. (get)))))
  9377. \end{lstlisting}
  9378. In this example, the lifetime of \code{x} extends beyond the lifetime
  9379. of the call to \code{f}. Thus, if we were to store \code{x} on the
  9380. stack frame for the call to \code{f}, it would be gone by the time we
  9381. call \code{inc} and \code{get}, leaving us with dangling pointers for
  9382. \code{x}. This example demonstrates that when a variable occurs free
  9383. inside a \code{lambda}, its lifetime becomes indefinite. Thus, the
  9384. value of the variable needs to live on the heap. The verb ``box'' is
  9385. often used for allocating a single value on the heap, producing a
  9386. pointer, and ``unbox'' for dereferencing the pointer.
  9387. We recommend solving these problems by ``boxing'' the local variables
  9388. that are in the intersection of 1) variables that appear on the
  9389. left-hand-side of a \code{set!} and 2) variables that occur free
  9390. inside a \code{lambda}. We shall introduce a new pass named
  9391. \code{convert-assignments} in Section~\ref{sec:convert-assignments} to
  9392. perform this translation. But before diving into the compiler passes,
  9393. we one more problem to discuss.
  9394. \section{Cyclic Control Flow and Dataflow Analysis}
  9395. \label{sec:dataflow-analysis}
  9396. Up until this point the control-flow graphs generated in
  9397. \code{explicate-control} were guaranteed to be acyclic. However, each
  9398. \code{while} loop introduces a cycle in the control-flow graph.
  9399. But does that matter?
  9400. %
  9401. Indeed it does. Recall that for register allocation, the compiler
  9402. performs liveness analysis to determine which variables can share the
  9403. same register. In Section~\ref{sec:liveness-analysis-r2} we analyze
  9404. the control-flow graph in reverse topological order, but topological
  9405. order is only well-defined for acyclic graphs.
  9406. Let us return to the example of computing the sum of the first five
  9407. positive integers. Here is the program after instruction selection but
  9408. before register allocation.
  9409. \begin{center}
  9410. \begin{minipage}{0.45\textwidth}
  9411. \begin{lstlisting}
  9412. (define (main) : Integer
  9413. mainstart:
  9414. movq $0, sum1
  9415. movq $5, i2
  9416. jmp block5
  9417. block5:
  9418. movq i2, tmp3
  9419. cmpq tmp3, $0
  9420. jl block7
  9421. jmp block8
  9422. \end{lstlisting}
  9423. \end{minipage}
  9424. \begin{minipage}{0.45\textwidth}
  9425. \begin{lstlisting}
  9426. block7:
  9427. addq i2, sum1
  9428. movq $1, tmp4
  9429. negq tmp4
  9430. addq tmp4, i2
  9431. jmp block5
  9432. block8:
  9433. movq $27, %rax
  9434. addq sum1, %rax
  9435. jmp mainconclusion
  9436. )
  9437. \end{lstlisting}
  9438. \end{minipage}
  9439. \end{center}
  9440. Recall that liveness analysis works backwards, starting at the end
  9441. of each function. For this example we could start with \code{block8}
  9442. because we know what is live at the beginning of the conclusion,
  9443. just \code{rax} and \code{rsp}. So the live-before set
  9444. for \code{block8} is $\{\ttm{rsp},\ttm{sum1}\}$.
  9445. %
  9446. Next we might try to analyze \code{block5} or \code{block7}, but
  9447. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9448. we are stuck.
  9449. The way out of this impasse comes from the realization that one can
  9450. perform liveness analysis starting with an empty live-after set to
  9451. compute an under-approximation of the live-before set. By
  9452. \emph{under-approximation}, we mean that the set only contains
  9453. variables that are really live, but it may be missing some. Next, the
  9454. under-approximations for each block can be improved by 1) updating the
  9455. live-after set for each block using the approximate live-before sets
  9456. from the other blocks and 2) perform liveness analysis again on each
  9457. block. In fact, by iterating this process, the under-approximations
  9458. eventually become the correct solutions!
  9459. %
  9460. This approach of iteratively analyzing a control-flow graph is
  9461. applicable to many static analysis problems and goes by the name
  9462. \emph{dataflow analysis}\index{dataflow analysis}. It was invented by
  9463. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  9464. Washington.
  9465. Let us apply this approach to the above example. We use the empty set
  9466. for the initial live-before set for each block. Let $m_0$ be the
  9467. following mapping from label names to sets of locations (variables and
  9468. registers).
  9469. \begin{center}
  9470. \begin{lstlisting}
  9471. mainstart: {}
  9472. block5: {}
  9473. block7: {}
  9474. block8: {}
  9475. \end{lstlisting}
  9476. \end{center}
  9477. Using the above live-before approximations, we determine the
  9478. live-after for each block and then apply liveness analysis to each
  9479. block. This produces our next approximation $m_1$ of the live-before
  9480. sets.
  9481. \begin{center}
  9482. \begin{lstlisting}
  9483. mainstart: {}
  9484. block5: {i2}
  9485. block7: {i2, sum1}
  9486. block8: {rsp, sum1}
  9487. \end{lstlisting}
  9488. \end{center}
  9489. For the second round, the live-after for \code{mainstart} is the
  9490. current live-before for \code{block5}, which is \code{\{i2\}}. So the
  9491. liveness analysis for \code{mainstart} computes the empty set. The
  9492. live-after for \code{block5} is the union of the live-before sets for
  9493. \code{block7} and \code{block8}, which is \code{\{i2 , rsp, sum1\}}.
  9494. So the liveness analysis for \code{block5} computes \code{\{i2 , rsp,
  9495. sum1\}}. The live-after for \code{block7} is the live-before for
  9496. \code{block5} (from the previous iteration), which is \code{\{i2\}}.
  9497. So the liveness analysis for \code{block7} remains \code{\{i2,
  9498. sum1\}}. Together these yield the following approximation $m_2$ of
  9499. the live-before sets.
  9500. \begin{center}
  9501. \begin{lstlisting}
  9502. mainstart: {}
  9503. block5: {i2, rsp, sum1}
  9504. block7: {i2, sum1}
  9505. block8: {rsp, sum1}
  9506. \end{lstlisting}
  9507. \end{center}
  9508. In the preceding iteration, only \code{block5} changed, so we can
  9509. limit our attention to \code{mainstart} and \code{block7}, the two
  9510. blocks that jump to \code{block5}. As a result, the live-before sets
  9511. for \code{mainstart} and \code{block7} are updated to include
  9512. \code{rsp}, yielding the following approximation $m_3$.
  9513. \begin{center}
  9514. \begin{lstlisting}
  9515. mainstart: {rsp}
  9516. block5: {i2, rsp, sum1}
  9517. block7: {i2, rsp, sum1}
  9518. block8: {rsp, sum1}
  9519. \end{lstlisting}
  9520. \end{center}
  9521. Because \code{block7} changed, we analyze \code{block5} once more, but
  9522. its live-before set remains \code{\{ i2, rsp, sum1 \}}. At this point
  9523. our approximations have converged, so $m_3$ is the solution.
  9524. This iteration process is guaranteed to converge to a solution by the
  9525. Kleene Fixed-Point Theorem, a general theorem about functions on
  9526. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9527. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9528. elements, a least element $\bot$ (pronounced bottom), and a join
  9529. operator $\sqcup$.\index{lattice}\index{bottom}\index{partial
  9530. ordering}\index{join}\footnote{Technically speaking, we will be
  9531. working with join semi-lattices.} When two elements are ordered $m_i
  9532. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  9533. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  9534. approximation than $m_i$. The bottom element $\bot$ represents the
  9535. complete lack of information, i.e., the worst approximation. The join
  9536. operator takes two lattice elements and combines their information,
  9537. i.e., it produces the least upper bound of the two.\index{least upper
  9538. bound}
  9539. A dataflow analysis typically involves two lattices: one lattice to
  9540. represent abstract states and another lattice that aggregates the
  9541. abstract states of all the blocks in the control-flow graph. For
  9542. liveness analysis, an abstract state is a set of locations. We form
  9543. the lattice $L$ by taking its elements to be sets of locations, the
  9544. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9545. set, and the join operator to be set union.
  9546. %
  9547. We form a second lattice $M$ by taking its elements to be mappings
  9548. from the block labels to sets of locations (elements of $L$). We
  9549. order the mappings point-wise, using the ordering of $L$. So given any
  9550. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9551. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9552. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9553. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  9554. We can think of one iteration of liveness analysis as being a function
  9555. $f$ on the lattice $M$. It takes a mapping as input and computes a new
  9556. mapping.
  9557. \[
  9558. f(m_i) = m_{i+1}
  9559. \]
  9560. Next let us think for a moment about what a final solution $m_s$
  9561. should look like. If we perform liveness analysis using the solution
  9562. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9563. solution should be a \emph{fixed point} of the function $f$.\index{fixed point}
  9564. \[
  9565. f(m_s) = m_s
  9566. \]
  9567. Furthermore, the solution should only include locations that are
  9568. forced to be there by performing liveness analysis on the program, so
  9569. the solution should be the \emph{least} fixed point.\index{least fixed point}
  9570. The Kleene Fixed-Point Theorem states that if a function $f$ is
  9571. monotone (better inputs produce better outputs), then the least fixed
  9572. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9573. chain} obtained by starting at $\bot$ and iterating $f$ as
  9574. follows.\index{Kleene Fixed-Point Theorem}
  9575. \[
  9576. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9577. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9578. \]
  9579. When a lattice contains only finitely-long ascending chains, then
  9580. every Kleene chain tops out at some fixed point after a number of
  9581. iterations of $f$. So that fixed point is also a least upper
  9582. bound of the chain.
  9583. \[
  9584. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9585. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9586. \]
  9587. The liveness analysis is indeed a monotone function and the lattice
  9588. $M$ only has finitely-long ascending chains because there are only a
  9589. finite number of variables and blocks in the program. Thus we are
  9590. guaranteed that iteratively applying liveness analysis to all blocks
  9591. in the program will eventually produce the least fixed point solution.
  9592. Next let us consider dataflow analysis in general and discuss the
  9593. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  9594. %
  9595. The algorithm has four parameters: the control-flow graph \code{G}, a
  9596. function \code{transfer} that applies the analysis to one block, the
  9597. \code{bottom} and \code{join} operator for the lattice of abstract
  9598. states. The algorithm begins by creating the bottom mapping,
  9599. represented by a hash table. It then pushes all of the nodes in the
  9600. control-flow graph onto the work list (a queue). The algorithm repeats
  9601. the \code{while} loop as long as there are items in the work list. In
  9602. each iteration, a node is popped from the work list and processed. The
  9603. \code{input} for the node is computed by taking the join of the
  9604. abstract states of all the predecessor nodes. The \code{transfer}
  9605. function is then applied to obtain the \code{output} abstract
  9606. state. If the output differs from the previous state for this block,
  9607. the mapping for this block is updated and its successor nodes are
  9608. pushed onto the work list.
  9609. \begin{figure}[tb]
  9610. \begin{lstlisting}
  9611. (define (analyze-dataflow G transfer bottom join)
  9612. (define mapping (make-hash))
  9613. (for ([v (in-vertices G)])
  9614. (dict-set! mapping v bottom))
  9615. (define worklist (make-queue))
  9616. (for ([v (in-vertices G)])
  9617. (enqueue! worklist v))
  9618. (define trans-G (transpose G))
  9619. (while (not (queue-empty? worklist))
  9620. (define node (dequeue! worklist))
  9621. (define input (for/fold ([state bottom])
  9622. ([pred (in-neighbors trans-G node)])
  9623. (join state (dict-ref mapping pred))))
  9624. (define output (transfer node input))
  9625. (cond [(not (equal? output (dict-ref mapping node)))
  9626. (dict-set! mapping node output)
  9627. (for ([v (in-neighbors G node)])
  9628. (enqueue! worklist v))]))
  9629. mapping)
  9630. \end{lstlisting}
  9631. \caption{Generic work list algorithm for dataflow analysis}
  9632. \label{fig:generic-dataflow}
  9633. \end{figure}
  9634. Having discussed the two complications that arise from adding support
  9635. for assignment and loops, we turn to discussing the one new compiler
  9636. pass and the significant changes to existing passes.
  9637. \section{Convert Assignments}
  9638. \label{sec:convert-assignments}
  9639. Recall that in Section~\ref{sec:assignment-scoping} we learned that
  9640. the combination of assignments and lexically-scoped functions requires
  9641. that we box those variables that are both assigned-to and that appear
  9642. free inside a \code{lambda}. The purpose of the
  9643. \code{convert-assignments} pass is to carry out that transformation.
  9644. We recommend placing this pass after \code{uniquify} but before
  9645. \code{reveal-functions}.
  9646. Consider again the first example from
  9647. Section~\ref{sec:assignment-scoping}:
  9648. \begin{lstlisting}
  9649. (let ([x 0])
  9650. (let ([y 0])
  9651. (let ([z 20])
  9652. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  9653. (begin
  9654. (set! x 10)
  9655. (set! y 12)
  9656. (f y))))))
  9657. \end{lstlisting}
  9658. The variables \code{x} and \code{y} are assigned-to. The variables
  9659. \code{x} and \code{z} occur free inside the \code{lambda}. Thus,
  9660. variable \code{x} needs to be boxed but not \code{y} and \code{z}.
  9661. The boxing of \code{x} consists of three transformations: initialize
  9662. \code{x} with a vector, replace reads from \code{x} with
  9663. \code{vector-ref}'s, and replace each \code{set!} on \code{x} with a
  9664. \code{vector-set!}. The output of \code{convert-assignments} for this
  9665. example is as follows.
  9666. \begin{lstlisting}
  9667. (define (main) : Integer
  9668. (let ([x0 (vector 0)])
  9669. (let ([y1 0])
  9670. (let ([z2 20])
  9671. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  9672. (+ a3 (+ (vector-ref x0 0) z2)))])
  9673. (begin
  9674. (vector-set! x0 0 10)
  9675. (set! y1 12)
  9676. (f4 y1)))))))
  9677. \end{lstlisting}
  9678. \paragraph{Assigned \& Free}
  9679. We recommend defining an auxiliary function named
  9680. \code{assigned\&free} that takes an expression and simultaneously
  9681. computes 1) a set of assigned variables $A$, 2) a set $F$ of variables
  9682. that occur free within lambda's, and 3) a new version of the
  9683. expression that records which bound variables occurred in the
  9684. intersection of $A$ and $F$. You can use the struct
  9685. \code{AssignedFree} to do this. Consider the case for
  9686. $\LET{x}{\itm{rhs}}{\itm{body}}$. Suppose the the recursive call on
  9687. $\itm{rhs}$ produces $\itm{rhs}'$, $A_r$, and $F_r$ and the recursive
  9688. call on the $\itm{body}$ produces $\itm{body}'$, $A_b$, and $F_b$. If
  9689. $x$ is in $A_b\cap F_b$, then transforms the \code{Let} as follows.
  9690. \begin{lstlisting}
  9691. (Let |$x$| |$rhs$| |$body$|)
  9692. |$\Rightarrow$|
  9693. (Let (AssignedFree |$x$|) |$rhs'$| |$body'$|)
  9694. \end{lstlisting}
  9695. If $x$ is not in $A_b\cap F_b$ then omit the use of \code{AssignedFree}.
  9696. The set of assigned variables for this \code{Let} is
  9697. $A_r \cup (A_b - \{x\})$
  9698. and the set of variables free in lambda's is
  9699. $F_r \cup (F_b - \{x\})$.
  9700. The case for $\SETBANG{x}{\itm{rhs}}$ is straightforward but
  9701. important. Recursively process \itm{rhs} to obtain \itm{rhs'}, $A_r$,
  9702. and $F_r$. The result is $\SETBANG{x}{\itm{rhs'}}$, $\{x\} \cup A_r$,
  9703. and $F_r$.
  9704. The case for $\LAMBDA{\itm{params}}{T}{\itm{body}}$ is a bit more
  9705. involved. Let \itm{body'}, $A_b$, and $F_b$ be the result of
  9706. recursively processing \itm{body}. Wrap each of parameter that occurs
  9707. in $A_b \cap F_b$ with \code{AssignedFree} to produce \itm{params'}.
  9708. Let $P$ be the set of parameter names in \itm{params}. The result is
  9709. $\LAMBDA{\itm{params'}}{T}{\itm{body'}}$, $A_b - P$, and $(F_b \cup
  9710. \mathrm{FV}(\itm{body})) - P$, where $\mathrm{FV}$ computes the free
  9711. variables of an expression (see Chapter~\ref{ch:lambdas}).
  9712. \paragraph{Convert Assignments}
  9713. Next we discuss the \code{convert-assignment} pass with its auxiliary
  9714. functions for expressions and definitions. The function for
  9715. expressions, \code{cnvt-assign-exp}, should take an expression and a
  9716. set of assigned-and-free variables (obtained from the result of
  9717. \code{assigned\&free}. In the case for $\VAR{x}$, if $x$ is
  9718. assigned-and-free, then unbox it by translating $\VAR{x}$ to a
  9719. \code{vector-ref}.
  9720. \begin{lstlisting}
  9721. (Var |$x$|)
  9722. |$\Rightarrow$|
  9723. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  9724. \end{lstlisting}
  9725. %
  9726. In the case for $\LET{\LP\code{AssignedFree}\,
  9727. x\RP}{\itm{rhs}}{\itm{body}}$, recursively process \itm{rhs} to
  9728. obtain \itm{rhs'}. Next, recursively process \itm{body} to obtain
  9729. \itm{body'} but with $x$ added to the set of assigned-and-free
  9730. variables. Translate the let-expression as follows to bind $x$ to a
  9731. boxed value.
  9732. \begin{lstlisting}
  9733. (Let (AssignedFree |$x$|) |$rhs$| |$body$|)
  9734. |$\Rightarrow$|
  9735. (Let |$x$| (Prim 'vector (list |$rhs'$|)) |$body'$|)
  9736. \end{lstlisting}
  9737. %
  9738. In the case for $\SETBANG{x}{\itm{rhs}}$, recursively process
  9739. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in the assigned-and-free
  9740. variables, translate the \code{set!} into a \code{vector-set!}
  9741. as follows.
  9742. \begin{lstlisting}
  9743. (SetBang |$x$| |$\itm{rhs}$|)
  9744. |$\Rightarrow$|
  9745. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  9746. \end{lstlisting}
  9747. %
  9748. The case for \code{Lambda} is non-trivial, but it is similar to the
  9749. case for function definitions, which we discuss next.
  9750. The auxiliary function for definitions, \code{cnvt-assign-def},
  9751. applies assignment conversion to function definitions.
  9752. We translate a function definition as follows.
  9753. \begin{lstlisting}
  9754. (Def |$f$| |$\itm{params}$| |$T$| |$\itm{info}$| |$\itm{body_1}$|)
  9755. |$\Rightarrow$|
  9756. (Def |$f$| |$\itm{params'}$| |$T$| |$\itm{info}$| |$\itm{body_4}$|)
  9757. \end{lstlisting}
  9758. So it remains to explain \itm{params'} and $\itm{body}_4$.
  9759. Let \itm{body_2}, $A_b$, and $F_b$ be the result of
  9760. \code{assigned\&free} on $\itm{body_1}$.
  9761. Let $P$ be the parameter names in \itm{params}.
  9762. We then apply \code{cnvt-assign-exp} to $\itm{body_2}$ to
  9763. obtain \itm{body_3}, passing $A_b \cap F_b \cap P$
  9764. as the set of assigned-and-free variables.
  9765. Finally, we obtain \itm{body_4} by wrapping \itm{body_3}
  9766. in a sequence of let-expressions that box the parameters
  9767. that are in $A_b \cap F_b$.
  9768. %
  9769. Regarding \itm{params'}, change the names of the parameters that are
  9770. in $A_b \cap F_b$ to maintain uniqueness (and so the let-bound
  9771. variables can retain the original names). Recall the second example in
  9772. Section~\ref{sec:assignment-scoping} involving a counter
  9773. abstraction. The following is the output of assignment version for
  9774. function \code{f}.
  9775. \begin{lstlisting}
  9776. (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  9777. (vector
  9778. (lambda: () : Integer x1)
  9779. (lambda: () : Void (set! x1 (+ 1 x1)))))
  9780. |$\Rightarrow$|
  9781. (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  9782. (let ([x1 (vector param_x1)])
  9783. (vector (lambda: () : Integer (vector-ref x1 0))
  9784. (lambda: () : Void
  9785. (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  9786. \end{lstlisting}
  9787. \section{Remove Complex Operands}
  9788. \label{sec:rco-loop}
  9789. The three new language forms, \code{while}, \code{set!}, and
  9790. \code{begin} are all complex expressions and their subexpressions are
  9791. allowed to be complex. Figure~\ref{fig:r4-anf-syntax} defines the
  9792. output language $R_4^{\dagger}$ of this pass.
  9793. \begin{figure}[tp]
  9794. \centering
  9795. \fbox{
  9796. \begin{minipage}{0.96\textwidth}
  9797. \small
  9798. \[
  9799. \begin{array}{rcl}
  9800. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  9801. \mid \VOID{} } \\
  9802. \Exp &::=& \ldots \mid \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  9803. &\mid& \WHILE{\Exp}{\Exp} \mid \SETBANG{\Var}{\Exp}
  9804. \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  9805. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  9806. R^{\dagger}_8 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  9807. \end{array}
  9808. \]
  9809. \end{minipage}
  9810. }
  9811. \caption{$R_8^{\dagger}$ is $R_8$ in administrative normal form (ANF).}
  9812. \label{fig:r8-anf-syntax}
  9813. \end{figure}
  9814. As usual, when a complex expression appears in a grammar position that
  9815. needs to be atomic, such as the argument of a primitive operator, we
  9816. must introduce a temporary variable and bind it to the complex
  9817. expression. This approach applies, unchanged, to handle the new
  9818. language forms. For example, in the following code there are two
  9819. \code{begin} expressions appearing as arguments to \code{+}. The
  9820. output of \code{rco-exp} is shown below, in which the \code{begin}
  9821. expressions have been bound to temporary variables. Recall that
  9822. \code{let} expressions in $R_8^{\dagger}$ are allowed to have
  9823. arbitrary expressions in their right-hand-side expression, so it is
  9824. fine to place \code{begin} there.
  9825. \begin{lstlisting}
  9826. (let ([x0 10])
  9827. (let ([y1 0])
  9828. (+ (+ (begin (set! y1 (read)) x0)
  9829. (begin (set! x0 (read)) y1))
  9830. x0)))
  9831. |$\Rightarrow$|
  9832. (let ([x0 10])
  9833. (let ([y1 0])
  9834. (let ([tmp2 (begin (set! y1 (read)) x0)])
  9835. (let ([tmp3 (begin (set! x0 (read)) y1)])
  9836. (let ([tmp4 (+ tmp2 tmp3)])
  9837. (+ tmp4 x0))))))
  9838. \end{lstlisting}
  9839. \section{Explicate Control and $C_7$}
  9840. \label{sec:explicate-loop}
  9841. Recall that in the \code{explicate-control} pass we define one helper
  9842. function for each kind of position in the program. For the $R_1$
  9843. language of integers and variables we needed kinds of positions:
  9844. assignment and tail. The \code{if} expressions of $R_2$ introduced
  9845. predicate positions. For $R_8$, the \code{begin} expression introduces
  9846. yet another kind of position: effect position. Except for the last
  9847. subexpression, the subexpressions inside a \code{begin} are evaluated
  9848. only for their effect. Their result values are discarded. We can
  9849. generate better code by taking this fact into account.
  9850. The output language of \code{explicate-control} is $C_7$
  9851. (Figure~\ref{fig:c7-syntax}), which is nearly identical to $C_4$. The
  9852. only difference is that \code{Call}, \code{vector-set!}, and
  9853. \code{read} may also appear as statements.
  9854. \begin{figure}[tp]
  9855. \fbox{
  9856. \begin{minipage}{0.96\textwidth}
  9857. \small
  9858. \[
  9859. \begin{array}{lcl}
  9860. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  9861. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  9862. &\mid& \CALL{\Atm}{\LP\Atm\ldots\RP} \mid \READ{}\\
  9863. &\mid& \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP \\
  9864. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  9865. C_7 & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  9866. \end{array}
  9867. \]
  9868. \end{minipage}
  9869. }
  9870. \caption{The abstract syntax of $C_7$, extending $C_4$ (Figure~\ref{fig:c4-syntax}).}
  9871. \label{fig:c7-syntax}
  9872. \end{figure}
  9873. The new auxiliary function \code{explicate-effect} takes an expression
  9874. (in an effect position) and a promise of a continuation block. The
  9875. function returns a promise for a $\Tail$ that includes the generated
  9876. code for the input expression followed by the continuation block. If
  9877. the expression is obviously pure, that is, never causes side effects,
  9878. then the expression can be removed, so the result is just the
  9879. continuation block.
  9880. %
  9881. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  9882. case. First, you will need a fresh label $\itm{loop}$ for the top of
  9883. the loop. Recursively process the \itm{body} (in effect position)
  9884. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  9885. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  9886. \itm{body'} as the then-branch and the continuation block as the
  9887. else-branch. The result should be added to the control-flow graph with
  9888. the label \itm{loop}. The result for the whole \code{while} loop is a
  9889. \code{goto} to the \itm{loop} label. Note that the loop should only be
  9890. added to the control-flow graph if the loop is indeed used, which can
  9891. be accomplished using \code{delay}.
  9892. The auxiliary functions for tail, assignment, and predicate positions
  9893. need to be updated. The three new language forms, \code{while},
  9894. \code{set!}, and \code{begin}, can appear in assignment and tail
  9895. positions. Only \code{begin} may appear in predicate positions; the
  9896. other two have result type \code{Void}.
  9897. \section{Select Instructions}
  9898. \label{sec:select-instructions-loop}
  9899. Only three small additions are needed in the
  9900. \code{select-instructions} pass to handle the changes to $C_7$. That
  9901. is, \code{Call}, \code{read}, and \code{vector-set!} may now appear as
  9902. stand-alone statements instead of only appearing on the right-hand
  9903. side of an assignment statement. The code generation is nearly
  9904. identical; just leave off the instruction for moving the result into
  9905. the left-hand side.
  9906. \section{Register Allocation}
  9907. \label{sec:register-allocation-loop}
  9908. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  9909. loops in $R_8$ means that the control-flow graphs may contain cycles,
  9910. which complicates the liveness analysis needed for register
  9911. allocation.
  9912. \subsection{Liveness Analysis}
  9913. \label{sec:liveness-analysis-r8}
  9914. We recommend using the generic \code{analyze-dataflow} function that
  9915. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  9916. perform liveness analysis, replacing the code in
  9917. \code{uncover-live-CFG} that processed the basic blocks in topological
  9918. order (Section~\ref{sec:liveness-analysis-r2}).
  9919. The \code{analyze-dataflow} function has four parameters.
  9920. \begin{enumerate}
  9921. \item The first parameter \code{G} should be a directed graph from the
  9922. \code{racket/graph} package (see the sidebar in
  9923. Section~\ref{sec:build-interference}) that represents the
  9924. control-flow graph.
  9925. \item The second parameter \code{transfer} is a function that applies
  9926. liveness analysis to a basic block. It takes two parameters: the
  9927. label for the block to analyze and the live-after set for that
  9928. block. The transfer function should return the live-before set for
  9929. the block. Also, as a side-effect, it should update the block's
  9930. $\itm{info}$ with the liveness information for each instruction. To
  9931. implement the \code{transfer} function, you should be able to reuse
  9932. the code you already have for analyzing basic blocks.
  9933. \item The third and fourth parameters of \code{analyze-dataflow} are
  9934. \code{bottom} and \code{join} for the lattice of abstract states,
  9935. i.e. sets of locations. The bottom of the lattice is the empty set
  9936. \code{(set)} and the join operator is \code{set-union}.
  9937. \end{enumerate}
  9938. \begin{figure}[p]
  9939. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9940. \node (R4) at (0,2) {\large $R_8$};
  9941. \node (R4-2) at (3,2) {\large $R_8$};
  9942. \node (R4-3) at (6,2) {\large $R_8$};
  9943. \node (R4-4) at (9,2) {\large $R'_8$};
  9944. \node (F1-1) at (12,0) {\large $R'_8$};
  9945. \node (F1-2) at (9,0) {\large $R'_8$};
  9946. \node (F1-3) at (6,0) {\large $R'_8$};
  9947. \node (F1-4) at (3,0) {\large $R'_8$};
  9948. \node (F1-5) at (0,0) {\large $R'_8$};
  9949. \node (C3-2) at (3,-2) {\large $C_3$};
  9950. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  9951. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  9952. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  9953. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  9954. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  9955. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  9956. %% \path[->,bend left=15] (R4) edge [above] node
  9957. %% {\ttfamily\footnotesize type-check} (R4-2);
  9958. \path[->,bend left=15] (R4) edge [above] node
  9959. {\ttfamily\footnotesize shrink} (R4-2);
  9960. \path[->,bend left=15] (R4-2) edge [above] node
  9961. {\ttfamily\footnotesize uniquify} (R4-3);
  9962. \path[->,bend left=15] (R4-3) edge [above] node
  9963. {\ttfamily\footnotesize reveal-functions} (R4-4);
  9964. \path[->,bend left=15] (R4-4) edge [right] node
  9965. {\ttfamily\footnotesize convert-assignments} (F1-1);
  9966. \path[->,bend left=15] (F1-1) edge [below] node
  9967. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  9968. \path[->,bend right=15] (F1-2) edge [above] node
  9969. {\ttfamily\footnotesize limit-fun.} (F1-3);
  9970. \path[->,bend right=15] (F1-3) edge [above] node
  9971. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9972. \path[->,bend right=15] (F1-4) edge [above] node
  9973. {\ttfamily\footnotesize remove-complex.} (F1-5);
  9974. \path[->,bend right=15] (F1-5) edge [right] node
  9975. {\ttfamily\footnotesize explicate-control} (C3-2);
  9976. \path[->,bend left=15] (C3-2) edge [left] node
  9977. {\ttfamily\footnotesize select-instr.} (x86-2);
  9978. \path[->,bend right=15] (x86-2) edge [left] node
  9979. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  9980. \path[->,bend right=15] (x86-2-1) edge [below] node
  9981. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  9982. \path[->,bend right=15] (x86-2-2) edge [left] node
  9983. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  9984. \path[->,bend left=15] (x86-3) edge [above] node
  9985. {\ttfamily\footnotesize patch-instr.} (x86-4);
  9986. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  9987. \end{tikzpicture}
  9988. \caption{Diagram of the passes for $R_8$ (loops and assignment).}
  9989. \label{fig:R8-passes}
  9990. \end{figure}
  9991. Figure~\ref{fig:R8-passes} provides an overview of all the passes needed
  9992. for the compilation of $R_8$.
  9993. % TODO: challenge assignment
  9994. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9995. \chapter{Gradual Typing}
  9996. \label{ch:gradual-typing}
  9997. \index{gradual typing}
  9998. This chapter studies a language, $R_9$, in which the programmer can
  9999. choose between static and dynamic type checking for different regions
  10000. of a program, thereby mixing the statically typed $R_8$ language with
  10001. the dynamically typed $R_7$. There are several approaches to mixing
  10002. static and dynamic typing, including multi-language
  10003. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  10004. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  10005. we focus on \emph{gradual typing}\index{gradual typing}, in which the
  10006. programmer controls the amount of static versus dynamic checking by
  10007. adding or removing type annotations on parameters and
  10008. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  10009. %
  10010. The concrete syntax of $R_9$ is defined in
  10011. Figure~\ref{fig:r9-concrete-syntax} and its abstract syntax is defined
  10012. in Figure~\ref{fig:r9-syntax}. The main syntactic difference between
  10013. $R_8$ and $R_9$ is the additional \itm{param} and \itm{ret}
  10014. non-terminals that make type annotations optional. The return types
  10015. are not optional in the abstract syntax; the parser fills in
  10016. \code{Any} when the return type is not specified in the concrete
  10017. syntax.
  10018. \begin{figure}[tp]
  10019. \centering
  10020. \fbox{
  10021. \begin{minipage}{0.96\textwidth}
  10022. \small
  10023. \[
  10024. \begin{array}{lcl}
  10025. \itm{param} &::=& \Var \mid \LS\Var \key{:} \Type\RS \\
  10026. \itm{ret} &::=& \epsilon \mid \key{:} \Type \\
  10027. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  10028. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  10029. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  10030. &\mid& \gray{\key{\#t} \mid \key{\#f}
  10031. \mid (\key{and}\;\Exp\;\Exp)
  10032. \mid (\key{or}\;\Exp\;\Exp)
  10033. \mid (\key{not}\;\Exp) } \\
  10034. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  10035. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  10036. (\key{vector-ref}\;\Exp\;\Int)} \\
  10037. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  10038. \mid (\Exp \; \Exp\ldots) } \\
  10039. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  10040. \mid \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  10041. &\mid& \gray{ \CSETBANG{\Var}{\Exp}
  10042. \mid \CBEGIN{\Exp\ldots}{\Exp}
  10043. \mid \CWHILE{\Exp}{\Exp} } \\
  10044. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  10045. R_9 &::=& \gray{\Def\ldots \; \Exp}
  10046. \end{array}
  10047. \]
  10048. \end{minipage}
  10049. }
  10050. \caption{The concrete syntax of $R_9$, extending $R_8$ (Figure~\ref{fig:r8-concrete-syntax}).}
  10051. \label{fig:r9-concrete-syntax}
  10052. \end{figure}
  10053. \begin{figure}[tp]
  10054. \centering
  10055. \fbox{
  10056. \begin{minipage}{0.96\textwidth}
  10057. \small
  10058. \[
  10059. \begin{array}{lcl}
  10060. \itm{param} &::=& \Var \mid \LS\Var \key{:} \Type\RS \\
  10061. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  10062. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  10063. &\mid& \gray{ \BOOL{\itm{bool}}
  10064. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  10065. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  10066. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  10067. &\mid& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  10068. &\mid& \gray{ \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  10069. &\mid& \gray{ \WHILE{\Exp}{\Exp} } \\
  10070. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  10071. R_9 &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  10072. \end{array}
  10073. \]
  10074. \end{minipage}
  10075. }
  10076. \caption{The abstract syntax of $R_9$, extending $R_8$ (Figure~\ref{fig:r8-syntax}).}
  10077. \label{fig:r9-syntax}
  10078. \end{figure}
  10079. Both the type checker and the interpreter for $R_9$ require some
  10080. interesting changes to enable gradual typing, which we discuss in the
  10081. next two sections while revisiting the \code{map-vec} example from
  10082. Chapter~\ref{ch:functions}. In Figure~\ref{fig:gradual-map-vec} we
  10083. present the example again but this time we leave off the type
  10084. annotations from the \code{add1} function.
  10085. \begin{figure}[btp]
  10086. % gradual_test_9.rkt
  10087. \begin{lstlisting}
  10088. (define (map-vec [f : (Integer -> Integer)]
  10089. [v : (Vector Integer Integer)])
  10090. : (Vector Integer Integer)
  10091. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10092. (define (add1 x) (+ x 1))
  10093. (vector-ref (map-vec add1 (vector 0 41)) 1)
  10094. \end{lstlisting}
  10095. \caption{A partially-typed version of the \code{map-vec} example.}
  10096. \label{fig:gradual-map-vec}
  10097. \end{figure}
  10098. \section{Type Checking $R_9$, Casts, and $R'_9$}
  10099. \label{sec:gradual-type-check}
  10100. The type checker for $R_9$ uses the \code{Any} type for missing
  10101. parameter and return types. For example, the \code{x} parameter of
  10102. \code{add1} in Figure~\ref{fig:gradual-map-vec} is given the type
  10103. \code{Any} and the return type of \code{add1} is \code{Any}. Next
  10104. consider the \code{+} operator inside \code{add1}. It expects both
  10105. arguments to have type \code{Integer}, but its first argument \code{x}
  10106. has type \code{Any}. In a gradually typed language, such differences
  10107. are allowed so long as the types are \emph{consistent}, that is, they
  10108. are equal except in places where there is an \code{Any} type. The type
  10109. \code{Any} is consistent with every other type.
  10110. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  10111. \begin{figure}[tbp]
  10112. \begin{lstlisting}
  10113. (define/public (consistent? t1 t2)
  10114. (match* (t1 t2)
  10115. [('Integer 'Integer) #t]
  10116. [('Boolean 'Boolean) #t]
  10117. [('Void 'Void) #t]
  10118. [('Any t2) #t]
  10119. [(t1 'Any) #t]
  10120. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10121. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  10122. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10123. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  10124. (consistent? rt1 rt2))]
  10125. [(other wise) #f]))
  10126. \end{lstlisting}
  10127. \caption{The consistency predicate on types, a method in
  10128. \code{type-check-gradual-class}.}
  10129. \label{fig:consistent}
  10130. \end{figure}
  10131. Returning to the \code{map-vec} example of
  10132. Figure~\ref{fig:gradual-map-vec}, the \code{add1} function has type
  10133. \code{(Any -> Any)} but parameter \code{f} of \code{map-vec} has type
  10134. \code{(Integer -> Integer)}. The type checker for $R_9$ allows this
  10135. because the two types are consistent. In particular, \code{->} is
  10136. equal to \code{->} and because \code{Any} is consistent with
  10137. \code{Integer}.
  10138. Next consider a program with an error, such as applying the
  10139. \code{map-vec} to a function that sometimes returns a Boolean, as
  10140. shown in Figure~\ref{fig:map-vec-maybe-add1}. The type checker for
  10141. $R_9$ accepts this program because the type of \code{maybe-add1} is
  10142. consistent with the type of parameter \code{f} of \code{map-vec}, that
  10143. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  10144. Integer)}. One might say that a gradual type checker is optimistic
  10145. in that it accepts programs that might execute without a runtime type
  10146. error.
  10147. %
  10148. Unfortunately, running this program with input \code{1} triggers an
  10149. error when the \code{maybe-add1} function returns \code{\#t}. $R_9$
  10150. performs checking at runtime to ensure the integrity of the static
  10151. types, such as the \code{(Integer -> Integer)} annotation on parameter
  10152. \code{f} of \code{map-vec}. This runtime checking is carried out by a
  10153. new \code{Cast} form that is inserted by the type checker. Thus, the
  10154. output of the type checker is a program in the $R'_9$ language, which
  10155. adds \code{Cast} to $R_8$, as shown in
  10156. Figure~\ref{fig:r9-prime-syntax}.
  10157. \begin{figure}[tp]
  10158. \centering
  10159. \fbox{
  10160. \begin{minipage}{0.96\textwidth}
  10161. \small
  10162. \[
  10163. \begin{array}{lcl}
  10164. \Exp &::=& \ldots \mid \CAST{\Exp}{\Type}{\Type} \\
  10165. R'_9 &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  10166. \end{array}
  10167. \]
  10168. \end{minipage}
  10169. }
  10170. \caption{The abstract syntax of $R'_9$, extending $R_8$ (Figure~\ref{fig:r8-syntax}).}
  10171. \label{fig:r9-prime-syntax}
  10172. \end{figure}
  10173. \begin{figure}[tbp]
  10174. \begin{lstlisting}
  10175. (define (map-vec [f : (Integer -> Integer)]
  10176. [v : (Vector Integer Integer)])
  10177. : (Vector Integer Integer)
  10178. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10179. (define (add1 x) (+ x 1))
  10180. (define (true) #t)
  10181. (define (maybe-add1 x) (if (eq? 0 (read)) (add1 x) (true)))
  10182. (vector-ref (map-vec maybe-add1 (vector 0 41)) 0)
  10183. \end{lstlisting}
  10184. \caption{A variant of the \code{map-vec} example with an error.}
  10185. \label{fig:map-vec-maybe-add1}
  10186. \end{figure}
  10187. Figure~\ref{fig:map-vec-cast} shows the output of the type checker for
  10188. \code{map-vec} and \code{maybe-add1}. The idea is that \code{Cast} is
  10189. inserted every time the type checker sees two types that are
  10190. consistent but not equal. In the \code{add1} function, \code{x} is
  10191. cast to \code{Integer} and the result of the \code{+} is cast to
  10192. \code{Any}. In the call to \code{map-vec}, the \code{add1} argument
  10193. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  10194. \begin{figure}[btp]
  10195. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10196. (define (map-vec [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  10197. : (Vector Integer Integer)
  10198. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10199. (define (add1 [x : Any]) : Any
  10200. (cast (+ (cast x Any Integer) 1) Integer Any))
  10201. (define (true) : Any (cast #t Boolean Any))
  10202. (define (maybe-add1 [x : Any]) : Any
  10203. (if (eq? 0 (read)) (add1 x) (true)))
  10204. (vector-ref (map-vec (cast maybe-add1 (Any -> Any) (Integer -> Integer))
  10205. (vector 0 41)) 0)
  10206. \end{lstlisting}
  10207. \caption{Output of type checking \code{map-vec}
  10208. and \code{maybe-add1}.}
  10209. \label{fig:map-vec-cast}
  10210. \end{figure}
  10211. The type checker for $R_9$ is defined in
  10212. Figures~\ref{fig:type-check-R9-1}, \ref{fig:type-check-R9-2},
  10213. and \ref{fig:type-check-R9-3}.
  10214. \begin{figure}[tbp]
  10215. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10216. (define type-check-gradual-class
  10217. (class type-check-R8-class
  10218. (super-new)
  10219. (inherit operator-types type-predicates)
  10220. (define/override (type-check-exp env)
  10221. (lambda (e)
  10222. (define recur (type-check-exp env))
  10223. (match e
  10224. [(Prim 'vector-length (list e1))
  10225. (define-values (e1^ t) (recur e1))
  10226. (match t
  10227. [`(Vector ,ts ...)
  10228. (values (Prim 'vector-length (list e1^)) 'Integer)]
  10229. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  10230. [(Prim 'vector-ref (list e1 e2))
  10231. (define-values (e1^ t1) (recur e1))
  10232. (define-values (e2^ t2) (recur e2))
  10233. (check-consistent? t2 'Integer e)
  10234. (match t1
  10235. [`(Vector ,ts ...)
  10236. (match e2^
  10237. [(Int i)
  10238. (unless (and (0 . <= . i) (i . < . (length ts)))
  10239. (error 'type-check "invalid index ~a in ~a" i e))
  10240. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10241. [else (define e1^^ (make-cast e1^ t1 'Any))
  10242. (define e2^^ (make-cast e2^ t2 'Integer))
  10243. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  10244. ['Any
  10245. (define e2^^ (make-cast e2^ t2 'Integer))
  10246. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  10247. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  10248. [(Prim 'vector-set! (list e1 e2 e3) )
  10249. (define-values (e1^ t1) (recur e1))
  10250. (define-values (e2^ t2) (recur e2))
  10251. (define-values (e3^ t3) (recur e3))
  10252. (check-consistent? t2 'Integer e)
  10253. (match t1
  10254. [`(Vector ,ts ...)
  10255. (match e2^
  10256. [(Int i)
  10257. (unless (and (0 . <= . i) (i . < . (length ts)))
  10258. (error 'type-check "invalid index ~a in ~a" i e))
  10259. (check-consistent? (list-ref ts i) t3 e)
  10260. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  10261. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  10262. [else
  10263. (define e1^^ (make-cast e1^ t1 'Any))
  10264. (define e2^^ (make-cast e2^ t2 'Integer))
  10265. (define e3^^ (make-cast e3^ t3 'Any))
  10266. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  10267. ['Any
  10268. (define e2^^ (make-cast e2^ t2 'Integer))
  10269. (define e3^^ (make-cast e3^ t3 'Any))
  10270. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  10271. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  10272. \end{lstlisting}
  10273. \caption{Type checker for the $R_9$ language, part 1.}
  10274. \label{fig:type-check-R9-1}
  10275. \end{figure}
  10276. \begin{figure}[tbp]
  10277. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10278. [(Prim 'eq? (list e1 e2))
  10279. (define-values (e1^ t1) (recur e1))
  10280. (define-values (e2^ t2) (recur e2))
  10281. (check-consistent? t1 t2 e)
  10282. (define T (meet t1 t2))
  10283. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  10284. 'Boolean)]
  10285. [(Prim 'not (list e1))
  10286. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  10287. (Bool #t) (Bool #f)))]
  10288. [(Prim 'and (list e1 e2))
  10289. (recur (If e1 e2 (Bool #f)))]
  10290. [(Prim 'or (list e1 e2))
  10291. (define tmp (gensym 'tmp))
  10292. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  10293. [(Prim op es)
  10294. #:when (not (set-member? explicit-prim-ops op))
  10295. (define-values (new-es ts)
  10296. (for/lists (exprs types) ([e es])
  10297. (recur e)))
  10298. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  10299. (values (Prim op new-es^) t-ret)]
  10300. [(If e1 e2 e3)
  10301. (define-values (e1^ T1) (recur e1))
  10302. (define-values (e2^ T2) (recur e2))
  10303. (define-values (e3^ T3) (recur e3))
  10304. (check-consistent? T2 T3 e)
  10305. (match T1
  10306. ['Boolean
  10307. (define Tif (join T2 T3))
  10308. (values (If e1^ (make-cast e2^ T2 Tif)
  10309. (make-cast e3^ T3 Tif)) Tif)]
  10310. ['Any
  10311. (define Tif (meet T2 T3))
  10312. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  10313. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  10314. Tif)]
  10315. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  10316. [(HasType e1 T)
  10317. (define-values (e1^ T1) (recur e1))
  10318. (check-consistent? T1 T)
  10319. (values (make-cast e1^ T1 T) T)]
  10320. [(SetBang x e1)
  10321. (define-values (e1^ T1) (recur e1))
  10322. (define varT (dict-ref env x))
  10323. (check-consistent? T1 varT e)
  10324. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  10325. [(WhileLoop e1 e2)
  10326. (define-values (e1^ T1) (recur e1))
  10327. (check-consistent? T1 'Boolean e)
  10328. (define-values (e2^ T2) ((type-check-exp env) e2))
  10329. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  10330. \end{lstlisting}
  10331. \caption{Type checker for the $R_9$ language, part 2.}
  10332. \label{fig:type-check-R9-2}
  10333. \end{figure}
  10334. \begin{figure}[tbp]
  10335. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10336. [(Apply e1 e2s)
  10337. (define-values (e1^ T1) (recur e1))
  10338. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  10339. (match T1
  10340. [`(,T1ps ... -> ,T1rt)
  10341. (for ([T2 T2s] [Tp T1ps])
  10342. (check-consistent? T2 Tp e))
  10343. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  10344. (make-cast e2 src tgt)))
  10345. (values (Apply e1^ e2s^^) T1rt)]
  10346. [`Any
  10347. (define e1^^ (make-cast e1^ 'Any
  10348. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  10349. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  10350. (make-cast e2 src 'Any)))
  10351. (values (Apply e1^^ e2s^^) 'Any)]
  10352. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  10353. [(Lambda params Tr e1)
  10354. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  10355. (match p
  10356. [`[,x : ,T] (values x T)]
  10357. [(? symbol? x) (values x 'Any)])))
  10358. (define-values (e1^ T1)
  10359. ((type-check-exp (append (map cons xs Ts) env)) e1))
  10360. (check-consistent? Tr T1 e)
  10361. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  10362. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  10363. [else ((super type-check-exp env) e)]
  10364. )))
  10365. \end{lstlisting}
  10366. \caption{Type checker for the $R_9$ language, part 3.}
  10367. \label{fig:type-check-R9-3}
  10368. \end{figure}
  10369. \begin{figure}[tbp]
  10370. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10371. (define/public (join t1 t2)
  10372. (match* (t1 t2)
  10373. [('Integer 'Integer) 'Integer]
  10374. [('Boolean 'Boolean) 'Boolean]
  10375. [('Void 'Void) 'Void]
  10376. [('Any t2) t2]
  10377. [(t1 'Any) t1]
  10378. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10379. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  10380. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10381. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  10382. -> ,(join rt1 rt2))]))
  10383. (define/public (meet t1 t2)
  10384. (match* (t1 t2)
  10385. [('Integer 'Integer) 'Integer]
  10386. [('Boolean 'Boolean) 'Boolean]
  10387. [('Void 'Void) 'Void]
  10388. [('Any t2) 'Any]
  10389. [(t1 'Any) 'Any]
  10390. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10391. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  10392. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10393. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  10394. -> ,(meet rt1 rt2))]))
  10395. (define/public (make-cast e src tgt)
  10396. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  10397. (define/public (check-consistent? t1 t2 e)
  10398. (unless (consistent? t1 t2)
  10399. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  10400. (define/override (type-check-op op arg-types args e)
  10401. (match (dict-ref (operator-types) op)
  10402. [`(,param-types . ,return-type)
  10403. (for ([at arg-types] [pt param-types])
  10404. (check-consistent? at pt e))
  10405. (values return-type
  10406. (for/list ([e args] [s arg-types] [t param-types])
  10407. (make-cast e s t)))]
  10408. [else (error 'type-check-op "unrecognized ~a" op)]))
  10409. (define explicit-prim-ops
  10410. (set-union
  10411. (type-predicates)
  10412. (set 'procedure-arity 'eq?
  10413. 'vector 'vector-length 'vector-ref 'vector-set!
  10414. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  10415. (define/override (fun-def-type d)
  10416. (match d
  10417. [(Def f params rt info body)
  10418. (define ps
  10419. (for/list ([p params])
  10420. (match p
  10421. [`[,x : ,T] T]
  10422. [(? symbol?) 'Any]
  10423. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  10424. `(,@ps -> ,rt)]
  10425. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  10426. \end{lstlisting}
  10427. \caption{Auxiliary functions for type checking $R_9$.}
  10428. \label{fig:type-check-R9-aux}
  10429. \end{figure}
  10430. \clearpage
  10431. \section{Interpreting $R'_9$}
  10432. \label{sec:interp-casts}
  10433. The runtime behavior of first-order casts is straightforward, that is,
  10434. casts involving simple types such as \code{Integer} and
  10435. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  10436. can be accomplished with the \code{Inject} operator of $R_6$, which
  10437. puts the integer into a tagged value
  10438. (Figure~\ref{fig:interp-R6}). Similarly, a cast from \code{Any} to
  10439. \code{Integer} is accomplished with the \code{Project} operator, that
  10440. is, by checking the value's tag and either retrieving the underlying
  10441. integer or signaling an error if it the tag is not the one for
  10442. integers (Figure~\ref{fig:apply-project}).
  10443. %
  10444. Things get more interesting for higher-order casts, that is, casts
  10445. involving function or vector types.
  10446. Consider the cast of the function \code{maybe-add1} from \code{(Any ->
  10447. Any)} to \code{(Integer -> Integer)}. When a function flows through
  10448. this cast at runtime, we can't know in general whether the function
  10449. will always return an integer.\footnote{Predicting the return value of
  10450. a function is equivalent to the halting problem, which is
  10451. undecidable.} The $R'_9$ interpreter therefore delays the checking
  10452. of the cast until the function is applied. This is accomplished by
  10453. wrapping \code{maybe-add1} in a new function that casts its parameter
  10454. from \code{Integer} to \code{Any}, applies \code{maybe-add1}, and then
  10455. casts the return value from \code{Any} to \code{Integer}.
  10456. Turning our attention to casts involving vector types, we consider the
  10457. example in Figure~\ref{fig:map-vec-bang} that defines a
  10458. partially-typed version of \code{map-vec} whose parameter \code{v} has
  10459. type \code{(Vector Any Any)} and that updates \code{v} in place
  10460. instead of returning a new vector. So we name this function
  10461. \code{map-vec!}. We apply \code{map-vec!} to a vector of integers, so
  10462. the type checker inserts a cast from \code{(Vector Integer Integer)}
  10463. to \code{(Vector Any Any)}. A naive way for the $R'_9$ interpreter to
  10464. cast between vector types would be a build a new vector whose elements
  10465. are the result of casting each of the original elements to the
  10466. appropriate target type. However, this approach is only valid for
  10467. immutable vectors; and our vectors are mutable. In the example of
  10468. Figure~\ref{fig:map-vec-bang}, if the cast created a new vector, then
  10469. the updates inside of \code{map-vec!} would happen to the new vector
  10470. and not the original one.
  10471. \begin{figure}[tbp]
  10472. % gradual_test_11.rkt
  10473. \begin{lstlisting}
  10474. (define (map-vec! [f : (Any -> Any)]
  10475. [v : (Vector Any Any)]) : Void
  10476. (begin
  10477. (vector-set! v 0 (f (vector-ref v 0)))
  10478. (vector-set! v 1 (f (vector-ref v 1)))))
  10479. (define (add1 x) (+ x 1))
  10480. (let ([v (vector 0 41)])
  10481. (begin (map-vec! add1 v) (vector-ref v 1)))
  10482. \end{lstlisting}
  10483. \caption{An example involving casts on vectors.}
  10484. \label{fig:map-vec-bang}
  10485. \end{figure}
  10486. Instead the interpreter needs to create a new kind of value, a
  10487. \emph{vector proxy}, that intercepts every vector operation. On a
  10488. read, the proxy reads from the underlying vector and then applies a
  10489. cast to the resulting value. On a write, the proxy casts the argument
  10490. value and then performs the write to the underlying vector. For the
  10491. first \code{(vector-ref v 0)} in \code{map-vec!}, the proxy casts
  10492. \code{0} from \code{Integer} to \code{Any}. For the first
  10493. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  10494. to \code{Integer}.
  10495. The final category of cast that we need to consider are casts between
  10496. the \code{Any} type and either a function or a vector
  10497. type. Figure~\ref{fig:map-vec-any} shows a variant of \code{map-vec!}
  10498. in which parameter \code{v} does not have a type annotation, so it is
  10499. given type \code{Any}. In the call to \code{map-vec!}, the vector has
  10500. type \code{(Vector Integer Integer)} so the type checker inserts a
  10501. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  10502. thought is to use \code{Inject}, but that doesn't work because
  10503. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  10504. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  10505. to \code{Any}.
  10506. \begin{figure}[tbp]
  10507. \begin{lstlisting}
  10508. (define (map-vec! [f : (Any -> Any)] v) : Void
  10509. (begin
  10510. (vector-set! v 0 (f (vector-ref v 0)))
  10511. (vector-set! v 1 (f (vector-ref v 1)))))
  10512. (define (add1 x) (+ x 1))
  10513. (let ([v (vector 0 41)])
  10514. (begin (map-vec! add1 v) (vector-ref v 1)))
  10515. \end{lstlisting}
  10516. \caption{Casting a vector to \code{Any}.}
  10517. \label{fig:map-vec-any}
  10518. \end{figure}
  10519. The $R'_9$ interpreter uses an auxiliary function named
  10520. \code{apply-cast} to cast a value from a source type to a target type,
  10521. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  10522. of the kinds of casts that we've discussed in this section.
  10523. \begin{figure}[tbp]
  10524. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10525. (define/public (apply-cast v s t)
  10526. (match* (s t)
  10527. [(t1 t2) #:when (equal? t1 t2) v]
  10528. [('Any t2)
  10529. (match t2
  10530. [`(,ts ... -> ,rt)
  10531. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  10532. (define v^ (apply-project v any->any))
  10533. (apply-cast v^ any->any `(,@ts -> ,rt))]
  10534. [`(Vector ,ts ...)
  10535. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  10536. (define v^ (apply-project v vec-any))
  10537. (apply-cast v^ vec-any `(Vector ,@ts))]
  10538. [else (apply-project v t2)])]
  10539. [(t1 'Any)
  10540. (match t1
  10541. [`(,ts ... -> ,rt)
  10542. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  10543. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  10544. (apply-inject v^ (any-tag any->any))]
  10545. [`(Vector ,ts ...)
  10546. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  10547. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  10548. (apply-inject v^ (any-tag vec-any))]
  10549. [else (apply-inject v (any-tag t1))])]
  10550. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10551. (define x (gensym 'x))
  10552. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  10553. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  10554. (define cast-writes
  10555. (for/list ([t1 ts1] [t2 ts2])
  10556. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  10557. `(vector-proxy ,(vector v (apply vector cast-reads)
  10558. (apply vector cast-writes)))]
  10559. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10560. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  10561. `(function ,xs ,(Cast
  10562. (Apply (Value v)
  10563. (for/list ([x xs][t1 ts1][t2 ts2])
  10564. (Cast (Var x) t2 t1)))
  10565. rt1 rt2) ())]
  10566. ))
  10567. \end{lstlisting}
  10568. \caption{The \code{apply-cast} auxiliary method.}
  10569. \label{fig:apply-cast}
  10570. \end{figure}
  10571. The interpreter for $R'_9$ is defined in
  10572. Figure~\ref{fig:interp-R9-prime}, with the case for \code{Cast}
  10573. dispatching to \code{apply-cast}. To handle the addition of vector
  10574. proxies, we update the vector primitives in \code{interp-op} using the
  10575. functions in Figure~\ref{fig:guarded-vector}.
  10576. \begin{figure}[tbp]
  10577. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10578. (define interp-R9-prime-class
  10579. (class interp-R8-class
  10580. (super-new)
  10581. (inherit apply-fun apply-inject apply-project)
  10582. (define/override (interp-op op)
  10583. (match op
  10584. ['vector-length guarded-vector-length]
  10585. ['vector-ref guarded-vector-ref]
  10586. ['vector-set! guarded-vector-set!]
  10587. ['any-vector-ref (lambda (v i)
  10588. (match v [`(tagged ,v^ ,tg)
  10589. (guarded-vector-ref v^ i)]))]
  10590. ['any-vector-set! (lambda (v i a)
  10591. (match v [`(tagged ,v^ ,tg)
  10592. (guarded-vector-set! v^ i a)]))]
  10593. ['any-vector-length (lambda (v)
  10594. (match v [`(tagged ,v^ ,tg)
  10595. (guarded-vector-length v^)]))]
  10596. [else (super interp-op op)]
  10597. ))
  10598. (define/override ((interp-exp env) e)
  10599. (define (recur e) ((interp-exp env) e))
  10600. (match e
  10601. [(Value v) v]
  10602. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  10603. [else ((super interp-exp env) e)]))
  10604. ))
  10605. (define (interp-R9-prime p)
  10606. (send (new interp-R9-prime-class) interp-program p))
  10607. \end{lstlisting}
  10608. \caption{The interpreter for $R'_9$.}
  10609. \label{fig:interp-R9-prime}
  10610. \end{figure}
  10611. \begin{figure}[tbp]
  10612. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10613. (define (guarded-vector-ref vec i)
  10614. (match vec
  10615. [`(vector-proxy ,proxy)
  10616. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  10617. (define rd (vector-ref (vector-ref proxy 1) i))
  10618. (apply-fun rd (list val) 'guarded-vector-ref)]
  10619. [else (vector-ref vec i)]))
  10620. (define (guarded-vector-set! vec i arg)
  10621. (match vec
  10622. [`(vector-proxy ,proxy)
  10623. (define wr (vector-ref (vector-ref proxy 2) i))
  10624. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  10625. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  10626. [else (vector-set! vec i arg)]))
  10627. (define (guarded-vector-length vec)
  10628. (match vec
  10629. [`(vector-proxy ,proxy)
  10630. (guarded-vector-length (vector-ref proxy 0))]
  10631. [else (vector-length vec)]))
  10632. \end{lstlisting}
  10633. \caption{The guarded-vector auxiliary functions.}
  10634. \label{fig:guarded-vector}
  10635. \end{figure}
  10636. \section{Lower Casts}
  10637. \label{sec:lower-casts}
  10638. The next step in the journey towards x86 is the \code{lower-casts}
  10639. pass that translates the casts in $R'_9$ to the lower-level
  10640. \code{Inject} and \code{Project} operators and a new operator for
  10641. creating vector proxies, extending the $R'_8$ language to create
  10642. $R''_8$. We recommend creating an auxiliary function named
  10643. \code{lower-cast} that takes an expression (in $R'_9$), a source type,
  10644. and a target type, and translates it to expression in $R''_8$ that has
  10645. the same behavior as casting the expression from the source to the
  10646. target type in the interpreter.
  10647. The \code{lower-cast} function can follow a code structure similar to
  10648. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  10649. the interpreter for $R'_9$ because it must handle the same cases as
  10650. \code{apply-cast} and it needs to mimic the behavior of
  10651. \code{apply-cast}. The most interesting cases are those concerning the
  10652. casts between two vector types and between two function types.
  10653. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  10654. type to another vector type is accomplished by creating a proxy that
  10655. intercepts the operations on the underlying vector. Here we make the
  10656. creation of the proxy explicit with the \code{vector-proxy} primitive
  10657. operation. It takes three arguments, the first is an expression for
  10658. the vector, the second is a vector of functions for casting an element
  10659. that is being read from the vector, and the third is a vector of
  10660. functions for casting an element that is being written to the vector.
  10661. You can create the functions using \code{Lambda}. Also, as we shall
  10662. see in the next section, we need to differentiate these vectors from
  10663. the user-created ones, so we recommend using a new primitive operator
  10664. named \code{raw-vector} instead of \code{vector} to create these
  10665. vectors of functions. Figure~\ref{fig:map-vec-bang-lower-cast} shows
  10666. the output of \code{lower-casts} on the example in
  10667. Figure~\ref{fig:map-vec-bang} that involved casting a vector of
  10668. integers to a vector of \code{Any}.
  10669. \begin{figure}[tbp]
  10670. \begin{lstlisting}
  10671. (define (map-vec! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  10672. (begin
  10673. (vector-set! v 0 (f (vector-ref v 0)))
  10674. (vector-set! v 1 (f (vector-ref v 1)))))
  10675. (define (add1 [x : Any]) : Any
  10676. (inject (+ (project x Integer) 1) Integer))
  10677. (let ([v (vector 0 41)])
  10678. (begin
  10679. (map-vec! add1 (vector-proxy v
  10680. (raw-vector (lambda: ([x9 : Integer]) : Any
  10681. (inject x9 Integer))
  10682. (lambda: ([x9 : Integer]) : Any
  10683. (inject x9 Integer)))
  10684. (raw-vector (lambda: ([x9 : Any]) : Integer
  10685. (project x9 Integer))
  10686. (lambda: ([x9 : Any]) : Integer
  10687. (project x9 Integer)))))
  10688. (vector-ref v 1)))
  10689. \end{lstlisting}
  10690. \caption{Output of \code{lower-casts} on the example in
  10691. Figure~\ref{fig:map-vec-bang}.}
  10692. \label{fig:map-vec-bang-lower-cast}
  10693. \end{figure}
  10694. A cast from one function type to another function type is accomplished
  10695. by generating a \code{Lambda} whose parameter and return types match
  10696. the target function type. The body of the \code{Lambda} should cast
  10697. the parameters from the target type to the source type (yes,
  10698. backwards! functions are contravariant\index{contravariant} in the
  10699. parameters), then call the underlying function, and finally cast the
  10700. result from the source return type to the target return type.
  10701. Figure~\ref{fig:map-vec-lower-cast} shows the output of the
  10702. \code{lower-casts} pass on the \code{map-vec} example in
  10703. Figure~\ref{fig:gradual-map-vec}. Note that the \code{add1} argument
  10704. in the call to \code{map-vec} is wrapped in a \code{lambda}.
  10705. \begin{figure}[tbp]
  10706. \begin{lstlisting}
  10707. (define (map-vec [f : (Integer -> Integer)]
  10708. [v : (Vector Integer Integer)])
  10709. : (Vector Integer Integer)
  10710. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10711. (define (add1 [x : Any]) : Any
  10712. (inject (+ (project x Integer) 1) Integer))
  10713. (vector-ref (map-vec (lambda: ([x9 : Integer]) : Integer
  10714. (project (add1 (inject x9 Integer)) Integer))
  10715. (vector 0 41)) 1)
  10716. \end{lstlisting}
  10717. \caption{Output of \code{lower-casts} on the example in
  10718. Figure~\ref{fig:gradual-map-vec}.}
  10719. \label{fig:map-vec-lower-cast}
  10720. \end{figure}
  10721. \section{Differentiate Proxies}
  10722. \label{sec:differentiate-proxies}
  10723. So far the job of differentiating vectors and vector proxies has been
  10724. the job of the interpreter. For example, the interpreter for $R'_9$
  10725. implements \code{vector-ref} using the \code{guarded-vector-ref}
  10726. function in Figure~\ref{fig:guarded-vector}. In the
  10727. \code{differentiate-proxies} pass we shift this responsibility to the
  10728. generated code.
  10729. We begin by designing the output language $R_{\mathrm{proxy}}$. In
  10730. $R_9$ we used the type \code{Vector} for both real vectors and vector
  10731. proxies. In $R_{\mathrm{proxy}}$ we return the \code{Vector} type to
  10732. its original meaning, as the type of real vectors, and we introduce a
  10733. new type, \code{GVector}, whose values can be either real vectors or
  10734. vector proxies. This new type comes with a suite of new primitive
  10735. operations for creating and using values of type \code{GVector}. We
  10736. don't need to introduce a new type to represent vector proxies. A
  10737. proxy is represented by a vector containing three things: 1) the
  10738. underlying vector, 2) a vector of functions for casting elements that
  10739. are read from the vector, and 3) a vector of functions for casting
  10740. values to be written to the vector. So we define the following
  10741. abbreviation for the type of a vector proxy:
  10742. \[
  10743. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  10744. = (\ttm{Vector}~(\ttm{GVector}~ T\ldots) ~R~ W)
  10745. \to (\key{GVector}~ T' \ldots)
  10746. \]
  10747. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  10748. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  10749. %
  10750. Next we describe each of the new primitive operations.
  10751. \begin{description}
  10752. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  10753. (\key{GVector} $T \ldots$)]\ \\
  10754. %
  10755. This operation brands a vector as a value of the \code{GVector} type.
  10756. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  10757. $\to$ (\key{GVector} $T' \ldots$)]\ \\
  10758. %
  10759. This operation brands a vector proxy as value of the \code{GVector} type.
  10760. \item[\code{proxy?} : (\key{GVector} $T \ldots$) $\to$
  10761. \code{Boolean}] \ \\
  10762. %
  10763. returns true if the value is a vector proxy and false if it is a
  10764. real vector.
  10765. \item[\code{project-vector} : (\key{GVector} $T \ldots$) $\to$
  10766. (\key{Vector} $T \ldots$)]\ \\
  10767. %
  10768. Assuming that the input is a vector (and not a proxy), this
  10769. operation returns the vector.
  10770. \item[\code{proxy-vector-length} : (\key{GVector} $T \ldots$)
  10771. $\to$ \code{Boolean}]\ \\
  10772. %
  10773. Given a vector proxy, this operation returns the length of the
  10774. underlying vector.
  10775. \item[\code{proxy-vector-ref} : (\key{GVector} $T \ldots$)
  10776. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  10777. %
  10778. Given a vector proxy, this operation returns the $i$th element of
  10779. the underlying vector.
  10780. \item[\code{proxy-vector-set!} : (\key{GVector} $T \ldots$) $\to$ ($i$
  10781. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  10782. proxy, this operation writes a value to the $i$th element of the
  10783. underlying vector.
  10784. \end{description}
  10785. Now to discuss the translation that differentiates vectors from
  10786. proxies. First, every type annotation in the program must be
  10787. translated (recursively) to replace \code{Vector} with \code{GVector}.
  10788. Next, we must insert uses of \code{GVector} operations in the
  10789. appropriate places. For example, we wrap every vector creation with an
  10790. \code{inject-vector}.
  10791. \begin{lstlisting}
  10792. (vector |$e_1 \ldots e_n$|)
  10793. |$\Rightarrow$|
  10794. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  10795. \end{lstlisting}
  10796. The \code{raw-vector} operator that we introduced in the previous
  10797. section does not get injected.
  10798. \begin{lstlisting}
  10799. (raw-vector |$e_1 \ldots e_n$|)
  10800. |$\Rightarrow$|
  10801. (vector |$e'_1 \ldots e'_n$|)
  10802. \end{lstlisting}
  10803. The \code{vector-proxy} primitive translates as follows.
  10804. \begin{lstlisting}
  10805. (vector-proxy |$e_1~e_2~e_3$|)
  10806. |$\Rightarrow$|
  10807. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  10808. \end{lstlisting}
  10809. We translate the vector operations into conditional expressions that
  10810. check whether the value is a proxy and then dispatch to either the
  10811. appropriate proxy vector operation or the regular vector operation.
  10812. For example, the following is the translation for \code{vector-ref}.
  10813. \begin{lstlisting}
  10814. (vector-ref |$e_1$| |$i$|)
  10815. |$\Rightarrow$|
  10816. (let ([|$v~e_1$|])
  10817. (if (proxy? |$v$|)
  10818. (proxy-vector-ref |$v$| |$i$|)
  10819. (vector-ref (project-vector |$v$|) |$i$|)
  10820. \end{lstlisting}
  10821. Note in the case of a real vector, we must apply \code{project-vector}
  10822. before the \code{vector-ref}.
  10823. \section{Reveal Casts}
  10824. \label{sec:reveal-casts-gradual}
  10825. Recall that the \code{reveal-casts} pass
  10826. (Section~\ref{sec:reveal-casts-r6}) is responsible for lowering
  10827. \code{Inject} and \code{Project} into lower-level operations. In
  10828. particular, \code{Project} turns into a conditional expression that
  10829. inspects the tag and retrieves the underlying value. Here we need to
  10830. augment the translation of \code{Project} to handle the situation when
  10831. the target type is \code{GVector}. Instead of using
  10832. \code{vector-length} we need to use \code{proxy-vector-length}.
  10833. \begin{lstlisting}
  10834. (project |$e$| (GVector Any|$_1$| |$\ldots$| Any|$_n$|))
  10835. |$\Rightarrow$|
  10836. (let |$\itm{tmp}$| |$e'$|
  10837. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  10838. (let |$\itm{vec}$| (value-of |$\itm{tmp}$| (GVector Any |$\ldots$| Any))
  10839. (if (eq? (proxy-vector-length |$\itm{vec}$|) |$n$|) |$\itm{vec}$| (exit)))
  10840. (exit)))
  10841. \end{lstlisting}
  10842. \section{Closure Conversion}
  10843. \label{sec:closure-conversion-gradual}
  10844. The closure conversion pass only requires one minor adjustment. The
  10845. auxiliary function that translates type annotations needs to be
  10846. updated to handle the \code{GVector} type.
  10847. \section{Explicate Control}
  10848. \label{sec:explicate-control-gradual}
  10849. Update the \code{explicate-control} pass to handle the new primitive
  10850. operations on the \code{GVector} type.
  10851. \section{Select Instructions}
  10852. \label{sec:select-instructions-gradual}
  10853. Recall that the \code{select-instructions} pass is responsible for
  10854. lowering the primitive operations into x86 instructions. So we need
  10855. to translate the new \code{GVector} operations to x86. To do so, the
  10856. first question we need to answer is how will we differentiate the two
  10857. kinds of values (vectors and proxies) that can inhabit \code{GVector}.
  10858. We need just one bit to accomplish this, so we use the $57$th bit of
  10859. the 64-bit tag at the front of every vector (see
  10860. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  10861. for \code{inject-vector} we leave it that way.
  10862. \begin{lstlisting}
  10863. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  10864. |$\Rightarrow$|
  10865. movq |$e'_1$|, |$\itm{lhs'}$|
  10866. \end{lstlisting}
  10867. On the other hand, \code{inject-proxy} sets the $57$th bit to $1$.
  10868. \begin{lstlisting}
  10869. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  10870. |$\Rightarrow$|
  10871. movq |$e'_1$|, %r11
  10872. movq |$(1 << 57)$|, %rax
  10873. orq 0(%r11), %rax
  10874. movq %rax, 0(%r11)
  10875. movq %r11, |$\itm{lhs'}$|
  10876. \end{lstlisting}
  10877. The \code{proxy?} operation consumes the information so carefully
  10878. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  10879. isolates the $57$th bit to tell whether the value is a real vector or
  10880. a proxy.
  10881. \begin{lstlisting}
  10882. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  10883. |$\Rightarrow$|
  10884. movq |$e_1'$|, %r11
  10885. movq 0(%r11), %rax
  10886. sarq $57, %rax
  10887. andq $1, %rax
  10888. movq %rax, |$\itm{lhs'}$|
  10889. \end{lstlisting}
  10890. The \code{project-vector} operation is straightforward to translate,
  10891. so we leave it up to the reader.
  10892. Regarding the \code{proxy-vector} operations, the runtime provides
  10893. procedures that implement them (they are recursive functions!) so
  10894. here we simply need to translate these vector operations into the
  10895. appropriate function call. For example, here is the translation for
  10896. \code{proxy-vector-ref}.
  10897. \begin{lstlisting}
  10898. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  10899. |$\Rightarrow$|
  10900. movq |$e_1'$|, %rdi
  10901. movq |$e_2'$|, %rsi
  10902. callq proxy_vector_ref
  10903. movq %rax, |$\itm{lhs'}$|
  10904. \end{lstlisting}
  10905. We have another batch of vector operations to deal with, those for the
  10906. \code{Any} type. Recall that the type checker for $R_9$ generates an
  10907. \code{any-vector-ref} when there is a \code{vector-ref} on something
  10908. of type \code{Any}, and similarly for \code{any-vector-set!} and
  10909. \code{any-vector-length} (Figure~\ref{fig:type-check-R9-1}). In
  10910. Section~\ref{sec:select-r6} we selected instructions for these
  10911. operations based on the idea that the underlying value was a real
  10912. vector. But in the current setting, the underlying value is of type
  10913. \code{GVector}. So \code{any-vector-ref} can be translates to
  10914. pseudo-x86 as follows. We begin by projecting the underlying value out
  10915. of the tagged value and then call the \code{proxy\_vector\_ref}
  10916. procedure in the runtime.
  10917. \begin{lstlisting}
  10918. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  10919. movq |$\neg 111$|, %rdi
  10920. andq |$e_1'$|, %rdi
  10921. movq |$e_2'$|, %rsi
  10922. callq proxy_vector_ref
  10923. movq %rax, |$\itm{lhs'}$|
  10924. \end{lstlisting}
  10925. The \code{any-vector-set!} and \code{any-vector-length} operators can
  10926. be translated in a similar way.
  10927. \begin{exercise}\normalfont
  10928. Implement a compiler for the gradually-typed $R_9$ language by
  10929. extending and adapting your compiler for $R_8$. Create 10 new
  10930. partially-typed test programs. In addition to testing with these
  10931. new programs, also test your compiler on all the tests for $R_8$
  10932. and tests for $R_7$. Sometimes you may get a type checking error
  10933. on the $R_7$ programs but you can adapt them by inserting
  10934. a cast to the \code{Any} type around each subexpression
  10935. causing a type error. While $R_7$ doesn't have explicit casts,
  10936. you can induce one by wrapping the subexpression \code{e}
  10937. with a call to an un-annotated identity function, like this:
  10938. \code{((lambda (x) x) e)}.
  10939. \end{exercise}
  10940. \section{Further Reading}
  10941. This chapter just scratches the surface of gradual typing. The basic
  10942. approach described here is missing two key ingredients that one would
  10943. want in a implementation of gradual typing: blame
  10944. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  10945. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  10946. problem addressed by blame tracking is that when a cast on a
  10947. higher-order value fails, it often does so at a point in the program
  10948. that is far removed from the original cast. Blame tracking is a
  10949. technique for propagating extra information through casts and proxies
  10950. so that when a cast fails, the error message can point back to the
  10951. original location of the cast in the source program.
  10952. The problem addressed by space-efficient casts also relates to
  10953. higher-order casts. It turns out that in partially typed programs, a
  10954. function or vector can flow through very-many casts at runtime. With
  10955. the approach described in this chapter, each cast adds another
  10956. \code{lambda} wrapper or a vector proxy. Not only does this take up
  10957. considerable space, but it also makes the function calls and vector
  10958. operations slow. For example, a partially-typed version of quicksort
  10959. could, in the worst case, build a chain of proxies of length $O(n)$
  10960. around the vector, changing the overall time complexity of the
  10961. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  10962. solution to this problem by representing casts using the coercion
  10963. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  10964. long chains of proxies by compressing them into a concise normal
  10965. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  10966. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  10967. the Grift compiler.
  10968. \begin{center}
  10969. \url{https://github.com/Gradual-Typing/Grift}
  10970. \end{center}
  10971. There are also interesting interactions between gradual typing and
  10972. other language features, such as parametetric polymorphism,
  10973. information-flow types, and type inference, to name a few. We
  10974. recommend the reader to the online gradual typing bibliography:
  10975. \begin{center}
  10976. \url{http://samth.github.io/gradual-typing-bib/}
  10977. \end{center}
  10978. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10979. \chapter{Parametric Polymorphism}
  10980. \label{ch:parametric-polymorphism}
  10981. \index{parametric polymorphism}
  10982. \index{generics}
  10983. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  10984. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  10985. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10986. %% \chapter{High-level Optimization}
  10987. %% \label{ch:high-level-optimization}
  10988. %% This chapter will present a procedure inlining pass based on the
  10989. %% algorithm of \citet{Waddell:1997fk}.
  10990. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10991. \chapter{Appendix}
  10992. \section{Interpreters}
  10993. \label{appendix:interp}
  10994. \index{interpreter}
  10995. We provide interpreters for each of the source languages $R_0$, $R_1$,
  10996. $\ldots$ in the files \code{interp-R0.rkt}, \code{interp-R1.rkt}, etc.
  10997. The interpreters for the intermediate languages $C_0$ and $C_1$ are in
  10998. \code{interp-C0.rkt} and \code{interp-C1.rkt}. The interpreters for
  10999. $C_2$, $C_3$, pseudo-x86, and x86 are in the \key{interp.rkt} file.
  11000. \section{Utility Functions}
  11001. \label{appendix:utilities}
  11002. The utility functions described in this section are in the
  11003. \key{utilities.rkt} file of the support code.
  11004. \paragraph{\code{interp-tests}}
  11005. The \key{interp-tests} function runs the compiler passes and the
  11006. interpreters on each of the specified tests to check whether each pass
  11007. is correct. The \key{interp-tests} function has the following
  11008. parameters:
  11009. \begin{description}
  11010. \item[name (a string)] a name to identify the compiler,
  11011. \item[typechecker] a function of exactly one argument that either
  11012. raises an error using the \code{error} function when it encounters a
  11013. type error, or returns \code{\#f} when it encounters a type
  11014. error. If there is no type error, the type checker returns the
  11015. program.
  11016. \item[passes] a list with one entry per pass. An entry is a list with
  11017. four things:
  11018. \begin{enumerate}
  11019. \item a string giving the name of the pass,
  11020. \item the function that implements the pass (a translator from AST
  11021. to AST),
  11022. \item a function that implements the interpreter (a function from
  11023. AST to result value) for the output language,
  11024. \item and a type checker for the output language. Type checkers for
  11025. the $R$ and $C$ languages are provided in the support code. For
  11026. example, the type checkers for $R_1$ and $C_0$ are in
  11027. \code{type-check-R1.rkt}. The type checker entry is optional. The
  11028. support code does not provide type checkers for the x86 languages.
  11029. \end{enumerate}
  11030. \item[source-interp] an interpreter for the source language. The
  11031. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  11032. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  11033. \item[tests] a list of test numbers that specifies which tests to
  11034. run. (see below)
  11035. \end{description}
  11036. %
  11037. The \key{interp-tests} function assumes that the subdirectory
  11038. \key{tests} has a collection of Racket programs whose names all start
  11039. with the family name, followed by an underscore and then the test
  11040. number, ending with the file extension \key{.rkt}. Also, for each test
  11041. program that calls \code{read} one or more times, there is a file with
  11042. the same name except that the file extension is \key{.in} that
  11043. provides the input for the Racket program. If the test program is
  11044. expected to fail type checking, then there should be an empty file of
  11045. the same name but with extension \key{.tyerr}.
  11046. \paragraph{\code{compiler-tests}}
  11047. runs the compiler passes to generate x86 (a \key{.s} file) and then
  11048. runs the GNU C compiler (gcc) to generate machine code. It runs the
  11049. machine code and checks that the output is $42$. The parameters to the
  11050. \code{compiler-tests} function are similar to those of the
  11051. \code{interp-tests} function, and consist of
  11052. \begin{itemize}
  11053. \item a compiler name (a string),
  11054. \item a type checker,
  11055. \item description of the passes,
  11056. \item name of a test-family, and
  11057. \item a list of test numbers.
  11058. \end{itemize}
  11059. \paragraph{\code{compile-file}}
  11060. takes a description of the compiler passes (see the comment for
  11061. \key{interp-tests}) and returns a function that, given a program file
  11062. name (a string ending in \key{.rkt}), applies all of the passes and
  11063. writes the output to a file whose name is the same as the program file
  11064. name but with \key{.rkt} replaced with \key{.s}.
  11065. \paragraph{\code{read-program}}
  11066. takes a file path and parses that file (it must be a Racket program)
  11067. into an abstract syntax tree.
  11068. \paragraph{\code{parse-program}}
  11069. takes an S-expression representation of an abstract syntax tree and converts it into
  11070. the struct-based representation.
  11071. \paragraph{\code{assert}}
  11072. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  11073. and displays the message \key{msg} if the Boolean \key{bool} is false.
  11074. \paragraph{\code{lookup}}
  11075. % remove discussion of lookup? -Jeremy
  11076. takes a key and an alist, and returns the first value that is
  11077. associated with the given key, if there is one. If not, an error is
  11078. triggered. The alist may contain both immutable pairs (built with
  11079. \key{cons}) and mutable pairs (built with \key{mcons}).
  11080. %The \key{map2} function ...
  11081. \section{x86 Instruction Set Quick-Reference}
  11082. \label{sec:x86-quick-reference}
  11083. \index{x86}
  11084. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  11085. do. We write $A \to B$ to mean that the value of $A$ is written into
  11086. location $B$. Address offsets are given in bytes. The instruction
  11087. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  11088. registers (such as \code{\%rax}), or memory references (such as
  11089. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  11090. reference per instruction. Other operands must be immediates or
  11091. registers.
  11092. \begin{table}[tbp]
  11093. \centering
  11094. \begin{tabular}{l|l}
  11095. \textbf{Instruction} & \textbf{Operation} \\ \hline
  11096. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  11097. \texttt{negq} $A$ & $- A \to A$ \\
  11098. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  11099. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  11100. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  11101. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  11102. \texttt{retq} & Pops the return address and jumps to it \\
  11103. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  11104. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  11105. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  11106. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  11107. be an immediate) \\
  11108. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  11109. matches the condition code of the instruction, otherwise go to the
  11110. next instructions. The condition codes are \key{e} for ``equal'',
  11111. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  11112. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  11113. \texttt{jl} $L$ & \\
  11114. \texttt{jle} $L$ & \\
  11115. \texttt{jg} $L$ & \\
  11116. \texttt{jge} $L$ & \\
  11117. \texttt{jmp} $L$ & Jump to label $L$ \\
  11118. \texttt{movq} $A$, $B$ & $A \to B$ \\
  11119. \texttt{movzbq} $A$, $B$ &
  11120. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  11121. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  11122. and the extra bytes of $B$ are set to zero.} \\
  11123. & \\
  11124. & \\
  11125. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  11126. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  11127. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  11128. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  11129. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  11130. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  11131. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  11132. description of the condition codes. $A$ must be a single byte register
  11133. (e.g., \texttt{al} or \texttt{cl}).} \\
  11134. \texttt{setl} $A$ & \\
  11135. \texttt{setle} $A$ & \\
  11136. \texttt{setg} $A$ & \\
  11137. \texttt{setge} $A$ &
  11138. \end{tabular}
  11139. \vspace{5pt}
  11140. \caption{Quick-reference for the x86 instructions used in this book.}
  11141. \label{tab:x86-instr}
  11142. \end{table}
  11143. \cleardoublepage
  11144. \section{Concrete Syntax for Intermediate Languages}
  11145. The concrete syntax of $R_6$ is defined in
  11146. Figure~\ref{fig:r6-concrete-syntax}.
  11147. \begin{figure}[tp]
  11148. \centering
  11149. \fbox{
  11150. \begin{minipage}{0.97\textwidth}\small
  11151. \[
  11152. \begin{array}{lcl}
  11153. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  11154. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \key{Void}} \\
  11155. &\mid& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \mid \key{Any} \\
  11156. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void}
  11157. \mid \LP\key{Vector}\; \key{Any}\ldots\RP \\
  11158. &\mid& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  11159. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \mid \CPROJECT{\Exp}{\FType}\\
  11160. &\mid& \LP\key{any-vector-length}\;\Exp\RP
  11161. \mid \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  11162. &\mid& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  11163. &\mid& \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP
  11164. \mid \LP\key{void?}\;\Exp\RP \\
  11165. &\mid& \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \\
  11166. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  11167. R_6 &::=& \gray{\Def\ldots \; \Exp}
  11168. \end{array}
  11169. \]
  11170. \end{minipage}
  11171. }
  11172. \caption{The concrete syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax})
  11173. with \key{Any}.}
  11174. \label{fig:r6-concrete-syntax}
  11175. \end{figure}
  11176. The concrete syntax for $C_0$, $C_1$, $C_2$ and $C_3$ is
  11177. defined in Figures~\ref{fig:c0-concrete-syntax},
  11178. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax},
  11179. and \ref{fig:c3-concrete-syntax}, respectively.
  11180. \begin{figure}[tbp]
  11181. \fbox{
  11182. \begin{minipage}{0.96\textwidth}
  11183. \[
  11184. \begin{array}{lcl}
  11185. \Atm &::=& \Int \mid \Var \\
  11186. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  11187. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  11188. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  11189. C_0 & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  11190. \end{array}
  11191. \]
  11192. \end{minipage}
  11193. }
  11194. \caption{The concrete syntax of the $C_0$ intermediate language.}
  11195. \label{fig:c0-concrete-syntax}
  11196. \end{figure}
  11197. \begin{figure}[tbp]
  11198. \fbox{
  11199. \begin{minipage}{0.96\textwidth}
  11200. \small
  11201. \[
  11202. \begin{array}{lcl}
  11203. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  11204. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  11205. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  11206. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  11207. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  11208. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  11209. \mid \key{goto}~\itm{label}\key{;}\\
  11210. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  11211. C_1 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  11212. \end{array}
  11213. \]
  11214. \end{minipage}
  11215. }
  11216. \caption{The concrete syntax of the $C_1$ intermediate language.}
  11217. \label{fig:c1-concrete-syntax}
  11218. \end{figure}
  11219. \begin{figure}[tbp]
  11220. \fbox{
  11221. \begin{minipage}{0.96\textwidth}
  11222. \small
  11223. \[
  11224. \begin{array}{lcl}
  11225. \Atm &::=& \gray{ \Int \mid \Var \mid \itm{bool} } \\
  11226. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  11227. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  11228. &\mid& \gray{ \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP } \\
  11229. &\mid& \LP \key{allocate}~\Int~\Type \RP \\
  11230. &\mid& (\key{vector-ref}\;\Atm\;\Int) \mid (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  11231. &\mid& \LP \key{global-value}~\Var \RP \mid \LP \key{void} \RP \\
  11232. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \mid \LP\key{collect}~\Int \RP\\
  11233. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  11234. \mid \gray{ \key{goto}~\itm{label}\key{;} }\\
  11235. &\mid& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  11236. C_2 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  11237. \end{array}
  11238. \]
  11239. \end{minipage}
  11240. }
  11241. \caption{The concrete syntax of the $C_2$ intermediate language.}
  11242. \label{fig:c2-concrete-syntax}
  11243. \end{figure}
  11244. \begin{figure}[tp]
  11245. \fbox{
  11246. \begin{minipage}{0.96\textwidth}
  11247. \small
  11248. \[
  11249. \begin{array}{lcl}
  11250. \Atm &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  11251. \\
  11252. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  11253. \Exp &::= & \gray{ \Atm \mid \LP\key{read}\RP \mid \LP\key{-}\;\Atm\RP \mid \LP\key{+} \; \Atm\;\Atm\RP
  11254. \mid \LP\key{not}\;\Atm\RP \mid \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  11255. &\mid& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  11256. \mid \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  11257. &\mid& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \mid \LP\key{global-value} \,\itm{name}\RP \mid \LP\key{void}\RP } \\
  11258. &\mid& \LP\key{fun-ref}~\itm{label}\RP \mid \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  11259. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  11260. \mid \LP\key{collect} \,\itm{int}\RP }\\
  11261. \Tail &::= & \gray{\RETURN{\Exp} \mid \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  11262. &\mid& \gray{\LP\key{goto}\,\itm{label}\RP
  11263. \mid \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  11264. &\mid& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  11265. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  11266. C_3 & ::= & \Def\ldots
  11267. \end{array}
  11268. \]
  11269. \end{minipage}
  11270. }
  11271. \caption{The $C_3$ language, extending $C_2$ (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  11272. \label{fig:c3-concrete-syntax}
  11273. \end{figure}
  11274. \cleardoublepage
  11275. \addcontentsline{toc}{chapter}{Index}
  11276. \printindex
  11277. \cleardoublepage
  11278. \bibliographystyle{plainnat}
  11279. \bibliography{all}
  11280. \addcontentsline{toc}{chapter}{Bibliography}
  11281. \end{document}
  11282. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  11283. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  11284. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  11285. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  11286. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator jane
  11287. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  11288. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  11289. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  11290. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs Tt
  11291. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  11292. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  11293. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  11294. %% LocalWords: boolean type-check notq cmpq sete movzbq jmp al xorq
  11295. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  11296. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  11297. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  11298. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  11299. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  11300. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  11301. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  11302. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  11303. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  11304. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  11305. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  11306. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  11307. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  11308. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  11309. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  11310. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  11311. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  11312. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  11313. % LocalWords: struct symtab Friedman's MacOS Nystrom alist sam kate
  11314. % LocalWords: alists arity github unordered pqueue exprs ret param
  11315. % LocalWords: tyerr bytereg dh dl JmpIf HasType Osterlund Jacek TODO
  11316. % LocalWords: Gamari GlobalValue ProgramDefsExp prm ProgramDefs vn
  11317. % LocalWords: FunRef TailCall tailjmp IndirectCallq TailJmp Gilray
  11318. % LocalWords: dereference unbox Dataflow versa dataflow Kildall rhs
  11319. % LocalWords: Kleene enqueue dequeue AssignedFree FV cnvt SetBang tg
  11320. % LocalWords: ValueOf typechecker