book.tex 515 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383
  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. %% * continuations (frames in heap a la SML or segmented stack a la Dybvig)
  12. %% * exceptions
  13. %% * self hosting
  14. %% * I/O
  15. %% * foreign function interface
  16. %% * quasi-quote and unquote
  17. %% * macros (too difficult?)
  18. %% * alternative garbage collector
  19. %% * alternative register allocator
  20. %% * type classes
  21. %% * loop optimization (fusion, etc.)
  22. %% * deforestation
  23. %% * records with subtyping
  24. %% * object-oriented features
  25. %% - objects, object types, and structural subtyping (e.g. Abadi & Cardelli)
  26. %% - class-based objects and nominal subtyping (e.g. Featherweight Java)
  27. %% * multi-threading, fork join, futures, implicit parallelism
  28. %% * type analysis and specialization
  29. \documentclass[11pt]{book}
  30. \usepackage[T1]{fontenc}
  31. \usepackage[utf8]{inputenc}
  32. \usepackage{lmodern}
  33. \usepackage{hyperref}
  34. \usepackage{graphicx}
  35. \usepackage[english]{babel}
  36. \usepackage{listings}
  37. \usepackage{amsmath}
  38. \usepackage{amsthm}
  39. \usepackage{amssymb}
  40. \usepackage[numbers]{natbib}
  41. \usepackage{stmaryrd}
  42. \usepackage{xypic}
  43. \usepackage{semantic}
  44. \usepackage{wrapfig}
  45. \usepackage{tcolorbox}
  46. \usepackage{multirow}
  47. \usepackage{color}
  48. \usepackage{upquote}
  49. \usepackage{makeidx}
  50. \makeindex
  51. \definecolor{lightgray}{gray}{1}
  52. \newcommand{\black}[1]{{\color{black} #1}}
  53. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  54. \newcommand{\gray}[1]{{\color{gray} #1}}
  55. %% For pictures
  56. \usepackage{tikz}
  57. \usetikzlibrary{arrows.meta}
  58. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  59. % Computer Modern is already the default. -Jeremy
  60. %\renewcommand{\ttdefault}{cmtt}
  61. \definecolor{comment-red}{rgb}{0.8,0,0}
  62. \if01
  63. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  64. \newcommand{\margincomment}[1]{\marginpar{\color{comment-red}\tiny #1}}
  65. \else
  66. \newcommand{\rn}[1]{}
  67. \newcommand{\margincomment}[1]{}
  68. \fi
  69. \lstset{%
  70. language=Lisp,
  71. basicstyle=\ttfamily\small,
  72. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  73. deletekeywords={read,mapping,vector},
  74. escapechar=|,
  75. columns=flexible,
  76. moredelim=[is][\color{red}]{~}{~},
  77. showstringspaces=false
  78. }
  79. \newtheorem{theorem}{Theorem}
  80. \newtheorem{lemma}[theorem]{Lemma}
  81. \newtheorem{corollary}[theorem]{Corollary}
  82. \newtheorem{proposition}[theorem]{Proposition}
  83. \newtheorem{constraint}[theorem]{Constraint}
  84. \newtheorem{definition}[theorem]{Definition}
  85. \newtheorem{exercise}[theorem]{Exercise}
  86. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  87. % 'dedication' environment: To add a dedication paragraph at the start of book %
  88. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  89. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  90. \newenvironment{dedication}
  91. {
  92. \cleardoublepage
  93. \thispagestyle{empty}
  94. \vspace*{\stretch{1}}
  95. \hfill\begin{minipage}[t]{0.66\textwidth}
  96. \raggedright
  97. }
  98. {
  99. \end{minipage}
  100. \vspace*{\stretch{3}}
  101. \clearpage
  102. }
  103. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  104. % Chapter quote at the start of chapter %
  105. % Source: http://tex.stackexchange.com/a/53380 %
  106. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  107. \makeatletter
  108. \renewcommand{\@chapapp}{}% Not necessary...
  109. \newenvironment{chapquote}[2][2em]
  110. {\setlength{\@tempdima}{#1}%
  111. \def\chapquote@author{#2}%
  112. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  113. \itshape}
  114. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  115. \makeatother
  116. \input{defs}
  117. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  118. \title{\Huge \textbf{Essentials of Compilation} \\
  119. \huge The Incremental, Nano-Pass Approach}
  120. \author{\textsc{Jeremy G. Siek} \\
  121. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  122. Indiana University \\
  123. \\
  124. with contributions from: \\
  125. Carl Factora \\
  126. Andre Kuhlenschmidt \\
  127. Ryan R. Newton \\
  128. Ryan Scott \\
  129. Cameron Swords \\
  130. Michael M. Vitousek \\
  131. Michael Vollmer
  132. }
  133. \begin{document}
  134. \frontmatter
  135. \maketitle
  136. \begin{dedication}
  137. This book is dedicated to the programming language wonks at Indiana
  138. University.
  139. \end{dedication}
  140. \tableofcontents
  141. \listoffigures
  142. %\listoftables
  143. \mainmatter
  144. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  145. \chapter*{Preface}
  146. The tradition of compiler writing at Indiana University goes back to
  147. research and courses on programming languages by Professor Daniel
  148. Friedman in the 1970's and 1980's. Friedman conducted research on lazy
  149. evaluation~\citep{Friedman:1976aa} in the context of
  150. Lisp~\citep{McCarthy:1960dz} and then studied
  151. continuations~\citep{Felleisen:kx} and
  152. macros~\citep{Kohlbecker:1986dk} in the context of the
  153. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  154. of those courses, Kent Dybvig, went on to build Chez
  155. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  156. compiler for Scheme. After completing his Ph.D. at the University of
  157. North Carolina, he returned to teach at Indiana University.
  158. Throughout the 1990's and 2000's, Professor Dybvig continued
  159. development of Chez Scheme and taught the compiler course.
  160. The compiler course evolved to incorporate novel pedagogical ideas
  161. while also including elements of effective real-world compilers. One
  162. of Friedman's ideas was to split the compiler into many small
  163. ``passes'' so that the code for each pass would be easy to understood
  164. in isolation. In contrast, most compilers of the time were organized
  165. into only a few monolithic passes for reasons of compile-time
  166. efficiency. Another idea, called ``the game'', was to test the code
  167. generated by each pass on interpreters for each intermediate language,
  168. thereby helping to pinpoint errors in individual passes.
  169. %
  170. Dybvig, with later help from his students Dipanwita Sarkar and Andrew
  171. Keep, developed infrastructure to support this approach and evolved
  172. the course, first to use smaller micro-passes and then into even
  173. smaller nano-passes~\citep{Sarkar:2004fk,Keep:2012aa}. I was a student
  174. in this compiler course in the early 2000's as part of my
  175. Ph.D. studies at Indiana University. Needless to say, I enjoyed the
  176. course immensely!
  177. During that time, another graduate student named Abdulaziz Ghuloum
  178. observed that the front-to-back organization of the course made it
  179. difficult for students to understand the rationale for the compiler
  180. design. Ghuloum proposed an incremental approach in which the students
  181. start by implementing a complete compiler for a very small subset of
  182. the language. In each subsequent stage they add a feature to the
  183. language and then add or modify passes to handle the new
  184. feature~\citep{Ghuloum:2006bh}. In this way, the students see how the
  185. language features motivate aspects of the compiler design.
  186. After graduating from Indiana University in 2005, I went on to teach
  187. at the University of Colorado. I adapted the nano-pass and incremental
  188. approaches to compiling a subset of the Python
  189. language~\citep{Siek:2012ab}.
  190. %% Python and Scheme are quite different
  191. %% on the surface but there is a large overlap in the compiler techniques
  192. %% required for the two languages. Thus, I was able to teach much of the
  193. %% same content from the Indiana compiler course.
  194. I very much enjoyed teaching the course organized in this way, and
  195. even better, many of the students learned a lot and got excited about
  196. compilers.
  197. I returned to Indiana University in 2013. In my absence the compiler
  198. course had switched from the front-to-back organization to a
  199. back-to-front~\citep{Dybvig:2010aa}. While that organization also works
  200. well, I prefer the incremental approach and started porting and
  201. adapting the structure of the Colorado course back into the land of
  202. Scheme. In the meantime Indiana University had moved on from Scheme to
  203. Racket~\citep{plt-tr}, so the course is now about compiling a subset
  204. of Racket (and Typed Racket) to the x86 assembly language.
  205. This is the textbook for the incremental version of the compiler
  206. course at Indiana University (Spring 2016 - present). With this book
  207. I hope to make the Indiana compiler course available to people that
  208. have not had the chance to study compilers at Indiana University.
  209. %% I have captured what
  210. %% I think are the most important topics from \cite{Dybvig:2010aa} but
  211. %% have omitted topics that are less interesting conceptually. I have
  212. %% also made simplifications to reduce complexity. In this way, this
  213. %% book leans more towards pedagogy than towards the efficiency of the
  214. %% generated code. Also, the book differs in places where we I the
  215. %% opportunity to make the topics more fun, such as in relating register
  216. %% allocation to Sudoku (Chapter~\ref{ch:register-allocation-Rvar}).
  217. \section*{Prerequisites}
  218. The material in this book is challenging but rewarding. It is meant to
  219. prepare students for a lifelong career in programming languages.
  220. The book uses the Racket language both for the implementation of the
  221. compiler and for the language that is compiled, so a student should be
  222. proficient with Racket or Scheme prior to reading this book. There are
  223. many excellent resources for learning Scheme and
  224. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  225. It is helpful but not necessary for the student to have prior exposure
  226. to the x86 assembly language~\citep{Intel:2015aa}, as one might obtain
  227. from a computer systems
  228. course~\citep{Bryant:2010aa}. This book introduces the
  229. parts of x86-64 assembly language that are needed.
  230. %
  231. We follow the System V calling
  232. conventions~\citep{Bryant:2005aa,Matz:2013aa}, which means that the
  233. assembly code that we generate will work properly with our runtime
  234. system (written in C) when it is compiled using the GNU C compiler
  235. (\code{gcc}) on the Linux and MacOS operating systems. (Minor
  236. adjustments are needed for MacOS which we note as they arise.)
  237. %
  238. The GNU C compiler, when running on the Microsoft Windows operating
  239. system, follows the Microsoft x64 calling
  240. convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the assembly
  241. code that we generate will \emph{not} work properly with our runtime
  242. system on Windows. One option to consider for using a Windows computer
  243. is to run a virtual machine with Linux as the guest operating system.
  244. %\section*{Structure of book}
  245. % You might want to add short description about each chapter in this book.
  246. %\section*{About the companion website}
  247. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  248. %\begin{itemize}
  249. % \item A link to (freely downlodable) latest version of this document.
  250. % \item Link to download LaTeX source for this document.
  251. % \item Miscellaneous material (e.g. suggested readings etc).
  252. %\end{itemize}
  253. \section*{Acknowledgments}
  254. Many people have contributed to the ideas, techniques, and
  255. organization of this book and have taught courses based on it. Many
  256. of the compiler design decisions in this book are drawn from the
  257. assignment descriptions of \cite{Dybvig:2010aa}. We also would like
  258. to thank John Clements, Bor-Yuh Evan Chang, Daniel P. Friedman, Ronald
  259. Garcia, Abdulaziz Ghuloum, Jay McCarthy, Nate Nystrom, Dipanwita
  260. Sarkar, Oscar Waddell, and Michael Wollowski.
  261. \mbox{}\\
  262. \noindent Jeremy G. Siek \\
  263. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  264. %\noindent Spring 2016
  265. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  266. \chapter{Preliminaries}
  267. \label{ch:trees-recur}
  268. In this chapter we review the basic tools that are needed to implement
  269. a compiler. Programs are typically input by a programmer as text,
  270. i.e., a sequence of characters. The program-as-text representation is
  271. called \emph{concrete syntax}. We use concrete syntax to concisely
  272. write down and talk about programs. Inside the compiler, we use
  273. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  274. that efficiently supports the operations that the compiler needs to
  275. perform.\index{concrete syntax}\index{abstract syntax}\index{abstract
  276. syntax tree}\index{AST}\index{program}\index{parse} The translation
  277. from concrete syntax to abstract syntax is a process called
  278. \emph{parsing}~\citep{Aho:1986qf}. We do not cover the theory and
  279. implementation of parsing in this book. A parser is provided in the
  280. supporting materials for translating from concrete to abstract syntax.
  281. ASTs can be represented in many different ways inside the compiler,
  282. depending on the programming language used to write the compiler.
  283. %
  284. We use Racket's
  285. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  286. feature to represent ASTs (Section~\ref{sec:ast}). We use grammars to
  287. define the abstract syntax of programming languages
  288. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  289. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  290. recursive functions to construct and deconstruct ASTs
  291. (Section~\ref{sec:recursion}). This chapter provides an brief
  292. introduction to these ideas. \index{struct}
  293. \section{Abstract Syntax Trees and Racket Structures}
  294. \label{sec:ast}
  295. Compilers use abstract syntax trees to represent programs because they
  296. often need to ask questions like: for a given part of a program, what
  297. kind of language feature is it? What are its sub-parts? Consider the
  298. program on the left and its AST on the right. This program is an
  299. addition operation and it has two sub-parts, a read operation and a
  300. negation. The negation has another sub-part, the integer constant
  301. \code{8}. By using a tree to represent the program, we can easily
  302. follow the links to go from one part of a program to its sub-parts.
  303. \begin{center}
  304. \begin{minipage}{0.4\textwidth}
  305. \begin{lstlisting}
  306. (+ (read) (- 8))
  307. \end{lstlisting}
  308. \end{minipage}
  309. \begin{minipage}{0.4\textwidth}
  310. \begin{equation}
  311. \begin{tikzpicture}
  312. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  313. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  314. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  315. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  316. \draw[->] (plus) to (read);
  317. \draw[->] (plus) to (minus);
  318. \draw[->] (minus) to (8);
  319. \end{tikzpicture}
  320. \label{eq:arith-prog}
  321. \end{equation}
  322. \end{minipage}
  323. \end{center}
  324. We use the standard terminology for trees to describe ASTs: each
  325. circle above is called a \emph{node}. The arrows connect a node to its
  326. \emph{children} (which are also nodes). The top-most node is the
  327. \emph{root}. Every node except for the root has a \emph{parent} (the
  328. node it is the child of). If a node has no children, it is a
  329. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  330. \index{node}
  331. \index{children}
  332. \index{root}
  333. \index{parent}
  334. \index{leaf}
  335. \index{internal node}
  336. %% Recall that an \emph{symbolic expression} (S-expression) is either
  337. %% \begin{enumerate}
  338. %% \item an atom, or
  339. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  340. %% where $e_1$ and $e_2$ are each an S-expression.
  341. %% \end{enumerate}
  342. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  343. %% null value \code{'()}, etc. We can create an S-expression in Racket
  344. %% simply by writing a backquote (called a quasi-quote in Racket)
  345. %% followed by the textual representation of the S-expression. It is
  346. %% quite common to use S-expressions to represent a list, such as $a, b
  347. %% ,c$ in the following way:
  348. %% \begin{lstlisting}
  349. %% `(a . (b . (c . ())))
  350. %% \end{lstlisting}
  351. %% Each element of the list is in the first slot of a pair, and the
  352. %% second slot is either the rest of the list or the null value, to mark
  353. %% the end of the list. Such lists are so common that Racket provides
  354. %% special notation for them that removes the need for the periods
  355. %% and so many parenthesis:
  356. %% \begin{lstlisting}
  357. %% `(a b c)
  358. %% \end{lstlisting}
  359. %% The following expression creates an S-expression that represents AST
  360. %% \eqref{eq:arith-prog}.
  361. %% \begin{lstlisting}
  362. %% `(+ (read) (- 8))
  363. %% \end{lstlisting}
  364. %% When using S-expressions to represent ASTs, the convention is to
  365. %% represent each AST node as a list and to put the operation symbol at
  366. %% the front of the list. The rest of the list contains the children. So
  367. %% in the above case, the root AST node has operation \code{`+} and its
  368. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  369. %% diagram \eqref{eq:arith-prog}.
  370. %% To build larger S-expressions one often needs to splice together
  371. %% several smaller S-expressions. Racket provides the comma operator to
  372. %% splice an S-expression into a larger one. For example, instead of
  373. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  374. %% we could have first created an S-expression for AST
  375. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  376. %% S-expression.
  377. %% \begin{lstlisting}
  378. %% (define ast1.4 `(- 8))
  379. %% (define ast1.1 `(+ (read) ,ast1.4))
  380. %% \end{lstlisting}
  381. %% In general, the Racket expression that follows the comma (splice)
  382. %% can be any expression that produces an S-expression.
  383. We define a Racket \code{struct} for each kind of node. For this
  384. chapter we require just two kinds of nodes: one for integer constants
  385. and one for primitive operations. The following is the \code{struct}
  386. definition for integer constants.
  387. \begin{lstlisting}
  388. (struct Int (value))
  389. \end{lstlisting}
  390. An integer node includes just one thing: the integer value.
  391. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  392. \begin{lstlisting}
  393. (define eight (Int 8))
  394. \end{lstlisting}
  395. We say that the value created by \code{(Int 8)} is an
  396. \emph{instance} of the \code{Int} structure.
  397. The following is the \code{struct} definition for primitives operations.
  398. \begin{lstlisting}
  399. (struct Prim (op args))
  400. \end{lstlisting}
  401. A primitive operation node includes an operator symbol \code{op}
  402. and a list of children \code{args}. For example, to create
  403. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  404. \begin{lstlisting}
  405. (define neg-eight (Prim '- (list eight)))
  406. \end{lstlisting}
  407. Primitive operations may have zero or more children. The \code{read}
  408. operator has zero children:
  409. \begin{lstlisting}
  410. (define rd (Prim 'read '()))
  411. \end{lstlisting}
  412. whereas the addition operator has two children:
  413. \begin{lstlisting}
  414. (define ast1.1 (Prim '+ (list rd neg-eight)))
  415. \end{lstlisting}
  416. We have made a design choice regarding the \code{Prim} structure.
  417. Instead of using one structure for many different operations
  418. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  419. structure for each operation, as follows.
  420. \begin{lstlisting}
  421. (struct Read ())
  422. (struct Add (left right))
  423. (struct Neg (value))
  424. \end{lstlisting}
  425. The reason we choose to use just one structure is that in many parts
  426. of the compiler the code for the different primitive operators is the
  427. same, so we might as well just write that code once, which is enabled
  428. by using a single structure.
  429. When compiling a program such as \eqref{eq:arith-prog}, we need to
  430. know that the operation associated with the root node is addition and
  431. we need to be able to access its two children. Racket provides pattern
  432. matching to support these kinds of queries, as we see in
  433. Section~\ref{sec:pattern-matching}.
  434. In this book, we often write down the concrete syntax of a program
  435. even when we really have in mind the AST because the concrete syntax
  436. is more concise. We recommend that, in your mind, you always think of
  437. programs as abstract syntax trees.
  438. \section{Grammars}
  439. \label{sec:grammar}
  440. \index{integer}
  441. \index{literal}
  442. \index{constant}
  443. A programming language can be thought of as a \emph{set} of programs.
  444. The set is typically infinite (one can always create larger and larger
  445. programs), so one cannot simply describe a language by listing all of
  446. the programs in the language. Instead we write down a set of rules, a
  447. \emph{grammar}, for building programs. Grammars are often used to
  448. define the concrete syntax of a language, but they can also be used to
  449. describe the abstract syntax. We write our rules in a variant of
  450. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  451. \index{Backus-Naur Form}\index{BNF}
  452. As an example, we describe a small language, named \LangInt{}, that consists of
  453. integers and arithmetic operations.
  454. \index{grammar}
  455. The first grammar rule for the abstract syntax of \LangInt{} says that an
  456. instance of the \code{Int} structure is an expression:
  457. \begin{equation}
  458. \Exp ::= \INT{\Int} \label{eq:arith-int}
  459. \end{equation}
  460. %
  461. Each rule has a left-hand-side and a right-hand-side. The way to read
  462. a rule is that if you have an AST node that matches the
  463. right-hand-side, then you can categorize it according to the
  464. left-hand-side.
  465. %
  466. A name such as $\Exp$ that is defined by the grammar rules is a
  467. \emph{non-terminal}. \index{non-terminal}
  468. %
  469. The name $\Int$ is a also a non-terminal, but instead of defining it
  470. with a grammar rule, we define it with the following explanation. We
  471. make the simplifying design decision that all of the languages in this
  472. book only handle machine-representable integers. On most modern
  473. machines this corresponds to integers represented with 64-bits, i.e.,
  474. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  475. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  476. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  477. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  478. that the sequence of decimals represent an integer in range $-2^{62}$
  479. to $2^{62}-1$.
  480. The second grammar rule is the \texttt{read} operation that receives
  481. an input integer from the user of the program.
  482. \begin{equation}
  483. \Exp ::= \READ{} \label{eq:arith-read}
  484. \end{equation}
  485. The third rule says that, given an $\Exp$ node, the negation of that
  486. node is also an $\Exp$.
  487. \begin{equation}
  488. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  489. \end{equation}
  490. Symbols in typewriter font such as \key{-} and \key{read} are
  491. \emph{terminal} symbols and must literally appear in the program for
  492. the rule to be applicable.
  493. \index{terminal}
  494. We can apply these rules to categorize the ASTs that are in the
  495. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  496. \texttt{(Int 8)} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  497. following AST is an $\Exp$.
  498. \begin{center}
  499. \begin{minipage}{0.4\textwidth}
  500. \begin{lstlisting}
  501. (Prim '- (list (Int 8)))
  502. \end{lstlisting}
  503. \end{minipage}
  504. \begin{minipage}{0.25\textwidth}
  505. \begin{equation}
  506. \begin{tikzpicture}
  507. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  508. \node[draw, circle] (8) at (0, -1.2) {$8$};
  509. \draw[->] (minus) to (8);
  510. \end{tikzpicture}
  511. \label{eq:arith-neg8}
  512. \end{equation}
  513. \end{minipage}
  514. \end{center}
  515. The next grammar rule is for addition expressions:
  516. \begin{equation}
  517. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  518. \end{equation}
  519. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  520. \LangInt{}. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  521. \eqref{eq:arith-read} and we have already categorized \code{(Prim '-
  522. (list (Int 8)))} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  523. to show that
  524. \begin{lstlisting}
  525. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  526. \end{lstlisting}
  527. is an $\Exp$ in the \LangInt{} language.
  528. If you have an AST for which the above rules do not apply, then the
  529. AST is not in \LangInt{}. For example, the program \code{(- (read) (+ 8))}
  530. is not in \LangInt{} because there are no rules for \code{+} with only one
  531. argument, nor for \key{-} with two arguments. Whenever we define a
  532. language with a grammar, the language only includes those programs
  533. that are justified by the rules.
  534. The last grammar rule for \LangInt{} states that there is a \code{Program}
  535. node to mark the top of the whole program:
  536. \[
  537. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  538. \]
  539. The \code{Program} structure is defined as follows
  540. \begin{lstlisting}
  541. (struct Program (info body))
  542. \end{lstlisting}
  543. where \code{body} is an expression. In later chapters, the \code{info}
  544. part will be used to store auxiliary information but for now it is
  545. just the empty list.
  546. It is common to have many grammar rules with the same left-hand side
  547. but different right-hand sides, such as the rules for $\Exp$ in the
  548. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  549. combine several right-hand-sides into a single rule.
  550. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  551. in Figure~\ref{fig:r0-syntax}. The concrete syntax for \LangInt{} is
  552. defined in Figure~\ref{fig:r0-concrete-syntax}.
  553. The \code{read-program} function provided in \code{utilities.rkt} of
  554. the support materials reads a program in from a file (the sequence of
  555. characters in the concrete syntax of Racket) and parses it into an
  556. abstract syntax tree. See the description of \code{read-program} in
  557. Appendix~\ref{appendix:utilities} for more details.
  558. \begin{figure}[tp]
  559. \fbox{
  560. \begin{minipage}{0.96\textwidth}
  561. \[
  562. \begin{array}{rcl}
  563. \begin{array}{rcl}
  564. \Exp &::=& \Int \mid \LP\key{read}\RP \mid \LP\key{-}\;\Exp\RP \mid \LP\key{+} \; \Exp\;\Exp\RP\\
  565. \LangInt{} &::=& \Exp
  566. \end{array}
  567. \end{array}
  568. \]
  569. \end{minipage}
  570. }
  571. \caption{The concrete syntax of \LangInt{}.}
  572. \label{fig:r0-concrete-syntax}
  573. \end{figure}
  574. \begin{figure}[tp]
  575. \fbox{
  576. \begin{minipage}{0.96\textwidth}
  577. \[
  578. \begin{array}{rcl}
  579. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  580. &\mid& \ADD{\Exp}{\Exp} \\
  581. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  582. \end{array}
  583. \]
  584. \end{minipage}
  585. }
  586. \caption{The abstract syntax of \LangInt{}.}
  587. \label{fig:r0-syntax}
  588. \end{figure}
  589. \section{Pattern Matching}
  590. \label{sec:pattern-matching}
  591. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  592. the parts of an AST node. Racket provides the \texttt{match} form to
  593. access the parts of a structure. Consider the following example and
  594. the output on the right. \index{match} \index{pattern matching}
  595. \begin{center}
  596. \begin{minipage}{0.5\textwidth}
  597. \begin{lstlisting}
  598. (match ast1.1
  599. [(Prim op (list child1 child2))
  600. (print op)])
  601. \end{lstlisting}
  602. \end{minipage}
  603. \vrule
  604. \begin{minipage}{0.25\textwidth}
  605. \begin{lstlisting}
  606. '+
  607. \end{lstlisting}
  608. \end{minipage}
  609. \end{center}
  610. In the above example, the \texttt{match} form takes an AST
  611. \eqref{eq:arith-prog} and binds its parts to the three pattern
  612. variables \texttt{op}, \texttt{child1}, and \texttt{child2}, and then
  613. prints out the operator. In general, a match clause consists of a
  614. \emph{pattern} and a \emph{body}.\index{pattern} Patterns are
  615. recursively defined to be either a pattern variable, a structure name
  616. followed by a pattern for each of the structure's arguments, or an
  617. S-expression (symbols, lists, etc.). (See Chapter 12 of The Racket
  618. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  619. and Chapter 9 of The Racket
  620. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  621. for a complete description of \code{match}.)
  622. %
  623. The body of a match clause may contain arbitrary Racket code. The
  624. pattern variables can be used in the scope of the body, such as
  625. \code{op} in \code{(print op)}.
  626. A \code{match} form may contain several clauses, as in the following
  627. function \code{leaf?} that recognizes when an \LangInt{} node is a leaf in
  628. the AST. The \code{match} proceeds through the clauses in order,
  629. checking whether the pattern can match the input AST. The body of the
  630. first clause that matches is executed. The output of \code{leaf?} for
  631. several ASTs is shown on the right.
  632. \begin{center}
  633. \begin{minipage}{0.6\textwidth}
  634. \begin{lstlisting}
  635. (define (leaf? arith)
  636. (match arith
  637. [(Int n) #t]
  638. [(Prim 'read '()) #t]
  639. [(Prim '- (list e1)) #f]
  640. [(Prim '+ (list e1 e2)) #f]))
  641. (leaf? (Prim 'read '()))
  642. (leaf? (Prim '- (list (Int 8))))
  643. (leaf? (Int 8))
  644. \end{lstlisting}
  645. \end{minipage}
  646. \vrule
  647. \begin{minipage}{0.25\textwidth}
  648. \begin{lstlisting}
  649. #t
  650. #f
  651. #t
  652. \end{lstlisting}
  653. \end{minipage}
  654. \end{center}
  655. When writing a \code{match}, we refer to the grammar definition to
  656. identify which non-terminal we are expecting to match against, then we
  657. make sure that 1) we have one clause for each alternative of that
  658. non-terminal and 2) that the pattern in each clause corresponds to the
  659. corresponding right-hand side of a grammar rule. For the \code{match}
  660. in the \code{leaf?} function, we refer to the grammar for \LangInt{} in
  661. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  662. alternatives, so the \code{match} has 4 clauses. The pattern in each
  663. clause corresponds to the right-hand side of a grammar rule. For
  664. example, the pattern \code{(Prim '+ (list e1 e2))} corresponds to the
  665. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  666. patterns, replace non-terminals such as $\Exp$ with pattern variables
  667. of your choice (e.g. \code{e1} and \code{e2}).
  668. \section{Recursive Functions}
  669. \label{sec:recursion}
  670. \index{recursive function}
  671. Programs are inherently recursive. For example, an \LangInt{} expression is
  672. often made of smaller expressions. Thus, the natural way to process an
  673. entire program is with a recursive function. As a first example of
  674. such a recursive function, we define \texttt{exp?} below, which takes
  675. an arbitrary value and determines whether or not it is an \LangInt{}
  676. expression.
  677. %
  678. We say that a function is defined by \emph{structural recursion} when
  679. it is defined using a sequence of match clauses that correspond to a
  680. grammar, and the body of each clause makes a recursive call on each
  681. child node.\footnote{This principle of structuring code according to
  682. the data definition is advocated in the book \emph{How to Design
  683. Programs} \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}.
  684. Below we also define a second function, named \code{Rint?}, that
  685. determines whether an AST is an \LangInt{} program. In general we can
  686. expect to write one recursive function to handle each non-terminal in
  687. a grammar.\index{structural recursion}
  688. %
  689. \begin{center}
  690. \begin{minipage}{0.7\textwidth}
  691. \begin{lstlisting}
  692. (define (exp? ast)
  693. (match ast
  694. [(Int n) #t]
  695. [(Prim 'read '()) #t]
  696. [(Prim '- (list e)) (exp? e)]
  697. [(Prim '+ (list e1 e2))
  698. (and (exp? e1) (exp? e2))]
  699. [else #f]))
  700. (define (Rint? ast)
  701. (match ast
  702. [(Program '() e) (exp? e)]
  703. [else #f]))
  704. (Rint? (Program '() ast1.1)
  705. (Rint? (Program '()
  706. (Prim '- (list (Prim 'read '())
  707. (Prim '+ (list (Num 8)))))))
  708. \end{lstlisting}
  709. \end{minipage}
  710. \vrule
  711. \begin{minipage}{0.25\textwidth}
  712. \begin{lstlisting}
  713. #t
  714. #f
  715. \end{lstlisting}
  716. \end{minipage}
  717. \end{center}
  718. You may be tempted to merge the two functions into one, like this:
  719. \begin{center}
  720. \begin{minipage}{0.5\textwidth}
  721. \begin{lstlisting}
  722. (define (Rint? ast)
  723. (match ast
  724. [(Int n) #t]
  725. [(Prim 'read '()) #t]
  726. [(Prim '- (list e)) (Rint? e)]
  727. [(Prim '+ (list e1 e2)) (and (Rint? e1) (Rint? e2))]
  728. [(Program '() e) (Rint? e)]
  729. [else #f]))
  730. \end{lstlisting}
  731. \end{minipage}
  732. \end{center}
  733. %
  734. Sometimes such a trick will save a few lines of code, especially when
  735. it comes to the \code{Program} wrapper. Yet this style is generally
  736. \emph{not} recommended because it can get you into trouble.
  737. %
  738. For example, the above function is subtly wrong:
  739. \lstinline{(Rint? (Program '() (Program '() (Int 3))))}
  740. returns true when it should return false.
  741. \section{Interpreters}
  742. \label{sec:interp-Rint}
  743. \index{interpreter}
  744. In general, the intended behavior of a program is defined by the
  745. specification of the language. For example, the Scheme language is
  746. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  747. defined in its reference manual~\citep{plt-tr}. In this book we use
  748. interpreters to specify each language that we consider. An interpreter
  749. that is designated as the definition of a language is called a
  750. \emph{definitional interpreter}~\citep{reynolds72:_def_interp}.
  751. \index{definitional interpreter} We warm up by creating a definitional
  752. interpreter for the \LangInt{} language, which serves as a second example
  753. of structural recursion. The \texttt{interp-Rint} function is defined in
  754. Figure~\ref{fig:interp-Rint}. The body of the function is a match on the
  755. input program followed by a call to the \lstinline{interp-exp} helper
  756. function, which in turn has one match clause per grammar rule for
  757. \LangInt{} expressions.
  758. \begin{figure}[tp]
  759. \begin{lstlisting}
  760. (define (interp-exp e)
  761. (match e
  762. [(Int n) n]
  763. [(Prim 'read '())
  764. (define r (read))
  765. (cond [(fixnum? r) r]
  766. [else (error 'interp-exp "read expected an integer" r)])]
  767. [(Prim '- (list e))
  768. (define v (interp-exp e))
  769. (fx- 0 v)]
  770. [(Prim '+ (list e1 e2))
  771. (define v1 (interp-exp e1))
  772. (define v2 (interp-exp e2))
  773. (fx+ v1 v2)]))
  774. (define (interp-Rint p)
  775. (match p
  776. [(Program '() e) (interp-exp e)]))
  777. \end{lstlisting}
  778. \caption{Interpreter for the \LangInt{} language.}
  779. \label{fig:interp-Rint}
  780. \end{figure}
  781. Let us consider the result of interpreting a few \LangInt{} programs. The
  782. following program adds two integers.
  783. \begin{lstlisting}
  784. (+ 10 32)
  785. \end{lstlisting}
  786. The result is \key{42}, the answer to life, the universe, and
  787. everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to the
  788. Galaxy} by Douglas Adams.}.
  789. %
  790. We wrote the above program in concrete syntax whereas the parsed
  791. abstract syntax is:
  792. \begin{lstlisting}
  793. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  794. \end{lstlisting}
  795. The next example demonstrates that expressions may be nested within
  796. each other, in this case nesting several additions and negations.
  797. \begin{lstlisting}
  798. (+ 10 (- (+ 12 20)))
  799. \end{lstlisting}
  800. What is the result of the above program?
  801. As mentioned previously, the \LangInt{} language does not support
  802. arbitrarily-large integers, but only $63$-bit integers, so we
  803. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  804. in Racket.
  805. Suppose
  806. \[
  807. n = 999999999999999999
  808. \]
  809. which indeed fits in $63$-bits. What happens when we run the
  810. following program in our interpreter?
  811. \begin{lstlisting}
  812. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  813. \end{lstlisting}
  814. It produces an error:
  815. \begin{lstlisting}
  816. fx+: result is not a fixnum
  817. \end{lstlisting}
  818. We establish the convention that if running the definitional
  819. interpreter on a program produces an error then the meaning of that
  820. program is \emph{unspecified}\index{unspecified behavior}, unless the
  821. error is a \code{trapped-error}. A compiler for the language is under
  822. no obligations regarding programs with unspecified behavior; it does
  823. not have to produce an executable, and if it does, that executable can
  824. do anything. On the other hand, if the error is a
  825. \code{trapped-error}, then the compiler must produce an executable and
  826. it is required to report that an error occurred. To signal an error,
  827. exit with a return code of \code{255}. The interpreters in chapters
  828. \ref{ch:type-dynamic} and \ref{ch:gradual-typing} use
  829. \code{trapped-error}.
  830. %% This convention applies to the languages defined in this
  831. %% book, as a way to simplify the student's task of implementing them,
  832. %% but this convention is not applicable to all programming languages.
  833. %%
  834. Moving on to the last feature of the \LangInt{} language, the \key{read}
  835. operation prompts the user of the program for an integer. Recall that
  836. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  837. \code{8}. So if we run
  838. \begin{lstlisting}
  839. (interp-Rint (Program '() ast1.1))
  840. \end{lstlisting}
  841. and if the input is \code{50}, the result is \code{42}.
  842. We include the \key{read} operation in \LangInt{} so a clever student
  843. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  844. during compilation to obtain the output and then generates the trivial
  845. code to produce the output. (Yes, a clever student did this in the
  846. first instance of this course.)
  847. The job of a compiler is to translate a program in one language into a
  848. program in another language so that the output program behaves the
  849. same way as the input program does. This idea is depicted in the
  850. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  851. $\mathcal{L}_2$, and a definitional interpreter for each language.
  852. Given a compiler that translates from language $\mathcal{L}_1$ to
  853. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  854. compiler must translate it into some program $P_2$ such that
  855. interpreting $P_1$ and $P_2$ on their respective interpreters with
  856. same input $i$ yields the same output $o$.
  857. \begin{equation} \label{eq:compile-correct}
  858. \begin{tikzpicture}[baseline=(current bounding box.center)]
  859. \node (p1) at (0, 0) {$P_1$};
  860. \node (p2) at (3, 0) {$P_2$};
  861. \node (o) at (3, -2.5) {$o$};
  862. \path[->] (p1) edge [above] node {compile} (p2);
  863. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  864. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  865. \end{tikzpicture}
  866. \end{equation}
  867. In the next section we see our first example of a compiler.
  868. \section{Example Compiler: a Partial Evaluator}
  869. \label{sec:partial-evaluation}
  870. In this section we consider a compiler that translates \LangInt{} programs
  871. into \LangInt{} programs that may be more efficient, that is, this compiler
  872. is an optimizer. This optimizer eagerly computes the parts of the
  873. program that do not depend on any inputs, a process known as
  874. \emph{partial evaluation}~\citep{Jones:1993uq}.
  875. \index{partial evaluation}
  876. For example, given the following program
  877. \begin{lstlisting}
  878. (+ (read) (- (+ 5 3)))
  879. \end{lstlisting}
  880. our compiler will translate it into the program
  881. \begin{lstlisting}
  882. (+ (read) -8)
  883. \end{lstlisting}
  884. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  885. evaluator for the \LangInt{} language. The output of the partial evaluator
  886. is an \LangInt{} program. In Figure~\ref{fig:pe-arith}, the structural
  887. recursion over $\Exp$ is captured in the \code{pe-exp} function
  888. whereas the code for partially evaluating the negation and addition
  889. operations is factored into two separate helper functions:
  890. \code{pe-neg} and \code{pe-add}. The input to these helper
  891. functions is the output of partially evaluating the children.
  892. \begin{figure}[tp]
  893. \begin{lstlisting}
  894. (define (pe-neg r)
  895. (match r
  896. [(Int n) (Int (fx- 0 n))]
  897. [else (Prim '- (list r))]))
  898. (define (pe-add r1 r2)
  899. (match* (r1 r2)
  900. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  901. [(_ _) (Prim '+ (list r1 r2))]))
  902. (define (pe-exp e)
  903. (match e
  904. [(Int n) (Int n)]
  905. [(Prim 'read '()) (Prim 'read '())]
  906. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  907. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]))
  908. (define (pe-Rint p)
  909. (match p
  910. [(Program '() e) (Program '() (pe-exp e))]))
  911. \end{lstlisting}
  912. \caption{A partial evaluator for \LangInt{}.}
  913. \label{fig:pe-arith}
  914. \end{figure}
  915. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  916. arguments are integers and if they are, perform the appropriate
  917. arithmetic. Otherwise, they create an AST node for the arithmetic
  918. operation.
  919. To gain some confidence that the partial evaluator is correct, we can
  920. test whether it produces programs that get the same result as the
  921. input programs. That is, we can test whether it satisfies Diagram
  922. \ref{eq:compile-correct}. The following code runs the partial
  923. evaluator on several examples and tests the output program. The
  924. \texttt{parse-program} and \texttt{assert} functions are defined in
  925. Appendix~\ref{appendix:utilities}.\\
  926. \begin{minipage}{1.0\textwidth}
  927. \begin{lstlisting}
  928. (define (test-pe p)
  929. (assert "testing pe-Rint"
  930. (equal? (interp-Rint p) (interp-Rint (pe-Rint p)))))
  931. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  932. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  933. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  934. \end{lstlisting}
  935. \end{minipage}
  936. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  937. \chapter{Integers and Variables}
  938. \label{ch:int-exp}
  939. This chapter is about compiling a subset of Racket to x86-64 assembly
  940. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  941. integer arithmetic and local variable binding. We often refer to
  942. x86-64 simply as x86. The chapter begins with a description of the
  943. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  944. to of x86 assembly (Section~\ref{sec:x86}). The x86 assembly language
  945. is large so we discuss only the instructions needed for compiling
  946. \LangVar{}. We introduce more x86 instructions in later chapters.
  947. After introducing \LangVar{} and x86, we reflect on their differences
  948. and come up with a plan to break down the translation from \LangVar{}
  949. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  950. rest of the sections in this chapter give detailed hints regarding
  951. each step (Sections~\ref{sec:uniquify-Rvar} through \ref{sec:patch-s0}).
  952. We hope to give enough hints that the well-prepared reader, together
  953. with a few friends, can implement a compiler from \LangVar{} to x86 in
  954. a couple weeks. To give the reader a feeling for the scale of this
  955. first compiler, the instructor solution for the \LangVar{} compiler is
  956. approximately 500 lines of code.
  957. \section{The \LangVar{} Language}
  958. \label{sec:s0}
  959. \index{variable}
  960. The \LangVar{} language extends the \LangInt{} language with variable
  961. definitions. The concrete syntax of the \LangVar{} language is defined by
  962. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  963. syntax is defined in Figure~\ref{fig:r1-syntax}. The non-terminal
  964. \Var{} may be any Racket identifier. As in \LangInt{}, \key{read} is a
  965. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  966. operator. Similar to \LangInt{}, the abstract syntax of \LangVar{} includes the
  967. \key{Program} struct to mark the top of the program.
  968. %% The $\itm{info}$
  969. %% field of the \key{Program} structure contains an \emph{association
  970. %% list} (a list of key-value pairs) that is used to communicate
  971. %% auxiliary data from one compiler pass the next.
  972. Despite the simplicity of the \LangVar{} language, it is rich enough to
  973. exhibit several compilation techniques.
  974. \begin{figure}[tp]
  975. \centering
  976. \fbox{
  977. \begin{minipage}{0.96\textwidth}
  978. \[
  979. \begin{array}{rcl}
  980. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp}\\
  981. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  982. \LangVar{} &::=& \Exp
  983. \end{array}
  984. \]
  985. \end{minipage}
  986. }
  987. \caption{The concrete syntax of \LangVar{}.}
  988. \label{fig:r1-concrete-syntax}
  989. \end{figure}
  990. \begin{figure}[tp]
  991. \centering
  992. \fbox{
  993. \begin{minipage}{0.96\textwidth}
  994. \[
  995. \begin{array}{rcl}
  996. \Exp &::=& \INT{\Int} \mid \READ{} \\
  997. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  998. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  999. \LangVar{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1000. \end{array}
  1001. \]
  1002. \end{minipage}
  1003. }
  1004. \caption{The abstract syntax of \LangVar{}.}
  1005. \label{fig:r1-syntax}
  1006. \end{figure}
  1007. Let us dive further into the syntax and semantics of the \LangVar{}
  1008. language. The \key{let} feature defines a variable for use within its
  1009. body and initializes the variable with the value of an expression.
  1010. The abstract syntax for \key{let} is defined in
  1011. Figure~\ref{fig:r1-syntax}. The concrete syntax for \key{let} is
  1012. \begin{lstlisting}
  1013. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1014. \end{lstlisting}
  1015. For example, the following program initializes \code{x} to $32$ and then
  1016. evaluates the body \code{(+ 10 x)}, producing $42$.
  1017. \begin{lstlisting}
  1018. (let ([x (+ 12 20)]) (+ 10 x))
  1019. \end{lstlisting}
  1020. When there are multiple \key{let}'s for the same variable, the closest
  1021. enclosing \key{let} is used. That is, variable definitions overshadow
  1022. prior definitions. Consider the following program with two \key{let}'s
  1023. that define variables named \code{x}. Can you figure out the result?
  1024. \begin{lstlisting}
  1025. (let ([x 32]) (+ (let ([x 10]) x) x))
  1026. \end{lstlisting}
  1027. For the purposes of depicting which variable uses correspond to which
  1028. definitions, the following shows the \code{x}'s annotated with
  1029. subscripts to distinguish them. Double check that your answer for the
  1030. above is the same as your answer for this annotated version of the
  1031. program.
  1032. \begin{lstlisting}
  1033. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1034. \end{lstlisting}
  1035. The initializing expression is always evaluated before the body of the
  1036. \key{let}, so in the following, the \key{read} for \code{x} is
  1037. performed before the \key{read} for \code{y}. Given the input
  1038. $52$ then $10$, the following produces $42$ (not $-42$).
  1039. \begin{lstlisting}
  1040. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1041. \end{lstlisting}
  1042. \subsection{Extensible Interpreters via Method Overriding}
  1043. \label{sec:extensible-interp}
  1044. To prepare for discussing the interpreter for \LangVar{}, we need to
  1045. explain why we choose to implement the interpreter using
  1046. object-oriented programming, that is, as a collection of methods
  1047. inside of a class. Throughout this book we define many interpreters,
  1048. one for each of the languages that we study. Because each language
  1049. builds on the prior one, there is a lot of commonality between their
  1050. interpreters. We want to write down those common parts just once
  1051. instead of many times. A naive approach would be to have, for example,
  1052. the interpreter for \LangIf{} handle all of the new features in that
  1053. language and then have a default case that dispatches to the
  1054. interpreter for \LangVar{}. The following code sketches this idea.
  1055. \begin{center}
  1056. \begin{minipage}{0.45\textwidth}
  1057. \begin{lstlisting}
  1058. (define (interp-Rvar e)
  1059. (match e
  1060. [(Prim '- (list e))
  1061. (fx- 0 (interp-Rvar e))]
  1062. ...))
  1063. \end{lstlisting}
  1064. \end{minipage}
  1065. \begin{minipage}{0.45\textwidth}
  1066. \begin{lstlisting}
  1067. (define (interp-Rif e)
  1068. (match e
  1069. [(If cnd thn els)
  1070. (match (interp-Rif cnd)
  1071. [#t (interp-Rif thn)]
  1072. [#f (interp-Rif els)])]
  1073. ...
  1074. [else (interp-Rvar e)]))
  1075. \end{lstlisting}
  1076. \end{minipage}
  1077. \end{center}
  1078. The problem with this approach is that it does not handle situations
  1079. in which an \LangIf{} feature, like \code{If}, is nested inside an \LangVar{}
  1080. feature, like the \code{-} operator, as in the following program.
  1081. \begin{lstlisting}
  1082. (Prim '- (list (If (Bool #t) (Int 42) (Int 0))))
  1083. \end{lstlisting}
  1084. If we invoke \code{interp-Rif} on this program, it dispatches to
  1085. \code{interp-Rvar} to handle the \code{-} operator, but then it
  1086. recurisvely calls \code{interp-Rvar} again on the argument of \code{-},
  1087. which is an \code{If}. But there is no case for \code{If} in
  1088. \code{interp-Rvar}, so we get an error!
  1089. To make our interpreters extensible we need something called
  1090. \emph{open recursion}\index{open recursion}, where the tying of the
  1091. recursive knot is delayed to when the functions are
  1092. composed. Object-oriented languages provide open recursion with the
  1093. late-binding of overridden methods\index{method overriding}. The
  1094. following code sketches this idea for interpreting \LangVar{} and
  1095. \LangIf{} using the
  1096. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1097. \index{class} feature of Racket. We define one class for each
  1098. language and define a method for interpreting expressions inside each
  1099. class. The class for \LangIf{} inherits from the class for \LangVar{}
  1100. and the method \code{interp-exp} in \LangIf{} overrides the
  1101. \code{interp-exp} in \LangVar{}. Note that the default case of
  1102. \code{interp-exp} in \LangIf{} uses \code{super} to invoke
  1103. \code{interp-exp}, and because \LangIf{} inherits from \LangVar{},
  1104. that dispatches to the \code{interp-exp} in \LangVar{}.
  1105. \begin{center}
  1106. \begin{minipage}{0.45\textwidth}
  1107. \begin{lstlisting}
  1108. (define interp-Rvar-class
  1109. (class object%
  1110. (define/public (interp-exp e)
  1111. (match e
  1112. [(Prim '- (list e))
  1113. (fx- 0 (interp-exp e))]
  1114. ...))
  1115. ...))
  1116. \end{lstlisting}
  1117. \end{minipage}
  1118. \begin{minipage}{0.45\textwidth}
  1119. \begin{lstlisting}
  1120. (define interp-Rif-class
  1121. (class interp-Rvar-class
  1122. (define/override (interp-exp e)
  1123. (match e
  1124. [(If cnd thn els)
  1125. (match (interp-exp cnd)
  1126. [#t (interp-exp thn)]
  1127. [#f (interp-exp els)])]
  1128. ...
  1129. [else (super interp-exp e)]))
  1130. ...
  1131. ))
  1132. \end{lstlisting}
  1133. \end{minipage}
  1134. \end{center}
  1135. Getting back to the troublesome example, repeated here:
  1136. \begin{lstlisting}
  1137. (define e0 (Prim '- (list (If (Bool #t) (Int 42) (Int 0)))))
  1138. \end{lstlisting}
  1139. We can invoke the \code{interp-exp} method for \LangIf{} on this
  1140. expression by creating an object of the \LangIf{} class and sending it the
  1141. \code{interp-exp} method with the argument \code{e0}.
  1142. \begin{lstlisting}
  1143. (send (new interp-Rif-class) interp-exp e0)
  1144. \end{lstlisting}
  1145. The default case of \code{interp-exp} in \LangIf{} handles it by
  1146. dispatching to the \code{interp-exp} method in \LangVar{}, which
  1147. handles the \code{-} operator. But then for the recursive method call,
  1148. it dispatches back to \code{interp-exp} in \LangIf{}, where the
  1149. \code{If} is handled correctly. Thus, method overriding gives us the
  1150. open recursion that we need to implement our interpreters in an
  1151. extensible way.
  1152. \newpage
  1153. \subsection{Definitional Interpreter for \LangVar{}}
  1154. \begin{wrapfigure}[25]{r}[1.0in]{0.6\textwidth}
  1155. \small
  1156. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1157. An \emph{association list} (alist) is a list of key-value pairs.
  1158. For example, we can map people to their ages with an alist.
  1159. \index{alist}\index{association list}
  1160. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1161. (define ages
  1162. '((jane . 25) (sam . 24) (kate . 45)))
  1163. \end{lstlisting}
  1164. The \emph{dictionary} interface is for mapping keys to values.
  1165. Every alist implements this interface. \index{dictionary} The package
  1166. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1167. provides many functions for working with dictionaries. Here
  1168. are a few of them:
  1169. \begin{description}
  1170. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1171. returns the value associated with the given $\itm{key}$.
  1172. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1173. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1174. but otherwise is the same as $\itm{dict}$.
  1175. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1176. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1177. of keys and values in $\itm{dict}$. For example, the following
  1178. creates a new alist in which the ages are incremented.
  1179. \end{description}
  1180. \vspace{-10pt}
  1181. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1182. (for/list ([(k v) (in-dict ages)])
  1183. (cons k (add1 v)))
  1184. \end{lstlisting}
  1185. \end{tcolorbox}
  1186. \end{wrapfigure}
  1187. Having justified the use of classes and methods to implement
  1188. interpreters, we turn to the definitional interpreter for \LangVar{}
  1189. in Figure~\ref{fig:interp-Rvar}. It is similar to the interpreter for
  1190. \LangInt{} but adds two new \key{match} cases for variables and
  1191. \key{let}. For \key{let} we need a way to communicate the value bound
  1192. to a variable to all the uses of the variable. To accomplish this, we
  1193. maintain a mapping from variables to values. Throughout the compiler
  1194. we often need to map variables to information about them. We refer to
  1195. these mappings as
  1196. \emph{environments}\index{environment}.\footnote{Another common term
  1197. for environment in the compiler literature is \emph{symbol
  1198. table}\index{symbol table}.}
  1199. %
  1200. For simplicity, we use an association list (alist) to represent the
  1201. environment. The sidebar to the right gives a brief introduction to
  1202. alists and the \code{racket/dict} package. The \code{interp-exp}
  1203. function takes the current environment, \code{env}, as an extra
  1204. parameter. When the interpreter encounters a variable, it finds the
  1205. corresponding value using the \code{dict-ref} function. When the
  1206. interpreter encounters a \key{Let}, it evaluates the initializing
  1207. expression, extends the environment with the result value bound to the
  1208. variable, using \code{dict-set}, then evaluates the body of the
  1209. \key{Let}.
  1210. \begin{figure}[tp]
  1211. \begin{lstlisting}
  1212. (define interp-Rvar-class
  1213. (class object%
  1214. (super-new)
  1215. (define/public ((interp-exp env) e)
  1216. (match e
  1217. [(Int n) n]
  1218. [(Prim 'read '())
  1219. (define r (read))
  1220. (cond [(fixnum? r) r]
  1221. [else (error 'interp-exp "expected an integer" r)])]
  1222. [(Prim '- (list e)) (fx- 0 ((interp-exp env) e))]
  1223. [(Prim '+ (list e1 e2))
  1224. (fx+ ((interp-exp env) e1) ((interp-exp env) e2))]
  1225. [(Var x) (dict-ref env x)]
  1226. [(Let x e body)
  1227. (define new-env (dict-set env x ((interp-exp env) e)))
  1228. ((interp-exp new-env) body)]))
  1229. (define/public (interp-program p)
  1230. (match p
  1231. [(Program '() e) ((interp-exp '()) e)]))
  1232. ))
  1233. (define (interp-Rvar p)
  1234. (send (new interp-Rvar-class) interp-program p))
  1235. \end{lstlisting}
  1236. \caption{Interpreter for the \LangVar{} language.}
  1237. \label{fig:interp-Rvar}
  1238. \end{figure}
  1239. The goal for this chapter is to implement a compiler that translates
  1240. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  1241. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1242. computer as the $P_1$ program interpreted by \code{interp-Rvar}. That
  1243. is, they output the same integer $n$. We depict this correctness
  1244. criteria in the following diagram.
  1245. \[
  1246. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1247. \node (p1) at (0, 0) {$P_1$};
  1248. \node (p2) at (4, 0) {$P_2$};
  1249. \node (o) at (4, -2) {$n$};
  1250. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1251. \path[->] (p1) edge [left] node {\footnotesize\code{interp-Rvar}} (o);
  1252. \path[->] (p2) edge [right] node {\footnotesize\code{interp-x86int}} (o);
  1253. \end{tikzpicture}
  1254. \]
  1255. In the next section we introduce the \LangXInt{} subset of x86 that
  1256. suffices for compiling \LangVar{}.
  1257. \section{The \LangXInt{} Assembly Language}
  1258. \label{sec:x86}
  1259. \index{x86}
  1260. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  1261. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  1262. assembler.
  1263. %
  1264. A program begins with a \code{main} label followed by a sequence of
  1265. instructions. The \key{globl} directive says that the \key{main}
  1266. procedure is externally visible, which is necessary so that the
  1267. operating system can call it. In the grammar, ellipses such as
  1268. $\ldots$ are used to indicate a sequence of items, e.g., $\Instr
  1269. \ldots$ is a sequence of instructions.\index{instruction}
  1270. %
  1271. An x86 program is stored in the computer's memory. For our purposes,
  1272. the computer's memory is as a mapping of 64-bit addresses to 64-bit
  1273. values. The computer has a \emph{program counter} (PC)\index{program
  1274. counter}\index{PC} stored in the \code{rip} register that points to
  1275. the address of the next instruction to be executed. For most
  1276. instructions, the program counter is incremented after the instruction
  1277. is executed, so it points to the next instruction in memory. Most x86
  1278. instructions take two operands, where each operand is either an
  1279. integer constant (called \emph{immediate value}\index{immediate
  1280. value}), a \emph{register}\index{register}, or a memory location.
  1281. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1282. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1283. && \key{r8} \mid \key{r9} \mid \key{r10}
  1284. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1285. \mid \key{r14} \mid \key{r15}}
  1286. \begin{figure}[tp]
  1287. \fbox{
  1288. \begin{minipage}{0.96\textwidth}
  1289. \[
  1290. \begin{array}{lcl}
  1291. \Reg &::=& \allregisters{} \\
  1292. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1293. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1294. \key{subq} \; \Arg\key{,} \Arg \mid
  1295. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1296. && \key{callq} \; \mathit{label} \mid
  1297. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} \\
  1298. && \itm{label}\key{:}\; \Instr \\
  1299. \LangXInt{} &::= & \key{.globl main}\\
  1300. & & \key{main:} \; \Instr\ldots
  1301. \end{array}
  1302. \]
  1303. \end{minipage}
  1304. }
  1305. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  1306. \label{fig:x86-int-concrete}
  1307. \end{figure}
  1308. A register is a special kind of variable. Each one holds a 64-bit
  1309. value; there are 16 general-purpose registers in the computer and
  1310. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  1311. is written with a \key{\%} followed by the register name, such as
  1312. \key{\%rax}.
  1313. An immediate value is written using the notation \key{\$}$n$ where $n$
  1314. is an integer.
  1315. %
  1316. %
  1317. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1318. which obtains the address stored in register $r$ and then adds $n$
  1319. bytes to the address. The resulting address is used to load or store
  1320. to memory depending on whether it occurs as a source or destination
  1321. argument of an instruction.
  1322. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1323. source $s$ and destination $d$, applies the arithmetic operation, then
  1324. writes the result back to the destination $d$.
  1325. %
  1326. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1327. stores the result in $d$.
  1328. %
  1329. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  1330. specified by the label and $\key{retq}$ returns from a procedure to
  1331. its caller.
  1332. %
  1333. We discuss procedure calls in more detail later in this chapter and in
  1334. Chapter~\ref{ch:functions}. The instruction $\key{jmp}\,\itm{label}$
  1335. updates the program counter to the address of the instruction after
  1336. the specified label.
  1337. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  1338. all of the x86 instructions used in this book.
  1339. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent to
  1340. \code{(+ 10 32)}. The instruction \lstinline{movq $10, %rax}
  1341. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  1342. adds $32$ to the $10$ in \key{rax} and
  1343. puts the result, $42$, back into \key{rax}.
  1344. %
  1345. The last instruction, \key{retq}, finishes the \key{main} function by
  1346. returning the integer in \key{rax} to the operating system. The
  1347. operating system interprets this integer as the program's exit
  1348. code. By convention, an exit code of 0 indicates that a program
  1349. completed successfully, and all other exit codes indicate various
  1350. errors. Nevertheless, in this book we return the result of the program
  1351. as the exit code.
  1352. \begin{figure}[tbp]
  1353. \begin{lstlisting}
  1354. .globl main
  1355. main:
  1356. movq $10, %rax
  1357. addq $32, %rax
  1358. retq
  1359. \end{lstlisting}
  1360. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1361. \label{fig:p0-x86}
  1362. \end{figure}
  1363. The x86 assembly language varies in a couple ways depending on what
  1364. operating system it is assembled in. The code examples shown here are
  1365. correct on Linux and most Unix-like platforms, but when assembled on
  1366. Mac OS X, labels like \key{main} must be prefixed with an underscore,
  1367. as in \key{\_main}.
  1368. We exhibit the use of memory for storing intermediate results in the
  1369. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1370. equivalent to \code{(+ 52 (- 10))}. This program uses a region of
  1371. memory called the \emph{procedure call stack} (or \emph{stack} for
  1372. short). \index{stack}\index{procedure call stack} The stack consists
  1373. of a separate \emph{frame}\index{frame} for each procedure call. The
  1374. memory layout for an individual frame is shown in
  1375. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1376. \emph{stack pointer}\index{stack pointer} and points to the item at
  1377. the top of the stack. The stack grows downward in memory, so we
  1378. increase the size of the stack by subtracting from the stack pointer.
  1379. In the context of a procedure call, the \emph{return
  1380. address}\index{return address} is the instruction after the call
  1381. instruction on the caller side. The function call instruction,
  1382. \code{callq}, pushes the return address onto the stack prior to
  1383. jumping to the procedure. The register \key{rbp} is the \emph{base
  1384. pointer}\index{base pointer} and is used to access variables that
  1385. are stored in the frame of the current procedure call. The base
  1386. pointer of the caller is pushed onto the stack after the return
  1387. address and then the base pointer is set to the location of the old
  1388. base pointer. In Figure~\ref{fig:frame} we number the variables from
  1389. $1$ to $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$,
  1390. variable $2$ at $-16\key{(\%rbp)}$, etc.
  1391. \begin{figure}[tbp]
  1392. \begin{lstlisting}
  1393. start:
  1394. movq $10, -8(%rbp)
  1395. negq -8(%rbp)
  1396. movq -8(%rbp), %rax
  1397. addq $52, %rax
  1398. jmp conclusion
  1399. .globl main
  1400. main:
  1401. pushq %rbp
  1402. movq %rsp, %rbp
  1403. subq $16, %rsp
  1404. jmp start
  1405. conclusion:
  1406. addq $16, %rsp
  1407. popq %rbp
  1408. retq
  1409. \end{lstlisting}
  1410. \caption{An x86 program equivalent to \code{(+ 52 (- 10))}.}
  1411. \label{fig:p1-x86}
  1412. \end{figure}
  1413. \begin{figure}[tbp]
  1414. \centering
  1415. \begin{tabular}{|r|l|} \hline
  1416. Position & Contents \\ \hline
  1417. 8(\key{\%rbp}) & return address \\
  1418. 0(\key{\%rbp}) & old \key{rbp} \\
  1419. -8(\key{\%rbp}) & variable $1$ \\
  1420. -16(\key{\%rbp}) & variable $2$ \\
  1421. \ldots & \ldots \\
  1422. 0(\key{\%rsp}) & variable $n$\\ \hline
  1423. \end{tabular}
  1424. \caption{Memory layout of a frame.}
  1425. \label{fig:frame}
  1426. \end{figure}
  1427. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  1428. control is transferred from the operating system to the \code{main}
  1429. function. The operating system issues a \code{callq main} instruction
  1430. which pushes its return address on the stack and then jumps to
  1431. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  1432. by 16 bytes prior to the execution of any \code{callq} instruction, so
  1433. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  1434. alignment (because the \code{callq} pushed the return address). The
  1435. first three instructions are the typical \emph{prelude}\index{prelude}
  1436. for a procedure. The instruction \code{pushq \%rbp} saves the base
  1437. pointer for the caller onto the stack and subtracts $8$ from the stack
  1438. pointer. The second instruction \code{movq \%rsp, \%rbp} changes the
  1439. base pointer so that it points the location of the old base
  1440. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  1441. pointer down to make enough room for storing variables. This program
  1442. needs one variable ($8$ bytes) but we round up to 16 bytes so that
  1443. \code{rsp} is 16-byte aligned and we're ready to make calls to other
  1444. functions. The last instruction of the prelude is \code{jmp start},
  1445. which transfers control to the instructions that were generated from
  1446. the Racket expression \code{(+ 52 (- 10))}.
  1447. The first instruction under the \code{start} label is
  1448. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  1449. %
  1450. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  1451. %
  1452. The next instruction moves the $-10$ from variable $1$ into the
  1453. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  1454. the value in \code{rax}, updating its contents to $42$.
  1455. The three instructions under the label \code{conclusion} are the
  1456. typical \emph{conclusion}\index{conclusion} of a procedure. The first
  1457. two instructions restore the \code{rsp} and \code{rbp} registers to
  1458. the state they were in at the beginning of the procedure. The
  1459. instruction \key{addq \$16, \%rsp} moves the stack pointer back to
  1460. point at the old base pointer. Then \key{popq \%rbp} returns the old
  1461. base pointer to \key{rbp} and adds $8$ to the stack pointer. The last
  1462. instruction, \key{retq}, jumps back to the procedure that called this
  1463. one and adds $8$ to the stack pointer.
  1464. The compiler needs a convenient representation for manipulating x86
  1465. programs, so we define an abstract syntax for x86 in
  1466. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  1467. \LangXInt{}. The main difference compared to the concrete syntax of
  1468. \LangXInt{} (Figure~\ref{fig:x86-int-concrete}) is that labels are not
  1469. allowed in front of every instructions. Instead instructions are
  1470. grouped into \emph{blocks}\index{block}\index{basic block} with a
  1471. label associated with every block, which is why the \key{X86Program}
  1472. struct includes an alist mapping labels to blocks. The reason for this
  1473. organization becomes apparent in Chapter~\ref{ch:bool-types} when we
  1474. introduce conditional branching. The \code{Block} structure includes
  1475. an $\itm{info}$ field that is not needed for this chapter, but becomes
  1476. useful in Chapter~\ref{ch:register-allocation-Rvar}. For now, the
  1477. $\itm{info}$ field should contain an empty list. Also, regarding the
  1478. abstract syntax for \code{callq}, the \code{Callq} struct includes an
  1479. integer for representing the arity of the function, i.e., the number
  1480. of arguments, which is helpful to know during register allocation
  1481. (Chapter~\ref{ch:register-allocation-Rvar}).
  1482. \begin{figure}[tp]
  1483. \fbox{
  1484. \begin{minipage}{0.98\textwidth}
  1485. \small
  1486. \[
  1487. \begin{array}{lcl}
  1488. \Reg &::=& \allregisters{} \\
  1489. \Arg &::=& \IMM{\Int} \mid \REG{\Reg}
  1490. \mid \DEREF{\Reg}{\Int} \\
  1491. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  1492. \mid \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  1493. &\mid& \BININSTR{\code{movq}}{\Arg}{\Arg}
  1494. \mid \UNIINSTR{\code{negq}}{\Arg}\\
  1495. &\mid& \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  1496. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  1497. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP} \\
  1498. \LangXInt{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  1499. \end{array}
  1500. \]
  1501. \end{minipage}
  1502. }
  1503. \caption{The abstract syntax of \LangXInt{} assembly.}
  1504. \label{fig:x86-int-ast}
  1505. \end{figure}
  1506. \section{Planning the trip to x86 via the \LangCVar{} language}
  1507. \label{sec:plan-s0-x86}
  1508. To compile one language to another it helps to focus on the
  1509. differences between the two languages because the compiler will need
  1510. to bridge those differences. What are the differences between \LangVar{}
  1511. and x86 assembly? Here are some of the most important ones:
  1512. \begin{enumerate}
  1513. \item[(a)] x86 arithmetic instructions typically have two arguments
  1514. and update the second argument in place. In contrast, \LangVar{}
  1515. arithmetic operations take two arguments and produce a new value.
  1516. An x86 instruction may have at most one memory-accessing argument.
  1517. Furthermore, some instructions place special restrictions on their
  1518. arguments.
  1519. \item[(b)] An argument of an \LangVar{} operator can be a deeply-nested
  1520. expression, whereas x86 instructions restrict their arguments to be
  1521. integers constants, registers, and memory locations.
  1522. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1523. sequence of instructions and jumps to labeled positions, whereas in
  1524. \LangVar{} the order of evaluation is a left-to-right depth-first
  1525. traversal of the abstract syntax tree.
  1526. \item[(d)] A program in \LangVar{} can have any number of variables
  1527. whereas x86 has 16 registers and the procedure calls stack.
  1528. \item[(e)] Variables in \LangVar{} can overshadow other variables with the
  1529. same name. In x86, registers have unique names and memory locations
  1530. have unique addresses.
  1531. \end{enumerate}
  1532. We ease the challenge of compiling from \LangVar{} to x86 by breaking down
  1533. the problem into several steps, dealing with the above differences one
  1534. at a time. Each of these steps is called a \emph{pass} of the
  1535. compiler.\index{pass}\index{compiler pass}
  1536. %
  1537. This terminology comes from the way each step passes over the AST of
  1538. the program.
  1539. %
  1540. We begin by sketching how we might implement each pass, and give them
  1541. names. We then figure out an ordering of the passes and the
  1542. input/output language for each pass. The very first pass has
  1543. \LangVar{} as its input language and the last pass has \LangXInt{} as
  1544. its output language. In between we can choose whichever language is
  1545. most convenient for expressing the output of each pass, whether that
  1546. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  1547. our own design. Finally, to implement each pass we write one
  1548. recursive function per non-terminal in the grammar of the input
  1549. language of the pass. \index{intermediate language}
  1550. \begin{description}
  1551. \item[\key{select-instructions}] handles the difference between
  1552. \LangVar{} operations and x86 instructions. This pass converts each
  1553. \LangVar{} operation to a short sequence of instructions that
  1554. accomplishes the same task.
  1555. \item[\key{remove-complex-opera*}] ensures that each subexpression of
  1556. a primitive operation is a variable or integer, that is, an
  1557. \emph{atomic} expression. We refer to non-atomic expressions as
  1558. \emph{complex}. This pass introduces temporary variables to hold
  1559. the results of complex subexpressions.\index{atomic
  1560. expression}\index{complex expression}%
  1561. \footnote{The subexpressions of an operation are often called
  1562. operators and operands which explains the presence of
  1563. \code{opera*} in the name of this pass.}
  1564. \item[\key{explicate-control}] makes the execution order of the
  1565. program explicit. It convert the abstract syntax tree representation
  1566. into a control-flow graph in which each node contains a sequence of
  1567. statements and the edges between nodes say which nodes contain jumps
  1568. to other nodes.
  1569. \item[\key{assign-homes}] replaces the variables in \LangVar{} with
  1570. registers or stack locations in x86.
  1571. \item[\key{uniquify}] deals with the shadowing of variables by
  1572. renaming every variable to a unique name.
  1573. \end{description}
  1574. The next question is: in what order should we apply these passes? This
  1575. question can be challenging because it is difficult to know ahead of
  1576. time which orderings will be better (easier to implement, produce more
  1577. efficient code, etc.) so oftentimes trial-and-error is
  1578. involved. Nevertheless, we can try to plan ahead and make educated
  1579. choices regarding the ordering.
  1580. What should be the ordering of \key{explicate-control} with respect to
  1581. \key{uniquify}? The \key{uniquify} pass should come first because
  1582. \key{explicate-control} changes all the \key{let}-bound variables to
  1583. become local variables whose scope is the entire program, which would
  1584. confuse variables with the same name.
  1585. %
  1586. We place \key{remove-complex-opera*} before \key{explicate-control}
  1587. because the later removes the \key{let} form, but it is convenient to
  1588. use \key{let} in the output of \key{remove-complex-opera*}.
  1589. %
  1590. The ordering of \key{uniquify} with respect to
  1591. \key{remove-complex-opera*} does not matter so we arbitrarily choose
  1592. \key{uniquify} to come first.
  1593. Last, we consider \key{select-instructions} and \key{assign-homes}.
  1594. These two passes are intertwined. In Chapter~\ref{ch:functions} we
  1595. learn that, in x86, registers are used for passing arguments to
  1596. functions and it is preferable to assign parameters to their
  1597. corresponding registers. On the other hand, by selecting instructions
  1598. first we may run into a dead end in \key{assign-homes}. Recall that
  1599. only one argument of an x86 instruction may be a memory access but
  1600. \key{assign-homes} might fail to assign even one of them to a
  1601. register.
  1602. %
  1603. A sophisticated approach is to iteratively repeat the two passes until
  1604. a solution is found. However, to reduce implementation complexity we
  1605. recommend a simpler approach in which \key{select-instructions} comes
  1606. first, followed by the \key{assign-homes}, then a third pass named
  1607. \key{patch-instructions} that uses a reserved register to fix
  1608. outstanding problems.
  1609. \begin{figure}[tbp]
  1610. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1611. \node (Rvar) at (0,2) {\large \LangVar{}};
  1612. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  1613. \node (Rvar-3) at (6,2) {\large \LangVarANF{}};
  1614. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  1615. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  1616. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  1617. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  1618. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  1619. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  1620. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  1621. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvar-3);
  1622. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate-control} (Cvar-2);
  1623. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1624. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1625. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1626. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1627. \end{tikzpicture}
  1628. \caption{Diagram of the passes for compiling \LangVar{}. }
  1629. \label{fig:Rvar-passes}
  1630. \end{figure}
  1631. Figure~\ref{fig:Rvar-passes} presents the ordering of the compiler
  1632. passes and identifies the input and output language of each pass. The
  1633. last pass, \key{print-x86}, converts from the abstract syntax of
  1634. \LangXInt{} to the concrete syntax. In the following two sections
  1635. we discuss the \LangCVar{} intermediate language and the \LangXVar{}
  1636. dialect of x86. The remainder of this chapter gives hints regarding
  1637. the implementation of each of the compiler passes in
  1638. Figure~\ref{fig:Rvar-passes}.
  1639. %% The output of \key{uniquify} and \key{remove-complex-opera*}
  1640. %% are programs that are still in the \LangVar{} language, though the
  1641. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  1642. %% (Section~\ref{sec:remove-complex-opera-Rvar}).
  1643. %% %
  1644. %% The output of \key{explicate-control} is in an intermediate language
  1645. %% \LangCVar{} designed to make the order of evaluation explicit in its
  1646. %% syntax, which we introduce in the next section. The
  1647. %% \key{select-instruction} pass translates from \LangCVar{} to
  1648. %% \LangXVar{}. The \key{assign-homes} and
  1649. %% \key{patch-instructions}
  1650. %% passes input and output variants of x86 assembly.
  1651. \subsection{The \LangCVar{} Intermediate Language}
  1652. The output of \key{explicate-control} is similar to the $C$
  1653. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1654. categories for expressions and statements, so we name it \LangCVar{}. The
  1655. abstract syntax for \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  1656. (The concrete syntax for \LangCVar{} is in the Appendix,
  1657. Figure~\ref{fig:c0-concrete-syntax}.)
  1658. %
  1659. The \LangCVar{} language supports the same operators as \LangVar{} but
  1660. the arguments of operators are restricted to atomic
  1661. expressions. Instead of \key{let} expressions, \LangCVar{} has
  1662. assignment statements which can be executed in sequence using the
  1663. \key{Seq} form. A sequence of statements always ends with
  1664. \key{Return}, a guarantee that is baked into the grammar rules for
  1665. \itm{tail}. The naming of this non-terminal comes from the term
  1666. \emph{tail position}\index{tail position}, which refers to an
  1667. expression that is the last one to execute within a function.
  1668. A \LangCVar{} program consists of a control-flow graph represented as
  1669. an alist mapping labels to tails. This is more general than necessary
  1670. for the present chapter, as we do not yet introduce \key{goto} for
  1671. jumping to labels, but it saves us from having to change the syntax in
  1672. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1673. \key{start}, and the whole program is its tail.
  1674. %
  1675. The $\itm{info}$ field of the \key{CProgram} form, after the
  1676. \key{explicate-control} pass, contains a mapping from the symbol
  1677. \key{locals} to a list of variables, that is, a list of all the
  1678. variables used in the program. At the start of the program, these
  1679. variables are uninitialized; they become initialized on their first
  1680. assignment.
  1681. \begin{figure}[tbp]
  1682. \fbox{
  1683. \begin{minipage}{0.96\textwidth}
  1684. \[
  1685. \begin{array}{lcl}
  1686. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1687. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1688. &\mid& \ADD{\Atm}{\Atm}\\
  1689. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  1690. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1691. \LangCVar{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  1692. \end{array}
  1693. \]
  1694. \end{minipage}
  1695. }
  1696. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  1697. \label{fig:c0-syntax}
  1698. \end{figure}
  1699. The definitional interpreter for \LangCVar{} is in the support code
  1700. for this book, in the file \code{interp-Cvar.rkt}. The support code is
  1701. in a \code{github} repository at the following URL:
  1702. \begin{center}\footnotesize
  1703. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  1704. \end{center}
  1705. \subsection{The \LangXVar{} dialect}
  1706. The \LangXVar{} language is the output of the pass
  1707. \key{select-instructions}. It extends \LangXInt{} with an unbounded
  1708. number of program-scope variables and removes the restrictions
  1709. regarding instruction arguments.
  1710. \section{Uniquify Variables}
  1711. \label{sec:uniquify-Rvar}
  1712. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  1713. programs in which every \key{let} binds a unique variable name. For
  1714. example, the \code{uniquify} pass should translate the program on the
  1715. left into the program on the right. \\
  1716. \begin{tabular}{lll}
  1717. \begin{minipage}{0.4\textwidth}
  1718. \begin{lstlisting}
  1719. (let ([x 32])
  1720. (+ (let ([x 10]) x) x))
  1721. \end{lstlisting}
  1722. \end{minipage}
  1723. &
  1724. $\Rightarrow$
  1725. &
  1726. \begin{minipage}{0.4\textwidth}
  1727. \begin{lstlisting}
  1728. (let ([x.1 32])
  1729. (+ (let ([x.2 10]) x.2) x.1))
  1730. \end{lstlisting}
  1731. \end{minipage}
  1732. \end{tabular} \\
  1733. %
  1734. The following is another example translation, this time of a program
  1735. with a \key{let} nested inside the initializing expression of another
  1736. \key{let}.\\
  1737. \begin{tabular}{lll}
  1738. \begin{minipage}{0.4\textwidth}
  1739. \begin{lstlisting}
  1740. (let ([x (let ([x 4])
  1741. (+ x 1))])
  1742. (+ x 2))
  1743. \end{lstlisting}
  1744. \end{minipage}
  1745. &
  1746. $\Rightarrow$
  1747. &
  1748. \begin{minipage}{0.4\textwidth}
  1749. \begin{lstlisting}
  1750. (let ([x.2 (let ([x.1 4])
  1751. (+ x.1 1))])
  1752. (+ x.2 2))
  1753. \end{lstlisting}
  1754. \end{minipage}
  1755. \end{tabular}
  1756. We recommend implementing \code{uniquify} by creating a structurally
  1757. recursive function named \code{uniquify-exp} that mostly just copies
  1758. an expression. However, when encountering a \key{let}, it should
  1759. generate a unique name for the variable and associate the old name
  1760. with the new name in an alist.\footnote{The Racket function
  1761. \code{gensym} is handy for generating unique variable names.} The
  1762. \code{uniquify-exp} function needs to access this alist when it gets
  1763. to a variable reference, so we add a parameter to \code{uniquify-exp}
  1764. for the alist.
  1765. The skeleton of the \code{uniquify-exp} function is shown in
  1766. Figure~\ref{fig:uniquify-Rvar}. The function is curried so that it is
  1767. convenient to partially apply it to an alist and then apply it to
  1768. different expressions, as in the last case for primitive operations in
  1769. Figure~\ref{fig:uniquify-Rvar}. The
  1770. %
  1771. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  1772. %
  1773. form of Racket is useful for transforming each element of a list to
  1774. produce a new list.\index{for/list}
  1775. \begin{exercise}
  1776. \normalfont % I don't like the italics for exercises. -Jeremy
  1777. Complete the \code{uniquify} pass by filling in the blanks in
  1778. Figure~\ref{fig:uniquify-Rvar}, that is, implement the cases for
  1779. variables and for the \key{let} form in the file \code{compiler.rkt}
  1780. in the support code.
  1781. \end{exercise}
  1782. \begin{figure}[tbp]
  1783. \begin{lstlisting}
  1784. (define (uniquify-exp env)
  1785. (lambda (e)
  1786. (match e
  1787. [(Var x) ___]
  1788. [(Int n) (Int n)]
  1789. [(Let x e body) ___]
  1790. [(Prim op es)
  1791. (Prim op (for/list ([e es]) ((uniquify-exp env) e)))])))
  1792. (define (uniquify p)
  1793. (match p
  1794. [(Program '() e) (Program '() ((uniquify-exp '()) e))]))
  1795. \end{lstlisting}
  1796. \caption{Skeleton for the \key{uniquify} pass.}
  1797. \label{fig:uniquify-Rvar}
  1798. \end{figure}
  1799. \begin{exercise}
  1800. \normalfont % I don't like the italics for exercises. -Jeremy
  1801. Create five \LangVar{} programs that exercise the most interesting
  1802. parts of the \key{uniquify} pass, that is, the programs should include
  1803. \key{let} forms, variables, and variables that overshadow each other.
  1804. The five programs should be placed in the subdirectory named
  1805. \key{tests} and the file names should start with \code{var\_test\_}
  1806. followed by a unique integer and end with the file extension
  1807. \key{.rkt}.
  1808. %
  1809. The \key{run-tests.rkt} script in the support code checks whether the
  1810. output programs produce the same result as the input programs. The
  1811. script uses the \key{interp-tests} function
  1812. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1813. your \key{uniquify} pass on the example programs. The \code{passes}
  1814. parameter of \key{interp-tests} is a list that should have one entry
  1815. for each pass in your compiler. For now, define \code{passes} to
  1816. contain just one entry for \code{uniquify} as follows.
  1817. \begin{lstlisting}
  1818. (define passes
  1819. (list (list "uniquify" uniquify interp-Rvar type-check-Rvar)))
  1820. \end{lstlisting}
  1821. Run the \key{run-tests.rkt} script in the support code to check
  1822. whether the output programs produce the same result as the input
  1823. programs.
  1824. \end{exercise}
  1825. \section{Remove Complex Operands}
  1826. \label{sec:remove-complex-opera-Rvar}
  1827. The \code{remove-complex-opera*} pass compiles \LangVar{} programs into
  1828. \LangVar{} programs in which the arguments of operations are atomic
  1829. expressions. Put another way, this pass removes complex
  1830. operands\index{complex operand}, such as the expression \code{(- 10)}
  1831. in the program below. This is accomplished by introducing a new
  1832. \key{let}-bound variable, binding the complex operand to the new
  1833. variable, and then using the new variable in place of the complex
  1834. operand, as shown in the output of \code{remove-complex-opera*} on the
  1835. right.\\
  1836. \begin{tabular}{lll}
  1837. \begin{minipage}{0.4\textwidth}
  1838. % var_test_19.rkt
  1839. \begin{lstlisting}
  1840. (+ 52 (- 10))
  1841. \end{lstlisting}
  1842. \end{minipage}
  1843. &
  1844. $\Rightarrow$
  1845. &
  1846. \begin{minipage}{0.4\textwidth}
  1847. \begin{lstlisting}
  1848. (let ([tmp.1 (- 10)])
  1849. (+ 52 tmp.1))
  1850. \end{lstlisting}
  1851. \end{minipage}
  1852. \end{tabular}
  1853. \begin{figure}[tp]
  1854. \centering
  1855. \fbox{
  1856. \begin{minipage}{0.96\textwidth}
  1857. \[
  1858. \begin{array}{rcl}
  1859. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1860. \Exp &::=& \Atm \mid \READ{} \\
  1861. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  1862. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  1863. R^{\dagger}_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1864. \end{array}
  1865. \]
  1866. \end{minipage}
  1867. }
  1868. \caption{\LangVarANF{} is \LangVar{} in administrative normal form (ANF).}
  1869. \label{fig:r1-anf-syntax}
  1870. \end{figure}
  1871. Figure~\ref{fig:r1-anf-syntax} presents the grammar for the output of
  1872. this pass, the language \LangVarANF{}. The only difference is that
  1873. operator arguments are required to be atomic expressions. In the
  1874. literature, this is called \emph{administrative normal form}, or ANF
  1875. for short~\citep{Danvy:1991fk,Flanagan:1993cg}. \index{administrative
  1876. normal form} \index{ANF}
  1877. We recommend implementing this pass with two mutually recursive
  1878. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1879. \code{rco-atom} to subexpressions that are required to be atomic and
  1880. to apply \code{rco-exp} to subexpressions that can be atomic or
  1881. complex (see Figure~\ref{fig:r1-anf-syntax}). Both functions take an
  1882. \LangVar{} expression as input. The \code{rco-exp} function returns an
  1883. expression. The \code{rco-atom} function returns two things: an
  1884. atomic expression and alist mapping temporary variables to complex
  1885. subexpressions. You can return multiple things from a function using
  1886. Racket's \key{values} form and you can receive multiple things from a
  1887. function call using the \key{define-values} form. If you are not
  1888. familiar with these features, review the Racket documentation. Also,
  1889. 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}}
  1890. form is useful for applying a function to each
  1891. element of a list, in the case where the function returns multiple
  1892. values.
  1893. \index{for/lists}
  1894. The following shows the output of \code{rco-atom} on the expression
  1895. \code{(- 10)} (using concrete syntax to be concise).
  1896. \begin{tabular}{lll}
  1897. \begin{minipage}{0.4\textwidth}
  1898. \begin{lstlisting}
  1899. (- 10)
  1900. \end{lstlisting}
  1901. \end{minipage}
  1902. &
  1903. $\Rightarrow$
  1904. &
  1905. \begin{minipage}{0.4\textwidth}
  1906. \begin{lstlisting}
  1907. tmp.1
  1908. ((tmp.1 . (- 10)))
  1909. \end{lstlisting}
  1910. \end{minipage}
  1911. \end{tabular}
  1912. Take special care of programs such as the following one that binds a
  1913. variable to an atomic expression. You should leave such variable
  1914. bindings unchanged, as shown in to the program on the right \\
  1915. \begin{tabular}{lll}
  1916. \begin{minipage}{0.4\textwidth}
  1917. % var_test_20.rkt
  1918. \begin{lstlisting}
  1919. (let ([a 42])
  1920. (let ([b a])
  1921. b))
  1922. \end{lstlisting}
  1923. \end{minipage}
  1924. &
  1925. $\Rightarrow$
  1926. &
  1927. \begin{minipage}{0.4\textwidth}
  1928. \begin{lstlisting}
  1929. (let ([a 42])
  1930. (let ([b a])
  1931. b))
  1932. \end{lstlisting}
  1933. \end{minipage}
  1934. \end{tabular} \\
  1935. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  1936. produce the following output with unnecessary temporary variables.\\
  1937. \begin{minipage}{0.4\textwidth}
  1938. \begin{lstlisting}
  1939. (let ([tmp.1 42])
  1940. (let ([a tmp.1])
  1941. (let ([tmp.2 a])
  1942. (let ([b tmp.2])
  1943. b))))
  1944. \end{lstlisting}
  1945. \end{minipage}
  1946. \begin{exercise}\normalfont
  1947. %
  1948. Implement the \code{remove-complex-opera*} function in
  1949. \code{compiler.rkt}.
  1950. %
  1951. Create three new \LangInt{} programs that exercise the interesting
  1952. code in the \code{remove-complex-opera*} pass (Following the same file
  1953. name guidelines as before.).
  1954. %
  1955. In the \code{run-tests.rkt} script, add the following entry to the
  1956. list of \code{passes} and then run the script to test your compiler.
  1957. \begin{lstlisting}
  1958. (list "remove-complex" remove-complex-opera* interp-Rvar type-check-Rvar)
  1959. \end{lstlisting}
  1960. While debugging your compiler, it is often useful to see the
  1961. intermediate programs that are output from each pass. To print the
  1962. intermeidate programs, place the following before the call to
  1963. \code{interp-tests} in \code{run-tests.rkt}.
  1964. \begin{lstlisting}
  1965. (debug-level 1)
  1966. \end{lstlisting}
  1967. \end{exercise}
  1968. \section{Explicate Control}
  1969. \label{sec:explicate-control-Rvar}
  1970. The \code{explicate-control} pass compiles \LangVar{} programs into \LangCVar{}
  1971. programs that make the order of execution explicit in their
  1972. syntax. For now this amounts to flattening \key{let} constructs into a
  1973. sequence of assignment statements. For example, consider the following
  1974. \LangVar{} program.\\
  1975. % var_test_11.rkt
  1976. \begin{minipage}{0.96\textwidth}
  1977. \begin{lstlisting}
  1978. (let ([y (let ([x 20])
  1979. (+ x (let ([x 22]) x)))])
  1980. y)
  1981. \end{lstlisting}
  1982. \end{minipage}\\
  1983. %
  1984. The output of the previous pass and of \code{explicate-control} is
  1985. shown below. Recall that the right-hand-side of a \key{let} executes
  1986. before its body, so the order of evaluation for this program is to
  1987. assign \code{20} to \code{x.1}, \code{22} to \code{x.2}, and
  1988. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  1989. output of \code{explicate-control} makes this ordering explicit.\\
  1990. \begin{tabular}{lll}
  1991. \begin{minipage}{0.4\textwidth}
  1992. \begin{lstlisting}
  1993. (let ([y (let ([x.1 20])
  1994. (let ([x.2 22])
  1995. (+ x.1 x.2)))])
  1996. y)
  1997. \end{lstlisting}
  1998. \end{minipage}
  1999. &
  2000. $\Rightarrow$
  2001. &
  2002. \begin{minipage}{0.4\textwidth}
  2003. \begin{lstlisting}[language=C]
  2004. start:
  2005. x.1 = 20;
  2006. x.2 = 22;
  2007. y = (+ x.1 x.2);
  2008. return y;
  2009. \end{lstlisting}
  2010. \end{minipage}
  2011. \end{tabular}
  2012. \begin{figure}[tbp]
  2013. \begin{lstlisting}
  2014. (define (explicate-tail e)
  2015. (match e
  2016. [(Var x) ___]
  2017. [(Int n) (Return (Int n))]
  2018. [(Let x rhs body) ___]
  2019. [(Prim op es) ___]
  2020. [else (error "explicate-tail unhandled case" e)]))
  2021. (define (explicate-assign e x cont)
  2022. (match e
  2023. [(Var x) ___]
  2024. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  2025. [(Let y rhs body) ___]
  2026. [(Prim op es) ___]
  2027. [else (error "explicate-assign unhandled case" e)]))
  2028. (define (explicate-control p)
  2029. (match p
  2030. [(Program info body) ___]))
  2031. \end{lstlisting}
  2032. \caption{Skeleton for the \key{explicate-control} pass.}
  2033. \label{fig:explicate-control-Rvar}
  2034. \end{figure}
  2035. The organization of this pass depends on the notion of tail position
  2036. that we have alluded to earlier. Formally, \emph{tail
  2037. position}\index{tail position} in the context of \LangVar{} is
  2038. defined recursively by the following two rules.
  2039. \begin{enumerate}
  2040. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  2041. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  2042. \end{enumerate}
  2043. We recommend implementing \code{explicate-control} using two mutually
  2044. recursive functions, \code{explicate-tail} and
  2045. \code{explicate-assign}, as suggested in the skeleton code in
  2046. Figure~\ref{fig:explicate-control-Rvar}. The \code{explicate-tail}
  2047. function should be applied to expressions in tail position whereas the
  2048. \code{explicate-assign} should be applied to expressions that occur on
  2049. the right-hand-side of a \key{let}.
  2050. %
  2051. The \code{explicate-tail} function takes an \Exp{} in \LangVar{} as
  2052. input and produces a \Tail{} in \LangCVar{} (see
  2053. Figure~\ref{fig:c0-syntax}).
  2054. %
  2055. The \code{explicate-assign} function takes an \Exp{} in \LangVar{},
  2056. the variable that it is to be assigned to, and a \Tail{} in
  2057. \LangCVar{} for the code that will come after the assignment. The
  2058. \code{explicate-assign} function returns a $\Tail$ in \LangCVar{}.
  2059. The \code{explicate-assign} function is in accumulator-passing style
  2060. in that the \code{cont} parameter is used for accumulating the
  2061. output. The reader might be tempted to instead organize
  2062. \code{explicate-assign} in a more direct fashion, without the
  2063. \code{cont} parameter and perhaps using \code{append} to combine
  2064. statements. We warn against that alternative because the
  2065. accumulator-passing style is key to how we generate high-quality code
  2066. for conditional expressions in Chapter~\ref{ch:bool-types}.
  2067. \begin{exercise}\normalfont
  2068. %
  2069. Implement the \code{explicate-control} function in
  2070. \code{compiler.rkt}. Create three new \LangInt{} programs that
  2071. exercise the code in \code{explicate-control}.
  2072. %
  2073. In the \code{run-tests.rkt} script, add the following entry to the
  2074. list of \code{passes} and then run the script to test your compiler.
  2075. \begin{lstlisting}
  2076. (list "explicate control" explicate-control interp-Cvar type-check-Cvar)
  2077. \end{lstlisting}
  2078. \end{exercise}
  2079. \section{Select Instructions}
  2080. \label{sec:select-Rvar}
  2081. \index{instruction selection}
  2082. In the \code{select-instructions} pass we begin the work of
  2083. translating from \LangCVar{} to \LangXVar{}. The target language of
  2084. this pass is a variant of x86 that still uses variables, so we add an
  2085. AST node of the form $\VAR{\itm{var}}$ to the \Arg{} non-terminal of
  2086. the \LangXInt{} abstract syntax (Figure~\ref{fig:x86-int-ast}). We
  2087. recommend implementing the \code{select-instructions} with
  2088. three auxiliary functions, one for each of the non-terminals of
  2089. \LangCVar{}: $\Atm$, $\Stmt$, and $\Tail$.
  2090. The cases for $\Atm$ are straightforward, variables stay
  2091. the same and integer constants are changed to immediates:
  2092. $\INT{n}$ changes to $\IMM{n}$.
  2093. Next we consider the cases for $\Stmt$, starting with arithmetic
  2094. operations. For example, consider the addition operation. We can use
  2095. the \key{addq} instruction, but it performs an in-place update. So we
  2096. could move $\itm{arg}_1$ into the left-hand side \itm{var} and then
  2097. add $\itm{arg}_2$ to \itm{var}. \\
  2098. \begin{tabular}{lll}
  2099. \begin{minipage}{0.4\textwidth}
  2100. \begin{lstlisting}
  2101. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{arg}_2$|);
  2102. \end{lstlisting}
  2103. \end{minipage}
  2104. &
  2105. $\Rightarrow$
  2106. &
  2107. \begin{minipage}{0.4\textwidth}
  2108. \begin{lstlisting}
  2109. movq |$\itm{arg}_1$|, |$\itm{var}$|
  2110. addq |$\itm{arg}_2$|, |$\itm{var}$|
  2111. \end{lstlisting}
  2112. \end{minipage}
  2113. \end{tabular} \\
  2114. %
  2115. There are also cases that require special care to avoid generating
  2116. needlessly complicated code. For example, if one of the arguments of
  2117. the addition is the same variable as the left-hand side of the
  2118. assignment, then there is no need for the extra move instruction. The
  2119. assignment statement can be translated into a single \key{addq}
  2120. instruction as follows.\\
  2121. \begin{tabular}{lll}
  2122. \begin{minipage}{0.4\textwidth}
  2123. \begin{lstlisting}
  2124. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{var}$|);
  2125. \end{lstlisting}
  2126. \end{minipage}
  2127. &
  2128. $\Rightarrow$
  2129. &
  2130. \begin{minipage}{0.4\textwidth}
  2131. \begin{lstlisting}
  2132. addq |$\itm{arg}_1$|, |$\itm{var}$|
  2133. \end{lstlisting}
  2134. \end{minipage}
  2135. \end{tabular}
  2136. The \key{read} operation does not have a direct counterpart in x86
  2137. assembly, so we provide this functionality with the function
  2138. \code{read\_int} in the file \code{runtime.c}, written in
  2139. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  2140. functionality in this file as the \emph{runtime system}\index{runtime
  2141. system}, or simply the \emph{runtime} for short. When compiling your
  2142. generated x86 assembly code, you need to compile \code{runtime.c} to
  2143. \code{runtime.o} (an ``object file'', using \code{gcc} option
  2144. \code{-c}) and link it into the executable. For our purposes of code
  2145. generation, all you need to do is translate an assignment of
  2146. \key{read} into a call to the \code{read\_int} function followed by a
  2147. move from \code{rax} to the left-hand-side variable. (Recall that the
  2148. return value of a function goes into \code{rax}.) \\
  2149. \begin{tabular}{lll}
  2150. \begin{minipage}{0.3\textwidth}
  2151. \begin{lstlisting}
  2152. |$\itm{var}$| = (read);
  2153. \end{lstlisting}
  2154. \end{minipage}
  2155. &
  2156. $\Rightarrow$
  2157. &
  2158. \begin{minipage}{0.3\textwidth}
  2159. \begin{lstlisting}
  2160. callq read_int
  2161. movq %rax, |$\itm{var}$|
  2162. \end{lstlisting}
  2163. \end{minipage}
  2164. \end{tabular}
  2165. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  2166. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  2167. assignment to the \key{rax} register followed by a jump to the
  2168. conclusion of the program (so the conclusion needs to be labeled).
  2169. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  2170. recursively and then append the resulting instructions.
  2171. \begin{exercise}
  2172. \normalfont Implement the \key{select-instructions} pass in
  2173. \code{compiler.rkt}. Create three new example programs that are
  2174. designed to exercise all of the interesting cases in this pass.
  2175. %
  2176. In the \code{run-tests.rkt} script, add the following entry to the
  2177. list of \code{passes} and then run the script to test your compiler.
  2178. \begin{lstlisting}
  2179. (list "instruction selection" select-instructions interp-pseudo-x86-0)
  2180. \end{lstlisting}
  2181. \end{exercise}
  2182. \section{Assign Homes}
  2183. \label{sec:assign-Rvar}
  2184. The \key{assign-homes} pass compiles \LangXVar{} programs to
  2185. \LangXVar{} programs that no longer use program variables.
  2186. Thus, the \key{assign-homes} pass is responsible for placing all of
  2187. the program variables in registers or on the stack. For runtime
  2188. efficiency, it is better to place variables in registers, but as there
  2189. are only 16 registers, some programs must necessarily resort to
  2190. placing some variables on the stack. In this chapter we focus on the
  2191. mechanics of placing variables on the stack. We study an algorithm for
  2192. placing variables in registers in
  2193. Chapter~\ref{ch:register-allocation-Rvar}.
  2194. Consider again the following \LangVar{} program from
  2195. Section~\ref{sec:remove-complex-opera-Rvar}.
  2196. % var_test_20.rkt
  2197. \begin{lstlisting}
  2198. (let ([a 42])
  2199. (let ([b a])
  2200. b))
  2201. \end{lstlisting}
  2202. The output of \code{select-instructions} is shown on the left and the
  2203. output of \code{assign-homes} on the right. In this example, we
  2204. assign variable \code{a} to stack location \code{-8(\%rbp)} and
  2205. variable \code{b} to location \code{-16(\%rbp)}.\\
  2206. \begin{tabular}{l}
  2207. \begin{minipage}{0.4\textwidth}
  2208. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2209. locals-types:
  2210. a : Integer, b : Integer
  2211. start:
  2212. movq $42, a
  2213. movq a, b
  2214. movq b, %rax
  2215. jmp conclusion
  2216. \end{lstlisting}
  2217. \end{minipage}
  2218. {$\Rightarrow$}
  2219. \begin{minipage}{0.4\textwidth}
  2220. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2221. stack-space: 16
  2222. start:
  2223. movq $42, -8(%rbp)
  2224. movq -8(%rbp), -16(%rbp)
  2225. movq -16(%rbp), %rax
  2226. jmp conclusion
  2227. \end{lstlisting}
  2228. \end{minipage}
  2229. \end{tabular}
  2230. The \code{locals-types} entry in the $\itm{info}$ of the
  2231. \code{X86Program} node is an alist mapping all the variables in the
  2232. program to their types (for now just \code{Integer}). The
  2233. \code{assign-homes} pass should replace all uses of those variables
  2234. with stack locations. As an aside, the \code{locals-types} entry is
  2235. computed by \code{type-check-Cvar} in the support code, which installs
  2236. it in the $\itm{info}$ field of the \code{CProgram} node, which should
  2237. be propagated to the \code{X86Program} node.
  2238. In the process of assigning variables to stack locations, it is
  2239. convenient for you to compute and store the size of the frame (in
  2240. bytes) in the $\itm{info}$ field of the \key{X86Program} node, with
  2241. the key \code{stack-space}, which is needed later to generate the
  2242. conclusion of the \code{main} procedure. The x86-64 standard requires
  2243. the frame size to be a multiple of 16 bytes.\index{frame}
  2244. \begin{exercise}\normalfont
  2245. Implement the \key{assign-homes} pass in \code{compiler.rkt}, defining
  2246. auxiliary functions for the non-terminals \Arg{}, \Instr{}, and
  2247. \Block{}. We recommend that the auxiliary functions take an extra
  2248. parameter that is an alist mapping variable names to homes (stack
  2249. locations for now).
  2250. %
  2251. In the \code{run-tests.rkt} script, add the following entry to the
  2252. list of \code{passes} and then run the script to test your compiler.
  2253. \begin{lstlisting}
  2254. (list "assign homes" assign-homes interp-x86-0)
  2255. \end{lstlisting}
  2256. \end{exercise}
  2257. \section{Patch Instructions}
  2258. \label{sec:patch-s0}
  2259. The \code{patch-instructions} pass compiles from \LangXVar{} to
  2260. \LangXInt{} by making sure that each instruction adheres to the
  2261. restriction that at most one argument of an instruction may be a
  2262. memory reference.
  2263. We return to the following example.
  2264. % var_test_20.rkt
  2265. \begin{lstlisting}
  2266. (let ([a 42])
  2267. (let ([b a])
  2268. b))
  2269. \end{lstlisting}
  2270. The \key{assign-homes} pass produces the following output
  2271. for this program. \\
  2272. \begin{minipage}{0.5\textwidth}
  2273. \begin{lstlisting}
  2274. stack-space: 16
  2275. start:
  2276. movq $42, -8(%rbp)
  2277. movq -8(%rbp), -16(%rbp)
  2278. movq -16(%rbp), %rax
  2279. jmp conclusion
  2280. \end{lstlisting}
  2281. \end{minipage}\\
  2282. The second \key{movq} instruction is problematic because both
  2283. arguments are stack locations. We suggest fixing this problem by
  2284. moving from the source location to the register \key{rax} and then
  2285. from \key{rax} to the destination location, as follows.
  2286. \begin{lstlisting}
  2287. movq -8(%rbp), %rax
  2288. movq %rax, -16(%rbp)
  2289. \end{lstlisting}
  2290. \begin{exercise}
  2291. \normalfont Implement the \key{patch-instructions} pass in
  2292. \code{compiler.rkt}. Create three new example programs that are
  2293. designed to exercise all of the interesting cases in this pass.
  2294. %
  2295. In the \code{run-tests.rkt} script, add the following entry to the
  2296. list of \code{passes} and then run the script to test your compiler.
  2297. \begin{lstlisting}
  2298. (list "patch instructions" patch-instructions interp-x86-0)
  2299. \end{lstlisting}
  2300. \end{exercise}
  2301. \section{Print x86}
  2302. \label{sec:print-x86}
  2303. The last step of the compiler from \LangVar{} to x86 is to convert the
  2304. \LangXInt{} AST (defined in Figure~\ref{fig:x86-int-ast}) to the
  2305. string representation (defined in
  2306. Figure~\ref{fig:x86-int-concrete}). The Racket \key{format} and
  2307. \key{string-append} functions are useful in this regard. The main work
  2308. that this step needs to perform is to create the \key{main} function
  2309. and the standard instructions for its prelude and conclusion, as shown
  2310. in Figure~\ref{fig:p1-x86} of Section~\ref{sec:x86}. You will need to
  2311. know the amount of space needed for the stack frame, which you can
  2312. obtain from the \code{stack-space} entry in the $\itm{info}$ field of
  2313. the \key{X86Program} node.
  2314. When running on Mac OS X, you compiler should prefix an underscore to
  2315. labels like \key{main}. The Racket call \code{(system-type 'os)} is
  2316. useful for determining which operating system the compiler is running
  2317. on. It returns \code{'macosx}, \code{'unix}, or \code{'windows}.
  2318. \begin{exercise}\normalfont
  2319. %
  2320. Implement the \key{print-x86} pass in \code{compiler.rkt}.
  2321. %
  2322. In the \code{run-tests.rkt} script, add the following entry to the
  2323. list of \code{passes} and then run the script to test your compiler.
  2324. \begin{lstlisting}
  2325. (list "print x86" print-x86 #f)
  2326. \end{lstlisting}
  2327. %
  2328. Uncomment the call to the \key{compiler-tests} function
  2329. (Appendix~\ref{appendix:utilities}), which tests your complete
  2330. compiler by executing the generated x86 code. Compile the provided
  2331. \key{runtime.c} file to \key{runtime.o} using \key{gcc}. Run the
  2332. script to test your compiler.
  2333. \end{exercise}
  2334. \section{Challenge: Partial Evaluator for \LangVar{}}
  2335. \label{sec:pe-Rvar}
  2336. \index{partial evaluation}
  2337. This section describes optional challenge exercises that involve
  2338. adapting and improving the partial evaluator for \LangInt{} that was
  2339. introduced in Section~\ref{sec:partial-evaluation}.
  2340. \begin{exercise}\label{ex:pe-Rvar}
  2341. \normalfont
  2342. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2343. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  2344. instead of \LangInt{} programs. Recall that \LangVar{} adds \key{let} binding
  2345. and variables to the \LangInt{} language, so you will need to add cases for
  2346. them in the \code{pe-exp} function. Once complete, add the partial
  2347. evaluation pass to the front of your compiler and make sure that your
  2348. compiler still passes all of the tests.
  2349. \end{exercise}
  2350. The next exercise builds on Exercise~\ref{ex:pe-Rvar}.
  2351. \begin{exercise}
  2352. \normalfont
  2353. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2354. \code{pe-add} auxiliary functions with functions that know more about
  2355. arithmetic. For example, your partial evaluator should translate
  2356. \[
  2357. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  2358. \code{(+ 2 (read))}
  2359. \]
  2360. To accomplish this, the \code{pe-exp} function should produce output
  2361. in the form of the $\itm{residual}$ non-terminal of the following
  2362. grammar. The idea is that when processing an addition expression, we
  2363. can always produce either 1) an integer constant, 2) and addition
  2364. expression with an integer constant on the left-hand side but not the
  2365. right-hand side, or 3) or an addition expression in which neither
  2366. subexpression is a constant.
  2367. \[
  2368. \begin{array}{lcl}
  2369. \itm{inert} &::=& \Var \mid \LP\key{read}\RP \mid \LP\key{-} \;\Var\RP
  2370. \mid \LP\key{-} \;\LP\key{read}\RP\RP
  2371. \mid \LP\key{+} \; \itm{inert} \; \itm{inert}\RP\\
  2372. &\mid& \LP\key{let}~\LP\LS\Var~\itm{inert}\RS\RP~ \itm{inert} \RP \\
  2373. \itm{residual} &::=& \Int \mid \LP\key{+}\; \Int\; \itm{inert}\RP \mid \itm{inert}
  2374. \end{array}
  2375. \]
  2376. The \code{pe-add} and \code{pe-neg} functions may assume that their
  2377. inputs are $\itm{residual}$ expressions and they should return
  2378. $\itm{residual}$ expressions. Once the improvements are complete,
  2379. make sure that your compiler still passes all of the tests. After
  2380. all, fast code is useless if it produces incorrect results!
  2381. \end{exercise}
  2382. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2383. \chapter{Register Allocation}
  2384. \label{ch:register-allocation-Rvar}
  2385. \index{register allocation}
  2386. In Chapter~\ref{ch:int-exp} we learned how to store variables on the
  2387. stack. In this Chapter we learn how to improve the performance of the
  2388. generated code by placing some variables into registers. The CPU can
  2389. access a register in a single cycle, whereas accessing the stack can
  2390. take 10s to 100s of cycles. The program in Figure~\ref{fig:reg-eg}
  2391. serves as a running example. The source program is on the left and the
  2392. output of instruction selection is on the right. The program is almost
  2393. in the x86 assembly language but it still uses variables.
  2394. \begin{figure}
  2395. \begin{minipage}{0.45\textwidth}
  2396. Example \LangVar{} program:
  2397. % var_test_28.rkt
  2398. \begin{lstlisting}
  2399. (let ([v 1])
  2400. (let ([w 42])
  2401. (let ([x (+ v 7)])
  2402. (let ([y x])
  2403. (let ([z (+ x w)])
  2404. (+ z (- y)))))))
  2405. \end{lstlisting}
  2406. \end{minipage}
  2407. \begin{minipage}{0.45\textwidth}
  2408. After instruction selection:
  2409. \begin{lstlisting}
  2410. locals-types:
  2411. x : Integer, y : Integer,
  2412. z : Integer, t : Integer,
  2413. v : Integer, w : Integer
  2414. start:
  2415. movq $1, v
  2416. movq $42, w
  2417. movq v, x
  2418. addq $7, x
  2419. movq x, y
  2420. movq x, z
  2421. addq w, z
  2422. movq y, t
  2423. negq t
  2424. movq z, %rax
  2425. addq t, %rax
  2426. jmp conclusion
  2427. \end{lstlisting}
  2428. \end{minipage}
  2429. \caption{A running example for register allocation.}
  2430. \label{fig:reg-eg}
  2431. \end{figure}
  2432. The goal of register allocation is to fit as many variables into
  2433. registers as possible. Some programs have more variables than
  2434. registers so we cannot always map each variable to a different
  2435. register. Fortunately, it is common for different variables to be
  2436. needed during different periods of time during program execution, and
  2437. in such cases several variables can be mapped to the same register.
  2438. Consider variables \code{x} and \code{z} in Figure~\ref{fig:reg-eg}.
  2439. After the variable \code{x} is moved to \code{z} it is no longer
  2440. needed. Variable \code{z}, on the other hand, is used only after this
  2441. point, so \code{x} and \code{z} could share the same register. The
  2442. topic of Section~\ref{sec:liveness-analysis-Rvar} is how to compute
  2443. where a variable is needed. Once we have that information, we compute
  2444. which variables are needed at the same time, i.e., which ones
  2445. \emph{interfere} with each other, and represent this relation as an
  2446. undirected graph whose vertices are variables and edges indicate when
  2447. two variables interfere (Section~\ref{sec:build-interference}). We
  2448. then model register allocation as a graph coloring problem
  2449. (Section~\ref{sec:graph-coloring}).
  2450. If we run out of registers despite these efforts, we place the
  2451. remaining variables on the stack, similar to what we did in
  2452. Chapter~\ref{ch:int-exp}. It is common to use the verb \emph{spill}
  2453. for assigning a variable to a stack location. The decision to spill a
  2454. variable is handled as part of the graph coloring process
  2455. (Section~\ref{sec:graph-coloring}).
  2456. We make the simplifying assumption that each variable is assigned to
  2457. one location (a register or stack address). A more sophisticated
  2458. approach is to assign a variable to one or more locations in different
  2459. regions of the program. For example, if a variable is used many times
  2460. in short sequence and then only used again after many other
  2461. instructions, it could be more efficient to assign the variable to a
  2462. register during the initial sequence and then move it to the stack for
  2463. the rest of its lifetime. We refer the interested reader to
  2464. \citet{Cooper:2011aa} for more information 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.
  2472. %
  2473. Even though \LangVar{} does not include programmer-defined functions,
  2474. our generated code includes a \code{main} function that is called by
  2475. the operating system and our generated code contains calls to the
  2476. \code{read\_int} function.
  2477. Function calls require coordination between two pieces of code that
  2478. may be written by different programmers or generated by different
  2479. compilers. Here we follow the System V calling conventions that are
  2480. used by the GNU C compiler on Linux and
  2481. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  2482. %
  2483. The calling conventions include rules about how functions share the
  2484. use of registers. In particular, the caller is responsible for freeing
  2485. up some registers prior to the function call for use by the callee.
  2486. These are called the \emph{caller-saved registers}
  2487. \index{caller-saved registers}
  2488. and they are
  2489. \begin{lstlisting}
  2490. rax rcx rdx rsi rdi r8 r9 r10 r11
  2491. \end{lstlisting}
  2492. On the other hand, the callee is responsible for preserving the values
  2493. of the \emph{callee-saved registers}, \index{callee-saved registers}
  2494. which are
  2495. \begin{lstlisting}
  2496. rsp rbp rbx r12 r13 r14 r15
  2497. \end{lstlisting}
  2498. We can think about this caller/callee convention from two points of
  2499. view, the caller view and the callee view:
  2500. \begin{itemize}
  2501. \item The caller should assume that all the caller-saved registers get
  2502. overwritten with arbitrary values by the callee. On the other hand,
  2503. the caller can safely assume that all the callee-saved registers
  2504. contain the same values after the call that they did before the
  2505. call.
  2506. \item The callee can freely use any of the caller-saved registers.
  2507. However, if the callee wants to use a callee-saved register, the
  2508. callee must arrange to put the original value back in the register
  2509. prior to returning to the caller. This can be accomplished by saving
  2510. the value to the stack in the prelude of the function and restoring
  2511. the value in the conclusion of the function.
  2512. \end{itemize}
  2513. In x86, registers are also used for passing arguments to a function
  2514. and for the return value. In particular, the first six arguments to a
  2515. function are passed in the following six registers, in this order.
  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 never to
  2522. need more than six arguments. For now, the only function we care about
  2523. is \code{read\_int} and it takes zero arguments.
  2524. %
  2525. The register \code{rax} is used for the return value of a function.
  2526. The next question is how these calling conventions impact register
  2527. allocation. Consider the \LangVar{} 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, saving and restoring to the stack is
  2540. relatively slow. If \code{x} is not used many times, it may be better
  2541. to assign \code{x} to a stack location in the first place. Or better
  2542. yet, if we can arrange for \code{x} to be placed in a callee-saved
  2543. register, then it won't need to be saved and restored during function
  2544. 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-Rvar}). 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 a callee-saved register and 2) \code{rbx} is assigned to a variable
  2576. (\code{x}). The other callee-saved registers are not saved in the
  2577. prelude because they are not used. The prelude subtracts 8 bytes from
  2578. the \code{rsp} to make it 16-byte aligned and then jumps to the
  2579. \code{start} block. Shifting attention to the \code{conclusion}, we
  2580. see that \code{rbx} is restored from the stack with a \code{popq}
  2581. instruction. \index{prelude}\index{conclusion}
  2582. \begin{figure}[tp]
  2583. \begin{minipage}{0.45\textwidth}
  2584. Example \LangVar{} program:
  2585. %var_test_14.rkt
  2586. \begin{lstlisting}
  2587. (let ([x (read)])
  2588. (let ([y (read)])
  2589. (+ (+ x y) 42)))
  2590. \end{lstlisting}
  2591. \end{minipage}
  2592. \begin{minipage}{0.45\textwidth}
  2593. Generated x86 assembly:
  2594. \begin{lstlisting}
  2595. start:
  2596. callq read_int
  2597. movq %rax, %rbx
  2598. callq read_int
  2599. movq %rax, %rcx
  2600. addq %rcx, %rbx
  2601. movq %rbx, %rax
  2602. addq $42, %rax
  2603. jmp _conclusion
  2604. .globl main
  2605. main:
  2606. pushq %rbp
  2607. movq %rsp, %rbp
  2608. pushq %rbx
  2609. subq $8, %rsp
  2610. jmp start
  2611. conclusion:
  2612. addq $8, %rsp
  2613. popq %rbx
  2614. popq %rbp
  2615. retq
  2616. \end{lstlisting}
  2617. \end{minipage}
  2618. \caption{An example with function calls.}
  2619. \label{fig:example-calling-conventions}
  2620. \end{figure}
  2621. \clearpage
  2622. \section{Liveness Analysis}
  2623. \label{sec:liveness-analysis-Rvar}
  2624. \index{liveness analysis}
  2625. The \code{uncover-live} pass performs \emph{liveness analysis}, that
  2626. is, it discovers which variables are in-use in different regions of a
  2627. program.
  2628. %
  2629. A variable or register is \emph{live} at a program point if its
  2630. current value is used at some later point in the program. We
  2631. refer to variables and registers collectively as \emph{locations}.
  2632. %
  2633. Consider the following code fragment in which there are two writes to
  2634. \code{b}. Are \code{a} and \code{b} both live at the same time?
  2635. \begin{center}
  2636. \begin{minipage}{0.96\textwidth}
  2637. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2638. movq $5, a
  2639. movq $30, b
  2640. movq a, c
  2641. movq $10, b
  2642. addq b, c
  2643. \end{lstlisting}
  2644. \end{minipage}
  2645. \end{center}
  2646. The answer is no because \code{a} is live from line 1 to 3 and
  2647. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  2648. line 2 is never used because it is overwritten (line 4) before the
  2649. next read (line 5).
  2650. \begin{wrapfigure}[19]{l}[1.0in]{0.6\textwidth}
  2651. \small
  2652. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  2653. A \emph{set} is an unordered collection of elements without duplicates.
  2654. \index{set}
  2655. \begin{description}
  2656. \item[$\LP\code{set}\,v\,\ldots\RP$] constructs a set containing the specified elements.
  2657. \item[$\LP\code{set-union}\,set_1\,set_2\RP$] returns the union of the two sets.
  2658. \item[$\LP\code{set-subtract}\,set_1\,set_2\RP$] returns the difference of the two sets.
  2659. \item[$\LP\code{set-member?}\,set\,v\RP$] is element $v$ in $set$?
  2660. \item[$\LP\code{set-count}\,set\RP$] how many unique elements are in $set$?
  2661. \item[$\LP\code{set->list}\,set\RP$] converts the set to a list.
  2662. \end{description}
  2663. \end{tcolorbox}
  2664. \end{wrapfigure}
  2665. The live locations can be computed by traversing the instruction
  2666. sequence back to front (i.e., backwards in execution order). Let
  2667. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2668. $L_{\mathsf{after}}(k)$ for the set of live locations after
  2669. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2670. locations before instruction $I_k$. The live locations after an
  2671. instruction are always the same as the live locations before the next
  2672. instruction. \index{live-after} \index{live-before}
  2673. \begin{equation} \label{eq:live-after-before-next}
  2674. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2675. \end{equation}
  2676. To start things off, there are no live locations after the last
  2677. instruction, so
  2678. \begin{equation}\label{eq:live-last-empty}
  2679. L_{\mathsf{after}}(n) = \emptyset
  2680. \end{equation}
  2681. We then apply the following rule repeatedly, traversing the
  2682. instruction sequence back to front.
  2683. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2684. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2685. \end{equation}
  2686. where $W(k)$ are the locations written to by instruction $I_k$ and
  2687. $R(k)$ are the locations read by instruction $I_k$.
  2688. There is a special case for \code{jmp} instructions. The locations
  2689. that are live before a \code{jmp} should be the locations in
  2690. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  2691. maintaining an alist named \code{label->live} that maps each label to
  2692. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  2693. now the only \code{jmp} in a \LangXVar{} program is the one at the
  2694. end, to the conclusion. (For example, see Figure~\ref{fig:reg-eg}.)
  2695. The conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should
  2696. map \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  2697. Let us walk through the above example, applying these formulas
  2698. starting with the instruction on line 5. We collect the answers in
  2699. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  2700. \code{addq b, c} instruction is $\emptyset$ because it is the last
  2701. instruction (formula~\ref{eq:live-last-empty}). The
  2702. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  2703. because it reads from variables \code{b} and \code{c}
  2704. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  2705. \[
  2706. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  2707. \]
  2708. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2709. the live-before set from line 5 to be the live-after set for this
  2710. instruction (formula~\ref{eq:live-after-before-next}).
  2711. \[
  2712. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  2713. \]
  2714. This move instruction writes to \code{b} and does not read from any
  2715. variables, so we have the following live-before set
  2716. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2717. \[
  2718. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  2719. \]
  2720. The live-before for instruction \code{movq a, c}
  2721. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  2722. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2723. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  2724. variable that is not live and does not read from a variable.
  2725. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2726. because it writes to variable \code{a}.
  2727. \begin{figure}[tbp]
  2728. \begin{minipage}{0.45\textwidth}
  2729. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2730. movq $5, a
  2731. movq $30, b
  2732. movq a, c
  2733. movq $10, b
  2734. addq b, c
  2735. \end{lstlisting}
  2736. \end{minipage}
  2737. \vrule\hspace{10pt}
  2738. \begin{minipage}{0.45\textwidth}
  2739. \begin{align*}
  2740. L_{\mathsf{before}}(1)= \emptyset,
  2741. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  2742. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  2743. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  2744. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  2745. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  2746. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  2747. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  2748. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  2749. L_{\mathsf{after}}(5)= \emptyset
  2750. \end{align*}
  2751. \end{minipage}
  2752. \caption{Example output of liveness analysis on a short example.}
  2753. \label{fig:liveness-example-0}
  2754. \end{figure}
  2755. \begin{exercise}\normalfont
  2756. Perform liveness analysis on the running example in
  2757. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  2758. sets for each instruction. Compare your answers to the solution
  2759. shown in Figure~\ref{fig:live-eg}.
  2760. \end{exercise}
  2761. \begin{figure}[tp]
  2762. \hspace{20pt}
  2763. \begin{minipage}{0.45\textwidth}
  2764. \begin{lstlisting}
  2765. |$\{\ttm{rsp}\}$|
  2766. movq $1, v
  2767. |$\{\ttm{v},\ttm{rsp}\}$|
  2768. movq $42, w
  2769. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  2770. movq v, x
  2771. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  2772. addq $7, x
  2773. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  2774. movq x, y
  2775. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  2776. movq x, z
  2777. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  2778. addq w, z
  2779. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  2780. movq y, t
  2781. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  2782. negq t
  2783. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  2784. movq z, %rax
  2785. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  2786. addq t, %rax
  2787. |$\{\ttm{rax},\ttm{rsp}\}$|
  2788. jmp conclusion
  2789. \end{lstlisting}
  2790. \end{minipage}
  2791. \caption{The running example annotated with live-after sets.}
  2792. \label{fig:live-eg}
  2793. \end{figure}
  2794. \begin{exercise}\normalfont
  2795. Implement the \code{uncover-live} pass. Store the sequence of
  2796. live-after sets in the $\itm{info}$ field of the \code{Block}
  2797. structure.
  2798. %
  2799. We recommend creating an auxiliary function that takes a list of
  2800. instructions and an initial live-after set (typically empty) and
  2801. returns the list of live-after sets.
  2802. %
  2803. We also recommend creating auxiliary functions to 1) compute the set
  2804. of locations that appear in an \Arg{}, 2) compute the locations read
  2805. by an instruction (the $R$ function), and 3) the locations written by
  2806. an instruction (the $W$ function). The \code{callq} instruction should
  2807. include all of the caller-saved registers in its write-set $W$ because
  2808. the calling convention says that those registers may be written to
  2809. during the function call. Likewise, the \code{callq} instruction
  2810. should include the appropriate argument-passing registers in its
  2811. read-set $R$, depending on the arity of the function being
  2812. called. (This is why the abstract syntax for \code{callq} includes the
  2813. arity.)
  2814. \end{exercise}
  2815. \clearpage
  2816. \section{Build the Interference Graph}
  2817. \label{sec:build-interference}
  2818. \begin{wrapfigure}[25]{r}[1.0in]{0.6\textwidth}
  2819. \small
  2820. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  2821. A \emph{graph} is a collection of vertices and edges where each
  2822. edge connects two vertices. A graph is \emph{directed} if each
  2823. edge points from a source to a target. Otherwise the graph is
  2824. \emph{undirected}.
  2825. \index{graph}\index{directed graph}\index{undirected graph}
  2826. \begin{description}
  2827. %% We currently don't use directed graphs. We instead use
  2828. %% directed multi-graphs. -Jeremy
  2829. %% \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  2830. %% directed graph from a list of edges. Each edge is a list
  2831. %% containing the source and target vertex.
  2832. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  2833. undirected graph from a list of edges. Each edge is represented by
  2834. a list containing two vertices.
  2835. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  2836. inserts a vertex into the graph.
  2837. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  2838. inserts an edge between the two vertices into the graph.
  2839. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  2840. returns a sequence of all the neighbors of the given vertex.
  2841. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  2842. returns a sequence of all the vertices in the graph.
  2843. \end{description}
  2844. \end{tcolorbox}
  2845. \end{wrapfigure}
  2846. Based on the liveness analysis, we know where each location is live.
  2847. However, during register allocation, we need to answer questions of
  2848. the specific form: are locations $u$ and $v$ live at the same time?
  2849. (And therefore cannot be assigned to the same register.) To make this
  2850. question more efficient to answer, we create an explicit data
  2851. structure, an \emph{interference graph}\index{interference graph}. An
  2852. interference graph is an undirected graph that has an edge between two
  2853. locations if they are live at the same time, that is, if they
  2854. interfere with each other.
  2855. An obvious way to compute the interference graph is to look at the set
  2856. of live locations between each instruction and the next and add an edge to the graph
  2857. for every pair of variables in the same set. This approach is less
  2858. than ideal for two reasons. First, it can be expensive because it
  2859. takes $O(n^2)$ time to consider at every pair in a set of $n$ live
  2860. locations. Second, in the special case where two locations hold the
  2861. same value (because one was assigned to the other), they can be live
  2862. at the same time without interfering with each other.
  2863. A better way to compute the interference graph is to focus on
  2864. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  2865. must not overwrite something in a live location. So for each
  2866. instruction, we create an edge between the locations being written to
  2867. and the live locations. (Except that one should not create self
  2868. edges.) Note that for the \key{callq} instruction, we consider all of
  2869. the caller-saved registers as being written to, so an edge is added
  2870. between every live variable and every caller-saved register. For
  2871. \key{movq}, we deal with the above-mentioned special case by not
  2872. adding an edge between a live variable $v$ and the destination if $v$
  2873. matches the source. So we have the following two rules.
  2874. \begin{enumerate}
  2875. \item If instruction $I_k$ is a move such as \key{movq} $s$\key{,}
  2876. $d$, then add the edge $(d,v)$ for every $v \in
  2877. L_{\mathsf{after}}(k)$ unless $v = d$ or $v = s$.
  2878. \item For any other instruction $I_k$, for every $d \in W(k)$
  2879. add an edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  2880. %% \item If instruction $I_k$ is an arithmetic instruction such as
  2881. %% \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2882. %% L_{\mathsf{after}}(k)$ unless $v = d$.
  2883. %% \item If instruction $I_k$ is of the form \key{callq}
  2884. %% $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2885. %% register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2886. \end{enumerate}
  2887. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  2888. the above rules to each instruction. We highlight a few of the
  2889. instructions. The first instruction is \lstinline{movq $1, v} and the
  2890. live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies, so \code{v}
  2891. interferes with \code{rsp}.
  2892. %
  2893. The fourth instruction is \lstinline{addq $7, x} and the live-after
  2894. set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so $\ttm{x}$
  2895. interferes with \ttm{w} and \ttm{rsp}.
  2896. %
  2897. The next instruction is \lstinline{movq x, y} and the live-after set
  2898. is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1 applies, so \ttm{y}
  2899. interferes with \ttm{w} and \ttm{rsp} but not \ttm{x} because \ttm{x}
  2900. is the source of the move and therefore \ttm{x} and \ttm{y} hold the
  2901. same value. Figure~\ref{fig:interference-results} lists the
  2902. interference results for all of the instructions and the resulting
  2903. interference graph is shown in Figure~\ref{fig:interfere}.
  2904. \begin{figure}[tbp]
  2905. \begin{quote}
  2906. \begin{tabular}{ll}
  2907. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  2908. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  2909. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  2910. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  2911. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  2912. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  2913. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  2914. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  2915. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  2916. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  2917. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  2918. \lstinline!jmp conclusion!& no interference.
  2919. \end{tabular}
  2920. \end{quote}
  2921. \caption{Interference results for the running example.}
  2922. \label{fig:interference-results}
  2923. \end{figure}
  2924. \begin{figure}[tbp]
  2925. \large
  2926. \[
  2927. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2928. \node (rax) at (0,0) {$\ttm{rax}$};
  2929. \node (rsp) at (9,2) {$\ttm{rsp}$};
  2930. \node (t1) at (0,2) {$\ttm{t}$};
  2931. \node (z) at (3,2) {$\ttm{z}$};
  2932. \node (x) at (6,2) {$\ttm{x}$};
  2933. \node (y) at (3,0) {$\ttm{y}$};
  2934. \node (w) at (6,0) {$\ttm{w}$};
  2935. \node (v) at (9,0) {$\ttm{v}$};
  2936. \draw (t1) to (rax);
  2937. \draw (t1) to (z);
  2938. \draw (z) to (y);
  2939. \draw (z) to (w);
  2940. \draw (x) to (w);
  2941. \draw (y) to (w);
  2942. \draw (v) to (w);
  2943. \draw (v) to (rsp);
  2944. \draw (w) to (rsp);
  2945. \draw (x) to (rsp);
  2946. \draw (y) to (rsp);
  2947. \path[-.,bend left=15] (z) edge node {} (rsp);
  2948. \path[-.,bend left=10] (t1) edge node {} (rsp);
  2949. \draw (rax) to (rsp);
  2950. \end{tikzpicture}
  2951. \]
  2952. \caption{The interference graph of the example program.}
  2953. \label{fig:interfere}
  2954. \end{figure}
  2955. %% Our next concern is to choose a data structure for representing the
  2956. %% interference graph. There are many choices for how to represent a
  2957. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2958. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2959. %% data structure is to study the algorithm that uses the data structure,
  2960. %% determine what operations need to be performed, and then choose the
  2961. %% data structure that provide the most efficient implementations of
  2962. %% those operations. Often times the choice of data structure can have an
  2963. %% effect on the time complexity of the algorithm, as it does here. If
  2964. %% you skim the next section, you will see that the register allocation
  2965. %% algorithm needs to ask the graph for all of its vertices and, given a
  2966. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2967. %% correct choice of graph representation is that of an adjacency
  2968. %% list. There are helper functions in \code{utilities.rkt} for
  2969. %% representing graphs using the adjacency list representation:
  2970. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2971. %% (Appendix~\ref{appendix:utilities}).
  2972. %% %
  2973. %% \margincomment{\footnotesize To do: change to use the
  2974. %% Racket graph library. \\ --Jeremy}
  2975. %% %
  2976. %% In particular, those functions use a hash table to map each vertex to
  2977. %% the set of adjacent vertices, and the sets are represented using
  2978. %% Racket's \key{set}, which is also a hash table.
  2979. \begin{exercise}\normalfont
  2980. Implement the compiler pass named \code{build-interference} according
  2981. to the algorithm suggested above. We recommend using the \code{graph}
  2982. package to create and inspect the interference graph. The output
  2983. graph of this pass should be stored in the $\itm{info}$ field of the
  2984. program, under the key \code{conflicts}.
  2985. \end{exercise}
  2986. \section{Graph Coloring via Sudoku}
  2987. \label{sec:graph-coloring}
  2988. \index{graph coloring}
  2989. \index{Sudoku}
  2990. \index{color}
  2991. We come to the main event, mapping variables to registers and stack
  2992. locations. Variables that interfere with each other must be mapped to
  2993. different locations. In terms of the interference graph, this means
  2994. that adjacent vertices must be mapped to different locations. If we
  2995. think of locations as colors, the register allocation problem becomes
  2996. the graph coloring problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2997. The reader may be more familiar with the graph coloring problem than he
  2998. or she realizes; the popular game of Sudoku is an instance of the
  2999. graph coloring problem. The following describes how to build a graph
  3000. out of an initial Sudoku board.
  3001. \begin{itemize}
  3002. \item There is one vertex in the graph for each Sudoku square.
  3003. \item There is an edge between two vertices if the corresponding squares
  3004. are in the same row, in the same column, or if the squares are in
  3005. the same $3\times 3$ region.
  3006. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  3007. \item Based on the initial assignment of numbers to squares in the
  3008. Sudoku board, assign the corresponding colors to the corresponding
  3009. vertices in the graph.
  3010. \end{itemize}
  3011. If you can color the remaining vertices in the graph with the nine
  3012. colors, then you have also solved the corresponding game of Sudoku.
  3013. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  3014. the corresponding graph with colored vertices. We map the Sudoku
  3015. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  3016. sampling of the vertices (the colored ones) because showing edges for
  3017. all of the vertices would make the graph unreadable.
  3018. \begin{figure}[tbp]
  3019. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  3020. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  3021. \caption{A Sudoku game board and the corresponding colored graph.}
  3022. \label{fig:sudoku-graph}
  3023. \end{figure}
  3024. It turns out that some techniques for playing Sudoku correspond to
  3025. heuristics used in graph coloring algorithms. For example, one of the
  3026. basic techniques for Sudoku is called Pencil Marks. The idea is to use
  3027. a process of elimination to determine what numbers are no longer
  3028. available for a square and write down those numbers in the square
  3029. (writing very small). For example, if the number $1$ is assigned to a
  3030. square, then write the pencil mark $1$ in all the squares in the same
  3031. row, column, and region.
  3032. %
  3033. The Pencil Marks technique corresponds to the notion of
  3034. \emph{saturation}\index{saturation} due to \cite{Brelaz:1979eu}. The
  3035. saturation of a vertex, in Sudoku terms, is the set of numbers that
  3036. are no longer available. In graph terminology, we have the following
  3037. definition:
  3038. \begin{equation*}
  3039. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  3040. \text{ and } \mathrm{color}(v) = c \}
  3041. \end{equation*}
  3042. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  3043. edge with $u$.
  3044. Using the Pencil Marks technique leads to a simple strategy for
  3045. filling in numbers: if there is a square with only one possible number
  3046. left, then choose that number! But what if there are no squares with
  3047. only one possibility left? One brute-force approach is to try them
  3048. all: choose the first one and if it ultimately leads to a solution,
  3049. great. If not, backtrack and choose the next possibility. One good
  3050. thing about Pencil Marks is that it reduces the degree of branching in
  3051. the search tree. Nevertheless, backtracking can be horribly time
  3052. consuming. One way to reduce the amount of backtracking is to use the
  3053. most-constrained-first heuristic. That is, when choosing a square,
  3054. always choose one with the fewest possibilities left (the vertex with
  3055. the highest saturation). The idea is that choosing highly constrained
  3056. squares earlier rather than later is better because later on there may
  3057. not be any possibilities left in the highly saturated squares.
  3058. However, register allocation is easier than Sudoku because the
  3059. register allocator can map variables to stack locations when the
  3060. registers run out. Thus, it makes sense to replace backtracking with
  3061. greedy search: make the best choice at the time and keep going. We
  3062. still wish to minimize the number of colors needed, so we use the
  3063. most-constrained-first heuristic in the greedy search.
  3064. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  3065. algorithm for register allocation based on saturation and the
  3066. most-constrained-first heuristic. It is roughly equivalent to the
  3067. DSATUR
  3068. algorithm~\citep{Brelaz:1979eu,Gebremedhin:1999fk,Omari:2006uq}. Just
  3069. as in Sudoku, the algorithm represents colors with integers. The
  3070. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  3071. for register allocation. The integers $k$ and larger correspond to
  3072. stack locations. The registers that are not used for register
  3073. allocation, such as \code{rax}, are assigned to negative integers. In
  3074. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  3075. %% One might wonder why we include registers at all in the liveness
  3076. %% analysis and interference graph. For example, we never allocate a
  3077. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  3078. %% leave them out. As we see in Chapter~\ref{ch:tuples}, when we begin
  3079. %% to use register for passing arguments to functions, it will be
  3080. %% necessary for those registers to appear in the interference graph
  3081. %% because those registers will also be assigned to variables, and we
  3082. %% don't want those two uses to encroach on each other. Regarding
  3083. %% registers such as \code{rax} and \code{rsp} that are not used for
  3084. %% variables, we could omit them from the interference graph but that
  3085. %% would require adding special cases to our algorithm, which would
  3086. %% complicate the logic for little gain.
  3087. \begin{figure}[btp]
  3088. \centering
  3089. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  3090. Algorithm: DSATUR
  3091. Input: a graph |$G$|
  3092. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  3093. |$W \gets \mathrm{vertices}(G)$|
  3094. while |$W \neq \emptyset$| do
  3095. pick a vertex |$u$| from |$W$| with the highest saturation,
  3096. breaking ties randomly
  3097. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  3098. |$\mathrm{color}[u] \gets c$|
  3099. |$W \gets W - \{u\}$|
  3100. \end{lstlisting}
  3101. \caption{The saturation-based greedy graph coloring algorithm.}
  3102. \label{fig:satur-algo}
  3103. \end{figure}
  3104. With the DSATUR algorithm in hand, let us return to the running
  3105. example and consider how to color the interference graph in
  3106. Figure~\ref{fig:interfere}.
  3107. %
  3108. We start by assigning the register nodes to their own color. For
  3109. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  3110. assigned $-2$. The variables are not yet colored, so they are
  3111. annotated with a dash. We then update the saturation for vertices that
  3112. are adjacent to a register, obtaining the following annotated
  3113. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  3114. it interferes with both \code{rax} and \code{rsp}.
  3115. \[
  3116. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3117. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  3118. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  3119. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  3120. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  3121. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3122. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3123. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3124. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3125. \draw (t1) to (rax);
  3126. \draw (t1) to (z);
  3127. \draw (z) to (y);
  3128. \draw (z) to (w);
  3129. \draw (x) to (w);
  3130. \draw (y) to (w);
  3131. \draw (v) to (w);
  3132. \draw (v) to (rsp);
  3133. \draw (w) to (rsp);
  3134. \draw (x) to (rsp);
  3135. \draw (y) to (rsp);
  3136. \path[-.,bend left=15] (z) edge node {} (rsp);
  3137. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3138. \draw (rax) to (rsp);
  3139. \end{tikzpicture}
  3140. \]
  3141. The algorithm says to select a maximally saturated vertex. So we pick
  3142. $\ttm{t}$ and color it with the first available integer, which is
  3143. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  3144. and \ttm{rsp} because they interfere with $\ttm{t}$.
  3145. \[
  3146. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3147. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3148. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  3149. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  3150. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  3151. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3152. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3153. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3154. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3155. \draw (t1) to (rax);
  3156. \draw (t1) to (z);
  3157. \draw (z) to (y);
  3158. \draw (z) to (w);
  3159. \draw (x) to (w);
  3160. \draw (y) to (w);
  3161. \draw (v) to (w);
  3162. \draw (v) to (rsp);
  3163. \draw (w) to (rsp);
  3164. \draw (x) to (rsp);
  3165. \draw (y) to (rsp);
  3166. \path[-.,bend left=15] (z) edge node {} (rsp);
  3167. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3168. \draw (rax) to (rsp);
  3169. \end{tikzpicture}
  3170. \]
  3171. We repeat the process, selecting the next maximally saturated vertex,
  3172. which is \code{z}, and color it with the first available number, which
  3173. is $1$. We add $1$ to the saturation for the neighboring vertices
  3174. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  3175. \[
  3176. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3177. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3178. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3179. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3180. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3181. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3182. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3183. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3184. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3185. \draw (t1) to (rax);
  3186. \draw (t1) to (z);
  3187. \draw (z) to (y);
  3188. \draw (z) to (w);
  3189. \draw (x) to (w);
  3190. \draw (y) to (w);
  3191. \draw (v) to (w);
  3192. \draw (v) to (rsp);
  3193. \draw (w) to (rsp);
  3194. \draw (x) to (rsp);
  3195. \draw (y) to (rsp);
  3196. \path[-.,bend left=15] (z) edge node {} (rsp);
  3197. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3198. \draw (rax) to (rsp);
  3199. \end{tikzpicture}
  3200. \]
  3201. The most saturated vertices are now \code{w} and \code{y}. We color
  3202. \code{w} with the first available color, which is $0$.
  3203. \[
  3204. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3205. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3206. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3207. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3208. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3209. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3210. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  3211. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  3212. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  3213. \draw (t1) to (rax);
  3214. \draw (t1) to (z);
  3215. \draw (z) to (y);
  3216. \draw (z) to (w);
  3217. \draw (x) to (w);
  3218. \draw (y) to (w);
  3219. \draw (v) to (w);
  3220. \draw (v) to (rsp);
  3221. \draw (w) to (rsp);
  3222. \draw (x) to (rsp);
  3223. \draw (y) to (rsp);
  3224. \path[-.,bend left=15] (z) edge node {} (rsp);
  3225. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3226. \draw (rax) to (rsp);
  3227. \end{tikzpicture}
  3228. \]
  3229. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  3230. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  3231. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  3232. and \code{z}, whose colors are $0$ and $1$ respectively.
  3233. \[
  3234. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3235. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3236. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3237. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3238. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3239. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3240. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3241. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3242. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  3243. \draw (t1) to (rax);
  3244. \draw (t1) to (z);
  3245. \draw (z) to (y);
  3246. \draw (z) to (w);
  3247. \draw (x) to (w);
  3248. \draw (y) to (w);
  3249. \draw (v) to (w);
  3250. \draw (v) to (rsp);
  3251. \draw (w) to (rsp);
  3252. \draw (x) to (rsp);
  3253. \draw (y) to (rsp);
  3254. \path[-.,bend left=15] (z) edge node {} (rsp);
  3255. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3256. \draw (rax) to (rsp);
  3257. \end{tikzpicture}
  3258. \]
  3259. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  3260. \[
  3261. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3262. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3263. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3264. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3265. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3266. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3267. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3268. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3269. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3270. \draw (t1) to (rax);
  3271. \draw (t1) to (z);
  3272. \draw (z) to (y);
  3273. \draw (z) to (w);
  3274. \draw (x) to (w);
  3275. \draw (y) to (w);
  3276. \draw (v) to (w);
  3277. \draw (v) to (rsp);
  3278. \draw (w) to (rsp);
  3279. \draw (x) to (rsp);
  3280. \draw (y) to (rsp);
  3281. \path[-.,bend left=15] (z) edge node {} (rsp);
  3282. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3283. \draw (rax) to (rsp);
  3284. \end{tikzpicture}
  3285. \]
  3286. In the last step of the algorithm, we color \code{x} with $1$.
  3287. \[
  3288. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3289. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3290. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3291. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3292. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3293. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  3294. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3295. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3296. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3297. \draw (t1) to (rax);
  3298. \draw (t1) to (z);
  3299. \draw (z) to (y);
  3300. \draw (z) to (w);
  3301. \draw (x) to (w);
  3302. \draw (y) to (w);
  3303. \draw (v) to (w);
  3304. \draw (v) to (rsp);
  3305. \draw (w) to (rsp);
  3306. \draw (x) to (rsp);
  3307. \draw (y) to (rsp);
  3308. \path[-.,bend left=15] (z) edge node {} (rsp);
  3309. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3310. \draw (rax) to (rsp);
  3311. \end{tikzpicture}
  3312. \]
  3313. \begin{wrapfigure}[25]{r}[1.0in]{0.6\textwidth}
  3314. \small
  3315. \begin{tcolorbox}[title=Priority Queue]
  3316. A \emph{priority queue} is a collection of items in which the
  3317. removal of items is governed by priority. In a ``min'' queue,
  3318. lower priority items are removed first. An implementation is in
  3319. \code{priority\_queue.rkt} of the support code. \index{priority
  3320. queue} \index{minimum priority queue}
  3321. \begin{description}
  3322. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  3323. priority queue that uses the $\itm{cmp}$ predicate to determine
  3324. whether its first argument has lower or equal priority to its
  3325. second argument.
  3326. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  3327. items in the queue.
  3328. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  3329. the item into the queue and returns a handle for the item in the
  3330. queue.
  3331. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  3332. the lowest priority.
  3333. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  3334. notifies the queue that the priority has decreased for the item
  3335. associated with the given handle.
  3336. \end{description}
  3337. \end{tcolorbox}
  3338. \end{wrapfigure}
  3339. We recommend creating an auxiliary function named \code{color-graph}
  3340. that takes an interference graph and a list of all the variables in
  3341. the program. This function should return a mapping of variables to
  3342. their colors (represented as natural numbers). By creating this helper
  3343. function, you will be able to reuse it in Chapter~\ref{ch:functions}
  3344. when we add support for functions.
  3345. To prioritize the processing of highly saturated nodes inside the
  3346. \code{color-graph} function, we recommend using the priority queue
  3347. data structure (see the side bar on the right). In addition, you will
  3348. need to maintain a mapping from variables to their ``handles'' in the
  3349. priority queue so that you can notify the priority queue when their
  3350. saturation changes.
  3351. With the coloring complete, we finalize the assignment of variables to
  3352. registers and stack locations. We map the first $k$ colors to the $k$
  3353. registers and the rest of the colors to stack locations. Suppose for
  3354. the moment that we have just one register to use for register
  3355. allocation, \key{rcx}. Then we have the following map from colors to
  3356. locations.
  3357. \[
  3358. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  3359. \]
  3360. Composing this mapping with the coloring, we arrive at the following
  3361. assignment of variables to locations.
  3362. \begin{gather*}
  3363. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  3364. \ttm{w} \mapsto \key{\%rcx}, \,
  3365. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  3366. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  3367. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  3368. \ttm{t} \mapsto \key{\%rcx} \}
  3369. \end{gather*}
  3370. Adapt the code from the \code{assign-homes} pass
  3371. (Section~\ref{sec:assign-Rvar}) to replace the variables with their
  3372. assigned location. Applying the above assignment to our running
  3373. example, on the left, yields the program on the right.
  3374. % why frame size of 32? -JGS
  3375. \begin{center}
  3376. \begin{minipage}{0.3\textwidth}
  3377. \begin{lstlisting}
  3378. movq $1, v
  3379. movq $42, w
  3380. movq v, x
  3381. addq $7, x
  3382. movq x, y
  3383. movq x, z
  3384. addq w, z
  3385. movq y, t
  3386. negq t
  3387. movq z, %rax
  3388. addq t, %rax
  3389. jmp conclusion
  3390. \end{lstlisting}
  3391. \end{minipage}
  3392. $\Rightarrow\qquad$
  3393. \begin{minipage}{0.45\textwidth}
  3394. \begin{lstlisting}
  3395. movq $1, -8(%rbp)
  3396. movq $42, %rcx
  3397. movq -8(%rbp), -8(%rbp)
  3398. addq $7, -8(%rbp)
  3399. movq -8(%rbp), -16(%rbp)
  3400. movq -8(%rbp), -8(%rbp)
  3401. addq %rcx, -8(%rbp)
  3402. movq -16(%rbp), %rcx
  3403. negq %rcx
  3404. movq -8(%rbp), %rax
  3405. addq %rcx, %rax
  3406. jmp conclusion
  3407. \end{lstlisting}
  3408. \end{minipage}
  3409. \end{center}
  3410. \begin{exercise}\normalfont
  3411. %
  3412. Implement the compiler pass \code{allocate-registers}.
  3413. %
  3414. Create five programs that exercise all of the register allocation
  3415. algorithm, including spilling variables to the stack.
  3416. %
  3417. Replace \code{assign-homes} in the list of \code{passes} in the
  3418. \code{run-tests.rkt} script with the three new passes:
  3419. \code{uncover-live}, \code{build-interference}, and
  3420. \code{allocate-registers}.
  3421. %
  3422. Temporarily remove the \code{print-x86} pass from the list of passes
  3423. and the call to \code{compiler-tests}.
  3424. %
  3425. Run the script to test the register allocator.
  3426. \end{exercise}
  3427. \section{Patch Instructions}
  3428. \label{sec:patch-instructions}
  3429. The remaining step in the compilation to x86 is to ensure that the
  3430. instructions have at most one argument that is a memory access.
  3431. In the running example, the instruction \code{movq -8(\%rbp), -16(\%rbp)}
  3432. is problematic. The fix is to first move \code{-8(\%rbp)}
  3433. into \code{rax} and then move \code{rax} into \code{-16(\%rbp)}.
  3434. %
  3435. The two moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  3436. problematic, but they can be fixed by simply deleting them. In
  3437. general, we recommend deleting all the trivial moves whose source and
  3438. destination are the same location.
  3439. %
  3440. The following is the output of \code{patch-instructions} on the
  3441. running example.
  3442. \begin{center}
  3443. \begin{minipage}{0.4\textwidth}
  3444. \begin{lstlisting}
  3445. movq $1, -8(%rbp)
  3446. movq $42, %rcx
  3447. movq -8(%rbp), -8(%rbp)
  3448. addq $7, -8(%rbp)
  3449. movq -8(%rbp), -16(%rbp)
  3450. movq -8(%rbp), -8(%rbp)
  3451. addq %rcx, -8(%rbp)
  3452. movq -16(%rbp), %rcx
  3453. negq %rcx
  3454. movq -8(%rbp), %rax
  3455. addq %rcx, %rax
  3456. jmp conclusion
  3457. \end{lstlisting}
  3458. \end{minipage}
  3459. $\Rightarrow\qquad$
  3460. \begin{minipage}{0.45\textwidth}
  3461. \begin{lstlisting}
  3462. movq $1, -8(%rbp)
  3463. movq $42, %rcx
  3464. addq $7, -8(%rbp)
  3465. movq -8(%rbp), %rax
  3466. movq %rax, -16(%rbp)
  3467. addq %rcx, -8(%rbp)
  3468. movq -16(%rbp), %rcx
  3469. negq %rcx
  3470. movq -8(%rbp), %rax
  3471. addq %rcx, %rax
  3472. jmp conclusion
  3473. \end{lstlisting}
  3474. \end{minipage}
  3475. \end{center}
  3476. \begin{exercise}\normalfont
  3477. %
  3478. Implement the \code{patch-instructions} compiler pass.
  3479. %
  3480. Insert it after \code{allocate-registers} in the list of \code{passes}
  3481. in the \code{run-tests.rkt} script.
  3482. %
  3483. Run the script to test the \code{patch-instructions} pass.
  3484. \end{exercise}
  3485. \section{Print x86}
  3486. \label{sec:print-x86-reg-alloc}
  3487. \index{calling conventions}
  3488. \index{prelude}\index{conclusion}
  3489. Recall that the \code{print-x86} pass generates the prelude and
  3490. conclusion instructions to satisfy the x86 calling conventions
  3491. (Section~\ref{sec:calling-conventions}). With the addition of the
  3492. register allocator, the callee-saved registers used by the register
  3493. allocator must be saved in the prelude and restored in the conclusion.
  3494. In the \code{allocate-registers} pass, add an entry to the \itm{info}
  3495. of \code{X86Program} named \code{used-callee} that stores the set of
  3496. callee-saved registers that were assigned to variables. The
  3497. \code{print-x86} pass can then access this information to decide which
  3498. callee-saved registers need to be saved and restored.
  3499. %
  3500. When calculating the size of the frame to adjust the \code{rsp} in the
  3501. prelude, make sure to take into account the space used for saving the
  3502. callee-saved registers. Also, don't forget that the frame needs to be
  3503. a multiple of 16 bytes!
  3504. An overview of all of the passes involved in register allocation is
  3505. shown in Figure~\ref{fig:reg-alloc-passes}.
  3506. \begin{figure}[tbp]
  3507. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3508. \node (Rvar) at (0,2) {\large \LangVar{}};
  3509. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  3510. \node (Rvar-3) at (6,2) {\large \LangVar{}};
  3511. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  3512. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  3513. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  3514. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  3515. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  3516. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  3517. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  3518. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  3519. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvar-3);
  3520. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate-control} (Cvar-1);
  3521. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  3522. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  3523. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  3524. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  3525. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  3526. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  3527. \end{tikzpicture}
  3528. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  3529. \label{fig:reg-alloc-passes}
  3530. \end{figure}
  3531. \begin{exercise}\normalfont
  3532. Update the \code{print-x86} pass as described in this section.
  3533. %
  3534. In the \code{run-tests.rkt} script, reinstate \code{print-x86} in the
  3535. list of passes and the call to \code{compiler-tests}.
  3536. %
  3537. Run the script to test the complete compiler for \LangVar{} that
  3538. performs register allocation.
  3539. \end{exercise}
  3540. \section{Challenge: Move Biasing}
  3541. \label{sec:move-biasing}
  3542. \index{move biasing}
  3543. This section describes an enhancement to the register allocator for
  3544. students looking for an extra challenge or who have a deeper interest
  3545. in register allocation.
  3546. To motivate the need for move biasing we return to the running example
  3547. but this time use all of the general purpose registers. So we have
  3548. the following mapping of color numbers to registers.
  3549. \[
  3550. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi} \}
  3551. \]
  3552. Using the same assignment of variables to color numbers that was
  3553. produced by the register allocator described in the last section, we
  3554. get the following program.
  3555. \begin{center}
  3556. \begin{minipage}{0.3\textwidth}
  3557. \begin{lstlisting}
  3558. movq $1, v
  3559. movq $42, w
  3560. movq v, x
  3561. addq $7, x
  3562. movq x, y
  3563. movq x, z
  3564. addq w, z
  3565. movq y, t
  3566. negq t
  3567. movq z, %rax
  3568. addq t, %rax
  3569. jmp conclusion
  3570. \end{lstlisting}
  3571. \end{minipage}
  3572. $\Rightarrow\qquad$
  3573. \begin{minipage}{0.45\textwidth}
  3574. \begin{lstlisting}
  3575. movq $1, %rdx
  3576. movq $42, %rcx
  3577. movq %rdx, %rdx
  3578. addq $7, %rdx
  3579. movq %rdx, %rsi
  3580. movq %rdx, %rdx
  3581. addq %rcx, %rdx
  3582. movq %rsi, %rcx
  3583. negq %rcx
  3584. movq %rdx, %rax
  3585. addq %rcx, %rax
  3586. jmp conclusion
  3587. \end{lstlisting}
  3588. \end{minipage}
  3589. \end{center}
  3590. In the above output code there are two \key{movq} instructions that
  3591. can be removed because their source and target are the same. However,
  3592. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  3593. register, we could instead remove three \key{movq} instructions. We
  3594. can accomplish this by taking into account which variables appear in
  3595. \key{movq} instructions with which other variables.
  3596. We say that two variables $p$ and $q$ are \emph{move
  3597. related}\index{move related} if they participate together in a
  3598. \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  3599. \key{movq} $q$\key{,} $p$. When the register allocator chooses a color
  3600. for a variable, it should prefer a color that has already been used
  3601. for a move-related variable (assuming that they do not interfere). Of
  3602. course, this preference should not override the preference for
  3603. registers over stack locations. This preference should be used as a
  3604. tie breaker when choosing between registers or when choosing between
  3605. stack locations.
  3606. We recommend representing the move relationships in a graph, similar
  3607. to how we represented interference. The following is the \emph{move
  3608. graph} for our running example.
  3609. \[
  3610. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3611. \node (rax) at (0,0) {$\ttm{rax}$};
  3612. \node (rsp) at (9,2) {$\ttm{rsp}$};
  3613. \node (t) at (0,2) {$\ttm{t}$};
  3614. \node (z) at (3,2) {$\ttm{z}$};
  3615. \node (x) at (6,2) {$\ttm{x}$};
  3616. \node (y) at (3,0) {$\ttm{y}$};
  3617. \node (w) at (6,0) {$\ttm{w}$};
  3618. \node (v) at (9,0) {$\ttm{v}$};
  3619. \draw (v) to (x);
  3620. \draw (x) to (y);
  3621. \draw (x) to (z);
  3622. \draw (y) to (t);
  3623. \end{tikzpicture}
  3624. \]
  3625. Now we replay the graph coloring, pausing to see the coloring of
  3626. \code{y}. Recall the following configuration. The most saturated vertices
  3627. were \code{w} and \code{y}.
  3628. \[
  3629. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3630. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3631. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3632. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3633. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3634. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3635. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3636. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3637. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  3638. \draw (t1) to (rax);
  3639. \draw (t1) to (z);
  3640. \draw (z) to (y);
  3641. \draw (z) to (w);
  3642. \draw (x) to (w);
  3643. \draw (y) to (w);
  3644. \draw (v) to (w);
  3645. \draw (v) to (rsp);
  3646. \draw (w) to (rsp);
  3647. \draw (x) to (rsp);
  3648. \draw (y) to (rsp);
  3649. \path[-.,bend left=15] (z) edge node {} (rsp);
  3650. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3651. \draw (rax) to (rsp);
  3652. \end{tikzpicture}
  3653. \]
  3654. %
  3655. Last time we chose to color \code{w} with $0$. But this time we see
  3656. that \code{w} is not move related to any vertex, but \code{y} is move
  3657. related to \code{t}. So we choose to color \code{y} the same color as
  3658. \code{t}, $0$.
  3659. \[
  3660. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3661. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3662. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3663. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3664. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3665. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3666. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  3667. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  3668. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  3669. \draw (t1) to (rax);
  3670. \draw (t1) to (z);
  3671. \draw (z) to (y);
  3672. \draw (z) to (w);
  3673. \draw (x) to (w);
  3674. \draw (y) to (w);
  3675. \draw (v) to (w);
  3676. \draw (v) to (rsp);
  3677. \draw (w) to (rsp);
  3678. \draw (x) to (rsp);
  3679. \draw (y) to (rsp);
  3680. \path[-.,bend left=15] (z) edge node {} (rsp);
  3681. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3682. \draw (rax) to (rsp);
  3683. \end{tikzpicture}
  3684. \]
  3685. Now \code{w} is the most saturated, so we color it $2$.
  3686. \[
  3687. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3688. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3689. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3690. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3691. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3692. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  3693. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  3694. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  3695. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  3696. \draw (t1) to (rax);
  3697. \draw (t1) to (z);
  3698. \draw (z) to (y);
  3699. \draw (z) to (w);
  3700. \draw (x) to (w);
  3701. \draw (y) to (w);
  3702. \draw (v) to (w);
  3703. \draw (v) to (rsp);
  3704. \draw (w) to (rsp);
  3705. \draw (x) to (rsp);
  3706. \draw (y) to (rsp);
  3707. \path[-.,bend left=15] (z) edge node {} (rsp);
  3708. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3709. \draw (rax) to (rsp);
  3710. \end{tikzpicture}
  3711. \]
  3712. At this point, vertices \code{x} and \code{v} are most saturated, but
  3713. \code{x} is move related to \code{y} and \code{z}, so we color
  3714. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  3715. \[
  3716. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3717. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3718. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3719. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3720. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3721. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  3722. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  3723. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  3724. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  3725. \draw (t1) to (rax);
  3726. \draw (t) to (z);
  3727. \draw (z) to (y);
  3728. \draw (z) to (w);
  3729. \draw (x) to (w);
  3730. \draw (y) to (w);
  3731. \draw (v) to (w);
  3732. \draw (v) to (rsp);
  3733. \draw (w) to (rsp);
  3734. \draw (x) to (rsp);
  3735. \draw (y) to (rsp);
  3736. \path[-.,bend left=15] (z) edge node {} (rsp);
  3737. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3738. \draw (rax) to (rsp);
  3739. \end{tikzpicture}
  3740. \]
  3741. So we have the following assignment of variables to registers.
  3742. \begin{gather*}
  3743. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  3744. \ttm{w} \mapsto \key{\%rsi}, \,
  3745. \ttm{x} \mapsto \key{\%rcx}, \,
  3746. \ttm{y} \mapsto \key{\%rcx}, \,
  3747. \ttm{z} \mapsto \key{\%rdx}, \,
  3748. \ttm{t} \mapsto \key{\%rcx} \}
  3749. \end{gather*}
  3750. We apply this register assignment to the running example, on the left,
  3751. to obtain the code in the middle. The \code{patch-instructions} then
  3752. removes the three trivial moves to obtain the code on the right.
  3753. \begin{minipage}{0.25\textwidth}
  3754. \begin{lstlisting}
  3755. movq $1, v
  3756. movq $42, w
  3757. movq v, x
  3758. addq $7, x
  3759. movq x, y
  3760. movq x, z
  3761. addq w, z
  3762. movq y, t
  3763. negq t
  3764. movq z, %rax
  3765. addq t, %rax
  3766. jmp conclusion
  3767. \end{lstlisting}
  3768. \end{minipage}
  3769. $\Rightarrow\qquad$
  3770. \begin{minipage}{0.25\textwidth}
  3771. \begin{lstlisting}
  3772. movq $1, %rcx
  3773. movq $42, %rsi
  3774. movq %rcx, %rcx
  3775. addq $7, %rcx
  3776. movq %rcx, %rcx
  3777. movq %rcx, %rdx
  3778. addq %rsi, %rdx
  3779. movq %rcx, %rcx
  3780. negq %rcx
  3781. movq %rdx, %rax
  3782. addq %rcx, %rax
  3783. jmp conclusion
  3784. \end{lstlisting}
  3785. \end{minipage}
  3786. $\Rightarrow\qquad$
  3787. \begin{minipage}{0.25\textwidth}
  3788. \begin{lstlisting}
  3789. movq $1, %rcx
  3790. movq $42, %rsi
  3791. addq $7, %rcx
  3792. movq %rcx, %rdx
  3793. addq %rsi, %rdx
  3794. negq %rcx
  3795. movq %rdx, %rax
  3796. addq %rcx, %rax
  3797. jmp conclusion
  3798. \end{lstlisting}
  3799. \end{minipage}
  3800. \begin{exercise}\normalfont
  3801. Change your implementation of \code{allocate-registers} to take move
  3802. biasing into account. Create two new tests that include at least one
  3803. opportunity for move biasing and visually inspect the output x86
  3804. programs to make sure that your move biasing is working properly. Make
  3805. sure that your compiler still passes all of the tests.
  3806. \end{exercise}
  3807. \margincomment{\footnotesize To do: another neat challenge would be to do
  3808. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3809. %% \subsection{Output of the Running Example}
  3810. %% \label{sec:reg-alloc-output}
  3811. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  3812. the running example (Figure~\ref{fig:reg-eg}) with register allocation
  3813. and move biasing. To demonstrate both the use of registers and the
  3814. stack, we have limited the register allocator to use just two
  3815. registers: \code{rbx} and \code{rcx}. In the prelude\index{prelude}
  3816. of the \code{main} function, we push \code{rbx} onto the stack because
  3817. it is a callee-saved register and it was assigned to variable by the
  3818. register allocator. We subtract \code{8} from the \code{rsp} at the
  3819. end of the prelude to reserve space for the one spilled variable.
  3820. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  3821. Moving on the the \code{start} block, we see how the registers were
  3822. allocated. Variables \code{v}, \code{x}, and \code{y} were assigned to
  3823. \code{rbx} and variable \code{z} was assigned to \code{rcx}. Variable
  3824. \code{w} was spilled to the stack location \code{-16(\%rbp)}. Recall
  3825. that the prelude saved the callee-save register \code{rbx} onto the
  3826. stack. The spilled variables must be placed lower on the stack than
  3827. the saved callee-save registers, so in this case \code{w} is placed at
  3828. \code{-16(\%rbp)}.
  3829. In the \code{conclusion}\index{conclusion}, we undo the work that was
  3830. done in the prelude. We move the stack pointer up by \code{8} bytes
  3831. (the room for spilled variables), then we pop the old values of
  3832. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  3833. \code{retq} to return control to the operating system.
  3834. \begin{figure}[tbp]
  3835. % var_test_28.rkt
  3836. % (use-minimal-set-of-registers! #t)
  3837. % and only rbx rcx
  3838. % tmp 0 rbx
  3839. % z 1 rcx
  3840. % y 0 rbx
  3841. % w 2 16(%rbp)
  3842. % v 0 rbx
  3843. % x 0 rbx
  3844. \begin{lstlisting}
  3845. start:
  3846. movq $1, %rbx
  3847. movq $42, -16(%rbp)
  3848. addq $7, %rbx
  3849. movq %rbx, %rcx
  3850. addq -16(%rbp), %rcx
  3851. negq %rbx
  3852. movq %rcx, %rax
  3853. addq %rbx, %rax
  3854. jmp conclusion
  3855. .globl main
  3856. main:
  3857. pushq %rbp
  3858. movq %rsp, %rbp
  3859. pushq %rbx
  3860. subq $8, %rsp
  3861. jmp start
  3862. conclusion:
  3863. addq $8, %rsp
  3864. popq %rbx
  3865. popq %rbp
  3866. retq
  3867. \end{lstlisting}
  3868. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  3869. \label{fig:running-example-x86}
  3870. \end{figure}
  3871. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3872. \chapter{Booleans and Control Flow}
  3873. \label{ch:bool-types}
  3874. \index{Boolean}
  3875. \index{control flow}
  3876. \index{conditional expression}
  3877. The \LangInt{} and \LangVar{} languages only have a single kind of
  3878. value, integers. In this chapter we add a second kind of value, the
  3879. Booleans, to create the \LangIf{} language. The Boolean values
  3880. \emph{true} and \emph{false} are written \key{\#t} and \key{\#f}
  3881. respectively in Racket. The \LangIf{} language includes several
  3882. operations that involve Booleans (\key{and}, \key{not}, \key{eq?},
  3883. \key{<}, etc.) and the conditional \key{if} expression. With the
  3884. addition of \key{if}, programs can have non-trivial control flow which
  3885. impacts \code{explicate-control} and liveness analysis. Also, because
  3886. we now have two kinds of values, we need to handle programs that apply
  3887. an operation to the wrong kind of value, such as \code{(not 1)}.
  3888. There are two language design options for such situations. One option
  3889. is to signal an error and the other is to provide a wider
  3890. interpretation of the operation. The Racket language uses a mixture of
  3891. these two options, depending on the operation and the kind of
  3892. value. For example, the result of \code{(not 1)} in Racket is
  3893. \code{\#f} because Racket treats non-zero integers as if they were
  3894. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  3895. error in Racket because \code{car} expects a pair.
  3896. Typed Racket makes similar design choices as Racket, except much of
  3897. the error detection happens at compile time instead of run time. Typed
  3898. Racket accepts and runs \code{(not 1)}, producing \code{\#f}. But in
  3899. the case of \code{(car 1)}, Typed Racket reports a compile-time error
  3900. because Typed Racket expects the type of the argument to be of the
  3901. form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  3902. The \LangIf{} language performs type checking during compilation like
  3903. Typed Racket. In Chapter~\ref{ch:type-dynamic} we study the
  3904. alternative choice, that is, a dynamically typed language like Racket.
  3905. The \LangIf{} language is a subset of Typed Racket; for some
  3906. operations we are more restrictive, for example, rejecting
  3907. \code{(not 1)}.
  3908. This chapter is organized as follows. We begin by defining the syntax
  3909. and interpreter for the \LangIf{} language
  3910. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  3911. checking and build a type checker for \LangIf{}
  3912. (Section~\ref{sec:type-check-Rif}). To compile \LangIf{} we need to
  3913. enlarge the intermediate language \LangCVar{} into \LangCIf{}
  3914. (Section~\ref{sec:Cif}) and \LangXInt{} into \LangXIf{}
  3915. (Section~\ref{sec:x86-if}). The remaining sections of this chapter
  3916. discuss how our compiler passes change to accommodate Booleans and
  3917. conditional control flow. There is one new pass, named \code{shrink},
  3918. that translates some operators into others, thereby reducing the
  3919. number of operators that need to be handled in later passes. The
  3920. largest changes occur in \code{explicate-control}, to translate
  3921. \code{if} expressions into control-flow graphs
  3922. (Section~\ref{sec:explicate-control-Rif}). Regarding register
  3923. allocation, the liveness analysis now has multiple basic blocks to
  3924. process and there is the interesting question of how to handle
  3925. conditional jumps.
  3926. \section{The \LangIf{} Language}
  3927. \label{sec:lang-if}
  3928. The concrete syntax of the \LangIf{} language is defined in
  3929. Figure~\ref{fig:Rif-concrete-syntax} and the abstract syntax is defined
  3930. in Figure~\ref{fig:Rif-syntax}. The \LangIf{} language includes all of
  3931. \LangVar{} (shown in gray), the Boolean literals \code{\#t} and
  3932. \code{\#f}, and the conditional \code{if} expression. We expand the
  3933. operators to include
  3934. \begin{enumerate}
  3935. \item subtraction on integers,
  3936. \item the logical operators \key{and}, \key{or} and \key{not},
  3937. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  3938. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  3939. comparing integers.
  3940. \end{enumerate}
  3941. We reorganize the abstract syntax for the primitive operations in
  3942. Figure~\ref{fig:Rif-syntax}, using only one grammar rule for all of
  3943. them. This means that the grammar no longer checks whether the arity
  3944. of an operators matches the number of arguments. That responsibility
  3945. is moved to the type checker for \LangIf{}, which we introduce in
  3946. Section~\ref{sec:type-check-Rif}.
  3947. \begin{figure}[tp]
  3948. \centering
  3949. \fbox{
  3950. \begin{minipage}{0.96\textwidth}
  3951. \[
  3952. \begin{array}{lcl}
  3953. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3954. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3955. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} } \mid \CSUB{\Exp}{\Exp} \\
  3956. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} } \\
  3957. &\mid& \itm{bool}
  3958. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  3959. \mid (\key{not}\;\Exp) \\
  3960. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} \\
  3961. \LangIf{} &::=& \Exp
  3962. \end{array}
  3963. \]
  3964. \end{minipage}
  3965. }
  3966. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  3967. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  3968. \label{fig:Rif-concrete-syntax}
  3969. \end{figure}
  3970. \begin{figure}[tp]
  3971. \centering
  3972. \fbox{
  3973. \begin{minipage}{0.96\textwidth}
  3974. \[
  3975. \begin{array}{lcl}
  3976. \itm{bool} &::=& \code{\#t} \mid \code{\#f} \\
  3977. \itm{cmp} &::= & \code{eq?} \mid \code{<} \mid \code{<=} \mid \code{>} \mid \code{>=} \\
  3978. \itm{op} &::= & \itm{cmp} \mid \code{read} \mid \code{+} \mid \code{-}
  3979. \mid \code{and} \mid \code{or} \mid \code{not} \\
  3980. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  3981. &\mid& \PRIM{\itm{op}}{\Exp\ldots}\\
  3982. &\mid& \BOOL{\itm{bool}} \mid \IF{\Exp}{\Exp}{\Exp} \\
  3983. \LangIf{} &::=& \PROGRAM{\code{'()}}{\Exp}
  3984. \end{array}
  3985. \]
  3986. \end{minipage}
  3987. }
  3988. \caption{The abstract syntax of \LangIf{}.}
  3989. \label{fig:Rif-syntax}
  3990. \end{figure}
  3991. Figure~\ref{fig:interp-Rif} defines the interpreter for \LangIf{},
  3992. which inherits from the interpreter for \LangVar{}
  3993. (Figure~\ref{fig:interp-Rvar}). The literals \code{\#t} and \code{\#f}
  3994. evaluate to the corresponding Boolean values. The conditional
  3995. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  3996. \itm{cnd} and then either evaluates \itm{thn} or \itm{els} depending
  3997. on whether \itm{cnd} produced \code{\#t} or \code{\#f}. The logical
  3998. operations \code{not} and \code{and} behave as you might expect, but
  3999. note that the \code{and} operation is short-circuiting. That is, given
  4000. the expression $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not
  4001. evaluated if $e_1$ evaluates to \code{\#f}.
  4002. With the increase in the number of primitive operations, the
  4003. interpreter would become repetitive without some care. We refactor
  4004. the case for \code{Prim}, moving the code that differs with each
  4005. operation into the \code{interp-op} method shown in in
  4006. Figure~\ref{fig:interp-op-Rif}. We handle the \code{and} operation
  4007. separately because of its short-circuiting behavior.
  4008. \begin{figure}[tbp]
  4009. \begin{lstlisting}
  4010. (define interp-Rif-class
  4011. (class interp-Rvar-class
  4012. (super-new)
  4013. (define/public (interp-op op) ...)
  4014. (define/override ((interp-exp env) e)
  4015. (define recur (interp-exp env))
  4016. (match e
  4017. [(Bool b) b]
  4018. [(If cnd thn els)
  4019. (match (recur cnd)
  4020. [#t (recur thn)]
  4021. [#f (recur els)])]
  4022. [(Prim 'and (list e1 e2))
  4023. (match (recur e1)
  4024. [#t (match (recur e2) [#t #t] [#f #f])]
  4025. [#f #f])]
  4026. [(Prim op args)
  4027. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  4028. [else ((super interp-exp env) e)]))
  4029. ))
  4030. (define (interp-Rif p)
  4031. (send (new interp-Rif-class) interp-program p))
  4032. \end{lstlisting}
  4033. \caption{Interpreter for the \LangIf{} language. (See
  4034. Figure~\ref{fig:interp-op-Rif} for \code{interp-op}.)}
  4035. \label{fig:interp-Rif}
  4036. \end{figure}
  4037. \begin{figure}[tbp]
  4038. \begin{lstlisting}
  4039. (define/public (interp-op op)
  4040. (match op
  4041. ['+ fx+]
  4042. ['- fx-]
  4043. ['read read-fixnum]
  4044. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  4045. ['or (lambda (v1 v2)
  4046. (cond [(and (boolean? v1) (boolean? v2))
  4047. (or v1 v2)]))]
  4048. ['eq? (lambda (v1 v2)
  4049. (cond [(or (and (fixnum? v1) (fixnum? v2))
  4050. (and (boolean? v1) (boolean? v2))
  4051. (and (vector? v1) (vector? v2)))
  4052. (eq? v1 v2)]))]
  4053. ['< (lambda (v1 v2)
  4054. (cond [(and (fixnum? v1) (fixnum? v2))
  4055. (< v1 v2)]))]
  4056. ['<= (lambda (v1 v2)
  4057. (cond [(and (fixnum? v1) (fixnum? v2))
  4058. (<= v1 v2)]))]
  4059. ['> (lambda (v1 v2)
  4060. (cond [(and (fixnum? v1) (fixnum? v2))
  4061. (> v1 v2)]))]
  4062. ['>= (lambda (v1 v2)
  4063. (cond [(and (fixnum? v1) (fixnum? v2))
  4064. (>= v1 v2)]))]
  4065. [else (error 'interp-op "unknown operator")]))
  4066. \end{lstlisting}
  4067. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  4068. \label{fig:interp-op-Rif}
  4069. \end{figure}
  4070. \section{Type Checking \LangIf{} Programs}
  4071. \label{sec:type-check-Rif}
  4072. \index{type checking}
  4073. \index{semantic analysis}
  4074. It is helpful to think about type checking in two complementary
  4075. ways. A type checker predicts the type of value that will be produced
  4076. by each expression in the program. For \LangIf{}, we have just two types,
  4077. \key{Integer} and \key{Boolean}. So a type checker should predict that
  4078. \begin{lstlisting}
  4079. (+ 10 (- (+ 12 20)))
  4080. \end{lstlisting}
  4081. produces an \key{Integer} while
  4082. \begin{lstlisting}
  4083. (and (not #f) #t)
  4084. \end{lstlisting}
  4085. produces a \key{Boolean}.
  4086. Another way to think about type checking is that it enforces a set of
  4087. rules about which operators can be applied to which kinds of
  4088. values. For example, our type checker for \LangIf{} signals an error
  4089. for the below expression
  4090. \begin{lstlisting}
  4091. (not (+ 10 (- (+ 12 20))))
  4092. \end{lstlisting}
  4093. The subexpression \code{(+ 10 (- (+ 12 20)))} has type \key{Integer}
  4094. but the type checker enforces the rule that the argument of \code{not}
  4095. must be a \key{Boolean}.
  4096. We implement type checking using classes and methods because they
  4097. provide the open recursion needed to reuse code as we extend the type
  4098. checker in later chapters, analogous to the use of classes and methods
  4099. for the interpreters (Section~\ref{sec:extensible-interp}).
  4100. We separate the type checker for the \LangVar{} fragment into its own
  4101. class, shown in Figure~\ref{fig:type-check-Rvar}. The type checker for
  4102. \LangIf{} is shown in Figure~\ref{fig:type-check-Rif} and it inherits
  4103. from the type checker for \LangVar{}. These type checkers are in the
  4104. files \code{type-check-Rvar.rkt} and \code{type-check-Rif.rkt} of the
  4105. support code.
  4106. %
  4107. Each type checker is a structurally recursive function over the AST.
  4108. Given an input expression \code{e}, the type checker either signals an
  4109. error or returns an expression and its type (\key{Integer} or
  4110. \key{Boolean}). It returns an expression because there are situations
  4111. in which we want to change or update the expression.
  4112. Next we discuss the \code{match} cases in \code{type-check-exp} of
  4113. Figure~\ref{fig:type-check-Rvar}. The type of an integer constant is
  4114. \code{Integer}. To handle variables, the type checker uses the
  4115. environment \code{env} to map variables to types. Consider the case
  4116. for \key{let}. We type check the initializing expression to obtain
  4117. its type \key{T} and then associate type \code{T} with the variable
  4118. \code{x} in the environment used to type check the body of the
  4119. \key{let}. Thus, when the type checker encounters a use of variable
  4120. \code{x}, it can find its type in the environment. Regarding
  4121. primitive operators, we recursively analyze the arguments and then
  4122. invoke \code{type-check-op} to check whether the argument types are
  4123. allowed.
  4124. Several auxiliary methods are used in the type checker. The method
  4125. \code{operator-types} defines a dictionary that maps the operator
  4126. names to their parameter and return types. The \code{type-equal?}
  4127. method determines whether two types are equal, which for now simply
  4128. dispatches to \code{equal?} (deep equality). The
  4129. \code{check-type-equal?} method triggers an error if the two types are
  4130. not equal. The \code{type-check-op} method looks up the operator in
  4131. the \code{operator-types} dictionary and then checks whether the
  4132. argument types are equal to the parameter types. The result is the
  4133. return type of the operator.
  4134. \begin{figure}[tbp]
  4135. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4136. (define type-check-Rvar-class
  4137. (class object%
  4138. (super-new)
  4139. (define/public (operator-types)
  4140. '((+ . ((Integer Integer) . Integer))
  4141. (- . ((Integer) . Integer))
  4142. (read . (() . Integer))))
  4143. (define/public (type-equal? t1 t2) (equal? t1 t2))
  4144. (define/public (check-type-equal? t1 t2 e)
  4145. (unless (type-equal? t1 t2)
  4146. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  4147. (define/public (type-check-op op arg-types e)
  4148. (match (dict-ref (operator-types) op)
  4149. [`(,param-types . ,return-type)
  4150. (for ([at arg-types] [pt param-types])
  4151. (check-type-equal? at pt e))
  4152. return-type]
  4153. [else (error 'type-check-op "unrecognized ~a" op)]))
  4154. (define/public (type-check-exp env)
  4155. (lambda (e)
  4156. (match e
  4157. [(Int n) (values (Int n) 'Integer)]
  4158. [(Var x) (values (Var x) (dict-ref env x))]
  4159. [(Let x e body)
  4160. (define-values (e^ Te) ((type-check-exp env) e))
  4161. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  4162. (values (Let x e^ b) Tb)]
  4163. [(Prim op es)
  4164. (define-values (new-es ts)
  4165. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  4166. (values (Prim op new-es) (type-check-op op ts e))]
  4167. [else (error 'type-check-exp "couldn't match" e)])))
  4168. (define/public (type-check-program e)
  4169. (match e
  4170. [(Program info body)
  4171. (define-values (body^ Tb) ((type-check-exp '()) body))
  4172. (check-type-equal? Tb 'Integer body)
  4173. (Program info body^)]
  4174. [else (error 'type-check-Rvar "couldn't match ~a" e)]))
  4175. ))
  4176. (define (type-check-Rvar p)
  4177. (send (new type-check-Rvar-class) type-check-program p))
  4178. \end{lstlisting}
  4179. \caption{Type checker for the \LangVar{} language.}
  4180. \label{fig:type-check-Rvar}
  4181. \end{figure}
  4182. \begin{figure}[tbp]
  4183. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4184. (define type-check-Rif-class
  4185. (class type-check-Rvar-class
  4186. (super-new)
  4187. (inherit check-type-equal?)
  4188. (define/override (operator-types)
  4189. (append '((- . ((Integer Integer) . Integer))
  4190. (and . ((Boolean Boolean) . Boolean))
  4191. (or . ((Boolean Boolean) . Boolean))
  4192. (< . ((Integer Integer) . Boolean))
  4193. (<= . ((Integer Integer) . Boolean))
  4194. (> . ((Integer Integer) . Boolean))
  4195. (>= . ((Integer Integer) . Boolean))
  4196. (not . ((Boolean) . Boolean))
  4197. )
  4198. (super operator-types)))
  4199. (define/override (type-check-exp env)
  4200. (lambda (e)
  4201. (match e
  4202. [(Prim 'eq? (list e1 e2))
  4203. (define-values (e1^ T1) ((type-check-exp env) e1))
  4204. (define-values (e2^ T2) ((type-check-exp env) e2))
  4205. (check-type-equal? T1 T2 e)
  4206. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  4207. [(Bool b) (values (Bool b) 'Boolean)]
  4208. [(If cnd thn els)
  4209. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  4210. (define-values (thn^ Tt) ((type-check-exp env) thn))
  4211. (define-values (els^ Te) ((type-check-exp env) els))
  4212. (check-type-equal? Tc 'Boolean e)
  4213. (check-type-equal? Tt Te e)
  4214. (values (If cnd^ thn^ els^) Te)]
  4215. [else ((super type-check-exp env) e)])))
  4216. ))
  4217. (define (type-check-Rif p)
  4218. (send (new type-check-Rif-class) type-check-program p))
  4219. \end{lstlisting}
  4220. \caption{Type checker for the \LangIf{} language.}
  4221. \label{fig:type-check-Rif}
  4222. \end{figure}
  4223. Next we discuss the type checker for \LangIf{} in
  4224. Figure~\ref{fig:type-check-Rif}. The operator \code{eq?} requires the
  4225. two arguments to have the same type. The type of a Boolean constant is
  4226. \code{Boolean}. The condition of an \code{if} must be of
  4227. \code{Boolean} type and the two branches must have the same type. The
  4228. \code{operator-types} function adds dictionary entries for the other
  4229. new operators.
  4230. \begin{exercise}\normalfont
  4231. Create 10 new test programs in \LangIf{}. Half of the programs should
  4232. have a type error. For those programs, create an empty file with the
  4233. same base name but with file extension \code{.tyerr}. For example, if
  4234. the test \code{cond\_test\_14.rkt} is expected to error, then create
  4235. an empty file named \code{cond\_test\_14.tyerr}. This indicates to
  4236. \code{interp-tests} and \code{compiler-tests} that a type error is
  4237. expected. The other half of the test programs should not have type
  4238. errors.
  4239. In the \code{run-tests.rkt} script, change the second argument of
  4240. \code{interp-tests} and \code{compiler-tests} to
  4241. \code{type-check-Rif}, which causes the type checker to run prior to
  4242. the compiler passes. Temporarily change the \code{passes} to an empty
  4243. list and run the script, thereby checking that the new test programs
  4244. either type check or not as intended.
  4245. \end{exercise}
  4246. \section{The \LangCIf{} Intermediate Language}
  4247. \label{sec:Cif}
  4248. Figure~\ref{fig:c1-syntax} defines the abstract syntax of the
  4249. \LangCIf{} intermediate language. (The concrete syntax is in the
  4250. Appendix, Figure~\ref{fig:c1-concrete-syntax}.) Compared to
  4251. \LangCVar{}, the \LangCIf{} language adds logical and comparison
  4252. operators to the \Exp{} non-terminal and the literals \key{\#t} and
  4253. \key{\#f} to the \Arg{} non-terminal.
  4254. Regarding control flow, \LangCIf{} adds \key{goto} and \code{if}
  4255. statements to the \Tail{} non-terminal. The condition of an \code{if}
  4256. statement is a comparison operation and the branches are \code{goto}
  4257. statements, making it straightforward to compile \code{if} statements
  4258. to x86.
  4259. \begin{figure}[tp]
  4260. \fbox{
  4261. \begin{minipage}{0.96\textwidth}
  4262. \small
  4263. \[
  4264. \begin{array}{lcl}
  4265. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  4266. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  4267. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  4268. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4269. &\mid& \UNIOP{\key{'not}}{\Atm}
  4270. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  4271. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  4272. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  4273. \mid \GOTO{\itm{label}} \\
  4274. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  4275. \LangCIf{} & ::= & \gray{\CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}}
  4276. \end{array}
  4277. \]
  4278. \end{minipage}
  4279. }
  4280. \caption{The abstract syntax of \LangCIf{}, an extension of \LangCVar{}
  4281. (Figure~\ref{fig:c0-syntax}).}
  4282. \label{fig:c1-syntax}
  4283. \end{figure}
  4284. \section{The \LangXIf{} Language}
  4285. \label{sec:x86-if}
  4286. \index{x86} To implement the new logical operations, the comparison
  4287. operations, and the \key{if} expression, we need to delve further into
  4288. the x86 language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1}
  4289. define the concrete and abstract syntax for the \LangXIf{} subset
  4290. of x86, which includes instructions for logical operations,
  4291. comparisons, and conditional jumps.
  4292. One challenge is that x86 does not provide an instruction that
  4293. directly implements logical negation (\code{not} in \LangIf{} and
  4294. \LangCIf{}). However, the \code{xorq} instruction can be used to
  4295. encode \code{not}. The \key{xorq} instruction takes two arguments,
  4296. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  4297. bit of its arguments, and writes the results into its second argument.
  4298. Recall the truth table for exclusive-or:
  4299. \begin{center}
  4300. \begin{tabular}{l|cc}
  4301. & 0 & 1 \\ \hline
  4302. 0 & 0 & 1 \\
  4303. 1 & 1 & 0
  4304. \end{tabular}
  4305. \end{center}
  4306. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  4307. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  4308. for the bit $1$, the result is the opposite of the second bit. Thus,
  4309. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  4310. the first argument:
  4311. \[
  4312. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  4313. \qquad\Rightarrow\qquad
  4314. \begin{array}{l}
  4315. \key{movq}~ \Arg\key{,} \Var\\
  4316. \key{xorq}~ \key{\$1,} \Var
  4317. \end{array}
  4318. \]
  4319. \begin{figure}[tp]
  4320. \fbox{
  4321. \begin{minipage}{0.96\textwidth}
  4322. \[
  4323. \begin{array}{lcl}
  4324. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  4325. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4326. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} } \mid \key{\%}\itm{bytereg}\\
  4327. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4328. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \mid
  4329. \key{subq} \; \Arg\key{,} \Arg \mid
  4330. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid } \\
  4331. && \gray{ \key{callq} \; \itm{label} \mid
  4332. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} } \\
  4333. && \gray{ \itm{label}\key{:}\; \Instr }
  4334. \mid \key{xorq}~\Arg\key{,}~\Arg
  4335. \mid \key{cmpq}~\Arg\key{,}~\Arg \mid \\
  4336. && \key{set}cc~\Arg
  4337. \mid \key{movzbq}~\Arg\key{,}~\Arg
  4338. \mid \key{j}cc~\itm{label}
  4339. \\
  4340. \LangXIf{} &::= & \gray{ \key{.globl main} }\\
  4341. & & \gray{ \key{main:} \; \Instr\ldots }
  4342. \end{array}
  4343. \]
  4344. \end{minipage}
  4345. }
  4346. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  4347. \label{fig:x86-1-concrete}
  4348. \end{figure}
  4349. \begin{figure}[tp]
  4350. \fbox{
  4351. \begin{minipage}{0.98\textwidth}
  4352. \small
  4353. \[
  4354. \begin{array}{lcl}
  4355. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  4356. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4357. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}}
  4358. \mid \BYTEREG{\itm{bytereg}} \\
  4359. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4360. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  4361. \mid \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  4362. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  4363. \mid \UNIINSTR{\code{negq}}{\Arg} } \\
  4364. &\mid& \gray{ \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  4365. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  4366. &\mid& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  4367. \mid \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  4368. &\mid& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  4369. \mid \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  4370. &\mid& \JMPIF{\itm{cc}}{\itm{label}} \\
  4371. \Block &::= & \gray{\BLOCK{\itm{info}}{\LP\Instr\ldots\RP}} \\
  4372. \LangXIf{} &::= & \gray{\XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}}
  4373. \end{array}
  4374. \]
  4375. \end{minipage}
  4376. }
  4377. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  4378. \label{fig:x86-1}
  4379. \end{figure}
  4380. Next we consider the x86 instructions that are relevant for compiling
  4381. the comparison operations. The \key{cmpq} instruction compares its two
  4382. arguments to determine whether one argument is less than, equal, or
  4383. greater than the other argument. The \key{cmpq} instruction is unusual
  4384. regarding the order of its arguments and where the result is
  4385. placed. The argument order is backwards: if you want to test whether
  4386. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  4387. \key{cmpq} is placed in the special EFLAGS register. This register
  4388. cannot be accessed directly but it can be queried by a number of
  4389. instructions, including the \key{set} instruction. The instruction
  4390. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  4391. depending on whether the comparison comes out according to the
  4392. condition code \itm{cc} (\key{e} for equal, \key{l} for less, \key{le}
  4393. for less-or-equal, \key{g} for greater, \key{ge} for
  4394. greater-or-equal). The \key{set} instruction has an annoying quirk in
  4395. that its destination argument must be single byte register, such as
  4396. \code{al} (L for lower bits) or \code{ah} (H for higher bits), which
  4397. are part of the \code{rax} register. Thankfully, the \key{movzbq}
  4398. instruction can be used to move from a single byte register to a
  4399. normal 64-bit register. The abstract syntax for the \code{set}
  4400. instruction differs from the concrete syntax in that it separates the
  4401. instruction name from the condition code.
  4402. The x86 instruction for conditional jump is relevant to the
  4403. compilation of \key{if} expressions. The instruction
  4404. $\key{j}\itm{cc}~\itm{label}$ updates the program counter to point to
  4405. the instruction after \itm{label} depending on whether the result in
  4406. the EFLAGS register matches the condition code \itm{cc}, otherwise the
  4407. jump instruction falls through to the next instruction. Like the
  4408. abstract syntax for \code{set}, the abstract syntax for conditional
  4409. jump separates the instruction name from the condition code. For
  4410. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  4411. the conditional jump instruction relies on the EFLAGS register, it is
  4412. common for it to be immediately preceded by a \key{cmpq} instruction
  4413. to set the EFLAGS register.
  4414. \section{Shrink the \LangIf{} Language}
  4415. \label{sec:shrink-Rif}
  4416. The \LangIf{} language includes several operators that are easily
  4417. expressible with other operators. For example, subtraction is
  4418. expressible using addition and negation.
  4419. \[
  4420. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  4421. \]
  4422. Several of the comparison operations are expressible using less-than
  4423. and logical negation.
  4424. \[
  4425. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  4426. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  4427. \]
  4428. The \key{let} is needed in the above translation to ensure that
  4429. expression $e_1$ is evaluated before $e_2$.
  4430. By performing these translations in the front-end of the compiler, the
  4431. later passes of the compiler do not need to deal with these operators,
  4432. making the passes shorter.
  4433. %% On the other hand, sometimes
  4434. %% these translations make it more difficult to generate the most
  4435. %% efficient code with respect to the number of instructions. However,
  4436. %% these differences typically do not affect the number of accesses to
  4437. %% memory, which is the primary factor that determines execution time on
  4438. %% modern computer architectures.
  4439. \begin{exercise}\normalfont
  4440. Implement the pass \code{shrink} to remove subtraction, \key{and},
  4441. \key{or}, \key{<=}, \key{>}, and \key{>=} from the language by
  4442. translating them to other constructs in \LangIf{}.
  4443. %
  4444. Create six test programs that involve these operators.
  4445. %
  4446. In the \code{run-tests.rkt} script, add the following entry for
  4447. \code{shrink} to the list of passes (it should be the only pass at
  4448. this point).
  4449. \begin{lstlisting}
  4450. (list "shrink" shrink interp-Rif type-check-Rif)
  4451. \end{lstlisting}
  4452. This instructs \code{interp-tests} to run the intepreter
  4453. \code{interp-Rif} and the type checker \code{type-check-Rif} on the
  4454. output of \code{shrink}.
  4455. %
  4456. Run the script to test your compiler on all the test programs.
  4457. \end{exercise}
  4458. \section{Uniquify Variables}
  4459. \label{sec:uniquify-Rif}
  4460. Add cases to \code{uniquify-exp} to handle Boolean constants and
  4461. \code{if} expressions.
  4462. \begin{exercise}\normalfont
  4463. Update the \code{uniquify-exp} for \LangIf{} and add the following
  4464. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  4465. \begin{lstlisting}
  4466. (list "uniquify" uniquify interp-Rif type-check-Rif)
  4467. \end{lstlisting}
  4468. Run the script to test your compiler.
  4469. \end{exercise}
  4470. \section{Remove Complex Operands}
  4471. \label{sec:remove-complex-opera-Rif}
  4472. The output language for this pass is \LangIfANF{}
  4473. (Figure~\ref{fig:Rif-anf-syntax}), the administrative normal form of
  4474. \LangIf{}. The \code{Bool} form is an atomic expressions but
  4475. \code{If} is not. All three sub-expressions of an \code{If} are
  4476. allowed to be complex expressions but the operands of \code{not} and
  4477. the comparisons must be atoms.
  4478. Add cases for \code{Bool} and \code{If} to the \code{rco-exp} and
  4479. \code{rco-atom} functions according to whether the output needs to be
  4480. \Exp{} or \Atm{} as specified in the grammar for \LangIfANF{}.
  4481. Regarding \code{If}, it is particularly important to \textbf{not}
  4482. replace its condition with a temporary variable because that would
  4483. interfere with the generation of high-quality output in the
  4484. \code{explicate-control} pass.
  4485. \begin{figure}[tp]
  4486. \centering
  4487. \fbox{
  4488. \begin{minipage}{0.96\textwidth}
  4489. \[
  4490. \begin{array}{rcl}
  4491. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} } \mid \BOOL{\itm{bool}}\\
  4492. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  4493. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4494. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  4495. &\mid& \UNIOP{\key{not}}{\Atm} \\
  4496. &\mid& \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4497. R^{\dagger}_2 &::=& \PROGRAM{\code{()}}{\Exp}
  4498. \end{array}
  4499. \]
  4500. \end{minipage}
  4501. }
  4502. \caption{\LangIfANF{} is \LangIf{} in administrative normal form (ANF).}
  4503. \label{fig:Rif-anf-syntax}
  4504. \end{figure}
  4505. \begin{exercise}\normalfont
  4506. %
  4507. Add cases for Boolean constants and \code{if} to the \code{rco-atom}
  4508. and \code{rco-exp} functions in \code{compiler.rkt}.
  4509. %
  4510. Create three new \LangInt{} programs that exercise the interesting
  4511. code in this pass.
  4512. %
  4513. In the \code{run-tests.rkt} script, add the following entry to the
  4514. list of \code{passes} and then run the script to test your compiler.
  4515. \begin{lstlisting}
  4516. (list "remove-complex" remove-complex-opera* interp-Rif type-check-Rif)
  4517. \end{lstlisting}
  4518. \end{exercise}
  4519. \section{Explicate Control}
  4520. \label{sec:explicate-control-Rif}
  4521. Recall that the purpose of \code{explicate-control} is to make the
  4522. order of evaluation explicit in the syntax of the program. With the
  4523. addition of \key{if} this get more interesting.
  4524. As a motivating example, consider the following program that has an
  4525. \key{if} expression nested in the predicate of another \key{if}.
  4526. % cond_test_41.rkt
  4527. \begin{center}
  4528. \begin{minipage}{0.96\textwidth}
  4529. \begin{lstlisting}
  4530. (let ([x (read)])
  4531. (let ([y (read)])
  4532. (if (if (< x 1) (eq? x 0) (eq? x 2))
  4533. (+ y 2)
  4534. (+ y 10))))
  4535. \end{lstlisting}
  4536. \end{minipage}
  4537. \end{center}
  4538. %
  4539. The naive way to compile \key{if} and the comparison would be to
  4540. handle each of them in isolation, regardless of their context. Each
  4541. comparison would be translated into a \key{cmpq} instruction followed
  4542. by a couple instructions to move the result from the EFLAGS register
  4543. into a general purpose register or stack location. Each \key{if} would
  4544. be translated into a \key{cmpq} instruction followed by a conditional
  4545. jump. The generated code for the inner \key{if} in the above example
  4546. would be as follows.
  4547. \begin{center}
  4548. \begin{minipage}{0.96\textwidth}
  4549. \begin{lstlisting}
  4550. ...
  4551. cmpq $1, x ;; (< x 1)
  4552. setl %al
  4553. movzbq %al, tmp
  4554. cmpq $1, tmp ;; (if ...)
  4555. je then_branch_1
  4556. jmp else_branch_1
  4557. ...
  4558. \end{lstlisting}
  4559. \end{minipage}
  4560. \end{center}
  4561. However, if we take context into account we can do better and reduce
  4562. the use of \key{cmpq} instructions for accessing the EFLAG register.
  4563. Our goal will be compile \key{if} expressions so that the relevant
  4564. comparison instruction appears directly before the conditional jump.
  4565. For example, we want to generate the following code for the inner
  4566. \code{if}.
  4567. \begin{center}
  4568. \begin{minipage}{0.96\textwidth}
  4569. \begin{lstlisting}
  4570. ...
  4571. cmpq $1, x
  4572. je then_branch_1
  4573. jmp else_branch_1
  4574. ...
  4575. \end{lstlisting}
  4576. \end{minipage}
  4577. \end{center}
  4578. One way to achieve this is to reorganize the code at the level of
  4579. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  4580. the following code.
  4581. \begin{center}
  4582. \begin{minipage}{0.96\textwidth}
  4583. \begin{lstlisting}
  4584. (let ([x (read)])
  4585. (let ([y (read)])
  4586. (if (< x 1)
  4587. (if (eq? x 0)
  4588. (+ y 2)
  4589. (+ y 10))
  4590. (if (eq? x 2)
  4591. (+ y 2)
  4592. (+ y 10)))))
  4593. \end{lstlisting}
  4594. \end{minipage}
  4595. \end{center}
  4596. Unfortunately, this approach duplicates the two branches from the
  4597. outer \code{if} and a compiler must never duplicate code!
  4598. We need a way to perform the above transformation but without
  4599. duplicating code. That is, we need a way for different parts of a
  4600. program to refer to the same piece of code. At the level of x86
  4601. assembly this is straightforward because we can label the code for
  4602. each branch and insert jumps in all the places that need to execute
  4603. the branch. In our intermediate language, we need to move away from
  4604. abstract syntax \emph{trees} and instead use \emph{graphs}. In
  4605. particular, we use a standard program representation called a
  4606. \emph{control flow graph} (CFG), due to Frances Elizabeth
  4607. \citet{Allen:1970uq}. \index{control-flow graph} Each vertex is a
  4608. labeled sequence of code, called a \emph{basic block}, and each edge
  4609. represents a jump to another block. The \key{CProgram} construct of
  4610. \LangCVar{} and \LangCIf{} contains a control flow graph represented
  4611. as an alist mapping labels to basic blocks. Each basic block is
  4612. represented by the $\Tail$ non-terminal.
  4613. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  4614. \code{remove-complex-opera*} pass and then the
  4615. \code{explicate-control} pass on the example program. We walk through
  4616. the output program and then discuss the algorithm.
  4617. %
  4618. Following the order of evaluation in the output of
  4619. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  4620. and then the comparison \lstinline{(< x 1)} in the predicate of the
  4621. inner \key{if}. In the output of \code{explicate-control}, in the
  4622. block labeled \code{start}, is two assignment statements followed by a
  4623. \code{if} statement that branches to \code{block40} or
  4624. \code{block41}. The blocks associated with those labels contain the
  4625. translations of the code \lstinline{(eq? x 0)} and \lstinline{(eq? x 2)},
  4626. respectively. In particular, we start \code{block40} with the
  4627. comparison \lstinline{(eq? x 0)} and then branch to \code{block38} or
  4628. \code{block39}, the two branches of the outer \key{if}, i.e.,
  4629. \lstinline{(+ y 2)} and \lstinline{(+ y 10)}. The story for
  4630. \code{block41} is similar.
  4631. \begin{figure}[tbp]
  4632. \begin{tabular}{lll}
  4633. \begin{minipage}{0.4\textwidth}
  4634. % cond_test_41.rkt
  4635. \begin{lstlisting}
  4636. (let ([x (read)])
  4637. (let ([y (read)])
  4638. (if (if (< x 1)
  4639. (eq? x 0)
  4640. (eq? x 2))
  4641. (+ y 2)
  4642. (+ y 10))))
  4643. \end{lstlisting}
  4644. \hspace{40pt}$\Downarrow$
  4645. \begin{lstlisting}
  4646. (let ([x (read)])
  4647. (let ([y (read)])
  4648. (if (if (< x 1)
  4649. (eq? x 0)
  4650. (eq? x 2))
  4651. (+ y 2)
  4652. (+ y 10))))
  4653. \end{lstlisting}
  4654. \end{minipage}
  4655. &
  4656. $\Rightarrow$
  4657. &
  4658. \begin{minipage}{0.55\textwidth}
  4659. \begin{lstlisting}
  4660. start:
  4661. x = (read);
  4662. y = (read);
  4663. if (< x 1) goto block40;
  4664. else goto block41;
  4665. block40:
  4666. if (eq? x 0) goto block38;
  4667. else goto block39;
  4668. block41:
  4669. if (eq? x 2) goto block38;
  4670. else goto block39;
  4671. block38:
  4672. return (+ y 2);
  4673. block39:
  4674. return (+ y 10);
  4675. \end{lstlisting}
  4676. \end{minipage}
  4677. \end{tabular}
  4678. \caption{Translation from \LangIf{} to \LangCIf{}
  4679. via the \code{explicate-control}.}
  4680. \label{fig:explicate-control-s1-38}
  4681. \end{figure}
  4682. %% The nice thing about the output of \code{explicate-control} is that
  4683. %% there are no unnecessary comparisons and every comparison is part of a
  4684. %% conditional jump.
  4685. %% The down-side of this output is that it includes
  4686. %% trivial blocks, such as the blocks labeled \code{block92} through
  4687. %% \code{block95}, that only jump to another block. We discuss a solution
  4688. %% to this problem in Section~\ref{sec:opt-jumps}.
  4689. Recall that in Section~\ref{sec:explicate-control-Rvar} we implement
  4690. \code{explicate-control} for \LangVar{} using two mutually recursive
  4691. functions, \code{explicate-tail} and \code{explicate-assign}. The
  4692. former function translates expressions in tail position whereas the
  4693. later function translates expressions on the right-hand-side of a
  4694. \key{let}. With the addition of \key{if} expression in \LangIf{} we
  4695. have a new kind of position to deal with: the predicate position of
  4696. the \key{if}. We need another function, \code{explicate-pred}, that
  4697. takes an \LangIf{} expression and two blocks for the then-branch and
  4698. else-branch. The output of \code{explicate-pred} is a block.
  4699. %
  4700. In the following paragraphs we discuss specific cases in the
  4701. \code{explicate-pred} function as well as additions to the
  4702. \code{explicate-tail} and \code{explicate-assign} functions.
  4703. \begin{figure}[tbp]
  4704. \begin{lstlisting}
  4705. (define (explicate-pred cnd thn els)
  4706. (match cnd
  4707. [(Var x) ___]
  4708. [(Let x rhs body) ___]
  4709. [(Prim 'not (list e)) ___]
  4710. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  4711. (IfStmt (Prim op arg*) (force (block->goto thn))
  4712. (force (block->goto els)))]
  4713. [(Bool b) (if b thn els)]
  4714. [(If cnd^ thn^ els^) ___]
  4715. [else (error "explicate-pred unhandled case" cnd)]))
  4716. \end{lstlisting}
  4717. \caption{Skeleton for the \key{explicate-pred} auxiliary function.}
  4718. \label{fig:explicate-pred}
  4719. \end{figure}
  4720. The skeleton for the \code{explicate-pred} function is given in
  4721. Figure~\ref{fig:explicate-pred}. It has a case for every expression
  4722. that can have type \code{Boolean}. We detail a few cases here and
  4723. leave the rest for the reader. The input to this function is an
  4724. expression and two blocks, \code{thn} and \code{els}, for the two
  4725. branches of the enclosing \key{if}.
  4726. %
  4727. Consider the case for Boolean constants in
  4728. Figure~\ref{fig:explicate-pred}. We perform a kind of partial
  4729. evaluation\index{partial evaluation} and output either the \code{thn}
  4730. or \code{els} branch depending on whether the constant is true or
  4731. false. This case demonstrates that we sometimes discard the \code{thn}
  4732. or \code{els} blocks that are input to \code{explicate-pred}.
  4733. The case for \key{if} in \code{explicate-pred} is particularly
  4734. illuminating because it deals with the challenges we discussed above
  4735. regarding nested \key{if} expressions
  4736. (Figure~\ref{fig:explicate-control-s1-38}). The \lstinline{thn^} and
  4737. \lstinline{els^} branches of the \key{if} inherit their context from
  4738. the current one, that is, predicate context. So you should recursively
  4739. apply \code{explicate-pred} to the \lstinline{thn^} and
  4740. \lstinline{els^} branches. For both of those recursive calls, pass
  4741. \code{thn} and \code{els} as the extra parameters. Thus, \code{thn}
  4742. and \code{els} may get used twice, once inside each recursive call. As
  4743. discussed above, to avoid duplicating code, we need to add them to the
  4744. control-flow graph so that we can instead refer to them by name and
  4745. execute them with a \key{goto}. However, as we saw in the cases above
  4746. for Boolean constants, the blocks \code{thn} and \code{els} may not
  4747. get used at all and we don't want to prematurely add them to the
  4748. control-flow graph if they end up being discarded.
  4749. The solution to this conundrum is to use \emph{lazy
  4750. evaluation}\index{lazy evaluation}\citep{Friedman:1976aa} to delay
  4751. adding the blocks to the control-flow graph until the points where we
  4752. know they will be used. Racket provides support for lazy evaluation
  4753. with the
  4754. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  4755. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  4756. \index{delay} creates a \emph{promise}\index{promise} in which the
  4757. evaluation of the expressions is postponed. When \key{(force}
  4758. $p$\key{)}\index{force} is applied to a promise $p$ for the first
  4759. time, the expressions $e_1 \ldots e_n$ are evaluated and the result of
  4760. $e_n$ is cached in the promise and returned. If \code{force} is
  4761. applied again to the same promise, then the cached result is returned.
  4762. If \code{force} is applied to an argument that is not a promise,
  4763. \code{force} simply returns the argument.
  4764. We use lazy evaluation for the input and output blocks of the
  4765. functions \code{explicate-pred} and \code{explicate-assign} and for
  4766. the output block of \code{explicate-tail}. So instead of taking and
  4767. returning blocks, they take and return promises. Furthermore, when we
  4768. come to a situation in which we a block might be used more than once,
  4769. as in the case for \code{if} in \code{explicate-pred}, we transform
  4770. the promise into a new promise that will add the block to the
  4771. control-flow graph and return a \code{goto}. The following auxiliary
  4772. function named \code{block->goto} accomplishes this task. It begins
  4773. with \code{delay} to create a promise. When forced, this promise will
  4774. force the original promise. If that returns a \code{goto} (because the
  4775. block was already added to the control-flow graph), then we return the
  4776. \code{goto}. Otherwise we add the block to the control-flow graph with
  4777. another auxiliary function named \code{add-node}. That function
  4778. returns the label for the new block, which we use to create a
  4779. \code{goto}.
  4780. \begin{lstlisting}
  4781. (define (block->goto block)
  4782. (delay
  4783. (define b (force block))
  4784. (match b
  4785. [(Goto label) (Goto label)]
  4786. [else (Goto (add-node b))])))
  4787. \end{lstlisting}
  4788. Returning to the discussion of \code{explicate-pred}
  4789. (Figure~\ref{fig:explicate-pred}), consider the case for comparison
  4790. operators. This is one of the base cases of the recursive function so
  4791. we translate the comparison to an \code{if} statement. We apply
  4792. \code{block->goto} to \code{thn} and \code{els} to obtain two promises
  4793. that will add then to the control-flow graph, which we can immediately
  4794. \code{force} to obtain the two goto's that form the branches of the
  4795. \code{if} statement.
  4796. %% Getting back to the case for \code{if} in \code{explicate-pred}, we
  4797. %% make the recursive calls to \code{explicate-pred} on the ``then'' and
  4798. %% ``else'' branches with the arguments \code{(block->goto} $B_1$\code{)}
  4799. %% and \code{(block->goto} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  4800. %% results from the two recursive calls. We complete the case for
  4801. %% \code{if} by recursively apply \code{explicate-pred} to the condition
  4802. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  4803. %% the result $B_5$.
  4804. %% \[
  4805. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  4806. %% \quad\Rightarrow\quad
  4807. %% B_5
  4808. %% \]
  4809. The \code{explicate-tail} and \code{explicate-assign} functions need
  4810. additional cases for Boolean constants and \key{if}.
  4811. %
  4812. In the cases for \code{if}, the two branches inherit the current
  4813. context, so in \code{explicate-tail} they are in tail position and in
  4814. \code{explicate-assign} they are in assignment position. The
  4815. \code{cont} parameter of \code{explicate-assign} is used in both
  4816. recursive calls, so make sure to use \code{block->goto} on it.
  4817. %% In the case for \code{if} in \code{explicate-tail}, the two branches
  4818. %% inherit the current context, so they are in tail position. Thus, the
  4819. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  4820. %% \code{explicate-tail}.
  4821. %% %
  4822. %% We need to pass $B_0$ as the accumulator argument for both of these
  4823. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  4824. %% Thus, we first apply \code{block->goto} to $B_0$ so that it gets added
  4825. %% to the control-flow graph and obtain a promised goto $G_0$.
  4826. %% %
  4827. %% Let $B_1$ be the result of \code{explicate-tail} on the ``then''
  4828. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate-tail}
  4829. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  4830. %% \code{explicate-pred} to the condition of the \key{if}, $B_1$, and
  4831. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  4832. %% \[
  4833. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  4834. %% \]
  4835. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  4836. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  4837. %% should not be confused with the labels for the blocks that appear in
  4838. %% the generated code. We initially construct unlabeled blocks; we only
  4839. %% attach labels to blocks when we add them to the control-flow graph, as
  4840. %% we see in the next case.
  4841. %% Next consider the case for \key{if} in the \code{explicate-assign}
  4842. %% function. The context of the \key{if} is an assignment to some
  4843. %% variable $x$ and then the control continues to some promised block
  4844. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  4845. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  4846. %% apply \code{block->goto} to it and obtain a promised goto $G_1$. The
  4847. %% branches of the \key{if} inherit the current context, so they are in
  4848. %% assignment positions. Let $B_2$ be the result of applying
  4849. %% \code{explicate-assign} to the ``then'' branch, variable $x$, and
  4850. %% $G_1$. Let $B_3$ be the result of applying \code{explicate-assign} to
  4851. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  4852. %% the result of applying \code{explicate-pred} to the predicate
  4853. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  4854. %% translates to the promise $B_4$.
  4855. %% \[
  4856. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  4857. %% \]
  4858. %% This completes the description of \code{explicate-control} for \LangIf{}.
  4859. The way in which the \code{shrink} pass transforms logical operations
  4860. such as \code{and} and \code{or} can impact the quality of code
  4861. generated by \code{explicate-control}. For example, consider the
  4862. following program.
  4863. % cond_test_21.rkt
  4864. \begin{lstlisting}
  4865. (if (and (eq? (read) 0) (eq? (read) 1))
  4866. 0
  4867. 42)
  4868. \end{lstlisting}
  4869. The \code{and} operation should transform into something that the
  4870. \code{explicate-pred} function can still analyze and descend through to
  4871. reach the underlying \code{eq?} conditions. Ideally, your
  4872. \code{explicate-control} pass should generate code similar to the
  4873. following for the above program.
  4874. \begin{center}
  4875. \begin{lstlisting}
  4876. start:
  4877. tmp1 = (read);
  4878. if (eq? tmp1 0) goto block40;
  4879. else goto block39;
  4880. block40:
  4881. tmp2 = (read);
  4882. if (eq? tmp2 1) goto block38;
  4883. else goto block39;
  4884. block38:
  4885. return 0;
  4886. block39:
  4887. return 42;
  4888. \end{lstlisting}
  4889. \end{center}
  4890. \begin{exercise}\normalfont
  4891. Implement the pass \code{explicate-control} by adding the cases for
  4892. Boolean constants and \key{if} to the \code{explicate-tail} and
  4893. \code{explicate-assign}. Implement the auxiliary function
  4894. \code{explicate-pred} for predicate contexts.
  4895. %
  4896. Create test cases that exercise all of the new cases in the code for
  4897. this pass.
  4898. %
  4899. Add the following entry to the list of \code{passes} in
  4900. \code{run-tests.rkt} and then run this script to test your compiler.
  4901. \begin{lstlisting}
  4902. (list "explicate-control" explicate-control interp-Cif type-check-Cif)
  4903. \end{lstlisting}
  4904. \end{exercise}
  4905. \section{Select Instructions}
  4906. \label{sec:select-Rif}
  4907. \index{instruction selection}
  4908. The \code{select-instructions} pass translate \LangCIf{} to
  4909. \LangXIfVar{}. Recall that we implement this pass using three
  4910. auxiliary functions, one for each of the non-terminals $\Atm$,
  4911. $\Stmt$, and $\Tail$.
  4912. For $\Atm$, we have new cases for the Booleans. We take the usual
  4913. approach of encoding them as integers, with true as 1 and false as 0.
  4914. \[
  4915. \key{\#t} \Rightarrow \key{1}
  4916. \qquad
  4917. \key{\#f} \Rightarrow \key{0}
  4918. \]
  4919. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  4920. be implemented in terms of \code{xorq} as we discussed at the
  4921. beginning of this section. Given an assignment
  4922. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  4923. if the left-hand side $\itm{var}$ is
  4924. the same as $\Atm$, then just the \code{xorq} suffices.
  4925. \[
  4926. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  4927. \quad\Rightarrow\quad
  4928. \key{xorq}~\key{\$}1\key{,}~\Var
  4929. \]
  4930. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  4931. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  4932. x86. Then we have
  4933. \[
  4934. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  4935. \quad\Rightarrow\quad
  4936. \begin{array}{l}
  4937. \key{movq}~\Arg\key{,}~\Var\\
  4938. \key{xorq}~\key{\$}1\key{,}~\Var
  4939. \end{array}
  4940. \]
  4941. Next consider the cases for \code{eq?} and less-than comparison.
  4942. Translating these operations to x86 is slightly involved due to the
  4943. unusual nature of the \key{cmpq} instruction discussed above. We
  4944. recommend translating an assignment from \code{eq?} into the following
  4945. sequence of three instructions. \\
  4946. \begin{tabular}{lll}
  4947. \begin{minipage}{0.4\textwidth}
  4948. \begin{lstlisting}
  4949. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  4950. \end{lstlisting}
  4951. \end{minipage}
  4952. &
  4953. $\Rightarrow$
  4954. &
  4955. \begin{minipage}{0.4\textwidth}
  4956. \begin{lstlisting}
  4957. cmpq |$\Arg_2$|, |$\Arg_1$|
  4958. sete %al
  4959. movzbq %al, |$\Var$|
  4960. \end{lstlisting}
  4961. \end{minipage}
  4962. \end{tabular} \\
  4963. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  4964. and \key{if} statements. Both are straightforward to translate to
  4965. x86. A \key{goto} becomes a jump instruction.
  4966. \[
  4967. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  4968. \]
  4969. An \key{if} statement becomes a compare instruction followed by a
  4970. conditional jump (for the ``then'' branch) and the fall-through is to
  4971. a regular jump (for the ``else'' branch).\\
  4972. \begin{tabular}{lll}
  4973. \begin{minipage}{0.4\textwidth}
  4974. \begin{lstlisting}
  4975. if (eq? |$\Atm_1$| |$\Atm_2$|) goto |$\ell_1$|;
  4976. else goto |$\ell_2$|;
  4977. \end{lstlisting}
  4978. \end{minipage}
  4979. &
  4980. $\Rightarrow$
  4981. &
  4982. \begin{minipage}{0.4\textwidth}
  4983. \begin{lstlisting}
  4984. cmpq |$\Arg_2$|, |$\Arg_1$|
  4985. je |$\ell_1$|
  4986. jmp |$\ell_2$|
  4987. \end{lstlisting}
  4988. \end{minipage}
  4989. \end{tabular} \\
  4990. \begin{exercise}\normalfont
  4991. Expand your \code{select-instructions} pass to handle the new features
  4992. of the \LangIf{} language.
  4993. %
  4994. Add the following entry to the list of \code{passes} in
  4995. \code{run-tests.rkt}
  4996. \begin{lstlisting}
  4997. (list "select-instructions" select-instructions interp-pseudo-x86-1)
  4998. \end{lstlisting}
  4999. %
  5000. Run the script to test your compiler on all the test programs.
  5001. \end{exercise}
  5002. \section{Register Allocation}
  5003. \label{sec:register-allocation-Rif}
  5004. \index{register allocation}
  5005. The changes required for \LangIf{} affect liveness analysis, building the
  5006. interference graph, and assigning homes, but the graph coloring
  5007. algorithm itself does not change.
  5008. \subsection{Liveness Analysis}
  5009. \label{sec:liveness-analysis-Rif}
  5010. \index{liveness analysis}
  5011. Recall that for \LangVar{} we implemented liveness analysis for a single
  5012. basic block (Section~\ref{sec:liveness-analysis-Rvar}). With the
  5013. addition of \key{if} expressions to \LangIf{}, \code{explicate-control}
  5014. produces many basic blocks arranged in a control-flow graph. We
  5015. recommend that you create a new auxiliary function named
  5016. \code{uncover-live-CFG} that applies liveness analysis to a
  5017. control-flow graph.
  5018. The first question we is: what order should we process the basic
  5019. blocks in the control-flow graph? Recall that to perform liveness
  5020. analysis on a basic block we need to know its live-after set. If a
  5021. basic block has no successors (i.e. no out-edges in the control flow
  5022. graph), then it has an empty live-after set and we can immediately
  5023. apply liveness analysis to it. If a basic block has some successors,
  5024. then we need to complete liveness analysis on those blocks first. In
  5025. graph theory, a sequence of nodes is in \emph{topological
  5026. order}\index{topological order} if each vertex comes before its
  5027. successors. We need the opposite, so we can transpose the graph
  5028. before computing a topological order.
  5029. %
  5030. Use the \code{tsort} and \code{transpose} functions of the Racket
  5031. \code{graph} package to accomplish this.
  5032. %
  5033. As an aside, a topological ordering is only guaranteed to exist if the
  5034. graph does not contain any cycles. That is indeed the case for the
  5035. control-flow graphs that we generate from \LangIf{} programs.
  5036. However, in Chapter~\ref{ch:loop} we add loops to \LangLoop{} and
  5037. learn how to handle cycles in the control-flow graph.
  5038. You'll need to construct a directed graph to represent the
  5039. control-flow graph. Do not use the \code{directed-graph} of the
  5040. \code{graph} package because that only allows at most one edge between
  5041. each pair of vertices, but a control-flow graph may have multiple
  5042. edges between a pair of vertices. The \code{multigraph.rkt} file in
  5043. the support code implements a graph representation that allows
  5044. multiple edges between a pair of vertices.
  5045. The next question is how to analyze jump instructions. Recall that in
  5046. Section~\ref{sec:liveness-analysis-Rvar} we maintain an alist named
  5047. \code{label->live} that maps each label to the set of live locations
  5048. at the beginning of its block. We use \code{label->live} to determine
  5049. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  5050. that we have many basic blocks, \code{label->live} needs to be updated
  5051. as we process the blocks. In particular, after performing liveness
  5052. analysis on a block, we take the live-before set of its first
  5053. instruction and associate that with the block's label in the
  5054. \code{label->live}.
  5055. In \LangXIfVar{} we also have the conditional jump
  5056. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  5057. this instruction is particularly interesting because during
  5058. compilation we do not know which way a conditional jump will go. So
  5059. we do not know whether to use the live-before set for the following
  5060. instruction or the live-before set for the $\itm{label}$. However,
  5061. there is no harm to the correctness of the compiler if we classify
  5062. more locations as live than the ones that are truly live during a
  5063. particular execution of the instruction. Thus, we can take the union
  5064. of the live-before sets from the following instruction and from the
  5065. mapping for $\itm{label}$ in \code{label->live}.
  5066. The auxiliary functions for computing the variables in an
  5067. instruction's argument and for computing the variables read-from ($R$)
  5068. or written-to ($W$) by an instruction need to be updated to handle the
  5069. new kinds of arguments and instructions in \LangXIfVar{}.
  5070. \begin{exercise}\normalfont
  5071. Update the \code{uncover-live} pass and implement the
  5072. \code{uncover-live-CFG} auxiliary function to apply liveness analysis
  5073. to the control-flow graph. Add the following entry to the list of
  5074. \code{passes} in the \code{run-tests.rkt} script.
  5075. \begin{lstlisting}
  5076. (list "uncover-live" uncover-live interp-pseudo-x86-1)
  5077. \end{lstlisting}
  5078. \end{exercise}
  5079. \subsection{Build the Interference Graph}
  5080. \label{sec:build-interference-Rif}
  5081. Many of the new instructions in \LangXIfVar{} can be handled in the
  5082. same way as the instructions in \LangXVar{}. Thus, if your code was
  5083. already quite general, it will not need to be changed to handle the
  5084. new instructions. If you code is not general enough, we recommend that
  5085. you change your code to be more general. For example, you can factor
  5086. out the computing of the the read and write sets for each kind of
  5087. instruction into two auxiliary functions.
  5088. Note that the \key{movzbq} instruction requires some special care,
  5089. similar to the \key{movq} instruction. See rule number 1 in
  5090. Section~\ref{sec:build-interference}.
  5091. \begin{exercise}\normalfont
  5092. Update the \code{build-interference} pass for \LangXIfVar{} and add the
  5093. following entries to the list of \code{passes} in the
  5094. \code{run-tests.rkt} script.
  5095. \begin{lstlisting}
  5096. (list "build-interference" build-interference interp-pseudo-x86-1)
  5097. (list "allocate-registers" allocate-registers interp-x86-1)
  5098. \end{lstlisting}
  5099. Run the script to test your compiler on all the \LangIf{} test
  5100. programs.
  5101. \end{exercise}
  5102. \section{Patch Instructions}
  5103. The second argument of the \key{cmpq} instruction must not be an
  5104. immediate value (such as an integer). So if you are comparing two
  5105. immediates, we recommend inserting a \key{movq} instruction to put the
  5106. second argument in \key{rax}. Also, recall that instructions may have
  5107. at most one memory reference.
  5108. %
  5109. The second argument of the \key{movzbq} must be a register.
  5110. %
  5111. There are no special restrictions on the jump instructions.
  5112. \begin{exercise}\normalfont
  5113. %
  5114. Update \code{patch-instructions} pass for \LangXIfVar{}.
  5115. %
  5116. Add the following entry to the list of \code{passes} in
  5117. \code{run-tests.rkt} and then run this script to test your compiler.
  5118. \begin{lstlisting}
  5119. (list "patch-instructions" patch-instructions interp-x86-1)
  5120. \end{lstlisting}
  5121. \end{exercise}
  5122. \begin{figure}[tbp]
  5123. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5124. \node (Rif) at (0,2) {\large \LangIf{}};
  5125. \node (Rif-2) at (3,2) {\large \LangIf{}};
  5126. \node (Rif-3) at (6,2) {\large \LangIf{}};
  5127. \node (Rif-4) at (9,2) {\large \LangIf{}};
  5128. \node (Rif-5) at (12,2) {\large \LangIf{}};
  5129. \node (C1-1) at (3,0) {\large \LangCIf{}};
  5130. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  5131. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  5132. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  5133. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  5134. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  5135. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  5136. \path[->,bend left=15] (Rif) edge [above] node {\ttfamily\footnotesize type-check} (Rif-2);
  5137. \path[->,bend left=15] (Rif-2) edge [above] node {\ttfamily\footnotesize shrink} (Rif-3);
  5138. \path[->,bend left=15] (Rif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Rif-4);
  5139. \path[->,bend left=15] (Rif-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rif-5);
  5140. \path[->,bend left=15] (Rif-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C1-1);
  5141. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select-instructions} (x86-2);
  5142. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  5143. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  5144. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  5145. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  5146. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86 } (x86-5);
  5147. \end{tikzpicture}
  5148. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  5149. \label{fig:Rif-passes}
  5150. \end{figure}
  5151. Figure~\ref{fig:Rif-passes} lists all the passes needed for the
  5152. compilation of \LangIf{}.
  5153. \section{An Example Translation}
  5154. Figure~\ref{fig:if-example-x86} shows a simple example program in
  5155. \LangIf{} translated to x86, showing the results of
  5156. \code{explicate-control}, \code{select-instructions}, and the final
  5157. x86 assembly code.
  5158. \begin{figure}[tbp]
  5159. \begin{tabular}{lll}
  5160. \begin{minipage}{0.4\textwidth}
  5161. % cond_test_20.rkt
  5162. \begin{lstlisting}
  5163. (if (eq? (read) 1) 42 0)
  5164. \end{lstlisting}
  5165. $\Downarrow$
  5166. \begin{lstlisting}
  5167. start:
  5168. tmp7951 = (read);
  5169. if (eq? tmp7951 1)
  5170. goto block7952;
  5171. else
  5172. goto block7953;
  5173. block7952:
  5174. return 42;
  5175. block7953:
  5176. return 0;
  5177. \end{lstlisting}
  5178. $\Downarrow$
  5179. \begin{lstlisting}
  5180. start:
  5181. callq read_int
  5182. movq %rax, tmp7951
  5183. cmpq $1, tmp7951
  5184. je block7952
  5185. jmp block7953
  5186. block7953:
  5187. movq $0, %rax
  5188. jmp conclusion
  5189. block7952:
  5190. movq $42, %rax
  5191. jmp conclusion
  5192. \end{lstlisting}
  5193. \end{minipage}
  5194. &
  5195. $\Rightarrow\qquad$
  5196. \begin{minipage}{0.4\textwidth}
  5197. \begin{lstlisting}
  5198. start:
  5199. callq read_int
  5200. movq %rax, %rcx
  5201. cmpq $1, %rcx
  5202. je block7952
  5203. jmp block7953
  5204. block7953:
  5205. movq $0, %rax
  5206. jmp conclusion
  5207. block7952:
  5208. movq $42, %rax
  5209. jmp conclusion
  5210. .globl main
  5211. main:
  5212. pushq %rbp
  5213. movq %rsp, %rbp
  5214. pushq %r13
  5215. pushq %r12
  5216. pushq %rbx
  5217. pushq %r14
  5218. subq $0, %rsp
  5219. jmp start
  5220. conclusion:
  5221. addq $0, %rsp
  5222. popq %r14
  5223. popq %rbx
  5224. popq %r12
  5225. popq %r13
  5226. popq %rbp
  5227. retq
  5228. \end{lstlisting}
  5229. \end{minipage}
  5230. \end{tabular}
  5231. \caption{Example compilation of an \key{if} expression to x86.}
  5232. \label{fig:if-example-x86}
  5233. \end{figure}
  5234. \section{Challenge: Remove Jumps}
  5235. \label{sec:opt-jumps}
  5236. %% Recall that in the example output of \code{explicate-control} in
  5237. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  5238. %% \code{block60} are trivial blocks, they do nothing but jump to another
  5239. %% block. The first goal of this challenge assignment is to remove those
  5240. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  5241. %% \code{explicate-control} on the left and shows the result of bypassing
  5242. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  5243. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  5244. %% \code{block55}. The optimized code on the right of
  5245. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  5246. %% \code{then} branch jumping directly to \code{block55}. The story is
  5247. %% similar for the \code{else} branch, as well as for the two branches in
  5248. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  5249. %% have been optimized in this way, there are no longer any jumps to
  5250. %% blocks \code{block57} through \code{block60}, so they can be removed.
  5251. %% \begin{figure}[tbp]
  5252. %% \begin{tabular}{lll}
  5253. %% \begin{minipage}{0.4\textwidth}
  5254. %% \begin{lstlisting}
  5255. %% block62:
  5256. %% tmp54 = (read);
  5257. %% if (eq? tmp54 2) then
  5258. %% goto block59;
  5259. %% else
  5260. %% goto block60;
  5261. %% block61:
  5262. %% tmp53 = (read);
  5263. %% if (eq? tmp53 0) then
  5264. %% goto block57;
  5265. %% else
  5266. %% goto block58;
  5267. %% block60:
  5268. %% goto block56;
  5269. %% block59:
  5270. %% goto block55;
  5271. %% block58:
  5272. %% goto block56;
  5273. %% block57:
  5274. %% goto block55;
  5275. %% block56:
  5276. %% return (+ 700 77);
  5277. %% block55:
  5278. %% return (+ 10 32);
  5279. %% start:
  5280. %% tmp52 = (read);
  5281. %% if (eq? tmp52 1) then
  5282. %% goto block61;
  5283. %% else
  5284. %% goto block62;
  5285. %% \end{lstlisting}
  5286. %% \end{minipage}
  5287. %% &
  5288. %% $\Rightarrow$
  5289. %% &
  5290. %% \begin{minipage}{0.55\textwidth}
  5291. %% \begin{lstlisting}
  5292. %% block62:
  5293. %% tmp54 = (read);
  5294. %% if (eq? tmp54 2) then
  5295. %% goto block55;
  5296. %% else
  5297. %% goto block56;
  5298. %% block61:
  5299. %% tmp53 = (read);
  5300. %% if (eq? tmp53 0) then
  5301. %% goto block55;
  5302. %% else
  5303. %% goto block56;
  5304. %% block56:
  5305. %% return (+ 700 77);
  5306. %% block55:
  5307. %% return (+ 10 32);
  5308. %% start:
  5309. %% tmp52 = (read);
  5310. %% if (eq? tmp52 1) then
  5311. %% goto block61;
  5312. %% else
  5313. %% goto block62;
  5314. %% \end{lstlisting}
  5315. %% \end{minipage}
  5316. %% \end{tabular}
  5317. %% \caption{Optimize jumps by removing trivial blocks.}
  5318. %% \label{fig:optimize-jumps}
  5319. %% \end{figure}
  5320. %% The name of this pass is \code{optimize-jumps}. We recommend
  5321. %% implementing this pass in two phases. The first phrase builds a hash
  5322. %% table that maps labels to possibly improved labels. The second phase
  5323. %% changes the target of each \code{goto} to use the improved label. If
  5324. %% the label is for a trivial block, then the hash table should map the
  5325. %% label to the first non-trivial block that can be reached from this
  5326. %% label by jumping through trivial blocks. If the label is for a
  5327. %% non-trivial block, then the hash table should map the label to itself;
  5328. %% we do not want to change jumps to non-trivial blocks.
  5329. %% The first phase can be accomplished by constructing an empty hash
  5330. %% table, call it \code{short-cut}, and then iterating over the control
  5331. %% flow graph. Each time you encouter a block that is just a \code{goto},
  5332. %% then update the hash table, mapping the block's source to the target
  5333. %% of the \code{goto}. Also, the hash table may already have mapped some
  5334. %% labels to the block's source, to you must iterate through the hash
  5335. %% table and update all of those so that they instead map to the target
  5336. %% of the \code{goto}.
  5337. %% For the second phase, we recommend iterating through the $\Tail$ of
  5338. %% each block in the program, updating the target of every \code{goto}
  5339. %% according to the mapping in \code{short-cut}.
  5340. %% \begin{exercise}\normalfont
  5341. %% Implement the \code{optimize-jumps} pass as a transformation from
  5342. %% \LangCIf{} to \LangCIf{}, coming after the \code{explicate-control} pass.
  5343. %% Check that \code{optimize-jumps} removes trivial blocks in a few
  5344. %% example programs. Then check that your compiler still passes all of
  5345. %% your tests.
  5346. %% \end{exercise}
  5347. There is an opportunity for optimizing jumps that is apparent in the
  5348. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  5349. ends with a jump to \code{block7953} and there are no other jumps to
  5350. \code{block7953} in the rest of the program. In this situation we can
  5351. avoid the runtime overhead of this jump by merging \code{block7953}
  5352. into the preceding block, in this case the \code{start} block.
  5353. Figure~\ref{fig:remove-jumps} shows the output of
  5354. \code{select-instructions} on the left and the result of this
  5355. optimization on the right.
  5356. \begin{figure}[tbp]
  5357. \begin{tabular}{lll}
  5358. \begin{minipage}{0.5\textwidth}
  5359. % cond_test_20.rkt
  5360. \begin{lstlisting}
  5361. start:
  5362. callq read_int
  5363. movq %rax, tmp7951
  5364. cmpq $1, tmp7951
  5365. je block7952
  5366. jmp block7953
  5367. block7953:
  5368. movq $0, %rax
  5369. jmp conclusion
  5370. block7952:
  5371. movq $42, %rax
  5372. jmp conclusion
  5373. \end{lstlisting}
  5374. \end{minipage}
  5375. &
  5376. $\Rightarrow\qquad$
  5377. \begin{minipage}{0.4\textwidth}
  5378. \begin{lstlisting}
  5379. start:
  5380. callq read_int
  5381. movq %rax, tmp7951
  5382. cmpq $1, tmp7951
  5383. je block7952
  5384. movq $0, %rax
  5385. jmp conclusion
  5386. block7952:
  5387. movq $42, %rax
  5388. jmp conclusion
  5389. \end{lstlisting}
  5390. \end{minipage}
  5391. \end{tabular}
  5392. \caption{Merging basic blocks by removing unnecessary jumps.}
  5393. \label{fig:remove-jumps}
  5394. \end{figure}
  5395. \begin{exercise}\normalfont
  5396. %
  5397. Implement a pass named \code{remove-jumps} that merges basic blocks
  5398. into their preceding basic block, when there is only one preceding
  5399. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  5400. %
  5401. In the \code{run-tests.rkt} script, add the following entry to the
  5402. list of \code{passes} between \code{allocate-registers}
  5403. and \code{patch-instructions}.
  5404. \begin{lstlisting}
  5405. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  5406. \end{lstlisting}
  5407. Run this script to test your compiler.
  5408. %
  5409. Check that \code{remove-jumps} accomplishes the goal of merging basic
  5410. blocks on several test programs.
  5411. \end{exercise}
  5412. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5413. \chapter{Tuples and Garbage Collection}
  5414. \label{ch:tuples}
  5415. \index{tuple}
  5416. \index{vector}
  5417. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  5418. all the IR grammars are spelled out! \\ --Jeremy}
  5419. \margincomment{\scriptsize Be more explicit about how to deal with
  5420. the root stack. \\ --Jeremy}
  5421. In this chapter we study the implementation of mutable tuples, called
  5422. vectors in Racket. This language feature is the first to use the
  5423. computer's \emph{heap}\index{heap} because the lifetime of a Racket
  5424. tuple is indefinite, that is, a tuple lives forever from the
  5425. programmer's viewpoint. Of course, from an implementer's viewpoint, it
  5426. is important to reclaim the space associated with a tuple when it is
  5427. no longer needed, which is why we also study \emph{garbage collection}
  5428. \emph{garbage collection} techniques in this chapter.
  5429. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  5430. interpreter and type checker. The \LangVec{} language extends the \LangIf{}
  5431. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  5432. \code{void} value. The reason for including the later is that the
  5433. \code{vector-set!} operation returns a value of type
  5434. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  5435. called the \code{Unit} type in the programming languages
  5436. literature. Racket's \code{Void} type is inhabited by a single value
  5437. \code{void} which corresponds to \code{unit} or \code{()} in the
  5438. literature~\citep{Pierce:2002hj}.}.
  5439. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  5440. copying live objects back and forth between two halves of the
  5441. heap. The garbage collector requires coordination with the compiler so
  5442. that it can see all of the \emph{root} pointers, that is, pointers in
  5443. registers or on the procedure call stack.
  5444. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  5445. discuss all the necessary changes and additions to the compiler
  5446. passes, including a new compiler pass named \code{expose-allocation}.
  5447. \section{The \LangVec{} Language}
  5448. \label{sec:r3}
  5449. Figure~\ref{fig:Rvec-concrete-syntax} defines the concrete syntax for
  5450. \LangVec{} and Figure~\ref{fig:Rvec-syntax} defines the abstract syntax. The
  5451. \LangVec{} language includes three new forms: \code{vector} for creating a
  5452. tuple, \code{vector-ref} for reading an element of a tuple, and
  5453. \code{vector-set!} for writing to an element of a tuple. The program
  5454. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  5455. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  5456. the 3-tuple, demonstrating that tuples are first-class values. The
  5457. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  5458. of the \key{if} is taken. The element at index $0$ of \code{t} is
  5459. \code{40}, to which we add \code{2}, the element at index $0$ of the
  5460. 1-tuple. So the result of the program is \code{42}.
  5461. \begin{figure}[tbp]
  5462. \centering
  5463. \fbox{
  5464. \begin{minipage}{0.96\textwidth}
  5465. \[
  5466. \begin{array}{lcl}
  5467. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  5468. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \key{Void}\\
  5469. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  5470. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  5471. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5472. \mid \LP\key{and}\;\Exp\;\Exp\RP
  5473. \mid \LP\key{or}\;\Exp\;\Exp\RP
  5474. \mid \LP\key{not}\;\Exp\RP } \\
  5475. &\mid& \gray{ \LP\itm{cmp}\;\Exp\;\Exp\RP
  5476. \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  5477. &\mid& \LP\key{vector}\;\Exp\ldots\RP
  5478. \mid \LP\key{vector-length}\;\Exp\RP \\
  5479. &\mid& \LP\key{vector-ref}\;\Exp\;\Int\RP
  5480. \mid \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP \\
  5481. &\mid& \LP\key{void}\RP \mid \LP\key{has-type}~\Exp~\Type\RP\\
  5482. \LangVec{} &::=& \Exp
  5483. \end{array}
  5484. \]
  5485. \end{minipage}
  5486. }
  5487. \caption{The concrete syntax of \LangVec{}, extending \LangIf{}
  5488. (Figure~\ref{fig:Rif-concrete-syntax}).}
  5489. \label{fig:Rvec-concrete-syntax}
  5490. \end{figure}
  5491. \begin{figure}[tbp]
  5492. \begin{lstlisting}
  5493. (let ([t (vector 40 #t (vector 2))])
  5494. (if (vector-ref t 1)
  5495. (+ (vector-ref t 0)
  5496. (vector-ref (vector-ref t 2) 0))
  5497. 44))
  5498. \end{lstlisting}
  5499. \caption{Example program that creates tuples and reads from them.}
  5500. \label{fig:vector-eg}
  5501. \end{figure}
  5502. \begin{figure}[tp]
  5503. \centering
  5504. \fbox{
  5505. \begin{minipage}{0.96\textwidth}
  5506. \[
  5507. \begin{array}{lcl}
  5508. \itm{op} &::=& \ldots \mid \code{vector} \mid \code{vector-length} \\
  5509. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  5510. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots}
  5511. \mid \BOOL{\itm{bool}}
  5512. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  5513. &\mid& \VECREF{\Exp}{\INT{\Int}}\\
  5514. &\mid& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  5515. &\mid& \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP \\
  5516. \LangVec{} &::=& \PROGRAM{\key{'()}}{\Exp}
  5517. \end{array}
  5518. \]
  5519. \end{minipage}
  5520. }
  5521. \caption{The abstract syntax of \LangVec{}.}
  5522. \label{fig:Rvec-syntax}
  5523. \end{figure}
  5524. \index{allocate}
  5525. \index{heap allocate}
  5526. Tuples are our first encounter with heap-allocated data, which raises
  5527. several interesting issues. First, variable binding performs a
  5528. shallow-copy when dealing with tuples, which means that different
  5529. variables can refer to the same tuple, that is, different variables
  5530. can be \emph{aliases} for the same entity. Consider the following
  5531. example in which both \code{t1} and \code{t2} refer to the same tuple.
  5532. Thus, the mutation through \code{t2} is visible when referencing the
  5533. tuple from \code{t1}, so the result of this program is \code{42}.
  5534. \index{alias}\index{mutation}
  5535. \begin{center}
  5536. \begin{minipage}{0.96\textwidth}
  5537. \begin{lstlisting}
  5538. (let ([t1 (vector 3 7)])
  5539. (let ([t2 t1])
  5540. (let ([_ (vector-set! t2 0 42)])
  5541. (vector-ref t1 0))))
  5542. \end{lstlisting}
  5543. \end{minipage}
  5544. \end{center}
  5545. The next issue concerns the lifetime of tuples. Of course, they are
  5546. created by the \code{vector} form, but when does their lifetime end?
  5547. Notice that \LangVec{} does not include an operation for deleting
  5548. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  5549. of static scoping. For example, the following program returns
  5550. \code{42} even though the variable \code{w} goes out of scope prior to
  5551. the \code{vector-ref} that reads from the vector it was bound to.
  5552. \begin{center}
  5553. \begin{minipage}{0.96\textwidth}
  5554. \begin{lstlisting}
  5555. (let ([v (vector (vector 44))])
  5556. (let ([x (let ([w (vector 42)])
  5557. (let ([_ (vector-set! v 0 w)])
  5558. 0))])
  5559. (+ x (vector-ref (vector-ref v 0) 0))))
  5560. \end{lstlisting}
  5561. \end{minipage}
  5562. \end{center}
  5563. From the perspective of programmer-observable behavior, tuples live
  5564. forever. Of course, if they really lived forever, then many programs
  5565. would run out of memory.\footnote{The \LangVec{} language does not have
  5566. looping or recursive functions, so it is nigh impossible to write a
  5567. program in \LangVec{} that will run out of memory. However, we add
  5568. recursive functions in the next Chapter!} A Racket implementation
  5569. must therefore perform automatic garbage collection.
  5570. Figure~\ref{fig:interp-Rvec} shows the definitional interpreter for the
  5571. \LangVec{} language. We define the \code{vector}, \code{vector-length},
  5572. \code{vector-ref}, and \code{vector-set!} operations for \LangVec{} in
  5573. terms of the corresponding operations in Racket. One subtle point is
  5574. that the \code{vector-set!} operation returns the \code{\#<void>}
  5575. value. The \code{\#<void>} value can be passed around just like other
  5576. values inside an \LangVec{} program and a \code{\#<void>} value can be
  5577. compared for equality with another \code{\#<void>} value. However,
  5578. there are no other operations specific to the the \code{\#<void>}
  5579. value in \LangVec{}. In contrast, Racket defines the \code{void?} predicate
  5580. that returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  5581. otherwise.
  5582. \begin{figure}[tbp]
  5583. \begin{lstlisting}
  5584. (define interp-Rvec-class
  5585. (class interp-Rif-class
  5586. (super-new)
  5587. (define/override (interp-op op)
  5588. (match op
  5589. ['eq? (lambda (v1 v2)
  5590. (cond [(or (and (fixnum? v1) (fixnum? v2))
  5591. (and (boolean? v1) (boolean? v2))
  5592. (and (vector? v1) (vector? v2))
  5593. (and (void? v1) (void? v2)))
  5594. (eq? v1 v2)]))]
  5595. ['vector vector]
  5596. ['vector-length vector-length]
  5597. ['vector-ref vector-ref]
  5598. ['vector-set! vector-set!]
  5599. [else (super interp-op op)]
  5600. ))
  5601. (define/override ((interp-exp env) e)
  5602. (define recur (interp-exp env))
  5603. (match e
  5604. [(HasType e t) (recur e)]
  5605. [(Void) (void)]
  5606. [else ((super interp-exp env) e)]
  5607. ))
  5608. ))
  5609. (define (interp-Rvec p)
  5610. (send (new interp-Rvec-class) interp-program p))
  5611. \end{lstlisting}
  5612. \caption{Interpreter for the \LangVec{} language.}
  5613. \label{fig:interp-Rvec}
  5614. \end{figure}
  5615. Figure~\ref{fig:type-check-Rvec} shows the type checker for \LangVec{}, which
  5616. deserves some explanation. When allocating a vector, we need to know
  5617. which elements of the vector are pointers (i.e. are also vectors). We
  5618. can obtain this information during type checking. The type checker in
  5619. Figure~\ref{fig:type-check-Rvec} not only computes the type of an
  5620. expression, it also wraps every \key{vector} creation with the form
  5621. $(\key{HasType}~e~T)$, where $T$ is the vector's type.
  5622. %
  5623. To create the s-expression for the \code{Vector} type in
  5624. Figure~\ref{fig:type-check-Rvec}, we use the
  5625. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  5626. operator} \code{,@} to insert the list \code{t*} without its usual
  5627. start and end parentheses. \index{unquote-slicing}
  5628. \begin{figure}[tp]
  5629. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5630. (define type-check-Rvec-class
  5631. (class type-check-Rif-class
  5632. (super-new)
  5633. (inherit check-type-equal?)
  5634. (define/override (type-check-exp env)
  5635. (lambda (e)
  5636. (define recur (type-check-exp env))
  5637. (match e
  5638. [(Void) (values (Void) 'Void)]
  5639. [(Prim 'vector es)
  5640. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  5641. (define t `(Vector ,@t*))
  5642. (values (HasType (Prim 'vector e*) t) t)]
  5643. [(Prim 'vector-ref (list e1 (Int i)))
  5644. (define-values (e1^ t) (recur e1))
  5645. (match t
  5646. [`(Vector ,ts ...)
  5647. (unless (and (0 . <= . i) (i . < . (length ts)))
  5648. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  5649. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  5650. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  5651. [(Prim 'vector-set! (list e1 (Int i) arg) )
  5652. (define-values (e-vec t-vec) (recur e1))
  5653. (define-values (e-arg^ t-arg) (recur arg))
  5654. (match t-vec
  5655. [`(Vector ,ts ...)
  5656. (unless (and (0 . <= . i) (i . < . (length ts)))
  5657. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  5658. (check-type-equal? (list-ref ts i) t-arg e)
  5659. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  5660. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  5661. [(Prim 'vector-length (list e))
  5662. (define-values (e^ t) (recur e))
  5663. (match t
  5664. [`(Vector ,ts ...)
  5665. (values (Prim 'vector-length (list e^)) 'Integer)]
  5666. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  5667. [(Prim 'eq? (list arg1 arg2))
  5668. (define-values (e1 t1) (recur arg1))
  5669. (define-values (e2 t2) (recur arg2))
  5670. (match* (t1 t2)
  5671. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  5672. [(other wise) (check-type-equal? t1 t2 e)])
  5673. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  5674. [(HasType (Prim 'vector es) t)
  5675. ((type-check-exp env) (Prim 'vector es))]
  5676. [(HasType e1 t)
  5677. (define-values (e1^ t^) (recur e1))
  5678. (check-type-equal? t t^ e)
  5679. (values (HasType e1^ t) t)]
  5680. [else ((super type-check-exp env) e)]
  5681. )))
  5682. ))
  5683. (define (type-check-Rvec p)
  5684. (send (new type-check-Rvec-class) type-check-program p))
  5685. \end{lstlisting}
  5686. \caption{Type checker for the \LangVec{} language.}
  5687. \label{fig:type-check-Rvec}
  5688. \end{figure}
  5689. \section{Garbage Collection}
  5690. \label{sec:GC}
  5691. Here we study a relatively simple algorithm for garbage collection
  5692. that is the basis of state-of-the-art garbage
  5693. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  5694. particular, we describe a two-space copying
  5695. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  5696. perform the
  5697. copy~\citep{Cheney:1970aa}.
  5698. \index{copying collector}
  5699. \index{two-space copying collector}
  5700. Figure~\ref{fig:copying-collector} gives a
  5701. coarse-grained depiction of what happens in a two-space collector,
  5702. showing two time steps, prior to garbage collection (on the top) and
  5703. after garbage collection (on the bottom). In a two-space collector,
  5704. the heap is divided into two parts named the FromSpace and the
  5705. ToSpace. Initially, all allocations go to the FromSpace until there is
  5706. not enough room for the next allocation request. At that point, the
  5707. garbage collector goes to work to make more room.
  5708. \index{ToSpace}
  5709. \index{FromSpace}
  5710. The garbage collector must be careful not to reclaim tuples that will
  5711. be used by the program in the future. Of course, it is impossible in
  5712. general to predict what a program will do, but we can over approximate
  5713. the will-be-used tuples by preserving all tuples that could be
  5714. accessed by \emph{any} program given the current computer state. A
  5715. program could access any tuple whose address is in a register or on
  5716. the procedure call stack. These addresses are called the \emph{root
  5717. set}\index{root set}. In addition, a program could access any tuple that is
  5718. transitively reachable from the root set. Thus, it is safe for the
  5719. garbage collector to reclaim the tuples that are not reachable in this
  5720. way.
  5721. So the goal of the garbage collector is twofold:
  5722. \begin{enumerate}
  5723. \item preserve all tuple that are reachable from the root set via a
  5724. path of pointers, that is, the \emph{live} tuples, and
  5725. \item reclaim the memory of everything else, that is, the
  5726. \emph{garbage}.
  5727. \end{enumerate}
  5728. A copying collector accomplishes this by copying all of the live
  5729. objects from the FromSpace into the ToSpace and then performs a sleight
  5730. of hand, treating the ToSpace as the new FromSpace and the old
  5731. FromSpace as the new ToSpace. In the example of
  5732. Figure~\ref{fig:copying-collector}, there are three pointers in the
  5733. root set, one in a register and two on the stack. All of the live
  5734. objects have been copied to the ToSpace (the right-hand side of
  5735. Figure~\ref{fig:copying-collector}) in a way that preserves the
  5736. pointer relationships. For example, the pointer in the register still
  5737. points to a 2-tuple whose first element is a 3-tuple and whose second
  5738. element is a 2-tuple. There are four tuples that are not reachable
  5739. from the root set and therefore do not get copied into the ToSpace.
  5740. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  5741. created by a well-typed program in \LangVec{} because it contains a
  5742. cycle. However, creating cycles will be possible once we get to \LangAny{}.
  5743. We design the garbage collector to deal with cycles to begin with so
  5744. we will not need to revisit this issue.
  5745. \begin{figure}[tbp]
  5746. \centering
  5747. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  5748. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  5749. \caption{A copying collector in action.}
  5750. \label{fig:copying-collector}
  5751. \end{figure}
  5752. There are many alternatives to copying collectors (and their bigger
  5753. siblings, the generational collectors) when its comes to garbage
  5754. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  5755. reference counting~\citep{Collins:1960aa}. The strengths of copying
  5756. collectors are that allocation is fast (just a comparison and pointer
  5757. increment), there is no fragmentation, cyclic garbage is collected,
  5758. and the time complexity of collection only depends on the amount of
  5759. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  5760. main disadvantages of a two-space copying collector is that it uses a
  5761. lot of space and takes a long time to perform the copy, though these
  5762. problems are ameliorated in generational collectors. Racket and
  5763. Scheme programs tend to allocate many small objects and generate a lot
  5764. of garbage, so copying and generational collectors are a good fit.
  5765. Garbage collection is an active research topic, especially concurrent
  5766. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  5767. developing new techniques and revisiting old
  5768. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  5769. meet every year at the International Symposium on Memory Management to
  5770. present these findings.
  5771. \subsection{Graph Copying via Cheney's Algorithm}
  5772. \label{sec:cheney}
  5773. \index{Cheney's algorithm}
  5774. Let us take a closer look at the copying of the live objects. The
  5775. allocated objects and pointers can be viewed as a graph and we need to
  5776. copy the part of the graph that is reachable from the root set. To
  5777. make sure we copy all of the reachable vertices in the graph, we need
  5778. an exhaustive graph traversal algorithm, such as depth-first search or
  5779. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  5780. such algorithms take into account the possibility of cycles by marking
  5781. which vertices have already been visited, so as to ensure termination
  5782. of the algorithm. These search algorithms also use a data structure
  5783. such as a stack or queue as a to-do list to keep track of the vertices
  5784. that need to be visited. We use breadth-first search and a trick
  5785. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  5786. and copying tuples into the ToSpace.
  5787. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  5788. copy progresses. The queue is represented by a chunk of contiguous
  5789. memory at the beginning of the ToSpace, using two pointers to track
  5790. the front and the back of the queue. The algorithm starts by copying
  5791. all tuples that are immediately reachable from the root set into the
  5792. ToSpace to form the initial queue. When we copy a tuple, we mark the
  5793. old tuple to indicate that it has been visited. We discuss how this
  5794. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  5795. pointers inside the copied tuples in the queue still point back to the
  5796. FromSpace. Once the initial queue has been created, the algorithm
  5797. enters a loop in which it repeatedly processes the tuple at the front
  5798. of the queue and pops it off the queue. To process a tuple, the
  5799. algorithm copies all the tuple that are directly reachable from it to
  5800. the ToSpace, placing them at the back of the queue. The algorithm then
  5801. updates the pointers in the popped tuple so they point to the newly
  5802. copied tuples.
  5803. \begin{figure}[tbp]
  5804. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  5805. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  5806. \label{fig:cheney}
  5807. \end{figure}
  5808. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  5809. tuple whose second element is $42$ to the back of the queue. The other
  5810. pointer goes to a tuple that has already been copied, so we do not
  5811. need to copy it again, but we do need to update the pointer to the new
  5812. location. This can be accomplished by storing a \emph{forwarding
  5813. pointer} to the new location in the old tuple, back when we initially
  5814. copied the tuple into the ToSpace. This completes one step of the
  5815. algorithm. The algorithm continues in this way until the front of the
  5816. queue is empty, that is, until the front catches up with the back.
  5817. \subsection{Data Representation}
  5818. \label{sec:data-rep-gc}
  5819. The garbage collector places some requirements on the data
  5820. representations used by our compiler. First, the garbage collector
  5821. needs to distinguish between pointers and other kinds of data. There
  5822. are several ways to accomplish this.
  5823. \begin{enumerate}
  5824. \item Attached a tag to each object that identifies what type of
  5825. object it is~\citep{McCarthy:1960dz}.
  5826. \item Store different types of objects in different
  5827. regions~\citep{Steele:1977ab}.
  5828. \item Use type information from the program to either generate
  5829. type-specific code for collecting or to generate tables that can
  5830. guide the
  5831. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  5832. \end{enumerate}
  5833. Dynamically typed languages, such as Lisp, need to tag objects
  5834. anyways, so option 1 is a natural choice for those languages.
  5835. However, \LangVec{} is a statically typed language, so it would be
  5836. unfortunate to require tags on every object, especially small and
  5837. pervasive objects like integers and Booleans. Option 3 is the
  5838. best-performing choice for statically typed languages, but comes with
  5839. a relatively high implementation complexity. To keep this chapter
  5840. within a 2-week time budget, we recommend a combination of options 1
  5841. and 2, using separate strategies for the stack and the heap.
  5842. Regarding the stack, we recommend using a separate stack for pointers,
  5843. which we call a \emph{root stack}\index{root stack} (a.k.a. ``shadow
  5844. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  5845. is, when a local variable needs to be spilled and is of type
  5846. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  5847. stack instead of the normal procedure call stack. Furthermore, we
  5848. always spill vector-typed variables if they are live during a call to
  5849. the collector, thereby ensuring that no pointers are in registers
  5850. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  5851. example from Figure~\ref{fig:copying-collector} and contrasts it with
  5852. the data layout using a root stack. The root stack contains the two
  5853. pointers from the regular stack and also the pointer in the second
  5854. register.
  5855. \begin{figure}[tbp]
  5856. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  5857. \caption{Maintaining a root stack to facilitate garbage collection.}
  5858. \label{fig:shadow-stack}
  5859. \end{figure}
  5860. The problem of distinguishing between pointers and other kinds of data
  5861. also arises inside of each tuple on the heap. We solve this problem by
  5862. attaching a tag, an extra 64-bits, to each
  5863. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  5864. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  5865. that we have drawn the bits in a big-endian way, from right-to-left,
  5866. with bit location 0 (the least significant bit) on the far right,
  5867. which corresponds to the direction of the x86 shifting instructions
  5868. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  5869. is dedicated to specifying which elements of the tuple are pointers,
  5870. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  5871. indicates there is a pointer and a 0 bit indicates some other kind of
  5872. data. The pointer mask starts at bit location 7. We have limited
  5873. tuples to a maximum size of 50 elements, so we just need 50 bits for
  5874. the pointer mask. The tag also contains two other pieces of
  5875. information. The length of the tuple (number of elements) is stored in
  5876. bits location 1 through 6. Finally, the bit at location 0 indicates
  5877. whether the tuple has yet to be copied to the ToSpace. If the bit has
  5878. value 1, then this tuple has not yet been copied. If the bit has
  5879. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  5880. of a pointer are always zero anyways because our tuples are 8-byte
  5881. aligned.)
  5882. \begin{figure}[tbp]
  5883. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  5884. \caption{Representation of tuples in the heap.}
  5885. \label{fig:tuple-rep}
  5886. \end{figure}
  5887. \subsection{Implementation of the Garbage Collector}
  5888. \label{sec:organize-gz}
  5889. \index{prelude}
  5890. An implementation of the copying collector is provided in the
  5891. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  5892. interface to the garbage collector that is used by the compiler. The
  5893. \code{initialize} function creates the FromSpace, ToSpace, and root
  5894. stack and should be called in the prelude of the \code{main}
  5895. function. The arguments of \code{initialize} are the root stack size
  5896. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  5897. good choice for both. The \code{initialize} function puts the address
  5898. of the beginning of the FromSpace into the global variable
  5899. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  5900. the address that is 1-past the last element of the FromSpace. (We use
  5901. half-open intervals to represent chunks of
  5902. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  5903. points to the first element of the root stack.
  5904. As long as there is room left in the FromSpace, your generated code
  5905. can allocate tuples simply by moving the \code{free\_ptr} forward.
  5906. %
  5907. The amount of room left in FromSpace is the difference between the
  5908. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  5909. function should be called when there is not enough room left in the
  5910. FromSpace for the next allocation. The \code{collect} function takes
  5911. a pointer to the current top of the root stack (one past the last item
  5912. that was pushed) and the number of bytes that need to be
  5913. allocated. The \code{collect} function performs the copying collection
  5914. and leaves the heap in a state such that the next allocation will
  5915. succeed.
  5916. \begin{figure}[tbp]
  5917. \begin{lstlisting}
  5918. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  5919. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  5920. int64_t* free_ptr;
  5921. int64_t* fromspace_begin;
  5922. int64_t* fromspace_end;
  5923. int64_t** rootstack_begin;
  5924. \end{lstlisting}
  5925. \caption{The compiler's interface to the garbage collector.}
  5926. \label{fig:gc-header}
  5927. \end{figure}
  5928. %% \begin{exercise}
  5929. %% In the file \code{runtime.c} you will find the implementation of
  5930. %% \code{initialize} and a partial implementation of \code{collect}.
  5931. %% The \code{collect} function calls another function, \code{cheney},
  5932. %% to perform the actual copy, and that function is left to the reader
  5933. %% to implement. The following is the prototype for \code{cheney}.
  5934. %% \begin{lstlisting}
  5935. %% static void cheney(int64_t** rootstack_ptr);
  5936. %% \end{lstlisting}
  5937. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  5938. %% rootstack (which is an array of pointers). The \code{cheney} function
  5939. %% also communicates with \code{collect} through the global
  5940. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  5941. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  5942. %% the ToSpace:
  5943. %% \begin{lstlisting}
  5944. %% static int64_t* tospace_begin;
  5945. %% static int64_t* tospace_end;
  5946. %% \end{lstlisting}
  5947. %% The job of the \code{cheney} function is to copy all the live
  5948. %% objects (reachable from the root stack) into the ToSpace, update
  5949. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  5950. %% update the root stack so that it points to the objects in the
  5951. %% ToSpace, and finally to swap the global pointers for the FromSpace
  5952. %% and ToSpace.
  5953. %% \end{exercise}
  5954. %% \section{Compiler Passes}
  5955. %% \label{sec:code-generation-gc}
  5956. The introduction of garbage collection has a non-trivial impact on our
  5957. compiler passes. We introduce a new compiler pass named
  5958. \code{expose-allocation}. We make
  5959. significant changes to \code{select-instructions},
  5960. \code{build-interference}, \code{allocate-registers}, and
  5961. \code{print-x86} and make minor changes in several more passes. The
  5962. following program will serve as our running example. It creates two
  5963. tuples, one nested inside the other. Both tuples have length one. The
  5964. program accesses the element in the inner tuple tuple via two vector
  5965. references.
  5966. % tests/s2_17.rkt
  5967. \begin{lstlisting}
  5968. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  5969. \end{lstlisting}
  5970. \section{Shrink}
  5971. \label{sec:shrink-Rvec}
  5972. Recall that the \code{shrink} pass translates the primitives operators
  5973. into a smaller set of primitives. Because this pass comes after type
  5974. checking, but before the passes that require the type information in
  5975. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  5976. to wrap \code{HasType} around each AST node that it generates.
  5977. \section{Expose Allocation}
  5978. \label{sec:expose-allocation}
  5979. The pass \code{expose-allocation} lowers the \code{vector} creation
  5980. form into a conditional call to the collector followed by the
  5981. allocation. We choose to place the \code{expose-allocation} pass
  5982. before \code{remove-complex-opera*} because the code generated by
  5983. \code{expose-allocation} contains complex operands. We also place
  5984. \code{expose-allocation} before \code{explicate-control} because
  5985. \code{expose-allocation} introduces new variables using \code{let},
  5986. but \code{let} is gone after \code{explicate-control}.
  5987. The output of \code{expose-allocation} is a language \LangAlloc{} that
  5988. extends \LangVec{} with the three new forms that we use in the translation
  5989. of the \code{vector} form.
  5990. \[
  5991. \begin{array}{lcl}
  5992. \Exp &::=& \cdots
  5993. \mid (\key{collect} \,\itm{int})
  5994. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  5995. \mid (\key{global-value} \,\itm{name})
  5996. \end{array}
  5997. \]
  5998. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  5999. $n$ bytes. It will become a call to the \code{collect} function in
  6000. \code{runtime.c} in \code{select-instructions}. The
  6001. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  6002. \index{allocate}
  6003. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  6004. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  6005. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  6006. a global variable, such as \code{free\_ptr}.
  6007. In the following, we show the transformation for the \code{vector}
  6008. form into 1) a sequence of let-bindings for the initializing
  6009. expressions, 2) a conditional call to \code{collect}, 3) a call to
  6010. \code{allocate}, and 4) the initialization of the vector. In the
  6011. following, \itm{len} refers to the length of the vector and
  6012. \itm{bytes} is how many total bytes need to be allocated for the
  6013. vector, which is 8 for the tag plus \itm{len} times 8.
  6014. \begin{lstlisting}
  6015. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  6016. |$\Longrightarrow$|
  6017. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  6018. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  6019. (global-value fromspace_end))
  6020. (void)
  6021. (collect |\itm{bytes}|))])
  6022. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  6023. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  6024. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  6025. |$v$|) ... )))) ...)
  6026. \end{lstlisting}
  6027. In the above, we suppressed all of the \code{has-type} forms in the
  6028. output for the sake of readability. The placement of the initializing
  6029. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  6030. sequence of \code{vector-set!} is important, as those expressions may
  6031. trigger garbage collection and we cannot have an allocated but
  6032. uninitialized tuple on the heap during a collection.
  6033. Figure~\ref{fig:expose-alloc-output} shows the output of the
  6034. \code{expose-allocation} pass on our running example.
  6035. \begin{figure}[tbp]
  6036. % tests/s2_17.rkt
  6037. \begin{lstlisting}
  6038. (vector-ref
  6039. (vector-ref
  6040. (let ([vecinit7976
  6041. (let ([vecinit7972 42])
  6042. (let ([collectret7974
  6043. (if (< (+ (global-value free_ptr) 16)
  6044. (global-value fromspace_end))
  6045. (void)
  6046. (collect 16)
  6047. )])
  6048. (let ([alloc7971 (allocate 1 (Vector Integer))])
  6049. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  6050. alloc7971)
  6051. )
  6052. )
  6053. )
  6054. ])
  6055. (let ([collectret7978
  6056. (if (< (+ (global-value free_ptr) 16)
  6057. (global-value fromspace_end))
  6058. (void)
  6059. (collect 16)
  6060. )])
  6061. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  6062. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  6063. alloc7975)
  6064. )
  6065. )
  6066. )
  6067. 0)
  6068. 0)
  6069. \end{lstlisting}
  6070. \caption{Output of the \code{expose-allocation} pass, minus
  6071. all of the \code{has-type} forms.}
  6072. \label{fig:expose-alloc-output}
  6073. \end{figure}
  6074. \section{Remove Complex Operands}
  6075. \label{sec:remove-complex-opera-Rvec}
  6076. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  6077. should all be treated as complex operands.
  6078. %% A new case for
  6079. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  6080. %% handled carefully to prevent the \code{Prim} node from being separated
  6081. %% from its enclosing \code{HasType}.
  6082. Figure~\ref{fig:Rvec-anf-syntax}
  6083. shows the grammar for the output language \LangVecANF{} of this
  6084. pass, which is \LangVec{} in administrative normal form.
  6085. \begin{figure}[tp]
  6086. \centering
  6087. \fbox{
  6088. \begin{minipage}{0.96\textwidth}
  6089. \small
  6090. \[
  6091. \begin{array}{rcl}
  6092. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }
  6093. \mid \VOID{} \\
  6094. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  6095. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  6096. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  6097. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  6098. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  6099. &\mid& \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  6100. \mid \LP\key{GlobalValue}~\Var\RP\\
  6101. % &\mid& \LP\key{HasType}~\Exp~\Type\RP \\
  6102. R^{\dagger}_3 &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  6103. \end{array}
  6104. \]
  6105. \end{minipage}
  6106. }
  6107. \caption{\LangVecANF{} is \LangVec{} in administrative normal form (ANF).}
  6108. \label{fig:Rvec-anf-syntax}
  6109. \end{figure}
  6110. \section{Explicate Control and the \LangCVec{} language}
  6111. \label{sec:explicate-control-r3}
  6112. \begin{figure}[tp]
  6113. \fbox{
  6114. \begin{minipage}{0.96\textwidth}
  6115. \small
  6116. \[
  6117. \begin{array}{lcl}
  6118. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  6119. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  6120. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  6121. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  6122. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  6123. &\mid& \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  6124. &\mid& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  6125. &\mid& \LP\key{Prim}~\key{'vector-set!}\,\LP\Atm\,\INT{\Int}\,\Atm\RP\RP\\
  6126. &\mid& \LP\key{GlobalValue} \,\Var\RP \mid \LP\key{Void}\RP\\
  6127. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  6128. \mid \LP\key{Collect} \,\itm{int}\RP \\
  6129. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  6130. \mid \GOTO{\itm{label}} } \\
  6131. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  6132. \LangCVec{} & ::= & \gray{ \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }
  6133. \end{array}
  6134. \]
  6135. \end{minipage}
  6136. }
  6137. \caption{The abstract syntax of \LangCVec{}, extending \LangCIf{}
  6138. (Figure~\ref{fig:c1-syntax}).}
  6139. \label{fig:c2-syntax}
  6140. \end{figure}
  6141. The output of \code{explicate-control} is a program in the
  6142. intermediate language \LangCVec{}, whose abstract syntax is defined in
  6143. Figure~\ref{fig:c2-syntax}. (The concrete syntax is defined in
  6144. Figure~\ref{fig:c2-concrete-syntax} of the Appendix.) The new forms
  6145. of \LangCVec{} include the \key{allocate}, \key{vector-ref}, and
  6146. \key{vector-set!}, and \key{global-value} expressions and the
  6147. \code{collect} statement. The \code{explicate-control} pass can treat
  6148. these new forms much like the other expression forms that we've
  6149. already encoutered.
  6150. \section{Select Instructions and the \LangXGlobal{} Language}
  6151. \label{sec:select-instructions-gc}
  6152. \index{instruction selection}
  6153. %% void (rep as zero)
  6154. %% allocate
  6155. %% collect (callq collect)
  6156. %% vector-ref
  6157. %% vector-set!
  6158. %% global (postpone)
  6159. In this pass we generate x86 code for most of the new operations that
  6160. were needed to compile tuples, including \code{Allocate},
  6161. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  6162. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  6163. the later has a different concrete syntax (see
  6164. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  6165. \index{x86}
  6166. The \code{vector-ref} and \code{vector-set!} forms translate into
  6167. \code{movq} instructions. (The plus one in the offset is to get past
  6168. the tag at the beginning of the tuple representation.)
  6169. \begin{lstlisting}
  6170. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  6171. |$\Longrightarrow$|
  6172. movq |$\itm{vec}'$|, %r11
  6173. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  6174. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  6175. |$\Longrightarrow$|
  6176. movq |$\itm{vec}'$|, %r11
  6177. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  6178. movq $0, |$\itm{lhs'}$|
  6179. \end{lstlisting}
  6180. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  6181. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  6182. register \code{r11} ensures that offset expression
  6183. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  6184. removing \code{r11} from consideration by the register allocating.
  6185. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  6186. \code{rax}. Then the generated code for \code{vector-set!} would be
  6187. \begin{lstlisting}
  6188. movq |$\itm{vec}'$|, %rax
  6189. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  6190. movq $0, |$\itm{lhs}'$|
  6191. \end{lstlisting}
  6192. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  6193. \code{patch-instructions} would insert a move through \code{rax}
  6194. as follows.
  6195. \begin{lstlisting}
  6196. movq |$\itm{vec}'$|, %rax
  6197. movq |$\itm{arg}'$|, %rax
  6198. movq %rax, |$8(n+1)$|(%rax)
  6199. movq $0, |$\itm{lhs}'$|
  6200. \end{lstlisting}
  6201. But the above sequence of instructions does not work because we're
  6202. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  6203. $\itm{arg}'$) at the same time!
  6204. We compile the \code{allocate} form to operations on the
  6205. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  6206. is the next free address in the FromSpace, so we copy it into
  6207. \code{r11} and then move it forward by enough space for the tuple
  6208. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  6209. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  6210. initialize the \itm{tag} and finally copy the address in \code{r11} to
  6211. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  6212. tag is organized. We recommend using the Racket operations
  6213. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  6214. during compilation. The type annotation in the \code{vector} form is
  6215. used to determine the pointer mask region of the tag.
  6216. \begin{lstlisting}
  6217. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  6218. |$\Longrightarrow$|
  6219. movq free_ptr(%rip), %r11
  6220. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  6221. movq $|$\itm{tag}$|, 0(%r11)
  6222. movq %r11, |$\itm{lhs}'$|
  6223. \end{lstlisting}
  6224. The \code{collect} form is compiled to a call to the \code{collect}
  6225. function in the runtime. The arguments to \code{collect} are 1) the
  6226. top of the root stack and 2) the number of bytes that need to be
  6227. allocated. We use another dedicated register, \code{r15}, to
  6228. store the pointer to the top of the root stack. So \code{r15} is not
  6229. available for use by the register allocator.
  6230. \begin{lstlisting}
  6231. (collect |$\itm{bytes}$|)
  6232. |$\Longrightarrow$|
  6233. movq %r15, %rdi
  6234. movq $|\itm{bytes}|, %rsi
  6235. callq collect
  6236. \end{lstlisting}
  6237. \begin{figure}[tp]
  6238. \fbox{
  6239. \begin{minipage}{0.96\textwidth}
  6240. \[
  6241. \begin{array}{lcl}
  6242. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)} \\
  6243. \LangXGlobal{} &::= & \gray{ \key{.globl main} }\\
  6244. & & \gray{ \key{main:} \; \Instr\ldots }
  6245. \end{array}
  6246. \]
  6247. \end{minipage}
  6248. }
  6249. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  6250. \label{fig:x86-2-concrete}
  6251. \end{figure}
  6252. \begin{figure}[tp]
  6253. \fbox{
  6254. \begin{minipage}{0.96\textwidth}
  6255. \small
  6256. \[
  6257. \begin{array}{lcl}
  6258. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  6259. \mid \BYTEREG{\Reg}} \\
  6260. &\mid& (\key{Global}~\Var) \\
  6261. \LangXGlobal{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  6262. \end{array}
  6263. \]
  6264. \end{minipage}
  6265. }
  6266. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  6267. \label{fig:x86-2}
  6268. \end{figure}
  6269. The concrete and abstract syntax of the \LangXGlobal{} language is
  6270. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  6271. differs from \LangXIf{} just in the addition of the form for global
  6272. variables.
  6273. %
  6274. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  6275. \code{select-instructions} pass on the running example.
  6276. \begin{figure}[tbp]
  6277. \centering
  6278. % tests/s2_17.rkt
  6279. \begin{minipage}[t]{0.5\textwidth}
  6280. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6281. block35:
  6282. movq free_ptr(%rip), alloc9024
  6283. addq $16, free_ptr(%rip)
  6284. movq alloc9024, %r11
  6285. movq $131, 0(%r11)
  6286. movq alloc9024, %r11
  6287. movq vecinit9025, 8(%r11)
  6288. movq $0, initret9026
  6289. movq alloc9024, %r11
  6290. movq 8(%r11), tmp9034
  6291. movq tmp9034, %r11
  6292. movq 8(%r11), %rax
  6293. jmp conclusion
  6294. block36:
  6295. movq $0, collectret9027
  6296. jmp block35
  6297. block38:
  6298. movq free_ptr(%rip), alloc9020
  6299. addq $16, free_ptr(%rip)
  6300. movq alloc9020, %r11
  6301. movq $3, 0(%r11)
  6302. movq alloc9020, %r11
  6303. movq vecinit9021, 8(%r11)
  6304. movq $0, initret9022
  6305. movq alloc9020, vecinit9025
  6306. movq free_ptr(%rip), tmp9031
  6307. movq tmp9031, tmp9032
  6308. addq $16, tmp9032
  6309. movq fromspace_end(%rip), tmp9033
  6310. cmpq tmp9033, tmp9032
  6311. jl block36
  6312. jmp block37
  6313. block37:
  6314. movq %r15, %rdi
  6315. movq $16, %rsi
  6316. callq 'collect
  6317. jmp block35
  6318. block39:
  6319. movq $0, collectret9023
  6320. jmp block38
  6321. \end{lstlisting}
  6322. \end{minipage}
  6323. \begin{minipage}[t]{0.45\textwidth}
  6324. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6325. start:
  6326. movq $42, vecinit9021
  6327. movq free_ptr(%rip), tmp9028
  6328. movq tmp9028, tmp9029
  6329. addq $16, tmp9029
  6330. movq fromspace_end(%rip), tmp9030
  6331. cmpq tmp9030, tmp9029
  6332. jl block39
  6333. jmp block40
  6334. block40:
  6335. movq %r15, %rdi
  6336. movq $16, %rsi
  6337. callq 'collect
  6338. jmp block38
  6339. \end{lstlisting}
  6340. \end{minipage}
  6341. \caption{Output of the \code{select-instructions} pass.}
  6342. \label{fig:select-instr-output-gc}
  6343. \end{figure}
  6344. \clearpage
  6345. \section{Register Allocation}
  6346. \label{sec:reg-alloc-gc}
  6347. \index{register allocation}
  6348. As discussed earlier in this chapter, the garbage collector needs to
  6349. access all the pointers in the root set, that is, all variables that
  6350. are vectors. It will be the responsibility of the register allocator
  6351. to make sure that:
  6352. \begin{enumerate}
  6353. \item the root stack is used for spilling vector-typed variables, and
  6354. \item if a vector-typed variable is live during a call to the
  6355. collector, it must be spilled to ensure it is visible to the
  6356. collector.
  6357. \end{enumerate}
  6358. The later responsibility can be handled during construction of the
  6359. interference graph, by adding interference edges between the call-live
  6360. vector-typed variables and all the callee-saved registers. (They
  6361. already interfere with the caller-saved registers.) The type
  6362. information for variables is in the \code{Program} form, so we
  6363. recommend adding another parameter to the \code{build-interference}
  6364. function to communicate this alist.
  6365. The spilling of vector-typed variables to the root stack can be
  6366. handled after graph coloring, when choosing how to assign the colors
  6367. (integers) to registers and stack locations. The \code{Program} output
  6368. of this pass changes to also record the number of spills to the root
  6369. stack.
  6370. % build-interference
  6371. %
  6372. % callq
  6373. % extra parameter for var->type assoc. list
  6374. % update 'program' and 'if'
  6375. % allocate-registers
  6376. % allocate spilled vectors to the rootstack
  6377. % don't change color-graph
  6378. \section{Print x86}
  6379. \label{sec:print-x86-gc}
  6380. \index{prelude}\index{conclusion}
  6381. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  6382. \code{print-x86} pass on the running example. In the prelude and
  6383. conclusion of the \code{main} function, we treat the root stack very
  6384. much like the regular stack in that we move the root stack pointer
  6385. (\code{r15}) to make room for the spills to the root stack, except
  6386. that the root stack grows up instead of down. For the running
  6387. example, there was just one spill so we increment \code{r15} by 8
  6388. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  6389. One issue that deserves special care is that there may be a call to
  6390. \code{collect} prior to the initializing assignments for all the
  6391. variables in the root stack. We do not want the garbage collector to
  6392. accidentally think that some uninitialized variable is a pointer that
  6393. needs to be followed. Thus, we zero-out all locations on the root
  6394. stack in the prelude of \code{main}. In
  6395. Figure~\ref{fig:print-x86-output-gc}, the instruction
  6396. %
  6397. \lstinline{movq $0, (%r15)}
  6398. %
  6399. accomplishes this task. The garbage collector tests each root to see
  6400. if it is null prior to dereferencing it.
  6401. \begin{figure}[htbp]
  6402. \begin{minipage}[t]{0.5\textwidth}
  6403. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6404. block35:
  6405. movq free_ptr(%rip), %rcx
  6406. addq $16, free_ptr(%rip)
  6407. movq %rcx, %r11
  6408. movq $131, 0(%r11)
  6409. movq %rcx, %r11
  6410. movq -8(%r15), %rax
  6411. movq %rax, 8(%r11)
  6412. movq $0, %rdx
  6413. movq %rcx, %r11
  6414. movq 8(%r11), %rcx
  6415. movq %rcx, %r11
  6416. movq 8(%r11), %rax
  6417. jmp conclusion
  6418. block36:
  6419. movq $0, %rcx
  6420. jmp block35
  6421. block38:
  6422. movq free_ptr(%rip), %rcx
  6423. addq $16, free_ptr(%rip)
  6424. movq %rcx, %r11
  6425. movq $3, 0(%r11)
  6426. movq %rcx, %r11
  6427. movq %rbx, 8(%r11)
  6428. movq $0, %rdx
  6429. movq %rcx, -8(%r15)
  6430. movq free_ptr(%rip), %rcx
  6431. addq $16, %rcx
  6432. movq fromspace_end(%rip), %rdx
  6433. cmpq %rdx, %rcx
  6434. jl block36
  6435. movq %r15, %rdi
  6436. movq $16, %rsi
  6437. callq collect
  6438. jmp block35
  6439. block39:
  6440. movq $0, %rcx
  6441. jmp block38
  6442. \end{lstlisting}
  6443. \end{minipage}
  6444. \begin{minipage}[t]{0.45\textwidth}
  6445. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6446. start:
  6447. movq $42, %rbx
  6448. movq free_ptr(%rip), %rdx
  6449. addq $16, %rdx
  6450. movq fromspace_end(%rip), %rcx
  6451. cmpq %rcx, %rdx
  6452. jl block39
  6453. movq %r15, %rdi
  6454. movq $16, %rsi
  6455. callq collect
  6456. jmp block38
  6457. .globl main
  6458. main:
  6459. pushq %rbp
  6460. movq %rsp, %rbp
  6461. pushq %r13
  6462. pushq %r12
  6463. pushq %rbx
  6464. pushq %r14
  6465. subq $0, %rsp
  6466. movq $16384, %rdi
  6467. movq $16384, %rsi
  6468. callq initialize
  6469. movq rootstack_begin(%rip), %r15
  6470. movq $0, (%r15)
  6471. addq $8, %r15
  6472. jmp start
  6473. conclusion:
  6474. subq $8, %r15
  6475. addq $0, %rsp
  6476. popq %r14
  6477. popq %rbx
  6478. popq %r12
  6479. popq %r13
  6480. popq %rbp
  6481. retq
  6482. \end{lstlisting}
  6483. \end{minipage}
  6484. \caption{Output of the \code{print-x86} pass.}
  6485. \label{fig:print-x86-output-gc}
  6486. \end{figure}
  6487. \begin{figure}[p]
  6488. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6489. \node (Rvec) at (0,2) {\large \LangVec{}};
  6490. \node (Rvec-2) at (3,2) {\large \LangVec{}};
  6491. \node (Rvec-3) at (6,2) {\large \LangVec{}};
  6492. \node (Rvec-4) at (9,2) {\large \LangVec{}};
  6493. \node (Rvec-5) at (12,2) {\large \LangAlloc{}};
  6494. \node (C2-4) at (3,0) {\large \LangCVec{}};
  6495. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  6496. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  6497. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  6498. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  6499. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  6500. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  6501. %\path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize type-check} (Rvec-2);
  6502. \path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize shrink} (Rvec-2);
  6503. \path[->,bend left=15] (Rvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Rvec-3);
  6504. \path[->,bend left=15] (Rvec-3) edge [above] node {\ttfamily\footnotesize expose-alloc.} (Rvec-4);
  6505. \path[->,bend left=15] (Rvec-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvec-5);
  6506. \path[->,bend left=20] (Rvec-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-4);
  6507. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select-instr.} (x86-2);
  6508. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6509. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  6510. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6511. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  6512. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  6513. \end{tikzpicture}
  6514. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  6515. \label{fig:Rvec-passes}
  6516. \end{figure}
  6517. Figure~\ref{fig:Rvec-passes} gives an overview of all the passes needed
  6518. for the compilation of \LangVec{}.
  6519. \section{Challenge: Simple Structures}
  6520. \label{sec:simple-structures}
  6521. \index{struct}
  6522. \index{structure}
  6523. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  6524. $R^s_3$, which extends $R^3$ with support for simple structures.
  6525. Recall that a \code{struct} in Typed Racket is a user-defined data
  6526. type that contains named fields and that is heap allocated, similar to
  6527. a vector. The following is an example of a structure definition, in
  6528. this case the definition of a \code{point} type.
  6529. \begin{lstlisting}
  6530. (struct point ([x : Integer] [y : Integer]) #:mutable)
  6531. \end{lstlisting}
  6532. \begin{figure}[tbp]
  6533. \centering
  6534. \fbox{
  6535. \begin{minipage}{0.96\textwidth}
  6536. \[
  6537. \begin{array}{lcl}
  6538. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6539. \mid (\key{Vector}\;\Type \ldots) \mid \key{Void} } \mid \Var \\
  6540. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6541. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  6542. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  6543. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6544. \mid (\key{and}\;\Exp\;\Exp)
  6545. \mid (\key{or}\;\Exp\;\Exp)
  6546. \mid (\key{not}\;\Exp) } \\
  6547. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  6548. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  6549. &\mid& \gray{ (\key{vector}\;\Exp \ldots)
  6550. \mid (\key{vector-ref}\;\Exp\;\Int) } \\
  6551. &\mid& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  6552. &\mid& \gray{ (\key{void}) } \mid (\Var\;\Exp \ldots)\\
  6553. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  6554. R^s_3 &::=& \Def \ldots \; \Exp
  6555. \end{array}
  6556. \]
  6557. \end{minipage}
  6558. }
  6559. \caption{The concrete syntax of $R^s_3$, extending \LangVec{}
  6560. (Figure~\ref{fig:Rvec-concrete-syntax}).}
  6561. \label{fig:r3s-concrete-syntax}
  6562. \end{figure}
  6563. An instance of a structure is created using function call syntax, with
  6564. the name of the structure in the function position:
  6565. \begin{lstlisting}
  6566. (point 7 12)
  6567. \end{lstlisting}
  6568. Function-call syntax is also used to read the value in a field of a
  6569. structure. The function name is formed by the structure name, a dash,
  6570. and the field name. The following example uses \code{point-x} and
  6571. \code{point-y} to access the \code{x} and \code{y} fields of two point
  6572. instances.
  6573. \begin{center}
  6574. \begin{lstlisting}
  6575. (let ([pt1 (point 7 12)])
  6576. (let ([pt2 (point 4 3)])
  6577. (+ (- (point-x pt1) (point-x pt2))
  6578. (- (point-y pt1) (point-y pt2)))))
  6579. \end{lstlisting}
  6580. \end{center}
  6581. Similarly, to write to a field of a structure, use its set function,
  6582. whose name starts with \code{set-}, followed by the structure name,
  6583. then a dash, then the field name, and concluded with an exclamation
  6584. mark. The following example uses \code{set-point-x!} to change the
  6585. \code{x} field from \code{7} to \code{42}.
  6586. \begin{center}
  6587. \begin{lstlisting}
  6588. (let ([pt (point 7 12)])
  6589. (let ([_ (set-point-x! pt 42)])
  6590. (point-x pt)))
  6591. \end{lstlisting}
  6592. \end{center}
  6593. \begin{exercise}\normalfont
  6594. Extend your compiler with support for simple structures, compiling
  6595. $R^s_3$ to x86 assembly code. Create five new test cases that use
  6596. structures and test your compiler.
  6597. \end{exercise}
  6598. \section{Challenge: Generational Collection}
  6599. The copying collector described in Section~\ref{sec:GC} can incur
  6600. significant runtime overhead because the call to \code{collect} takes
  6601. time proportional to all of the live data. One way to reduce this
  6602. overhead is to reduce how much data is inspected in each call to
  6603. \code{collect}. In particular, researchers have observed that recently
  6604. allocated data is more likely to become garbage then data that has
  6605. survived one or more previous calls to \code{collect}. This insight
  6606. motivated the creation of \emph{generational garbage collectors}
  6607. \index{generational garbage collector} that
  6608. 1) segregates data according to its age into two or more generations,
  6609. 2) allocates less space for younger generations, so collecting them is
  6610. faster, and more space for the older generations, and 3) performs
  6611. collection on the younger generations more frequently then for older
  6612. generations~\citep{Wilson:1992fk}.
  6613. For this challenge assignment, the goal is to adapt the copying
  6614. collector implemented in \code{runtime.c} to use two generations, one
  6615. for young data and one for old data. Each generation consists of a
  6616. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  6617. \code{collect} function to use the two generations.
  6618. \begin{enumerate}
  6619. \item Copy the young generation's FromSpace to its ToSpace then switch
  6620. the role of the ToSpace and FromSpace
  6621. \item If there is enough space for the requested number of bytes in
  6622. the young FromSpace, then return from \code{collect}.
  6623. \item If there is not enough space in the young FromSpace for the
  6624. requested bytes, then move the data from the young generation to the
  6625. old one with the following steps:
  6626. \begin{enumerate}
  6627. \item If there is enough room in the old FromSpace, copy the young
  6628. FromSpace to the old FromSpace and then return.
  6629. \item If there is not enough room in the old FromSpace, then collect
  6630. the old generation by copying the old FromSpace to the old ToSpace
  6631. and swap the roles of the old FromSpace and ToSpace.
  6632. \item If there is enough room now, copy the young FromSpace to the
  6633. old FromSpace and return. Otherwise, allocate a larger FromSpace
  6634. and ToSpace for the old generation. Copy the young FromSpace and
  6635. the old FromSpace into the larger FromSpace for the old
  6636. generation and then return.
  6637. \end{enumerate}
  6638. \end{enumerate}
  6639. We recommend that you generalize the \code{cheney} function so that it
  6640. can be used for all the copies mentioned above: between the young
  6641. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  6642. between the young FromSpace and old FromSpace. This can be
  6643. accomplished by adding parameters to \code{cheney} that replace its
  6644. use of the global variables \code{fromspace\_begin},
  6645. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  6646. Note that the collection of the young generation does not traverse the
  6647. old generation. This introduces a potential problem: there may be
  6648. young data that is only reachable through pointers in the old
  6649. generation. If these pointers are not taken into account, the
  6650. collector could throw away young data that is live! One solution,
  6651. called \emph{pointer recording}, is to maintain a set of all the
  6652. pointers from the old generation into the new generation and consider
  6653. this set as part of the root set. To maintain this set, the compiler
  6654. must insert extra instructions around every \code{vector-set!}. If the
  6655. vector being modified is in the old generation, and if the value being
  6656. written is a pointer into the new generation, than that pointer must
  6657. be added to the set. Also, if the value being overwritten was a
  6658. pointer into the new generation, then that pointer should be removed
  6659. from the set.
  6660. \begin{exercise}\normalfont
  6661. Adapt the \code{collect} function in \code{runtime.c} to implement
  6662. generational garbage collection, as outlined in this section.
  6663. Update the code generation for \code{vector-set!} to implement
  6664. pointer recording. Make sure that your new compiler and runtime
  6665. passes your test suite.
  6666. \end{exercise}
  6667. % TODO: challenge, implement homogeneous vectors
  6668. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6669. \chapter{Functions}
  6670. \label{ch:functions}
  6671. \index{function}
  6672. This chapter studies the compilation of functions similar to those
  6673. found in the C language. This corresponds to a subset of Typed Racket
  6674. in which only top-level function definitions are allowed. This kind of
  6675. function is an important stepping stone to implementing
  6676. lexically-scoped functions, that is, \key{lambda} abstractions, which
  6677. is the topic of Chapter~\ref{ch:lambdas}.
  6678. \section{The \LangFun{} Language}
  6679. The concrete and abstract syntax for function definitions and function
  6680. application is shown in Figures~\ref{fig:Rfun-concrete-syntax} and
  6681. \ref{fig:Rfun-syntax}, where we define the \LangFun{} language. Programs in
  6682. \LangFun{} begin with zero or more function definitions. The function
  6683. names from these definitions are in-scope for the entire program,
  6684. including all other function definitions (so the ordering of function
  6685. definitions does not matter). The concrete syntax for function
  6686. application\index{function application} is $(\Exp \; \Exp \ldots)$
  6687. where the first expression must
  6688. evaluate to a function and the rest are the arguments.
  6689. The abstract syntax for function application is
  6690. $\APPLY{\Exp}{\Exp\ldots}$.
  6691. %% The syntax for function application does not include an explicit
  6692. %% keyword, which is error prone when using \code{match}. To alleviate
  6693. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  6694. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  6695. Functions are first-class in the sense that a function pointer
  6696. \index{function pointer} is data and can be stored in memory or passed
  6697. as a parameter to another function. Thus, we introduce a function
  6698. type, written
  6699. \begin{lstlisting}
  6700. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  6701. \end{lstlisting}
  6702. for a function whose $n$ parameters have the types $\Type_1$ through
  6703. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  6704. these functions (with respect to Racket functions) is that they are
  6705. not lexically scoped. That is, the only external entities that can be
  6706. referenced from inside a function body are other globally-defined
  6707. functions. The syntax of \LangFun{} prevents functions from being nested
  6708. inside each other.
  6709. \begin{figure}[tp]
  6710. \centering
  6711. \fbox{
  6712. \begin{minipage}{0.96\textwidth}
  6713. \small
  6714. \[
  6715. \begin{array}{lcl}
  6716. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  6717. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void} } \mid (\Type \ldots \; \key{->}\; \Type) \\
  6718. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6719. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  6720. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  6721. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6722. \mid (\key{and}\;\Exp\;\Exp)
  6723. \mid (\key{or}\;\Exp\;\Exp)
  6724. \mid (\key{not}\;\Exp)} \\
  6725. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  6726. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  6727. (\key{vector-ref}\;\Exp\;\Int)} \\
  6728. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  6729. \mid \LP\key{has-type}~\Exp~\Type\RP } \\
  6730. &\mid& \LP\Exp \; \Exp \ldots\RP \\
  6731. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  6732. \LangFun{} &::=& \Def \ldots \; \Exp
  6733. \end{array}
  6734. \]
  6735. \end{minipage}
  6736. }
  6737. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-concrete-syntax}).}
  6738. \label{fig:Rfun-concrete-syntax}
  6739. \end{figure}
  6740. \begin{figure}[tp]
  6741. \centering
  6742. \fbox{
  6743. \begin{minipage}{0.96\textwidth}
  6744. \small
  6745. \[
  6746. \begin{array}{lcl}
  6747. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6748. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  6749. &\mid& \gray{ \BOOL{\itm{bool}}
  6750. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6751. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP }
  6752. \mid \APPLY{\Exp}{\Exp\ldots}\\
  6753. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}\\
  6754. \LangFun{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  6755. \end{array}
  6756. \]
  6757. \end{minipage}
  6758. }
  6759. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-syntax}).}
  6760. \label{fig:Rfun-syntax}
  6761. \end{figure}
  6762. The program in Figure~\ref{fig:Rfun-function-example} is a
  6763. representative example of defining and using functions in \LangFun{}. We
  6764. define a function \code{map-vec} that applies some other function
  6765. \code{f} to both elements of a vector and returns a new
  6766. vector containing the results. We also define a function \code{add1}.
  6767. The program applies
  6768. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  6769. \code{(vector 1 42)}, from which we return the \code{42}.
  6770. \begin{figure}[tbp]
  6771. \begin{lstlisting}
  6772. (define (map-vec [f : (Integer -> Integer)]
  6773. [v : (Vector Integer Integer)])
  6774. : (Vector Integer Integer)
  6775. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  6776. (define (add1 [x : Integer]) : Integer
  6777. (+ x 1))
  6778. (vector-ref (map-vec add1 (vector 0 41)) 1)
  6779. \end{lstlisting}
  6780. \caption{Example of using functions in \LangFun{}.}
  6781. \label{fig:Rfun-function-example}
  6782. \end{figure}
  6783. The definitional interpreter for \LangFun{} is in
  6784. Figure~\ref{fig:interp-Rfun}. The case for the \code{ProgramDefsExp} form is
  6785. responsible for setting up the mutual recursion between the top-level
  6786. function definitions. We use the classic back-patching \index{back-patching}
  6787. approach that uses mutable variables and makes two passes over the function
  6788. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  6789. top-level environment using a mutable cons cell for each function
  6790. definition. Note that the \code{lambda} value for each function is
  6791. incomplete; it does not yet include the environment. Once the
  6792. top-level environment is constructed, we then iterate over it and
  6793. update the \code{lambda} values to use the top-level environment.
  6794. \begin{figure}[tp]
  6795. \begin{lstlisting}
  6796. (define interp-Rfun-class
  6797. (class interp-Rvec-class
  6798. (super-new)
  6799. (define/override ((interp-exp env) e)
  6800. (define recur (interp-exp env))
  6801. (match e
  6802. [(Var x) (unbox (dict-ref env x))]
  6803. [(Let x e body)
  6804. (define new-env (dict-set env x (box (recur e))))
  6805. ((interp-exp new-env) body)]
  6806. [(Apply fun args)
  6807. (define fun-val (recur fun))
  6808. (define arg-vals (for/list ([e args]) (recur e)))
  6809. (match fun-val
  6810. [`(function (,xs ...) ,body ,fun-env)
  6811. (define params-args (for/list ([x xs] [arg arg-vals])
  6812. (cons x (box arg))))
  6813. (define new-env (append params-args fun-env))
  6814. ((interp-exp new-env) body)]
  6815. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  6816. [else ((super interp-exp env) e)]
  6817. ))
  6818. (define/public (interp-def d)
  6819. (match d
  6820. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  6821. (cons f (box `(function ,xs ,body ())))]))
  6822. (define/override (interp-program p)
  6823. (match p
  6824. [(ProgramDefsExp info ds body)
  6825. (let ([top-level (for/list ([d ds]) (interp-def d))])
  6826. (for/list ([f (in-dict-values top-level)])
  6827. (set-box! f (match (unbox f)
  6828. [`(function ,xs ,body ())
  6829. `(function ,xs ,body ,top-level)])))
  6830. ((interp-exp top-level) body))]))
  6831. ))
  6832. (define (interp-Rfun p)
  6833. (send (new interp-Rfun-class) interp-program p))
  6834. \end{lstlisting}
  6835. \caption{Interpreter for the \LangFun{} language.}
  6836. \label{fig:interp-Rfun}
  6837. \end{figure}
  6838. \margincomment{TODO: explain type checker}
  6839. The type checker for \LangFun{} is is in Figure~\ref{fig:type-check-Rfun}.
  6840. \begin{figure}[tp]
  6841. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6842. (define type-check-Rfun-class
  6843. (class type-check-Rvec-class
  6844. (super-new)
  6845. (inherit check-type-equal?)
  6846. (define/public (type-check-apply env e es)
  6847. (define-values (e^ ty) ((type-check-exp env) e))
  6848. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  6849. ((type-check-exp env) e)))
  6850. (match ty
  6851. [`(,ty^* ... -> ,rt)
  6852. (for ([arg-ty ty*] [param-ty ty^*])
  6853. (check-type-equal? arg-ty param-ty (Apply e es)))
  6854. (values e^ e* rt)]))
  6855. (define/override (type-check-exp env)
  6856. (lambda (e)
  6857. (match e
  6858. [(FunRef f)
  6859. (values (FunRef f) (dict-ref env f))]
  6860. [(Apply e es)
  6861. (define-values (e^ es^ rt) (type-check-apply env e es))
  6862. (values (Apply e^ es^) rt)]
  6863. [(Call e es)
  6864. (define-values (e^ es^ rt) (type-check-apply env e es))
  6865. (values (Call e^ es^) rt)]
  6866. [else ((super type-check-exp env) e)])))
  6867. (define/public (type-check-def env)
  6868. (lambda (e)
  6869. (match e
  6870. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  6871. (define new-env (append (map cons xs ps) env))
  6872. (define-values (body^ ty^) ((type-check-exp new-env) body))
  6873. (check-type-equal? ty^ rt body)
  6874. (Def f p:t* rt info body^)])))
  6875. (define/public (fun-def-type d)
  6876. (match d
  6877. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  6878. (define/override (type-check-program e)
  6879. (match e
  6880. [(ProgramDefsExp info ds body)
  6881. (define new-env (for/list ([d ds])
  6882. (cons (Def-name d) (fun-def-type d))))
  6883. (define ds^ (for/list ([d ds]) ((type-check-def new-env) d)))
  6884. (define-values (body^ ty) ((type-check-exp new-env) body))
  6885. (check-type-equal? ty 'Integer body)
  6886. (ProgramDefsExp info ds^ body^)]))))
  6887. (define (type-check-Rfun p)
  6888. (send (new type-check-Rfun-class) type-check-program p))
  6889. \end{lstlisting}
  6890. \caption{Type checker for the \LangFun{} language.}
  6891. \label{fig:type-check-Rfun}
  6892. \end{figure}
  6893. \section{Functions in x86}
  6894. \label{sec:fun-x86}
  6895. \margincomment{\tiny Make sure callee-saved registers are discussed
  6896. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  6897. \margincomment{\tiny Talk about the return address on the
  6898. stack and what callq and retq does.\\ --Jeremy }
  6899. The x86 architecture provides a few features to support the
  6900. implementation of functions. We have already seen that x86 provides
  6901. labels so that one can refer to the location of an instruction, as is
  6902. needed for jump instructions. Labels can also be used to mark the
  6903. beginning of the instructions for a function. Going further, we can
  6904. obtain the address of a label by using the \key{leaq} instruction and
  6905. PC-relative addressing. For example, the following puts the
  6906. address of the \code{add1} label into the \code{rbx} register.
  6907. \begin{lstlisting}
  6908. leaq add1(%rip), %rbx
  6909. \end{lstlisting}
  6910. The instruction pointer register \key{rip} (aka. the program counter
  6911. \index{program counter}) always points to the next instruction to be
  6912. executed. When combined with an label, as in \code{add1(\%rip)}, the
  6913. linker computes the distance $d$ between the address of \code{add1}
  6914. and where the \code{rip} would be at that moment and then changes
  6915. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  6916. the address of \code{add1}.
  6917. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  6918. jump to a function whose location is given by a label. To support
  6919. function calls in this chapter we instead will be jumping to a
  6920. function whose location is given by an address in a register, that is,
  6921. we need to make an \emph{indirect function call}. The x86 syntax for
  6922. this is a \code{callq} instruction but with an asterisk before the
  6923. register name.\index{indirect function call}
  6924. \begin{lstlisting}
  6925. callq *%rbx
  6926. \end{lstlisting}
  6927. \subsection{Calling Conventions}
  6928. \index{calling conventions}
  6929. The \code{callq} instruction provides partial support for implementing
  6930. functions: it pushes the return address on the stack and it jumps to
  6931. the target. However, \code{callq} does not handle
  6932. \begin{enumerate}
  6933. \item parameter passing,
  6934. \item pushing frames on the procedure call stack and popping them off,
  6935. or
  6936. \item determining how registers are shared by different functions.
  6937. \end{enumerate}
  6938. Regarding (1) parameter passing, recall that the following six
  6939. registers are used to pass arguments to a function, in this order.
  6940. \begin{lstlisting}
  6941. rdi rsi rdx rcx r8 r9
  6942. \end{lstlisting}
  6943. If there are
  6944. more than six arguments, then the convention is to use space on the
  6945. frame of the caller for the rest of the arguments. However, to ease
  6946. the implementation of efficient tail calls
  6947. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  6948. arguments.
  6949. %
  6950. Also recall that the register \code{rax} is for the return value of
  6951. the function.
  6952. \index{prelude}\index{conclusion}
  6953. Regarding (2) frames \index{frame} and the procedure call stack,
  6954. \index{procedure call stack} recall from Section~\ref{sec:x86} that
  6955. the stack grows down, with each function call using a chunk of space
  6956. called a frame. The caller sets the stack pointer, register
  6957. \code{rsp}, to the last data item in its frame. The callee must not
  6958. change anything in the caller's frame, that is, anything that is at or
  6959. above the stack pointer. The callee is free to use locations that are
  6960. below the stack pointer.
  6961. Recall that we are storing variables of vector type on the root stack.
  6962. So the prelude needs to move the root stack pointer \code{r15} up and
  6963. the conclusion needs to move the root stack pointer back down. Also,
  6964. the prelude must initialize to \code{0} this frame's slots in the root
  6965. stack to signal to the garbage collector that those slots do not yet
  6966. contain a pointer to a vector. Otherwise the garbage collector will
  6967. interpret the garbage bits in those slots as memory addresses and try
  6968. to traverse them, causing serious mayhem!
  6969. Regarding (3) the sharing of registers between different functions,
  6970. recall from Section~\ref{sec:calling-conventions} that the registers
  6971. are divided into two groups, the caller-saved registers and the
  6972. callee-saved registers. The caller should assume that all the
  6973. caller-saved registers get overwritten with arbitrary values by the
  6974. callee. That is why we recommend in
  6975. Section~\ref{sec:calling-conventions} that variables that are live
  6976. during a function call should not be assigned to caller-saved
  6977. registers.
  6978. On the flip side, if the callee wants to use a callee-saved register,
  6979. the callee must save the contents of those registers on their stack
  6980. frame and then put them back prior to returning to the caller. That
  6981. is why we recommended in Section~\ref{sec:calling-conventions} that if
  6982. the register allocator assigns a variable to a callee-saved register,
  6983. then the prelude of the \code{main} function must save that register
  6984. to the stack and the conclusion of \code{main} must restore it. This
  6985. recommendation now generalizes to all functions.
  6986. Also recall that the base pointer, register \code{rbp}, is used as a
  6987. point-of-reference within a frame, so that each local variable can be
  6988. accessed at a fixed offset from the base pointer
  6989. (Section~\ref{sec:x86}).
  6990. %
  6991. Figure~\ref{fig:call-frames} shows the general layout of the caller
  6992. and callee frames.
  6993. \begin{figure}[tbp]
  6994. \centering
  6995. \begin{tabular}{r|r|l|l} \hline
  6996. Caller View & Callee View & Contents & Frame \\ \hline
  6997. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  6998. 0(\key{\%rbp}) & & old \key{rbp} \\
  6999. -8(\key{\%rbp}) & & callee-saved $1$ \\
  7000. \ldots & & \ldots \\
  7001. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  7002. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  7003. \ldots & & \ldots \\
  7004. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  7005. %% & & \\
  7006. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  7007. %% & \ldots & \ldots \\
  7008. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  7009. \hline
  7010. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  7011. & 0(\key{\%rbp}) & old \key{rbp} \\
  7012. & -8(\key{\%rbp}) & callee-saved $1$ \\
  7013. & \ldots & \ldots \\
  7014. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  7015. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  7016. & \ldots & \ldots \\
  7017. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  7018. \end{tabular}
  7019. \caption{Memory layout of caller and callee frames.}
  7020. \label{fig:call-frames}
  7021. \end{figure}
  7022. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  7023. %% local variables and for storing the values of callee-saved registers
  7024. %% (we shall refer to all of these collectively as ``locals''), and that
  7025. %% at the beginning of a function we move the stack pointer \code{rsp}
  7026. %% down to make room for them.
  7027. %% We recommend storing the local variables
  7028. %% first and then the callee-saved registers, so that the local variables
  7029. %% can be accessed using \code{rbp} the same as before the addition of
  7030. %% functions.
  7031. %% To make additional room for passing arguments, we shall
  7032. %% move the stack pointer even further down. We count how many stack
  7033. %% arguments are needed for each function call that occurs inside the
  7034. %% body of the function and find their maximum. Adding this number to the
  7035. %% number of locals gives us how much the \code{rsp} should be moved at
  7036. %% the beginning of the function. In preparation for a function call, we
  7037. %% offset from \code{rsp} to set up the stack arguments. We put the first
  7038. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  7039. %% so on.
  7040. %% Upon calling the function, the stack arguments are retrieved by the
  7041. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  7042. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  7043. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  7044. %% the layout of the caller and callee frames. Notice how important it is
  7045. %% that we correctly compute the maximum number of arguments needed for
  7046. %% function calls; if that number is too small then the arguments and
  7047. %% local variables will smash into each other!
  7048. \subsection{Efficient Tail Calls}
  7049. \label{sec:tail-call}
  7050. In general, the amount of stack space used by a program is determined
  7051. by the longest chain of nested function calls. That is, if function
  7052. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  7053. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  7054. $n$ can grow quite large in the case of recursive or mutually
  7055. recursive functions. However, in some cases we can arrange to use only
  7056. constant space, i.e. $O(1)$, instead of $O(n)$.
  7057. If a function call is the last action in a function body, then that
  7058. call is said to be a \emph{tail call}\index{tail call}.
  7059. For example, in the following
  7060. program, the recursive call to \code{tail-sum} is a tail call.
  7061. \begin{center}
  7062. \begin{lstlisting}
  7063. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  7064. (if (eq? n 0)
  7065. r
  7066. (tail-sum (- n 1) (+ n r))))
  7067. (+ (tail-sum 5 0) 27)
  7068. \end{lstlisting}
  7069. \end{center}
  7070. At a tail call, the frame of the caller is no longer needed, so we
  7071. can pop the caller's frame before making the tail call. With this
  7072. approach, a recursive function that only makes tail calls will only
  7073. use $O(1)$ stack space. Functional languages like Racket typically
  7074. rely heavily on recursive functions, so they typically guarantee that
  7075. all tail calls will be optimized in this way.
  7076. \index{frame}
  7077. However, some care is needed with regards to argument passing in tail
  7078. calls. As mentioned above, for arguments beyond the sixth, the
  7079. convention is to use space in the caller's frame for passing
  7080. arguments. But for a tail call we pop the caller's frame and can no
  7081. longer use it. Another alternative is to use space in the callee's
  7082. frame for passing arguments. However, this option is also problematic
  7083. because the caller and callee's frame overlap in memory. As we begin
  7084. to copy the arguments from their sources in the caller's frame, the
  7085. target locations in the callee's frame might overlap with the sources
  7086. for later arguments! We solve this problem by not using the stack for
  7087. passing more than six arguments but instead using the heap, as we
  7088. describe in the Section~\ref{sec:limit-functions-r4}.
  7089. As mentioned above, for a tail call we pop the caller's frame prior to
  7090. making the tail call. The instructions for popping a frame are the
  7091. instructions that we usually place in the conclusion of a
  7092. function. Thus, we also need to place such code immediately before
  7093. each tail call. These instructions include restoring the callee-saved
  7094. registers, so it is good that the argument passing registers are all
  7095. caller-saved registers.
  7096. One last note regarding which instruction to use to make the tail
  7097. call. When the callee is finished, it should not return to the current
  7098. function, but it should return to the function that called the current
  7099. one. Thus, the return address that is already on the stack is the
  7100. right one, and we should not use \key{callq} to make the tail call, as
  7101. that would unnecessarily overwrite the return address. Instead we can
  7102. simply use the \key{jmp} instruction. Like the indirect function call,
  7103. we write an \emph{indirect jump}\index{indirect jump} with a register
  7104. prefixed with an asterisk. We recommend using \code{rax} to hold the
  7105. jump target because the preceding conclusion overwrites just about
  7106. everything else.
  7107. \begin{lstlisting}
  7108. jmp *%rax
  7109. \end{lstlisting}
  7110. \section{Shrink \LangFun{}}
  7111. \label{sec:shrink-r4}
  7112. The \code{shrink} pass performs a minor modification to ease the
  7113. later passes. This pass introduces an explicit \code{main} function
  7114. and changes the top \code{ProgramDefsExp} form to
  7115. \code{ProgramDefs} as follows.
  7116. \begin{lstlisting}
  7117. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  7118. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  7119. \end{lstlisting}
  7120. where $\itm{mainDef}$ is
  7121. \begin{lstlisting}
  7122. (Def 'main '() 'Integer '() |$\Exp'$|)
  7123. \end{lstlisting}
  7124. \section{Reveal Functions and the \LangFunRef{} language}
  7125. \label{sec:reveal-functions-r4}
  7126. The syntax of \LangFun{} is inconvenient for purposes of compilation in one
  7127. respect: it conflates the use of function names and local
  7128. variables. This is a problem because we need to compile the use of a
  7129. function name differently than the use of a local variable; we need to
  7130. use \code{leaq} to convert the function name (a label in x86) to an
  7131. address in a register. Thus, it is a good idea to create a new pass
  7132. that changes function references from just a symbol $f$ to
  7133. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  7134. output language, \LangFunRef{}, is defined in Figure~\ref{fig:f1-syntax}.
  7135. The concrete syntax for a function reference is $\CFUNREF{f}$.
  7136. \begin{figure}[tp]
  7137. \centering
  7138. \fbox{
  7139. \begin{minipage}{0.96\textwidth}
  7140. \[
  7141. \begin{array}{lcl}
  7142. \Exp &::=& \ldots \mid \FUNREF{\Var}\\
  7143. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7144. \LangFunRef{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  7145. \end{array}
  7146. \]
  7147. \end{minipage}
  7148. }
  7149. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  7150. (Figure~\ref{fig:Rfun-syntax}).}
  7151. \label{fig:f1-syntax}
  7152. \end{figure}
  7153. %% Distinguishing between calls in tail position and non-tail position
  7154. %% requires the pass to have some notion of context. We recommend using
  7155. %% two mutually recursive functions, one for processing expressions in
  7156. %% tail position and another for the rest.
  7157. Placing this pass after \code{uniquify} will make sure that there are
  7158. no local variables and functions that share the same name. On the
  7159. other hand, \code{reveal-functions} needs to come before the
  7160. \code{explicate-control} pass because that pass helps us compile
  7161. \code{FunRef} forms into assignment statements.
  7162. \section{Limit Functions}
  7163. \label{sec:limit-functions-r4}
  7164. Recall that we wish to limit the number of function parameters to six
  7165. so that we do not need to use the stack for argument passing, which
  7166. makes it easier to implement efficient tail calls. However, because
  7167. the input language \LangFun{} supports arbitrary numbers of function
  7168. arguments, we have some work to do!
  7169. This pass transforms functions and function calls that involve more
  7170. than six arguments to pass the first five arguments as usual, but it
  7171. packs the rest of the arguments into a vector and passes it as the
  7172. sixth argument.
  7173. Each function definition with too many parameters is transformed as
  7174. follows.
  7175. \begin{lstlisting}
  7176. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  7177. |$\Rightarrow$|
  7178. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  7179. \end{lstlisting}
  7180. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  7181. the occurrences of the later parameters with vector references.
  7182. \begin{lstlisting}
  7183. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  7184. \end{lstlisting}
  7185. For function calls with too many arguments, the \code{limit-functions}
  7186. pass transforms them in the following way.
  7187. \begin{tabular}{lll}
  7188. \begin{minipage}{0.2\textwidth}
  7189. \begin{lstlisting}
  7190. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  7191. \end{lstlisting}
  7192. \end{minipage}
  7193. &
  7194. $\Rightarrow$
  7195. &
  7196. \begin{minipage}{0.4\textwidth}
  7197. \begin{lstlisting}
  7198. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  7199. \end{lstlisting}
  7200. \end{minipage}
  7201. \end{tabular}
  7202. \section{Remove Complex Operands}
  7203. \label{sec:rco-r4}
  7204. The primary decisions to make for this pass is whether to classify
  7205. \code{FunRef} and \code{Apply} as either atomic or complex
  7206. expressions. Recall that a simple expression will eventually end up as
  7207. just an immediate argument of an x86 instruction. Function
  7208. application will be translated to a sequence of instructions, so
  7209. \code{Apply} must be classified as complex expression.
  7210. On the other hand, the arguments of \code{Apply} should be
  7211. atomic expressions.
  7212. %
  7213. Regarding \code{FunRef}, as discussed above, the function label needs
  7214. to be converted to an address using the \code{leaq} instruction. Thus,
  7215. even though \code{FunRef} seems rather simple, it needs to be
  7216. classified as a complex expression so that we generate an assignment
  7217. statement with a left-hand side that can serve as the target of the
  7218. \code{leaq}. Figure~\ref{fig:Rfun-anf-syntax} defines the
  7219. output language \LangFunANF{} of this pass.
  7220. \begin{figure}[tp]
  7221. \centering
  7222. \fbox{
  7223. \begin{minipage}{0.96\textwidth}
  7224. \small
  7225. \[
  7226. \begin{array}{rcl}
  7227. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  7228. \mid \VOID{} } \\
  7229. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  7230. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  7231. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  7232. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  7233. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  7234. &\mid& \gray{ \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  7235. \mid \LP\key{GlobalValue}~\Var\RP }\\
  7236. &\mid& \FUNREF{\Var} \mid \APPLY{\Atm}{\Atm\ldots}\\
  7237. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7238. R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  7239. \end{array}
  7240. \]
  7241. \end{minipage}
  7242. }
  7243. \caption{\LangFunANF{} is \LangFun{} in administrative normal form (ANF).}
  7244. \label{fig:Rfun-anf-syntax}
  7245. \end{figure}
  7246. \section{Explicate Control and the \LangCFun{} language}
  7247. \label{sec:explicate-control-r4}
  7248. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  7249. output of \key{explicate-control}. (The concrete syntax is given in
  7250. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.) The auxiliary
  7251. functions for assignment and tail contexts should be updated with
  7252. cases for \code{Apply} and \code{FunRef} and the function for
  7253. predicate context should be updated for \code{Apply} but not
  7254. \code{FunRef}. (A \code{FunRef} can't be a Boolean.) In assignment
  7255. and predicate contexts, \code{Apply} becomes \code{Call}, whereas in
  7256. tail position \code{Apply} becomes \code{TailCall}. We recommend
  7257. defining a new auxiliary function for processing function definitions.
  7258. This code is similar to the case for \code{Program} in \LangVec{}. The
  7259. top-level \code{explicate-control} function that handles the
  7260. \code{ProgramDefs} form of \LangFun{} can then apply this new function to
  7261. all the function definitions.
  7262. \begin{figure}[tp]
  7263. \fbox{
  7264. \begin{minipage}{0.96\textwidth}
  7265. \small
  7266. \[
  7267. \begin{array}{lcl}
  7268. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  7269. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  7270. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  7271. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  7272. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  7273. &\mid& \gray{ \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP } \\
  7274. &\mid& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  7275. &\mid& \gray{ \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP }\\
  7276. &\mid& \gray{ \LP\key{GlobalValue} \,\Var\RP \mid \LP\key{Void}\RP }\\
  7277. &\mid& \FUNREF{\itm{label}} \mid \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  7278. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  7279. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  7280. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  7281. \mid \GOTO{\itm{label}} } \\
  7282. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  7283. &\mid& \TAILCALL{\Atm}{\Atm\ldots} \\
  7284. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  7285. \LangCFun{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  7286. \end{array}
  7287. \]
  7288. \end{minipage}
  7289. }
  7290. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  7291. \label{fig:c3-syntax}
  7292. \end{figure}
  7293. \section{Select Instructions and the \LangXIndCall{} Language}
  7294. \label{sec:select-r4}
  7295. \index{instruction selection}
  7296. The output of select instructions is a program in the \LangXIndCall{}
  7297. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  7298. \index{x86}
  7299. \begin{figure}[tp]
  7300. \fbox{
  7301. \begin{minipage}{0.96\textwidth}
  7302. \small
  7303. \[
  7304. \begin{array}{lcl}
  7305. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)}
  7306. \mid \LP\key{fun-ref}\; \itm{label}\RP\\
  7307. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  7308. \Instr &::=& \ldots
  7309. \mid \key{callq}\;\key{*}\Arg \mid \key{tailjmp}\;\Arg
  7310. \mid \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  7311. \Block &::= & \Instr\ldots \\
  7312. \Def &::= & \LP\key{define} \; \LP\itm{label}\RP \;\LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\RP\\
  7313. \LangXIndCall{} &::= & \Def\ldots
  7314. \end{array}
  7315. \]
  7316. \end{minipage}
  7317. }
  7318. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  7319. \label{fig:x86-3-concrete}
  7320. \end{figure}
  7321. \begin{figure}[tp]
  7322. \fbox{
  7323. \begin{minipage}{0.96\textwidth}
  7324. \small
  7325. \[
  7326. \begin{array}{lcl}
  7327. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  7328. \mid \BYTEREG{\Reg} } \\
  7329. &\mid& \gray{ (\key{Global}~\Var) } \mid \FUNREF{\itm{label}} \\
  7330. \Instr &::=& \ldots \mid \INDCALLQ{\Arg}{\itm{int}}
  7331. \mid \TAILJMP{\Arg}{\itm{int}}\\
  7332. &\mid& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  7333. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  7334. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  7335. \LangXIndCall{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  7336. \end{array}
  7337. \]
  7338. \end{minipage}
  7339. }
  7340. \caption{The abstract syntax of \LangXIndCall{} (extends
  7341. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  7342. \label{fig:x86-3}
  7343. \end{figure}
  7344. An assignment of a function reference to a variable becomes a
  7345. load-effective-address instruction as follows: \\
  7346. \begin{tabular}{lcl}
  7347. \begin{minipage}{0.35\textwidth}
  7348. \begin{lstlisting}
  7349. |$\itm{lhs}$| = (fun-ref |$f$|);
  7350. \end{lstlisting}
  7351. \end{minipage}
  7352. &
  7353. $\Rightarrow$\qquad\qquad
  7354. &
  7355. \begin{minipage}{0.3\textwidth}
  7356. \begin{lstlisting}
  7357. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  7358. \end{lstlisting}
  7359. \end{minipage}
  7360. \end{tabular} \\
  7361. Regarding function definitions, we need to remove the parameters and
  7362. instead perform parameter passing using the conventions discussed in
  7363. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  7364. registers. We recommend turning the parameters into local variables
  7365. and generating instructions at the beginning of the function to move
  7366. from the argument passing registers to these local variables.
  7367. \begin{lstlisting}
  7368. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  7369. |$\Rightarrow$|
  7370. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  7371. \end{lstlisting}
  7372. The $G'$ control-flow graph is the same as $G$ except that the
  7373. \code{start} block is modified to add the instructions for moving from
  7374. the argument registers to the parameter variables. So the \code{start}
  7375. block of $G$ shown on the left is changed to the code on the right.
  7376. \begin{center}
  7377. \begin{minipage}{0.3\textwidth}
  7378. \begin{lstlisting}
  7379. start:
  7380. |$\itm{instr}_1$|
  7381. |$\vdots$|
  7382. |$\itm{instr}_n$|
  7383. \end{lstlisting}
  7384. \end{minipage}
  7385. $\Rightarrow$
  7386. \begin{minipage}{0.3\textwidth}
  7387. \begin{lstlisting}
  7388. start:
  7389. movq %rdi, |$x_1$|
  7390. movq %rsi, |$x_2$|
  7391. |$\vdots$|
  7392. |$\itm{instr}_1$|
  7393. |$\vdots$|
  7394. |$\itm{instr}_n$|
  7395. \end{lstlisting}
  7396. \end{minipage}
  7397. \end{center}
  7398. By changing the parameters to local variables, we are giving the
  7399. register allocator control over which registers or stack locations to
  7400. use for them. If you implemented the move-biasing challenge
  7401. (Section~\ref{sec:move-biasing}), the register allocator will try to
  7402. assign the parameter variables to the corresponding argument register,
  7403. in which case the \code{patch-instructions} pass will remove the
  7404. \code{movq} instruction. This happens in the example translation in
  7405. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  7406. the \code{add} function.
  7407. %
  7408. Also, note that the register allocator will perform liveness analysis
  7409. on this sequence of move instructions and build the interference
  7410. graph. So, for example, $x_1$ will be marked as interfering with
  7411. \code{rsi} and that will prevent the assignment of $x_1$ to
  7412. \code{rsi}, which is good, because that would overwrite the argument
  7413. that needs to move into $x_2$.
  7414. Next, consider the compilation of function calls. In the mirror image
  7415. of handling the parameters of function definitions, the arguments need
  7416. to be moved to the argument passing registers. The function call
  7417. itself is performed with an indirect function call. The return value
  7418. from the function is stored in \code{rax}, so it needs to be moved
  7419. into the \itm{lhs}.
  7420. \begin{lstlisting}
  7421. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  7422. |$\Rightarrow$|
  7423. movq |$\itm{arg}_1$|, %rdi
  7424. movq |$\itm{arg}_2$|, %rsi
  7425. |$\vdots$|
  7426. callq *|\itm{fun}|
  7427. movq %rax, |\itm{lhs}|
  7428. \end{lstlisting}
  7429. The \code{IndirectCallq} AST node includes an integer for the arity of
  7430. the function, i.e., the number of parameters. That information is
  7431. useful in the \code{uncover-live} pass for determining which
  7432. argument-passing registers are potentially read during the call.
  7433. For tail calls, the parameter passing is the same as non-tail calls:
  7434. generate instructions to move the arguments into to the argument
  7435. passing registers. After that we need to pop the frame from the
  7436. procedure call stack. However, we do not yet know how big the frame
  7437. is; that gets determined during register allocation. So instead of
  7438. generating those instructions here, we invent a new instruction that
  7439. means ``pop the frame and then do an indirect jump'', which we name
  7440. \code{TailJmp}. The abstract syntax for this instruction includes an
  7441. argument that specifies where to jump and an integer that represents
  7442. the arity of the function being called.
  7443. Recall that in Section~\ref{sec:explicate-control-Rvar} we recommended
  7444. using the label \code{start} for the initial block of a program, and
  7445. in Section~\ref{sec:select-Rvar} we recommended labeling the conclusion
  7446. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  7447. can be compiled to an assignment to \code{rax} followed by a jump to
  7448. \code{conclusion}. With the addition of function definitions, we will
  7449. have a starting block and conclusion for each function, but their
  7450. labels need to be unique. We recommend prepending the function's name
  7451. to \code{start} and \code{conclusion}, respectively, to obtain unique
  7452. labels. (Alternatively, one could \code{gensym} labels for the start
  7453. and conclusion and store them in the $\itm{info}$ field of the
  7454. function definition.)
  7455. \section{Register Allocation}
  7456. \label{sec:register-allocation-r4}
  7457. \subsection{Liveness Analysis}
  7458. \label{sec:liveness-analysis-r4}
  7459. \index{liveness analysis}
  7460. %% The rest of the passes need only minor modifications to handle the new
  7461. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  7462. %% \code{leaq}.
  7463. The \code{IndirectCallq} instruction should be treated like
  7464. \code{Callq} regarding its written locations $W$, in that they should
  7465. include all the caller-saved registers. Recall that the reason for
  7466. that is to force call-live variables to be assigned to callee-saved
  7467. registers or to be spilled to the stack.
  7468. Regarding the set of read locations $R$ the arity field of
  7469. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  7470. argument-passing registers should be considered as read by those
  7471. instructions.
  7472. \subsection{Build Interference Graph}
  7473. \label{sec:build-interference-r4}
  7474. With the addition of function definitions, we compute an interference
  7475. graph for each function (not just one for the whole program).
  7476. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  7477. spill vector-typed variables that are live during a call to the
  7478. \code{collect}. With the addition of functions to our language, we
  7479. need to revisit this issue. Many functions perform allocation and
  7480. therefore have calls to the collector inside of them. Thus, we should
  7481. not only spill a vector-typed variable when it is live during a call
  7482. to \code{collect}, but we should spill the variable if it is live
  7483. during any function call. Thus, in the \code{build-interference} pass,
  7484. we recommend adding interference edges between call-live vector-typed
  7485. variables and the callee-saved registers (in addition to the usual
  7486. addition of edges between call-live variables and the caller-saved
  7487. registers).
  7488. \subsection{Allocate Registers}
  7489. The primary change to the \code{allocate-registers} pass is adding an
  7490. auxiliary function for handling definitions (the \Def{} non-terminal
  7491. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  7492. logic is the same as described in
  7493. Chapter~\ref{ch:register-allocation-Rvar}, except now register
  7494. allocation is performed many times, once for each function definition,
  7495. instead of just once for the whole program.
  7496. \section{Patch Instructions}
  7497. In \code{patch-instructions}, you should deal with the x86
  7498. idiosyncrasy that the destination argument of \code{leaq} must be a
  7499. register. Additionally, you should ensure that the argument of
  7500. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  7501. code generation more convenient, because we trample many registers
  7502. before the tail call (as explained in the next section).
  7503. \section{Print x86}
  7504. For the \code{print-x86} pass, the cases for \code{FunRef} and
  7505. \code{IndirectCallq} are straightforward: output their concrete
  7506. syntax.
  7507. \begin{lstlisting}
  7508. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  7509. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  7510. \end{lstlisting}
  7511. The \code{TailJmp} node requires a bit work. A straightforward
  7512. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  7513. before the jump we need to pop the current frame. This sequence of
  7514. instructions is the same as the code for the conclusion of a function,
  7515. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  7516. Regarding function definitions, you will need to generate a prelude
  7517. and conclusion for each one. This code is similar to the prelude and
  7518. conclusion that you generated for the \code{main} function in
  7519. Chapter~\ref{ch:tuples}. To review, the prelude of every function
  7520. should carry out the following steps.
  7521. \begin{enumerate}
  7522. \item Start with \code{.global} and \code{.align} directives followed
  7523. by the label for the function. (See Figure~\ref{fig:add-fun} for an
  7524. example.)
  7525. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  7526. pointer.
  7527. \item Push to the stack all of the callee-saved registers that were
  7528. used for register allocation.
  7529. \item Move the stack pointer \code{rsp} down by the size of the stack
  7530. frame for this function, which depends on the number of regular
  7531. spills. (Aligned to 16 bytes.)
  7532. \item Move the root stack pointer \code{r15} up by the size of the
  7533. root-stack frame for this function, which depends on the number of
  7534. spilled vectors. \label{root-stack-init}
  7535. \item Initialize to zero all of the entries in the root-stack frame.
  7536. \item Jump to the start block.
  7537. \end{enumerate}
  7538. The prelude of the \code{main} function has one additional task: call
  7539. the \code{initialize} function to set up the garbage collector and
  7540. move the value of the global \code{rootstack\_begin} in
  7541. \code{r15}. This should happen before step \ref{root-stack-init}
  7542. above, which depends on \code{r15}.
  7543. The conclusion of every function should do the following.
  7544. \begin{enumerate}
  7545. \item Move the stack pointer back up by the size of the stack frame
  7546. for this function.
  7547. \item Restore the callee-saved registers by popping them from the
  7548. stack.
  7549. \item Move the root stack pointer back down by the size of the
  7550. root-stack frame for this function.
  7551. \item Restore \code{rbp} by popping it from the stack.
  7552. \item Return to the caller with the \code{retq} instruction.
  7553. \end{enumerate}
  7554. \begin{exercise}\normalfont
  7555. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  7556. Create 5 new programs that use functions, including examples that pass
  7557. functions and return functions from other functions, recursive
  7558. functions, functions that create vectors, and functions that make tail
  7559. calls. Test your compiler on these new programs and all of your
  7560. previously created test programs.
  7561. \end{exercise}
  7562. \begin{figure}[tbp]
  7563. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7564. \node (Rfun) at (0,2) {\large \LangFun{}};
  7565. \node (Rfun-1) at (3,2) {\large \LangFun{}};
  7566. \node (Rfun-2) at (6,2) {\large \LangFun{}};
  7567. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  7568. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  7569. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  7570. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  7571. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  7572. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  7573. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  7574. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  7575. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  7576. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  7577. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  7578. \path[->,bend left=15] (Rfun) edge [above] node
  7579. {\ttfamily\footnotesize shrink} (Rfun-1);
  7580. \path[->,bend left=15] (Rfun-1) edge [above] node
  7581. {\ttfamily\footnotesize uniquify} (Rfun-2);
  7582. \path[->,bend left=15] (Rfun-2) edge [right] node
  7583. {\ttfamily\footnotesize ~~reveal-functions} (F1-1);
  7584. \path[->,bend left=15] (F1-1) edge [below] node
  7585. {\ttfamily\footnotesize limit-functions} (F1-2);
  7586. \path[->,bend right=15] (F1-2) edge [above] node
  7587. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  7588. \path[->,bend right=15] (F1-3) edge [above] node
  7589. {\ttfamily\footnotesize remove-complex.} (F1-4);
  7590. \path[->,bend left=15] (F1-4) edge [right] node
  7591. {\ttfamily\footnotesize explicate-control} (C3-2);
  7592. \path[->,bend right=15] (C3-2) edge [left] node
  7593. {\ttfamily\footnotesize select-instr.} (x86-2);
  7594. \path[->,bend left=15] (x86-2) edge [left] node
  7595. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  7596. \path[->,bend right=15] (x86-2-1) edge [below] node
  7597. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  7598. \path[->,bend right=15] (x86-2-2) edge [left] node
  7599. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7600. \path[->,bend left=15] (x86-3) edge [above] node
  7601. {\ttfamily\footnotesize patch-instr.} (x86-4);
  7602. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  7603. \end{tikzpicture}
  7604. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  7605. \label{fig:Rfun-passes}
  7606. \end{figure}
  7607. Figure~\ref{fig:Rfun-passes} gives an overview of the passes for
  7608. compiling \LangFun{} to x86.
  7609. \section{An Example Translation}
  7610. \label{sec:functions-example}
  7611. Figure~\ref{fig:add-fun} shows an example translation of a simple
  7612. function in \LangFun{} to x86. The figure also includes the results of the
  7613. \code{explicate-control} and \code{select-instructions} passes.
  7614. \begin{figure}[htbp]
  7615. \begin{tabular}{ll}
  7616. \begin{minipage}{0.5\textwidth}
  7617. % s3_2.rkt
  7618. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7619. (define (add [x : Integer] [y : Integer])
  7620. : Integer
  7621. (+ x y))
  7622. (add 40 2)
  7623. \end{lstlisting}
  7624. $\Downarrow$
  7625. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7626. (define (add86 [x87 : Integer]
  7627. [y88 : Integer]) : Integer
  7628. add86start:
  7629. return (+ x87 y88);
  7630. )
  7631. (define (main) : Integer ()
  7632. mainstart:
  7633. tmp89 = (fun-ref add86);
  7634. (tail-call tmp89 40 2)
  7635. )
  7636. \end{lstlisting}
  7637. \end{minipage}
  7638. &
  7639. $\Rightarrow$
  7640. \begin{minipage}{0.5\textwidth}
  7641. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7642. (define (add86) : Integer
  7643. add86start:
  7644. movq %rdi, x87
  7645. movq %rsi, y88
  7646. movq x87, %rax
  7647. addq y88, %rax
  7648. jmp add11389conclusion
  7649. )
  7650. (define (main) : Integer
  7651. mainstart:
  7652. leaq (fun-ref add86), tmp89
  7653. movq $40, %rdi
  7654. movq $2, %rsi
  7655. tail-jmp tmp89
  7656. )
  7657. \end{lstlisting}
  7658. $\Downarrow$
  7659. \end{minipage}
  7660. \end{tabular}
  7661. \begin{tabular}{ll}
  7662. \begin{minipage}{0.3\textwidth}
  7663. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7664. .globl add86
  7665. .align 16
  7666. add86:
  7667. pushq %rbp
  7668. movq %rsp, %rbp
  7669. jmp add86start
  7670. add86start:
  7671. movq %rdi, %rax
  7672. addq %rsi, %rax
  7673. jmp add86conclusion
  7674. add86conclusion:
  7675. popq %rbp
  7676. retq
  7677. \end{lstlisting}
  7678. \end{minipage}
  7679. &
  7680. \begin{minipage}{0.5\textwidth}
  7681. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7682. .globl main
  7683. .align 16
  7684. main:
  7685. pushq %rbp
  7686. movq %rsp, %rbp
  7687. movq $16384, %rdi
  7688. movq $16384, %rsi
  7689. callq initialize
  7690. movq rootstack_begin(%rip), %r15
  7691. jmp mainstart
  7692. mainstart:
  7693. leaq add86(%rip), %rcx
  7694. movq $40, %rdi
  7695. movq $2, %rsi
  7696. movq %rcx, %rax
  7697. popq %rbp
  7698. jmp *%rax
  7699. mainconclusion:
  7700. popq %rbp
  7701. retq
  7702. \end{lstlisting}
  7703. \end{minipage}
  7704. \end{tabular}
  7705. \caption{Example compilation of a simple function to x86.}
  7706. \label{fig:add-fun}
  7707. \end{figure}
  7708. % Challenge idea: inlining! (simple version)
  7709. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7710. \chapter{Lexically Scoped Functions}
  7711. \label{ch:lambdas}
  7712. \index{lambda}
  7713. \index{lexical scoping}
  7714. This chapter studies lexically scoped functions as they appear in
  7715. functional languages such as Racket. By lexical scoping we mean that a
  7716. function's body may refer to variables whose binding site is outside
  7717. of the function, in an enclosing scope.
  7718. %
  7719. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  7720. \LangLam{}, which extends \LangFun{} with anonymous functions using the
  7721. \key{lambda} form. The body of the \key{lambda}, refers to three
  7722. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  7723. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  7724. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  7725. parameter of function \code{f}. The \key{lambda} is returned from the
  7726. function \code{f}. The main expression of the program includes two
  7727. calls to \code{f} with different arguments for \code{x}, first
  7728. \code{5} then \code{3}. The functions returned from \code{f} are bound
  7729. to variables \code{g} and \code{h}. Even though these two functions
  7730. were created by the same \code{lambda}, they are really different
  7731. functions because they use different values for \code{x}. Applying
  7732. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  7733. \code{15} produces \code{22}. The result of this program is \code{42}.
  7734. \begin{figure}[btp]
  7735. % s4_6.rkt
  7736. \begin{lstlisting}
  7737. (define (f [x : Integer]) : (Integer -> Integer)
  7738. (let ([y 4])
  7739. (lambda: ([z : Integer]) : Integer
  7740. (+ x (+ y z)))))
  7741. (let ([g (f 5)])
  7742. (let ([h (f 3)])
  7743. (+ (g 11) (h 15))))
  7744. \end{lstlisting}
  7745. \caption{Example of a lexically scoped function.}
  7746. \label{fig:lexical-scoping}
  7747. \end{figure}
  7748. The approach that we take for implementing lexically scoped
  7749. functions is to compile them into top-level function definitions,
  7750. translating from \LangLam{} into \LangFun{}. However, the compiler will need to
  7751. provide special treatment for variable occurrences such as \code{x}
  7752. and \code{y} in the body of the \code{lambda} of
  7753. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function may not
  7754. refer to variables defined outside of it. To identify such variable
  7755. occurrences, we review the standard notion of free variable.
  7756. \begin{definition}
  7757. A variable is \emph{free in expression} $e$ if the variable occurs
  7758. inside $e$ but does not have an enclosing binding in $e$.\index{free
  7759. variable}
  7760. \end{definition}
  7761. For example, in the expression \code{(+ x (+ y z))} the variables
  7762. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  7763. only \code{x} and \code{y} are free in the following expression
  7764. because \code{z} is bound by the \code{lambda}.
  7765. \begin{lstlisting}
  7766. (lambda: ([z : Integer]) : Integer
  7767. (+ x (+ y z)))
  7768. \end{lstlisting}
  7769. So the free variables of a \code{lambda} are the ones that will need
  7770. special treatment. We need to arrange for some way to transport, at
  7771. runtime, the values of those variables from the point where the
  7772. \code{lambda} was created to the point where the \code{lambda} is
  7773. applied. An efficient solution to the problem, due to
  7774. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  7775. free variables together with the function pointer for the lambda's
  7776. code, an arrangement called a \emph{flat closure} (which we shorten to
  7777. just ``closure''). \index{closure}\index{flat closure} Fortunately,
  7778. we have all the ingredients to make closures, Chapter~\ref{ch:tuples}
  7779. gave us vectors and Chapter~\ref{ch:functions} gave us function
  7780. pointers. The function pointer resides at index $0$ and the
  7781. values for the free variables will fill in the rest of the vector.
  7782. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  7783. how closures work. It's a three-step dance. The program first calls
  7784. function \code{f}, which creates a closure for the \code{lambda}. The
  7785. closure is a vector whose first element is a pointer to the top-level
  7786. function that we will generate for the \code{lambda}, the second
  7787. element is the value of \code{x}, which is \code{5}, and the third
  7788. element is \code{4}, the value of \code{y}. The closure does not
  7789. contain an element for \code{z} because \code{z} is not a free
  7790. variable of the \code{lambda}. Creating the closure is step 1 of the
  7791. dance. The closure is returned from \code{f} and bound to \code{g}, as
  7792. shown in Figure~\ref{fig:closures}.
  7793. %
  7794. The second call to \code{f} creates another closure, this time with
  7795. \code{3} in the second slot (for \code{x}). This closure is also
  7796. returned from \code{f} but bound to \code{h}, which is also shown in
  7797. Figure~\ref{fig:closures}.
  7798. \begin{figure}[tbp]
  7799. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  7800. \caption{Example closure representation for the \key{lambda}'s
  7801. in Figure~\ref{fig:lexical-scoping}.}
  7802. \label{fig:closures}
  7803. \end{figure}
  7804. Continuing with the example, consider the application of \code{g} to
  7805. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  7806. obtain the function pointer in the first element of the closure and
  7807. call it, passing in the closure itself and then the regular arguments,
  7808. in this case \code{11}. This technique for applying a closure is step
  7809. 2 of the dance.
  7810. %
  7811. But doesn't this \code{lambda} only take 1 argument, for parameter
  7812. \code{z}? The third and final step of the dance is generating a
  7813. top-level function for a \code{lambda}. We add an additional
  7814. parameter for the closure and we insert a \code{let} at the beginning
  7815. of the function for each free variable, to bind those variables to the
  7816. appropriate elements from the closure parameter.
  7817. %
  7818. This three-step dance is known as \emph{closure conversion}. We
  7819. discuss the details of closure conversion in
  7820. Section~\ref{sec:closure-conversion} and the code generated from the
  7821. example in Section~\ref{sec:example-lambda}. But first we define the
  7822. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  7823. \section{The \LangLam{} Language}
  7824. \label{sec:r5}
  7825. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  7826. functions and lexical scoping, is defined in
  7827. Figures~\ref{fig:Rlam-concrete-syntax} and ~\ref{fig:Rlam-syntax}. It adds
  7828. the \key{lambda} form to the grammar for \LangFun{}, which already has
  7829. syntax for function application.
  7830. \begin{figure}[tp]
  7831. \centering
  7832. \fbox{
  7833. \begin{minipage}{0.96\textwidth}
  7834. \small
  7835. \[
  7836. \begin{array}{lcl}
  7837. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7838. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}
  7839. \mid (\Type\ldots \; \key{->}\; \Type)} \\
  7840. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  7841. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  7842. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  7843. &\mid& \gray{\key{\#t} \mid \key{\#f}
  7844. \mid (\key{and}\;\Exp\;\Exp)
  7845. \mid (\key{or}\;\Exp\;\Exp)
  7846. \mid (\key{not}\;\Exp) } \\
  7847. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  7848. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  7849. (\key{vector-ref}\;\Exp\;\Int)} \\
  7850. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  7851. \mid (\Exp \; \Exp\ldots) } \\
  7852. &\mid& \LP \key{procedure-arity}~\Exp\RP \\
  7853. &\mid& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  7854. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  7855. \LangLam{} &::=& \gray{\Def\ldots \; \Exp}
  7856. \end{array}
  7857. \]
  7858. \end{minipage}
  7859. }
  7860. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-concrete-syntax})
  7861. with \key{lambda}.}
  7862. \label{fig:Rlam-concrete-syntax}
  7863. \end{figure}
  7864. \begin{figure}[tp]
  7865. \centering
  7866. \fbox{
  7867. \begin{minipage}{0.96\textwidth}
  7868. \small
  7869. \[
  7870. \begin{array}{lcl}
  7871. \itm{op} &::=& \ldots \mid \code{procedure-arity} \\
  7872. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  7873. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  7874. &\mid& \gray{ \BOOL{\itm{bool}}
  7875. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  7876. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  7877. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  7878. &\mid& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  7879. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  7880. \LangLam{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  7881. \end{array}
  7882. \]
  7883. \end{minipage}
  7884. }
  7885. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-syntax}).}
  7886. \label{fig:Rlam-syntax}
  7887. \end{figure}
  7888. \index{interpreter}
  7889. \label{sec:interp-Rlambda}
  7890. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  7891. \LangLam{}. The case for \key{lambda} saves the current environment
  7892. inside the returned \key{lambda}. Then the case for \key{Apply} uses
  7893. the environment from the \key{lambda}, the \code{lam-env}, when
  7894. interpreting the body of the \key{lambda}. The \code{lam-env}
  7895. environment is extended with the mapping of parameters to argument
  7896. values.
  7897. \begin{figure}[tbp]
  7898. \begin{lstlisting}
  7899. (define interp-Rlambda-class
  7900. (class interp-Rfun-class
  7901. (super-new)
  7902. (define/override (interp-op op)
  7903. (match op
  7904. ['procedure-arity
  7905. (lambda (v)
  7906. (match v
  7907. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  7908. [else (error 'interp-op "expected a function, not ~a" v)]))]
  7909. [else (super interp-op op)]))
  7910. (define/override ((interp-exp env) e)
  7911. (define recur (interp-exp env))
  7912. (match e
  7913. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  7914. `(function ,xs ,body ,env)]
  7915. [else ((super interp-exp env) e)]))
  7916. ))
  7917. (define (interp-Rlambda p)
  7918. (send (new interp-Rlambda-class) interp-program p))
  7919. \end{lstlisting}
  7920. \caption{Interpreter for \LangLam{}.}
  7921. \label{fig:interp-Rlambda}
  7922. \end{figure}
  7923. \label{sec:type-check-r5}
  7924. \index{type checking}
  7925. Figure~\ref{fig:type-check-Rlambda} shows how to type check the new
  7926. \key{lambda} form. The body of the \key{lambda} is checked in an
  7927. environment that includes the current environment (because it is
  7928. lexically scoped) and also includes the \key{lambda}'s parameters. We
  7929. require the body's type to match the declared return type.
  7930. \begin{figure}[tbp]
  7931. \begin{lstlisting}
  7932. (define (type-check-Rlambda env)
  7933. (lambda (e)
  7934. (match e
  7935. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  7936. (define-values (new-body bodyT)
  7937. ((type-check-exp (append (map cons xs Ts) env)) body))
  7938. (define ty `(,@Ts -> ,rT))
  7939. (cond
  7940. [(equal? rT bodyT)
  7941. (values (HasType (Lambda params rT new-body) ty) ty)]
  7942. [else
  7943. (error "mismatch in return type" bodyT rT)])]
  7944. ...
  7945. )))
  7946. \end{lstlisting}
  7947. \caption{Type checking the \key{lambda}'s in \LangLam{}.}
  7948. \label{fig:type-check-Rlambda}
  7949. \end{figure}
  7950. \section{Reveal Functions and the $F_2$ language}
  7951. \label{sec:reveal-functions-r5}
  7952. To support the \code{procedure-arity} operator we need to communicate
  7953. the arity of a function to the point of closure creation. We can
  7954. accomplish this by replacing the $\FUNREF{\Var}$ struct with one that
  7955. has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$. The
  7956. output of this pass is the language $F_2$, whose syntax is defined in
  7957. Figure~\ref{fig:f2-syntax}.
  7958. \begin{figure}[tp]
  7959. \centering
  7960. \fbox{
  7961. \begin{minipage}{0.96\textwidth}
  7962. \[
  7963. \begin{array}{lcl}
  7964. \Exp &::=& \ldots \mid \FUNREFARITY{\Var}{\Int}\\
  7965. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7966. F_2 &::=& \gray{\PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}}
  7967. \end{array}
  7968. \]
  7969. \end{minipage}
  7970. }
  7971. \caption{The abstract syntax $F_2$, an extension of \LangLam{}
  7972. (Figure~\ref{fig:Rlam-syntax}).}
  7973. \label{fig:f2-syntax}
  7974. \end{figure}
  7975. \section{Closure Conversion}
  7976. \label{sec:closure-conversion}
  7977. \index{closure conversion}
  7978. The compiling of lexically-scoped functions into top-level function
  7979. definitions is accomplished in the pass \code{convert-to-closures}
  7980. that comes after \code{reveal-functions} and before
  7981. \code{limit-functions}.
  7982. As usual, we implement the pass as a recursive function over the
  7983. AST. All of the action is in the cases for \key{Lambda} and
  7984. \key{Apply}. We transform a \key{Lambda} expression into an expression
  7985. that creates a closure, that is, a vector whose first element is a
  7986. function pointer and the rest of the elements are the free variables
  7987. of the \key{Lambda}. We use the struct \code{Closure} here instead of
  7988. using \code{vector} so that we can distinguish closures from vectors
  7989. in Section~\ref{sec:optimize-closures} and to record the arity. In
  7990. the generated code below, the \itm{name} is a unique symbol generated
  7991. to identify the function and the \itm{arity} is the number of
  7992. parameters (the length of \itm{ps}).
  7993. \begin{lstlisting}
  7994. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  7995. |$\Rightarrow$|
  7996. (Closure |\itm{arity}| (cons (FunRef |\itm{name}|) |\itm{fvs}|))
  7997. \end{lstlisting}
  7998. In addition to transforming each \key{Lambda} into a \key{Closure}, we
  7999. create a top-level function definition for each \key{Lambda}, as
  8000. shown below.\\
  8001. \begin{minipage}{0.8\textwidth}
  8002. \begin{lstlisting}
  8003. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  8004. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  8005. ...
  8006. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  8007. |\itm{body'}|)...))
  8008. \end{lstlisting}
  8009. \end{minipage}\\
  8010. The \code{clos} parameter refers to the closure. Translate the type
  8011. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  8012. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The types
  8013. $\itm{fvts}$ are the types of the free variables in the lambda and the
  8014. underscore \code{\_} is a dummy type that we use because it is rather
  8015. difficult to give a type to the function in the closure's
  8016. type.\footnote{To give an accurate type to a closure, we would need to
  8017. add existential types to the type checker~\citep{Minamide:1996ys}.}
  8018. The dummy type is considered to be equal to any other type during type
  8019. checking. The sequence of \key{Let} forms bind the free variables to
  8020. their values obtained from the closure.
  8021. Closure conversion turns functions into vectors, so the type
  8022. annotations in the program must also be translated. We recommend
  8023. defining a auxiliary recursive function for this purpose. Function
  8024. types should be translated as follows.
  8025. \begin{lstlisting}
  8026. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  8027. |$\Rightarrow$|
  8028. (Vector ((Vector _) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  8029. \end{lstlisting}
  8030. The above type says that the first thing in the vector is a function
  8031. pointer. The first parameter of the function pointer is a vector (a
  8032. closure) and the rest of the parameters are the ones from the original
  8033. function, with types $T'_1, \ldots, T'_n$. The \code{Vector} type for
  8034. the closure omits the types of the free variables because 1) those
  8035. types are not available in this context and 2) we do not need them in
  8036. the code that is generated for function application.
  8037. We transform function application into code that retrieves the
  8038. function pointer from the closure and then calls the function, passing
  8039. in the closure as the first argument. We bind $e'$ to a temporary
  8040. variable to avoid code duplication.
  8041. \begin{lstlisting}
  8042. (Apply |$e$| |\itm{es}|)
  8043. |$\Rightarrow$|
  8044. (Let |\itm{tmp}| |$e'$|
  8045. (Apply (Prim 'vector-ref (list (Var |\itm{tmp}|) (Int 0))) (cons |\itm{tmp}| |\itm{es'}|)))
  8046. \end{lstlisting}
  8047. There is also the question of what to do with references top-level
  8048. function definitions. To maintain a uniform translation of function
  8049. application, we turn function references into closures.
  8050. \begin{tabular}{lll}
  8051. \begin{minipage}{0.3\textwidth}
  8052. \begin{lstlisting}
  8053. (FunRefArity |$f$| |$n$|)
  8054. \end{lstlisting}
  8055. \end{minipage}
  8056. &
  8057. $\Rightarrow$
  8058. &
  8059. \begin{minipage}{0.5\textwidth}
  8060. \begin{lstlisting}
  8061. (Closure |$n$| (FunRef |$f$|) '())
  8062. \end{lstlisting}
  8063. \end{minipage}
  8064. \end{tabular} \\
  8065. %
  8066. The top-level function definitions need to be updated as well to take
  8067. an extra closure parameter.
  8068. \section{An Example Translation}
  8069. \label{sec:example-lambda}
  8070. Figure~\ref{fig:lexical-functions-example} shows the result of
  8071. \code{reveal-functions} and \code{convert-to-closures} for the example
  8072. program demonstrating lexical scoping that we discussed at the
  8073. beginning of this chapter.
  8074. \begin{figure}[tbp]
  8075. \begin{minipage}{0.8\textwidth}
  8076. % tests/lambda_test_6.rkt
  8077. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8078. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  8079. (let ([y8 4])
  8080. (lambda: ([z9 : Integer]) : Integer
  8081. (+ x7 (+ y8 z9)))))
  8082. (define (main) : Integer
  8083. (let ([g0 ((fun-ref-arity f6 1) 5)])
  8084. (let ([h1 ((fun-ref-arity f6 1) 3)])
  8085. (+ (g0 11) (h1 15)))))
  8086. \end{lstlisting}
  8087. $\Rightarrow$
  8088. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8089. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  8090. (let ([y8 4])
  8091. (closure 1 (list (fun-ref lambda2) x7 y8))))
  8092. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  8093. (let ([x7 (vector-ref fvs3 1)])
  8094. (let ([y8 (vector-ref fvs3 2)])
  8095. (+ x7 (+ y8 z9)))))
  8096. (define (main) : Integer
  8097. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6)))])
  8098. ((vector-ref clos5 0) clos5 5))])
  8099. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6)))])
  8100. ((vector-ref clos6 0) clos6 3))])
  8101. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  8102. \end{lstlisting}
  8103. \end{minipage}
  8104. \caption{Example of closure conversion.}
  8105. \label{fig:lexical-functions-example}
  8106. \end{figure}
  8107. \begin{exercise}\normalfont
  8108. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  8109. Create 5 new programs that use \key{lambda} functions and make use of
  8110. lexical scoping. Test your compiler on these new programs and all of
  8111. your previously created test programs.
  8112. \end{exercise}
  8113. \section{Expose Allocation}
  8114. \label{sec:expose-allocation-r5}
  8115. Compile the $\CLOSURE{\itm{arity}}{\LP\Exp\ldots\RP}$ form into code
  8116. that allocates and initializes a vector, similar to the translation of
  8117. the \code{vector} operator in Section~\ref{sec:expose-allocation}.
  8118. The only difference is replacing the use of
  8119. \ALLOC{\itm{len}}{\itm{type}} with
  8120. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  8121. \section{Explicate Control and \LangCLam{}}
  8122. \label{sec:explicate-r5}
  8123. The output language of \code{explicate-control} is \LangCLam{} whose
  8124. abstract syntax is defined in Figure~\ref{fig:c4-syntax}. The only
  8125. difference with respect to \LangCFun{} is the addition of the
  8126. \code{AllocateClosure} form to the grammar for $\Exp$. The handling
  8127. of \code{AllocateClosure} in the \code{explicate-control} pass is
  8128. similar to the handling of other expressions such as primitive
  8129. operators.
  8130. \begin{figure}[tp]
  8131. \fbox{
  8132. \begin{minipage}{0.96\textwidth}
  8133. \small
  8134. \[
  8135. \begin{array}{lcl}
  8136. \Exp &::= & \ldots
  8137. \mid \ALLOCCLOS{\Int}{\Type}{\Int} \\
  8138. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  8139. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  8140. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  8141. \mid \GOTO{\itm{label}} } \\
  8142. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  8143. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  8144. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  8145. \LangCLam{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  8146. \end{array}
  8147. \]
  8148. \end{minipage}
  8149. }
  8150. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  8151. \label{fig:c4-syntax}
  8152. \end{figure}
  8153. \section{Select Instructions}
  8154. \label{sec:select-instructions-Rlambda}
  8155. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  8156. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  8157. (Section~\ref{sec:select-instructions-gc}). The only difference is
  8158. that you should place the \itm{arity} in the tag that is stored at
  8159. position $0$ of the vector. Recall that in
  8160. Section~\ref{sec:select-instructions-gc} we used the first $56$ bits
  8161. of the 64-bit tag, but that the rest were unused. So the arity goes
  8162. into the tag in bit positions $57$ through $63$.
  8163. Compile the \code{procedure-arity} operator into a sequence of
  8164. instructions that access the tag from position $0$ of the vector and
  8165. shift it by $57$ bits to the right.
  8166. \begin{figure}[p]
  8167. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8168. \node (Rfun) at (0,2) {\large \LangFun{}};
  8169. \node (Rfun-2) at (3,2) {\large \LangFun{}};
  8170. \node (Rfun-3) at (6,2) {\large \LangFun{}};
  8171. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  8172. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  8173. \node (F1-3) at (6,0) {\large $F_1$};
  8174. \node (F1-4) at (3,0) {\large $F_1$};
  8175. \node (F1-5) at (0,0) {\large $F_1$};
  8176. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  8177. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  8178. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  8179. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  8180. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  8181. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  8182. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  8183. \path[->,bend left=15] (Rfun) edge [above] node
  8184. {\ttfamily\footnotesize shrink} (Rfun-2);
  8185. \path[->,bend left=15] (Rfun-2) edge [above] node
  8186. {\ttfamily\footnotesize uniquify} (Rfun-3);
  8187. \path[->,bend left=15] (Rfun-3) edge [right] node
  8188. {\ttfamily\footnotesize reveal-functions} (F1-1);
  8189. \path[->,bend left=15] (F1-1) edge [below] node
  8190. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  8191. \path[->,bend right=15] (F1-2) edge [above] node
  8192. {\ttfamily\footnotesize limit-fun.} (F1-3);
  8193. \path[->,bend right=15] (F1-3) edge [above] node
  8194. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  8195. \path[->,bend right=15] (F1-4) edge [above] node
  8196. {\ttfamily\footnotesize remove-complex.} (F1-5);
  8197. \path[->,bend right=15] (F1-5) edge [right] node
  8198. {\ttfamily\footnotesize explicate-control} (C3-2);
  8199. \path[->,bend left=15] (C3-2) edge [left] node
  8200. {\ttfamily\footnotesize select-instr.} (x86-2);
  8201. \path[->,bend right=15] (x86-2) edge [left] node
  8202. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  8203. \path[->,bend right=15] (x86-2-1) edge [below] node
  8204. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  8205. \path[->,bend right=15] (x86-2-2) edge [left] node
  8206. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  8207. \path[->,bend left=15] (x86-3) edge [above] node
  8208. {\ttfamily\footnotesize patch-instr.} (x86-4);
  8209. \path[->,bend left=15] (x86-4) edge [right] node
  8210. {\ttfamily\footnotesize print-x86} (x86-5);
  8211. \end{tikzpicture}
  8212. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  8213. functions.}
  8214. \label{fig:Rlambda-passes}
  8215. \end{figure}
  8216. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  8217. for the compilation of \LangLam{}.
  8218. \clearpage
  8219. \section{Challenge: Optimize Closures}
  8220. \label{sec:optimize-closures}
  8221. In this chapter we compiled lexically-scoped functions into a
  8222. relatively efficient representation: flat closures. However, even this
  8223. representation comes with some overhead. For example, consider the
  8224. following program with a function \code{tail-sum} that does not have
  8225. any free variables and where all the uses of \code{tail-sum} are in
  8226. applications where we know that only \code{tail-sum} is being applied
  8227. (and not any other functions).
  8228. \begin{center}
  8229. \begin{minipage}{0.95\textwidth}
  8230. \begin{lstlisting}
  8231. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  8232. (if (eq? n 0)
  8233. r
  8234. (tail-sum (- n 1) (+ n r))))
  8235. (+ (tail-sum 5 0) 27)
  8236. \end{lstlisting}
  8237. \end{minipage}
  8238. \end{center}
  8239. As described in this chapter, we uniformly apply closure conversion to
  8240. all functions, obtaining the following output for this program.
  8241. \begin{center}
  8242. \begin{minipage}{0.95\textwidth}
  8243. \begin{lstlisting}
  8244. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [r3 : Integer]) : Integer
  8245. (if (eq? n2 0)
  8246. r3
  8247. (let ([clos4 (closure (list (fun-ref tail_sum1)))])
  8248. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 r3)))))
  8249. (define (main) : Integer
  8250. (+ (let ([clos6 (closure (list (fun-ref tail_sum1)))])
  8251. ((vector-ref clos6 0) clos6 5 0)) 27))
  8252. \end{lstlisting}
  8253. \end{minipage}
  8254. \end{center}
  8255. In the previous Chapter, there would be no allocation in the program
  8256. and the calls to \code{tail-sum} would be direct calls. In contrast,
  8257. the above program allocates memory for each \code{closure} and the
  8258. calls to \code{tail-sum} are indirect. These two differences incur
  8259. considerable overhead in a program such as this one, where the
  8260. allocations and indirect calls occur inside a tight loop.
  8261. One might think that this problem is trivial to solve: can't we just
  8262. recognize calls of the form \code{((fun-ref $f$) $e_1 \ldots e_n$)}
  8263. and compile them to direct calls \code{((fun-ref $f$) $e'_1 \ldots
  8264. e'_n$)} instead of treating it like a call to a closure? We would
  8265. also drop the \code{fvs5} parameter of \code{tail\_sum1}.
  8266. %
  8267. However, this problem is not so trivial because a global function may
  8268. ``escape'' and become involved in applications that also involve
  8269. closures. Consider the following example in which the application
  8270. \code{(f 41)} needs to be compiled into a closure application, because
  8271. the \code{lambda} may get bound to \code{f}, but the \code{add1}
  8272. function might also get bound to \code{f}.
  8273. \begin{lstlisting}
  8274. (define (add1 [x : Integer]) : Integer
  8275. (+ x 1))
  8276. (let ([y (read)])
  8277. (let ([f (if (eq? (read) 0)
  8278. add1
  8279. (lambda: ([x : Integer]) : Integer (- x y)))])
  8280. (f 41)))
  8281. \end{lstlisting}
  8282. If a global function name is used in any way other than as the
  8283. operator in a direct call, then we say that the function
  8284. \emph{escapes}. If a global function does not escape, then we do not
  8285. need to perform closure conversion on the function.
  8286. \begin{exercise}\normalfont
  8287. Implement an auxiliary function for detecting which global
  8288. functions escape. Using that function, implement an improved version
  8289. of closure conversion that does not apply closure conversion to
  8290. global functions that do not escape but instead compiles them as
  8291. regular functions. Create several new test cases that check whether
  8292. you properly detect whether global functions escape or not.
  8293. \end{exercise}
  8294. So far we have reduced the overhead of calling global functions, but
  8295. it would also be nice to reduce the overhead of calling a
  8296. \code{lambda} when we can determine at compile time which
  8297. \code{lambda} will be called. We refer to such calls as \emph{known
  8298. calls}. Consider the following example in which a \code{lambda} is
  8299. bound to \code{f} and then applied.
  8300. \begin{lstlisting}
  8301. (let ([y (read)])
  8302. (let ([f (lambda: ([x : Integer]) : Integer
  8303. (+ x y))])
  8304. (f 21)))
  8305. \end{lstlisting}
  8306. Closure conversion compiles \code{(f 21)} into an indirect call:
  8307. \begin{lstlisting}
  8308. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  8309. (let ([y2 (vector-ref fvs6 1)])
  8310. (+ x3 y2)))
  8311. (define (main) : Integer
  8312. (let ([y2 (read)])
  8313. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  8314. ((vector-ref f4 0) f4 21))))
  8315. \end{lstlisting}
  8316. but we can instead compile the application \code{(f 21)} into a direct call
  8317. to \code{lambda5}:
  8318. \begin{lstlisting}
  8319. (define (main) : Integer
  8320. (let ([y2 (read)])
  8321. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  8322. ((fun-ref lambda5) f4 21))))
  8323. \end{lstlisting}
  8324. The problem of determining which lambda will be called from a
  8325. particular application is quite challenging in general and the topic
  8326. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  8327. following exercise we recommend that you compile an application to a
  8328. direct call when the operator is a variable and the variable is
  8329. \code{let}-bound to a closure. This can be accomplished by maintaining
  8330. an environment mapping \code{let}-bound variables to function names.
  8331. Extend the environment whenever you encounter a closure on the
  8332. right-hand side of a \code{let}, mapping the \code{let}-bound variable
  8333. to the name of the global function for the closure. This pass should
  8334. come after closure conversion.
  8335. \begin{exercise}\normalfont
  8336. Implement a compiler pass, named \code{optimize-known-calls}, that
  8337. compiles known calls into direct calls. Verify that your compiler is
  8338. successful in this regard on several example programs.
  8339. \end{exercise}
  8340. These exercises only scratches the surface of optimizing of
  8341. closures. A good next step for the interested reader is to look at the
  8342. work of \citet{Keep:2012ab}.
  8343. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8344. \chapter{Dynamic Typing}
  8345. \label{ch:type-dynamic}
  8346. \index{dynamic typing}
  8347. In this chapter we discuss the compilation of \LangDyn{}, a dynamically
  8348. typed language that is a subset of Racket. This is in contrast to the
  8349. previous chapters, which have studied the compilation of Typed
  8350. Racket. In dynamically typed languages such as \LangDyn{}, a given
  8351. expression may produce a value of a different type each time it is
  8352. executed. Consider the following example with a conditional \code{if}
  8353. expression that may return a Boolean or an integer depending on the
  8354. input to the program.
  8355. % part of dynamic_test_25.rkt
  8356. \begin{lstlisting}
  8357. (not (if (eq? (read) 1) #f 0))
  8358. \end{lstlisting}
  8359. Languages that allow expressions to produce different kinds of values
  8360. are called \emph{polymorphic}, a word composed of the Greek roots
  8361. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  8362. are several kinds of polymorphism in programming languages, such as
  8363. subtype polymorphism and parametric
  8364. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  8365. study in this chapter does not have a special name but it is the kind
  8366. that arises in dynamically typed languages.
  8367. Another characteristic of dynamically typed languages is that
  8368. primitive operations, such as \code{not}, are often defined to operate
  8369. on many different types of values. In fact, in Racket, the \code{not}
  8370. operator produces a result for any kind of value: given \code{\#f} it
  8371. returns \code{\#t} and given anything else it returns \code{\#f}.
  8372. Furthermore, even when primitive operations restrict their inputs to
  8373. values of a certain type, this restriction is enforced at runtime
  8374. instead of during compilation. For example, the following vector
  8375. reference results in a run-time contract violation because the index
  8376. must be in integer, not a Boolean such as \code{\#t}.
  8377. \begin{lstlisting}
  8378. (vector-ref (vector 42) #t)
  8379. \end{lstlisting}
  8380. \begin{figure}[tp]
  8381. \centering
  8382. \fbox{
  8383. \begin{minipage}{0.97\textwidth}
  8384. \[
  8385. \begin{array}{rcl}
  8386. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  8387. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp}
  8388. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} \\
  8389. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  8390. &\mid& \key{\#t} \mid \key{\#f}
  8391. \mid \CBINOP{\key{and}}{\Exp}{\Exp}
  8392. \mid \CBINOP{\key{or}}{\Exp}{\Exp}
  8393. \mid \CUNIOP{\key{not}}{\Exp} \\
  8394. &\mid& \LP\itm{cmp}\;\Exp\;\Exp\RP \mid \CIF{\Exp}{\Exp}{\Exp} \\
  8395. &\mid& \LP\key{vector}\;\Exp\ldots\RP \mid
  8396. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  8397. &\mid& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \mid \LP\key{void}\RP \\
  8398. &\mid& \LP\Exp \; \Exp\ldots\RP
  8399. \mid \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  8400. & \mid & \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP\\
  8401. & \mid & \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \mid \LP\key{void?}\;\Exp\RP \\
  8402. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  8403. \LangDyn{} &::=& \Def\ldots\; \Exp
  8404. \end{array}
  8405. \]
  8406. \end{minipage}
  8407. }
  8408. \caption{Syntax of \LangDyn{}, an untyped language (a subset of Racket).}
  8409. \label{fig:r7-concrete-syntax}
  8410. \end{figure}
  8411. \begin{figure}[tp]
  8412. \centering
  8413. \fbox{
  8414. \begin{minipage}{0.96\textwidth}
  8415. \small
  8416. \[
  8417. \begin{array}{lcl}
  8418. \Exp &::=& \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  8419. &\mid& \PRIM{\itm{op}}{\Exp\ldots} \\
  8420. &\mid& \BOOL{\itm{bool}}
  8421. \mid \IF{\Exp}{\Exp}{\Exp} \\
  8422. &\mid& \VOID{} \mid \APPLY{\Exp}{\Exp\ldots} \\
  8423. &\mid& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  8424. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  8425. \LangDyn{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  8426. \end{array}
  8427. \]
  8428. \end{minipage}
  8429. }
  8430. \caption{The abstract syntax of \LangDyn{}.}
  8431. \label{fig:r7-syntax}
  8432. \end{figure}
  8433. The concrete and abstract syntax of \LangDyn{}, our subset of Racket, is
  8434. defined in Figures~\ref{fig:r7-concrete-syntax} and
  8435. \ref{fig:r7-syntax}.
  8436. %
  8437. There is no type checker for \LangDyn{} because it is not a statically
  8438. typed language (it's dynamically typed!).
  8439. The definitional interpreter for \LangDyn{} is presented in
  8440. Figure~\ref{fig:interp-Rdyn} and its auxiliary functions are defined in
  8441. Figure~\ref{fig:interp-Rdyn-aux}. Consider the match case for
  8442. \code{(Int n)}. Instead of simply returning the integer \code{n} (as
  8443. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Rvar}), the
  8444. interpreter for \LangDyn{} creates a \emph{tagged value}\index{tagged
  8445. value} that combines an underlying value with a tag that identifies
  8446. what kind of value it is. We define the following struct
  8447. to represented tagged values.
  8448. \begin{lstlisting}
  8449. (struct Tagged (value tag) #:transparent)
  8450. \end{lstlisting}
  8451. The tags are \code{Integer}, \code{Boolean}, \code{Void},
  8452. \code{Vector}, and \code{Procedure}. Tags are closely related to types
  8453. but don't always capture all the information that a type does. For
  8454. example, a vector of type \code{(Vector Any Any)} is tagged with
  8455. \code{Vector} and a procedure of type \code{(Any Any -> Any)}
  8456. is tagged with \code{Procedure}.
  8457. Next consider the match case for \code{vector-ref}. The
  8458. \code{check-tag} auxiliary function (Figure~\ref{fig:interp-Rdyn-aux})
  8459. is used to ensure that the first argument is a vector and the second
  8460. is an integer. If they are not, a \code{trapped-error} is raised.
  8461. Recall from Section~\ref{sec:interp-Rint} that when a definition
  8462. interpreter raises a \code{trapped-error} error, the compiled code
  8463. must also signal an error by exiting with return code \code{255}. A
  8464. \code{trapped-error} is also raised if the index is not less than
  8465. length of the vector.
  8466. \begin{figure}[tbp]
  8467. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8468. (define ((interp-Rdyn-exp env) ast)
  8469. (define recur (interp-Rdyn-exp env))
  8470. (match ast
  8471. [(Var x) (lookup x env)]
  8472. [(Int n) (Tagged n 'Integer)]
  8473. [(Bool b) (Tagged b 'Boolean)]
  8474. [(Lambda xs rt body)
  8475. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  8476. [(Prim 'vector es)
  8477. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  8478. [(Prim 'vector-ref (list e1 e2))
  8479. (define vec (recur e1)) (define i (recur e2))
  8480. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  8481. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  8482. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  8483. (vector-ref (Tagged-value vec) (Tagged-value i))]
  8484. [(Prim 'vector-set! (list e1 e2 e3))
  8485. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  8486. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  8487. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  8488. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  8489. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  8490. (Tagged (void) 'Void)]
  8491. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  8492. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  8493. [(Prim 'or (list e1 e2))
  8494. (define v1 (recur e1))
  8495. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  8496. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  8497. [(Prim op (list e1))
  8498. #:when (set-member? type-predicates op)
  8499. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  8500. [(Prim op es)
  8501. (define args (map recur es))
  8502. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  8503. (unless (for/or ([expected-tags (op-tags op)])
  8504. (equal? expected-tags tags))
  8505. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  8506. (tag-value
  8507. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  8508. [(If q t f)
  8509. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  8510. [(Apply f es)
  8511. (define new-f (recur f)) (define args (map recur es))
  8512. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  8513. (match f-val
  8514. [`(function ,xs ,body ,lam-env)
  8515. (unless (eq? (length xs) (length args))
  8516. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  8517. (define new-env (append (map cons xs args) lam-env))
  8518. ((interp-Rdyn-exp new-env) body)]
  8519. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  8520. \end{lstlisting}
  8521. \caption{Interpreter for the \LangDyn{} language.}
  8522. \label{fig:interp-Rdyn}
  8523. \end{figure}
  8524. \begin{figure}[tbp]
  8525. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8526. (define (interp-op op)
  8527. (match op
  8528. ['+ fx+]
  8529. ['- fx-]
  8530. ['read read-fixnum]
  8531. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  8532. ['< (lambda (v1 v2)
  8533. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  8534. ['<= (lambda (v1 v2)
  8535. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  8536. ['> (lambda (v1 v2)
  8537. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  8538. ['>= (lambda (v1 v2)
  8539. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  8540. ['boolean? boolean?]
  8541. ['integer? fixnum?]
  8542. ['void? void?]
  8543. ['vector? vector?]
  8544. ['vector-length vector-length]
  8545. ['procedure? (match-lambda
  8546. [`(functions ,xs ,body ,env) #t] [else #f])]
  8547. [else (error 'interp-op "unknown operator" op)]))
  8548. (define (op-tags op)
  8549. (match op
  8550. ['+ '((Integer Integer))]
  8551. ['- '((Integer Integer) (Integer))]
  8552. ['read '(())]
  8553. ['not '((Boolean))]
  8554. ['< '((Integer Integer))]
  8555. ['<= '((Integer Integer))]
  8556. ['> '((Integer Integer))]
  8557. ['>= '((Integer Integer))]
  8558. ['vector-length '((Vector))]))
  8559. (define type-predicates
  8560. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  8561. (define (tag-value v)
  8562. (cond [(boolean? v) (Tagged v 'Boolean)]
  8563. [(fixnum? v) (Tagged v 'Integer)]
  8564. [(procedure? v) (Tagged v 'Procedure)]
  8565. [(vector? v) (Tagged v 'Vector)]
  8566. [(void? v) (Tagged v 'Void)]
  8567. [else (error 'tag-value "unidentified value ~a" v)]))
  8568. (define (check-tag val expected ast)
  8569. (define tag (Tagged-tag val))
  8570. (unless (eq? tag expected)
  8571. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  8572. \end{lstlisting}
  8573. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  8574. \label{fig:interp-Rdyn-aux}
  8575. \end{figure}
  8576. \clearpage
  8577. \section{Representation of Tagged Values}
  8578. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  8579. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  8580. values at the bit level. Because almost every operation in \LangDyn{}
  8581. involves manipulating tagged values, the representation must be
  8582. efficient. Recall that all of our values are 64 bits. We shall steal
  8583. the 3 right-most bits to encode the tag. We use $001$ to identify
  8584. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  8585. and $101$ for the void value. We define the following auxiliary
  8586. function for mapping types to tag codes.
  8587. \begin{align*}
  8588. \itm{tagof}(\key{Integer}) &= 001 \\
  8589. \itm{tagof}(\key{Boolean}) &= 100 \\
  8590. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  8591. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  8592. \itm{tagof}(\key{Void}) &= 101
  8593. \end{align*}
  8594. This stealing of 3 bits comes at some price: our integers are reduced
  8595. to ranging from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  8596. affect vectors and procedures because those values are addresses, and
  8597. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  8598. they are always $000$. Thus, we do not lose information by overwriting
  8599. the rightmost 3 bits with the tag and we can simply zero-out the tag
  8600. to recover the original address.
  8601. To make tagged values into first-class entities, we can give them a
  8602. type, called \code{Any}, and define operations such as \code{Inject}
  8603. and \code{Project} for creating and using them, yielding the \LangAny{}
  8604. intermediate language. We describe how to compile \LangDyn{} to \LangAny{} in
  8605. Section~\ref{sec:compile-r7} but first we describe the \LangAny{} language
  8606. in greater detail.
  8607. \section{The \LangAny{} Language}
  8608. \label{sec:r6-lang}
  8609. \begin{figure}[tp]
  8610. \centering
  8611. \fbox{
  8612. \begin{minipage}{0.96\textwidth}
  8613. \small
  8614. \[
  8615. \begin{array}{lcl}
  8616. \Type &::= & \ldots \mid \key{Any} \\
  8617. \itm{op} &::= & \ldots \mid \code{any-vector-length}
  8618. \mid \code{any-vector-ref} \mid \code{any-vector-set!}\\
  8619. &\mid& \code{boolean?} \mid \code{integer?} \mid \code{vector?}
  8620. \mid \code{procedure?} \mid \code{void?} \\
  8621. \Exp &::=& \ldots
  8622. \mid \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  8623. &\mid& \INJECT{\Exp}{\FType} \mid \PROJECT{\Exp}{\FType} \\
  8624. \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  8625. \LangAny{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  8626. \end{array}
  8627. \]
  8628. \end{minipage}
  8629. }
  8630. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Rlam-syntax}).}
  8631. \label{fig:r6-syntax}
  8632. \end{figure}
  8633. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:r6-syntax}.
  8634. (The concrete syntax of \LangAny{} is in the Appendix,
  8635. Figure~\ref{fig:r6-concrete-syntax}.) The $\INJECT{e}{T}$ form
  8636. converts the value produced by expression $e$ of type $T$ into a
  8637. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  8638. produced by expression $e$ into a value of type $T$ or else halts the
  8639. program if the type tag is not equivalent to $T$.
  8640. %
  8641. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  8642. restricted to a flat type $\FType$, which simplifies the
  8643. implementation and corresponds with what is needed for compiling \LangDyn{}.
  8644. The \code{any-vector} operators adapt the vector operations so that
  8645. they can be applied to a value of type \code{Any}. They also
  8646. generalize the vector operations in that the index is not restricted
  8647. to be a literal integer in the grammar but is allowed to be any
  8648. expression.
  8649. The type predicates such as \key{boolean?} expect their argument to
  8650. produce a tagged value; they return \key{\#t} if the tag corresponds
  8651. to the predicate and they return \key{\#f} otherwise.
  8652. The type checker for \LangAny{} is shown in
  8653. Figures~\ref{fig:type-check-Rany-part-1} and
  8654. \ref{fig:type-check-Rany-part-2} and uses the auxiliary functions in
  8655. Figure~\ref{fig:type-check-Rany-aux}.
  8656. %
  8657. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Rany} and the
  8658. auxiliary functions \code{apply-inject} and \code{apply-project} are
  8659. in Figure~\ref{fig:apply-project}.
  8660. \begin{figure}[btp]
  8661. \begin{lstlisting}[basicstyle=\ttfamily\small]
  8662. (define type-check-Rany-class
  8663. (class type-check-Rlambda-class
  8664. (super-new)
  8665. (inherit check-type-equal?)
  8666. (define/override (type-check-exp env)
  8667. (lambda (e)
  8668. (define recur (type-check-exp env))
  8669. (match e
  8670. [(Inject e1 ty)
  8671. (unless (flat-ty? ty)
  8672. (error 'type-check "may only inject from flat type, not ~a" ty))
  8673. (define-values (new-e1 e-ty) (recur e1))
  8674. (check-type-equal? e-ty ty e)
  8675. (values (Inject new-e1 ty) 'Any)]
  8676. [(Project e1 ty)
  8677. (unless (flat-ty? ty)
  8678. (error 'type-check "may only project to flat type, not ~a" ty))
  8679. (define-values (new-e1 e-ty) (recur e1))
  8680. (check-type-equal? e-ty 'Any e)
  8681. (values (Project new-e1 ty) ty)]
  8682. [(Prim 'any-vector-length (list e1))
  8683. (define-values (e1^ t1) (recur e1))
  8684. (check-type-equal? t1 'Any e)
  8685. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  8686. [(Prim 'any-vector-ref (list e1 e2))
  8687. (define-values (e1^ t1) (recur e1))
  8688. (define-values (e2^ t2) (recur e2))
  8689. (check-type-equal? t1 'Any e)
  8690. (check-type-equal? t2 'Integer e)
  8691. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  8692. [(Prim 'any-vector-set! (list e1 e2 e3))
  8693. (define-values (e1^ t1) (recur e1))
  8694. (define-values (e2^ t2) (recur e2))
  8695. (define-values (e3^ t3) (recur e3))
  8696. (check-type-equal? t1 'Any e)
  8697. (check-type-equal? t2 'Integer e)
  8698. (check-type-equal? t3 'Any e)
  8699. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  8700. \end{lstlisting}
  8701. \caption{Type checker for the \LangAny{} language, part 1.}
  8702. \label{fig:type-check-Rany-part-1}
  8703. \end{figure}
  8704. \begin{figure}[btp]
  8705. \begin{lstlisting}[basicstyle=\ttfamily\small]
  8706. [(ValueOf e ty)
  8707. (define-values (new-e e-ty) (recur e))
  8708. (values (ValueOf new-e ty) ty)]
  8709. [(Prim pred (list e1))
  8710. #:when (set-member? (type-predicates) pred)
  8711. (define-values (new-e1 e-ty) (recur e1))
  8712. (check-type-equal? e-ty 'Any e)
  8713. (values (Prim pred (list new-e1)) 'Boolean)]
  8714. [(If cnd thn els)
  8715. (define-values (cnd^ Tc) (recur cnd))
  8716. (define-values (thn^ Tt) (recur thn))
  8717. (define-values (els^ Te) (recur els))
  8718. (check-type-equal? Tc 'Boolean cnd)
  8719. (check-type-equal? Tt Te e)
  8720. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  8721. [(Exit) (values (Exit) '_)]
  8722. [(Prim 'eq? (list arg1 arg2))
  8723. (define-values (e1 t1) (recur arg1))
  8724. (define-values (e2 t2) (recur arg2))
  8725. (match* (t1 t2)
  8726. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  8727. [(other wise) (check-type-equal? t1 t2 e)])
  8728. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  8729. [else ((super type-check-exp env) e)])))
  8730. ))
  8731. \end{lstlisting}
  8732. \caption{Type checker for the \LangAny{} language, part 2.}
  8733. \label{fig:type-check-Rany-part-2}
  8734. \end{figure}
  8735. \begin{figure}[tbp]
  8736. \begin{lstlisting}
  8737. (define/override (operator-types)
  8738. (append
  8739. '((integer? . ((Any) . Boolean))
  8740. (vector? . ((Any) . Boolean))
  8741. (procedure? . ((Any) . Boolean))
  8742. (void? . ((Any) . Boolean))
  8743. (tag-of-any . ((Any) . Integer))
  8744. (make-any . ((_ Integer) . Any))
  8745. )
  8746. (super operator-types)))
  8747. (define/public (type-predicates)
  8748. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  8749. (define/public (combine-types t1 t2)
  8750. (match (list t1 t2)
  8751. [(list '_ t2) t2]
  8752. [(list t1 '_) t1]
  8753. [(list `(Vector ,ts1 ...)
  8754. `(Vector ,ts2 ...))
  8755. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  8756. (combine-types t1 t2)))]
  8757. [(list `(,ts1 ... -> ,rt1)
  8758. `(,ts2 ... -> ,rt2))
  8759. `(,@(for/list ([t1 ts1] [t2 ts2])
  8760. (combine-types t1 t2))
  8761. -> ,(combine-types rt1 rt2))]
  8762. [else t1]))
  8763. (define/public (flat-ty? ty)
  8764. (match ty
  8765. [(or `Integer `Boolean '_ `Void) #t]
  8766. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  8767. [`(,ts ... -> ,rt)
  8768. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  8769. [else #f]))
  8770. \end{lstlisting}
  8771. \caption{Auxiliary methods for type checking \LangAny{}.}
  8772. \label{fig:type-check-Rany-aux}
  8773. \end{figure}
  8774. \begin{figure}[btp]
  8775. \begin{lstlisting}
  8776. (define interp-Rany-class
  8777. (class interp-Rlambda-class
  8778. (super-new)
  8779. (define/override (interp-op op)
  8780. (match op
  8781. ['boolean? (match-lambda
  8782. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  8783. [else #f])]
  8784. ['integer? (match-lambda
  8785. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  8786. [else #f])]
  8787. ['vector? (match-lambda
  8788. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  8789. [else #f])]
  8790. ['procedure? (match-lambda
  8791. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  8792. [else #f])]
  8793. ['eq? (match-lambda*
  8794. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  8795. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  8796. [ls (apply (super interp-op op) ls)])]
  8797. ['any-vector-ref (lambda (v i)
  8798. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  8799. ['any-vector-set! (lambda (v i a)
  8800. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  8801. ['any-vector-length (lambda (v)
  8802. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  8803. [else (super interp-op op)]))
  8804. (define/override ((interp-exp env) e)
  8805. (define recur (interp-exp env))
  8806. (match e
  8807. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  8808. [(Project e ty2) (apply-project (recur e) ty2)]
  8809. [else ((super interp-exp env) e)]))
  8810. ))
  8811. (define (interp-Rany p)
  8812. (send (new interp-Rany-class) interp-program p))
  8813. \end{lstlisting}
  8814. \caption{Interpreter for \LangAny{}.}
  8815. \label{fig:interp-Rany}
  8816. \end{figure}
  8817. \begin{figure}[tbp]
  8818. \begin{lstlisting}
  8819. (define/public (apply-inject v tg) (Tagged v tg))
  8820. (define/public (apply-project v ty2)
  8821. (define tag2 (any-tag ty2))
  8822. (match v
  8823. [(Tagged v1 tag1)
  8824. (cond
  8825. [(eq? tag1 tag2)
  8826. (match ty2
  8827. [`(Vector ,ts ...)
  8828. (define l1 ((interp-op 'vector-length) v1))
  8829. (cond
  8830. [(eq? l1 (length ts)) v1]
  8831. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  8832. l1 (length ts))])]
  8833. [`(,ts ... -> ,rt)
  8834. (match v1
  8835. [`(function ,xs ,body ,env)
  8836. (cond [(eq? (length xs) (length ts)) v1]
  8837. [else
  8838. (error 'apply-project "arity mismatch ~a != ~a"
  8839. (length xs) (length ts))])]
  8840. [else (error 'apply-project "expected function not ~a" v1)])]
  8841. [else v1])]
  8842. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  8843. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  8844. \end{lstlisting}
  8845. \caption{Auxiliary functions for injection and projection.}
  8846. \label{fig:apply-project}
  8847. \end{figure}
  8848. \clearpage
  8849. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  8850. \label{sec:compile-r7}
  8851. The \code{cast-insert} pass compiles from \LangDyn{} to \LangAny{}.
  8852. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  8853. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  8854. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  8855. an expression $e'$ in \LangAny{} that has type \key{Any}. For example, the
  8856. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  8857. the Boolean \code{\#t}, which must be injected to produce an
  8858. expression of type \key{Any}.
  8859. %
  8860. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  8861. addition, is representative of compilation for many primitive
  8862. operations: the arguments have type \key{Any} and must be projected to
  8863. \key{Integer} before the addition can be performed.
  8864. The compilation of \key{lambda} (third row of
  8865. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  8866. produce type annotations: we simply use \key{Any}.
  8867. %
  8868. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  8869. has to account for some differences in behavior between \LangDyn{} and
  8870. \LangAny{}. The \LangDyn{} language is more permissive than \LangAny{} regarding what
  8871. kind of values can be used in various places. For example, the
  8872. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  8873. the arguments need not be of the same type (in that case the
  8874. result is \code{\#f}).
  8875. \begin{figure}[btp]
  8876. \centering
  8877. \begin{tabular}{|lll|} \hline
  8878. \begin{minipage}{0.27\textwidth}
  8879. \begin{lstlisting}
  8880. #t
  8881. \end{lstlisting}
  8882. \end{minipage}
  8883. &
  8884. $\Rightarrow$
  8885. &
  8886. \begin{minipage}{0.65\textwidth}
  8887. \begin{lstlisting}
  8888. (inject #t Boolean)
  8889. \end{lstlisting}
  8890. \end{minipage}
  8891. \\[2ex]\hline
  8892. \begin{minipage}{0.27\textwidth}
  8893. \begin{lstlisting}
  8894. (+ |$e_1$| |$e_2$|)
  8895. \end{lstlisting}
  8896. \end{minipage}
  8897. &
  8898. $\Rightarrow$
  8899. &
  8900. \begin{minipage}{0.65\textwidth}
  8901. \begin{lstlisting}
  8902. (inject
  8903. (+ (project |$e'_1$| Integer)
  8904. (project |$e'_2$| Integer))
  8905. Integer)
  8906. \end{lstlisting}
  8907. \end{minipage}
  8908. \\[2ex]\hline
  8909. \begin{minipage}{0.27\textwidth}
  8910. \begin{lstlisting}
  8911. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  8912. \end{lstlisting}
  8913. \end{minipage}
  8914. &
  8915. $\Rightarrow$
  8916. &
  8917. \begin{minipage}{0.65\textwidth}
  8918. \begin{lstlisting}
  8919. (inject
  8920. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  8921. (Any|$\ldots$|Any -> Any))
  8922. \end{lstlisting}
  8923. \end{minipage}
  8924. \\[2ex]\hline
  8925. \begin{minipage}{0.27\textwidth}
  8926. \begin{lstlisting}
  8927. (|$e_0$| |$e_1 \ldots e_n$|)
  8928. \end{lstlisting}
  8929. \end{minipage}
  8930. &
  8931. $\Rightarrow$
  8932. &
  8933. \begin{minipage}{0.65\textwidth}
  8934. \begin{lstlisting}
  8935. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  8936. \end{lstlisting}
  8937. \end{minipage}
  8938. \\[2ex]\hline
  8939. \begin{minipage}{0.27\textwidth}
  8940. \begin{lstlisting}
  8941. (vector-ref |$e_1$| |$e_2$|)
  8942. \end{lstlisting}
  8943. \end{minipage}
  8944. &
  8945. $\Rightarrow$
  8946. &
  8947. \begin{minipage}{0.65\textwidth}
  8948. \begin{lstlisting}
  8949. (any-vector-ref |$e_1'$| |$e_2'$|)
  8950. \end{lstlisting}
  8951. \end{minipage}
  8952. \\[2ex]\hline
  8953. \begin{minipage}{0.27\textwidth}
  8954. \begin{lstlisting}
  8955. (if |$e_1$| |$e_2$| |$e_3$|)
  8956. \end{lstlisting}
  8957. \end{minipage}
  8958. &
  8959. $\Rightarrow$
  8960. &
  8961. \begin{minipage}{0.65\textwidth}
  8962. \begin{lstlisting}
  8963. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  8964. \end{lstlisting}
  8965. \end{minipage}
  8966. \\[2ex]\hline
  8967. \begin{minipage}{0.27\textwidth}
  8968. \begin{lstlisting}
  8969. (eq? |$e_1$| |$e_2$|)
  8970. \end{lstlisting}
  8971. \end{minipage}
  8972. &
  8973. $\Rightarrow$
  8974. &
  8975. \begin{minipage}{0.65\textwidth}
  8976. \begin{lstlisting}
  8977. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  8978. \end{lstlisting}
  8979. \end{minipage}
  8980. \\[2ex]\hline
  8981. \begin{minipage}{0.27\textwidth}
  8982. \begin{lstlisting}
  8983. (not |$e_1$|)
  8984. \end{lstlisting}
  8985. \end{minipage}
  8986. &
  8987. $\Rightarrow$
  8988. &
  8989. \begin{minipage}{0.65\textwidth}
  8990. \begin{lstlisting}
  8991. (if (eq? |$e'_1$| (inject #f Boolean))
  8992. (inject #t Boolean) (inject #f Boolean))
  8993. \end{lstlisting}
  8994. \end{minipage}
  8995. \\[2ex]\hline
  8996. \end{tabular}
  8997. \caption{Cast Insertion}
  8998. \label{fig:compile-r7-r6}
  8999. \end{figure}
  9000. \section{Reveal Casts}
  9001. \label{sec:reveal-casts-r6}
  9002. % TODO: define R'_6
  9003. In the \code{reveal-casts} pass we recommend compiling \code{project}
  9004. into an \code{if} expression that checks whether the value's tag
  9005. matches the target type; if it does, the value is converted to a value
  9006. of the target type by removing the tag; if it does not, the program
  9007. exits. To perform these actions we need a new primitive operation,
  9008. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  9009. The \code{tag-of-any} operation retrieves the type tag from a tagged
  9010. value of type \code{Any}. The \code{ValueOf} form retrieves the
  9011. underlying value from a tagged value. The \code{ValueOf} form
  9012. includes the type for the underlying value which is used by the type
  9013. checker. Finally, the \code{Exit} form ends the execution of the
  9014. program.
  9015. If the target type of the projection is \code{Boolean} or
  9016. \code{Integer}, then \code{Project} can be translated as follows.
  9017. \begin{center}
  9018. \begin{minipage}{1.0\textwidth}
  9019. \begin{lstlisting}
  9020. (Project |$e$| |$\FType$|)
  9021. |$\Rightarrow$|
  9022. (Let |$\itm{tmp}$| |$e'$|
  9023. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  9024. (Int |$\itm{tagof}(\FType)$|)))
  9025. (ValueOf |$\itm{tmp}$| |$\FType$|)
  9026. (Exit)))
  9027. \end{lstlisting}
  9028. \end{minipage}
  9029. \end{center}
  9030. If the target type of the projection is a vector or function type,
  9031. then there is a bit more work to do. For vectors, check that the
  9032. length of the vector type matches the length of the vector (using the
  9033. \code{vector-length} primitive). For functions, check that the number
  9034. of parameters in the function type matches the function's arity (using
  9035. \code{procedure-arity}).
  9036. Regarding \code{inject}, we recommend compiling it to a slightly
  9037. lower-level primitive operation named \code{make-any}. This operation
  9038. takes a tag instead of a type.
  9039. \begin{center}
  9040. \begin{minipage}{1.0\textwidth}
  9041. \begin{lstlisting}
  9042. (Inject |$e$| |$\FType$|)
  9043. |$\Rightarrow$|
  9044. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  9045. \end{lstlisting}
  9046. \end{minipage}
  9047. \end{center}
  9048. The type predicates (\code{boolean?}, etc.) can be translated into
  9049. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  9050. translation of \code{Project}.
  9051. The \code{any-vector-ref} and \code{any-vector-set!} operations
  9052. combine the projection action with the vector operation. Also, the
  9053. read and write operations allow arbitrary expressions for the index so
  9054. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany-part-1})
  9055. cannot guarantee that the index is within bounds. Thus, we insert code
  9056. to perform bounds checking at runtime. The translation for
  9057. \code{any-vector-ref} is as follows and the other two operations are
  9058. translated in a similar way.
  9059. \begin{lstlisting}
  9060. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  9061. |$\Rightarrow$|
  9062. (Let |$v$| |$e'_1$|
  9063. (Let |$i$| |$e'_2$|
  9064. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  9065. (If (Prim '< (list (Var |$i$|)
  9066. (Prim 'any-vector-length (list (Var |$v$|)))))
  9067. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  9068. (Exit))))
  9069. \end{lstlisting}
  9070. \section{Remove Complex Operands}
  9071. \label{sec:rco-r6}
  9072. The \code{ValueOf} and \code{Exit} forms are both complex expressions.
  9073. The subexpression of \code{ValueOf} must be atomic.
  9074. \section{Explicate Control and \LangCAny{}}
  9075. \label{sec:explicate-r6}
  9076. The output of \code{explicate-control} is the \LangCAny{} language whose
  9077. syntax is defined in Figure~\ref{fig:c5-syntax}. The \code{ValueOf}
  9078. form that we added to \LangAny{} remains an expression and the \code{Exit}
  9079. expression becomes a $\Tail$. Also, note that the index argument of
  9080. \code{vector-ref} and \code{vector-set!} is an $\Atm$ instead
  9081. of an integer, as in \LangCVec{} (Figure~\ref{fig:c2-syntax}).
  9082. \begin{figure}[tp]
  9083. \fbox{
  9084. \begin{minipage}{0.96\textwidth}
  9085. \small
  9086. \[
  9087. \begin{array}{lcl}
  9088. \Exp &::= & \ldots
  9089. \mid \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  9090. &\mid& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  9091. &\mid& \VALUEOF{\Exp}{\FType} \\
  9092. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  9093. \mid \LP\key{Collect} \,\itm{int}\RP }\\
  9094. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  9095. \mid \GOTO{\itm{label}} } \\
  9096. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  9097. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  9098. \mid \LP\key{Exit}\RP \\
  9099. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  9100. \LangCLam{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  9101. \end{array}
  9102. \]
  9103. \end{minipage}
  9104. }
  9105. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  9106. \label{fig:c5-syntax}
  9107. \end{figure}
  9108. \section{Select Instructions}
  9109. \label{sec:select-r6}
  9110. In the \code{select-instructions} pass we translate the primitive
  9111. operations on the \code{Any} type to x86 instructions that involve
  9112. manipulating the 3 tag bits of the tagged value.
  9113. \paragraph{Make-any}
  9114. We recommend compiling the \key{make-any} primitive as follows if the
  9115. tag is for \key{Integer} or \key{Boolean}. The \key{salq} instruction
  9116. shifts the destination to the left by the number of bits specified its
  9117. source argument (in this case $3$, the length of the tag) and it
  9118. preserves the sign of the integer. We use the \key{orq} instruction to
  9119. combine the tag and the value to form the tagged value. \\
  9120. \begin{lstlisting}
  9121. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  9122. |$\Rightarrow$|
  9123. movq |$e'$|, |\itm{lhs'}|
  9124. salq $3, |\itm{lhs'}|
  9125. orq $|$\itm{tag}$|, |\itm{lhs'}|
  9126. \end{lstlisting}
  9127. The instruction selection for vectors and procedures is different
  9128. because their is no need to shift them to the left. The rightmost 3
  9129. bits are already zeros as described at the beginning of this
  9130. chapter. So we just combine the value and the tag using \key{orq}. \\
  9131. \begin{lstlisting}
  9132. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  9133. |$\Rightarrow$|
  9134. movq |$e'$|, |\itm{lhs'}|
  9135. orq $|$\itm{tag}$|, |\itm{lhs'}|
  9136. \end{lstlisting}
  9137. \paragraph{Tag-of-any}
  9138. Recall that the \code{tag-of-any} operation extracts the type tag from
  9139. a value of type \code{Any}. The type tag is the bottom three bits, so
  9140. we obtain the tag by taking the bitwise-and of the value with $111$
  9141. ($7$ in decimal).
  9142. \begin{lstlisting}
  9143. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  9144. |$\Rightarrow$|
  9145. movq |$e'$|, |\itm{lhs'}|
  9146. andq $7, |\itm{lhs'}|
  9147. \end{lstlisting}
  9148. \paragraph{ValueOf}
  9149. Like \key{make-any}, the instructions for \key{ValueOf} are different
  9150. depending on whether the type $T$ is a pointer (vector or procedure)
  9151. or not (Integer or Boolean). The following shows the instruction
  9152. selection for Integer and Boolean. We produce an untagged value by
  9153. shifting it to the right by 3 bits.
  9154. \begin{lstlisting}
  9155. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  9156. |$\Rightarrow$|
  9157. movq |$e'$|, |\itm{lhs'}|
  9158. sarq $3, |\itm{lhs'}|
  9159. \end{lstlisting}
  9160. %
  9161. In the case for vectors and procedures, there is no need to
  9162. shift. Instead we just need to zero-out the rightmost 3 bits. We
  9163. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  9164. decimal) and apply \code{bitwise-not} to obtain $\ldots 11111000$ (-8
  9165. in decimal) which we \code{movq} into the destination $\itm{lhs}$. We
  9166. then apply \code{andq} with the tagged value to get the desired
  9167. result. \\
  9168. \begin{lstlisting}
  9169. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  9170. |$\Rightarrow$|
  9171. movq $|$-8$|, |\itm{lhs'}|
  9172. andq |$e'$|, |\itm{lhs'}|
  9173. \end{lstlisting}
  9174. %% \paragraph{Type Predicates} We leave it to the reader to
  9175. %% devise a sequence of instructions to implement the type predicates
  9176. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  9177. \paragraph{Any-vector-length}
  9178. \begin{lstlisting}
  9179. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$a_1$|)))
  9180. |$\Longrightarrow$|
  9181. movq |$\neg 111$|, %r11
  9182. andq |$a_1'$|, %r11
  9183. movq 0(%r11), %r11
  9184. andq $126, %r11
  9185. sarq $1, %r11
  9186. movq %r11, |$\itm{lhs'}$|
  9187. \end{lstlisting}
  9188. \paragraph{Any-vector-ref}
  9189. The index may be an arbitrary atom so instead of computing the offset
  9190. at compile time, instructions need to be generated to compute the
  9191. offset at runtime as follows. Note the use of the new instruction
  9192. \code{imulq}.
  9193. \begin{center}
  9194. \begin{minipage}{0.96\textwidth}
  9195. \begin{lstlisting}
  9196. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$a_1$| |$a_2$|)))
  9197. |$\Longrightarrow$|
  9198. movq |$\neg 111$|, %r11
  9199. andq |$a_1'$|, %r11
  9200. movq |$a_2'$|, %rax
  9201. addq $1, %rax
  9202. imulq $8, %rax
  9203. addq %rax, %r11
  9204. movq 0(%r11) |$\itm{lhs'}$|
  9205. \end{lstlisting}
  9206. \end{minipage}
  9207. \end{center}
  9208. \paragraph{Any-vector-set!}
  9209. The code generation for \code{any-vector-set!} is similar to the other
  9210. \code{any-vector} operations.
  9211. \section{Register Allocation for \LangAny{}}
  9212. \label{sec:register-allocation-r6}
  9213. \index{register allocation}
  9214. There is an interesting interaction between tagged values and garbage
  9215. collection that has an impact on register allocation. A variable of
  9216. type \code{Any} might refer to a vector and therefore it might be a
  9217. root that needs to be inspected and copied during garbage
  9218. collection. Thus, we need to treat variables of type \code{Any} in a
  9219. similar way to variables of type \code{Vector} for purposes of
  9220. register allocation. In particular,
  9221. \begin{itemize}
  9222. \item If a variable of type \code{Any} is live during a function call,
  9223. then it must be spilled. This can be accomplished by changing
  9224. \code{build-interference} to mark all variables of type \code{Any}
  9225. that are live after a \code{callq} as interfering with all the
  9226. registers.
  9227. \item If a variable of type \code{Any} is spilled, it must be spilled
  9228. to the root stack instead of the normal procedure call stack.
  9229. \end{itemize}
  9230. Another concern regarding the root stack is that the garbage collector
  9231. needs to differentiate between (1) plain old pointers to tuples, (2) a
  9232. tagged value that points to a tuple, and (3) a tagged value that is
  9233. not a tuple. We enable this differentiation by choosing not to use the
  9234. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  9235. reserved for identifying plain old pointers to tuples. That way, if
  9236. one of the first three bits is set, then we have a tagged value and
  9237. inspecting the tag can differentiation between vectors ($010$) and the
  9238. other kinds of values.
  9239. \begin{exercise}\normalfont
  9240. Expand your compiler to handle \LangAny{} as discussed in the last few
  9241. sections. Create 5 new programs that use the \code{Any} type and the
  9242. new operations (\code{inject}, \code{project}, \code{boolean?},
  9243. etc.). Test your compiler on these new programs and all of your
  9244. previously created test programs.
  9245. \end{exercise}
  9246. \begin{exercise}\normalfont
  9247. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  9248. Create tests for \LangDyn{} by adapting ten of your previous test programs
  9249. by removing type annotations. Add 5 more tests programs that
  9250. specifically rely on the language being dynamically typed. That is,
  9251. they should not be legal programs in a statically typed language, but
  9252. nevertheless, they should be valid \LangDyn{} programs that run to
  9253. completion without error.
  9254. \end{exercise}
  9255. \begin{figure}[p]
  9256. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9257. \node (Rfun) at (0,4) {\large \LangDyn{}};
  9258. \node (Rfun-2) at (3,4) {\large \LangDyn{}};
  9259. \node (Rfun-3) at (6,4) {\large \LangDyn{}};
  9260. \node (Rfun-4) at (9,4) {\large \LangDynFunRef{}};
  9261. \node (Rfun-5) at (9,2) {\large \LangAnyFunRef{}};
  9262. \node (Rfun-6) at (12,2) {\large \LangAnyFunRef{}};
  9263. \node (Rfun-7) at (12,0) {\large \LangAnyFunRef{}};
  9264. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  9265. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  9266. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  9267. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  9268. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  9269. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  9270. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  9271. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  9272. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  9273. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  9274. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  9275. \path[->,bend left=15] (Rfun) edge [above] node
  9276. {\ttfamily\footnotesize shrink} (Rfun-2);
  9277. \path[->,bend left=15] (Rfun-2) edge [above] node
  9278. {\ttfamily\footnotesize uniquify} (Rfun-3);
  9279. \path[->,bend left=15] (Rfun-3) edge [above] node
  9280. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  9281. \path[->,bend right=15] (Rfun-4) edge [left] node
  9282. {\ttfamily\footnotesize cast-insert} (Rfun-5);
  9283. \path[->,bend left=15] (Rfun-5) edge [above] node
  9284. {\ttfamily\footnotesize check-bounds} (Rfun-6);
  9285. \path[->,bend left=15] (Rfun-6) edge [left] node
  9286. {\ttfamily\footnotesize reveal-casts} (Rfun-7);
  9287. \path[->,bend left=15] (Rfun-7) edge [below] node
  9288. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  9289. \path[->,bend right=15] (F1-2) edge [above] node
  9290. {\ttfamily\footnotesize limit-fun.} (F1-3);
  9291. \path[->,bend right=15] (F1-3) edge [above] node
  9292. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9293. \path[->,bend right=15] (F1-4) edge [above] node
  9294. {\ttfamily\footnotesize remove-complex.} (F1-5);
  9295. \path[->,bend right=15] (F1-5) edge [right] node
  9296. {\ttfamily\footnotesize explicate-control} (C3-2);
  9297. \path[->,bend left=15] (C3-2) edge [left] node
  9298. {\ttfamily\footnotesize select-instr.} (x86-2);
  9299. \path[->,bend right=15] (x86-2) edge [left] node
  9300. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  9301. \path[->,bend right=15] (x86-2-1) edge [below] node
  9302. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  9303. \path[->,bend right=15] (x86-2-2) edge [left] node
  9304. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  9305. \path[->,bend left=15] (x86-3) edge [above] node
  9306. {\ttfamily\footnotesize patch-instr.} (x86-4);
  9307. \path[->,bend left=15] (x86-4) edge [right] node
  9308. {\ttfamily\footnotesize print-x86} (x86-5);
  9309. \end{tikzpicture}
  9310. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  9311. \label{fig:Rdyn-passes}
  9312. \end{figure}
  9313. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  9314. for the compilation of \LangDyn{}.
  9315. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9316. \chapter{Loops and Assignment}
  9317. \label{ch:loop}
  9318. % TODO: define R'_8
  9319. % TODO: multi-graph
  9320. In this chapter we study two features that are the hallmarks of
  9321. imperative programming languages: loops and assignments to local
  9322. variables. The following example demonstrates these new features by
  9323. computing the sum of the first five positive integers.
  9324. % similar to loop_test_1.rkt
  9325. \begin{lstlisting}
  9326. (let ([sum 0])
  9327. (let ([i 5])
  9328. (begin
  9329. (while (> i 0)
  9330. (begin
  9331. (set! sum (+ sum i))
  9332. (set! i (- i 1))))
  9333. sum)))
  9334. \end{lstlisting}
  9335. The \code{while} loop consists of a condition and a body.
  9336. %
  9337. The \code{set!} consists of a variable and a right-hand-side expression.
  9338. %
  9339. The primary purpose of both the \code{while} loop and \code{set!} is
  9340. to cause side effects, so it is convenient to also include in a
  9341. language feature for sequencing side effects: the \code{begin}
  9342. expression. It consists of one or more subexpressions that are
  9343. evaluated left-to-right.
  9344. \section{The \LangLoop{} Language}
  9345. \begin{figure}[tp]
  9346. \centering
  9347. \fbox{
  9348. \begin{minipage}{0.96\textwidth}
  9349. \small
  9350. \[
  9351. \begin{array}{lcl}
  9352. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  9353. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  9354. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  9355. &\mid& \gray{\key{\#t} \mid \key{\#f}
  9356. \mid (\key{and}\;\Exp\;\Exp)
  9357. \mid (\key{or}\;\Exp\;\Exp)
  9358. \mid (\key{not}\;\Exp) } \\
  9359. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  9360. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  9361. (\key{vector-ref}\;\Exp\;\Int)} \\
  9362. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  9363. \mid (\Exp \; \Exp\ldots) } \\
  9364. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP
  9365. \mid \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  9366. &\mid& \CSETBANG{\Var}{\Exp}
  9367. \mid \CBEGIN{\Exp\ldots}{\Exp}
  9368. \mid \CWHILE{\Exp}{\Exp} \\
  9369. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  9370. \LangLoop{} &::=& \gray{\Def\ldots \; \Exp}
  9371. \end{array}
  9372. \]
  9373. \end{minipage}
  9374. }
  9375. \caption{The concrete syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:r6-concrete-syntax}).}
  9376. \label{fig:r8-concrete-syntax}
  9377. \end{figure}
  9378. \begin{figure}[tp]
  9379. \centering
  9380. \fbox{
  9381. \begin{minipage}{0.96\textwidth}
  9382. \small
  9383. \[
  9384. \begin{array}{lcl}
  9385. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  9386. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  9387. &\mid& \gray{ \BOOL{\itm{bool}}
  9388. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  9389. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  9390. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  9391. &\mid& \gray{ \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp} }\\
  9392. &\mid& \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  9393. \mid \WHILE{\Exp}{\Exp} \\
  9394. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  9395. \LangLoop{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  9396. \end{array}
  9397. \]
  9398. \end{minipage}
  9399. }
  9400. \caption{The abstract syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:r6-syntax}).}
  9401. \label{fig:r8-syntax}
  9402. \end{figure}
  9403. The concrete syntax of \LangLoop{} is defined in
  9404. Figure~\ref{fig:r8-concrete-syntax} and its abstract syntax is defined
  9405. in Figure~\ref{fig:r8-syntax}.
  9406. %
  9407. The definitional interpreter for \LangLoop{} is shown in
  9408. Figure~\ref{fig:interp-Rwhile}. We add three new cases for \code{SetBang},
  9409. \code{WhileLoop}, and \code{Begin} and we make changes to the cases
  9410. for \code{Var}, \code{Let}, and \code{Apply} regarding variables. To
  9411. support assignment to variables and to make their lifetimes indefinite
  9412. (see the second example in Section~\ref{sec:assignment-scoping}), we
  9413. box the value that is bound to each variable (in \code{Let}) and
  9414. function parameter (in \code{Apply}). The case for \code{Var} unboxes
  9415. the value.
  9416. %
  9417. Now to discuss the new cases. For \code{SetBang}, we lookup the
  9418. variable in the environment to obtain a boxed value and then we change
  9419. it using \code{set-box!} to the result of evaluating the right-hand
  9420. side. The result value of a \code{SetBang} is \code{void}.
  9421. %
  9422. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  9423. if the result is true, 2) evaluate the body.
  9424. The result value of a \code{while} loop is also \code{void}.
  9425. %
  9426. Finally, the $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  9427. subexpressions \itm{es} for their effects and then evaluates
  9428. and returns the result from \itm{body}.
  9429. \begin{figure}[tbp]
  9430. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9431. (define interp-Rwhile-class
  9432. (class interp-Rany-class
  9433. (super-new)
  9434. (define/override ((interp-exp env) e)
  9435. (define recur (interp-exp env))
  9436. (match e
  9437. [(SetBang x rhs)
  9438. (set-box! (lookup x env) (recur rhs))]
  9439. [(WhileLoop cnd body)
  9440. (define (loop)
  9441. (cond [(recur cnd) (recur body) (loop)]
  9442. [else (void)]))
  9443. (loop)]
  9444. [(Begin es body)
  9445. (for ([e es]) (recur e))
  9446. (recur body)]
  9447. [else ((super interp-exp env) e)]))
  9448. ))
  9449. (define (interp-Rwhile p)
  9450. (send (new interp-Rwhile-class) interp-program p))
  9451. \end{lstlisting}
  9452. \caption{Interpreter for \LangLoop{}.}
  9453. \label{fig:interp-Rwhile}
  9454. \end{figure}
  9455. The type checker for \LangLoop{} is define in
  9456. Figure~\ref{fig:type-check-Rwhile}. For \code{SetBang}, the type of the
  9457. variable and the right-hand-side must agree. The result type is
  9458. \code{Void}. For the \code{WhileLoop}, the condition must be a
  9459. \code{Boolean}. The result type is also \code{Void}. For
  9460. \code{Begin}, the result type is the type of its last subexpression.
  9461. \begin{figure}[tbp]
  9462. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9463. (define type-check-Rwhile-class
  9464. (class type-check-Rany-class
  9465. (super-new)
  9466. (inherit check-type-equal?)
  9467. (define/override (type-check-exp env)
  9468. (lambda (e)
  9469. (define recur (type-check-exp env))
  9470. (match e
  9471. [(SetBang x rhs)
  9472. (define-values (rhs^ rhsT) (recur rhs))
  9473. (define varT (dict-ref env x))
  9474. (check-type-equal? rhsT varT e)
  9475. (values (SetBang x rhs^) 'Void)]
  9476. [(WhileLoop cnd body)
  9477. (define-values (cnd^ Tc) (recur cnd))
  9478. (check-type-equal? Tc 'Boolean e)
  9479. (define-values (body^ Tbody) ((type-check-exp env) body))
  9480. (values (WhileLoop cnd^ body^) 'Void)]
  9481. [(Begin es body)
  9482. (define-values (es^ ts)
  9483. (for/lists (l1 l2) ([e es]) (recur e)))
  9484. (define-values (body^ Tbody) (recur body))
  9485. (values (Begin es^ body^) Tbody)]
  9486. [else ((super type-check-exp env) e)])))
  9487. ))
  9488. (define (type-check-Rwhile p)
  9489. (send (new type-check-Rwhile-class) type-check-program p))
  9490. \end{lstlisting}
  9491. \caption{Type checking \key{SetBang}, \key{WhileLoop},
  9492. and \code{Begin} in \LangLoop{}.}
  9493. \label{fig:type-check-Rwhile}
  9494. \end{figure}
  9495. At first glance, the translation of these language features to x86
  9496. seems straightforward because the \LangCFun{} intermediate language already
  9497. supports all of the ingredients that we need: assignment, \code{goto},
  9498. conditional branching, and sequencing. However, there are two
  9499. complications that arise which we discuss in the next two
  9500. sections. After that we introduce one new compiler pass and the
  9501. changes necessary to the existing passes.
  9502. \section{Assignment and Lexically Scoped Functions}
  9503. \label{sec:assignment-scoping}
  9504. The addition of assignment raises a problem with our approach to
  9505. implementing lexically-scoped functions. Consider the following
  9506. example in which function \code{f} has a free variable \code{x} that
  9507. is changed after \code{f} is created but before the call to \code{f}.
  9508. % loop_test_11.rkt
  9509. \begin{lstlisting}
  9510. (let ([x 0])
  9511. (let ([y 0])
  9512. (let ([z 20])
  9513. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  9514. (begin
  9515. (set! x 10)
  9516. (set! y 12)
  9517. (f y))))))
  9518. \end{lstlisting}
  9519. The correct output for this example is \code{42} because the call to
  9520. \code{f} is required to use the current value of \code{x} (which is
  9521. \code{10}). Unfortunately, the closure conversion pass
  9522. (Section~\ref{sec:closure-conversion}) generates code for the
  9523. \code{lambda} that copies the old value of \code{x} into a
  9524. closure. Thus, if we naively add support for assignment to our current
  9525. compiler, the output of this program would be \code{32}.
  9526. A first attempt at solving this problem would be to save a pointer to
  9527. \code{x} in the closure and change the occurrences of \code{x} inside
  9528. the lambda to dereference the pointer. Of course, this would require
  9529. assigning \code{x} to the stack and not to a register. However, the
  9530. problem goes a bit deeper. Consider the following example in which we
  9531. create a counter abstraction by creating a pair of functions that
  9532. share the free variable \code{x}.
  9533. % similar to loop_test_10.rkt
  9534. \begin{lstlisting}
  9535. (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  9536. (vector
  9537. (lambda: () : Integer x)
  9538. (lambda: () : Void (set! x (+ 1 x)))))
  9539. (let ([counter (f 0)])
  9540. (let ([get (vector-ref counter 0)])
  9541. (let ([inc (vector-ref counter 1)])
  9542. (begin
  9543. (inc)
  9544. (get)))))
  9545. \end{lstlisting}
  9546. In this example, the lifetime of \code{x} extends beyond the lifetime
  9547. of the call to \code{f}. Thus, if we were to store \code{x} on the
  9548. stack frame for the call to \code{f}, it would be gone by the time we
  9549. call \code{inc} and \code{get}, leaving us with dangling pointers for
  9550. \code{x}. This example demonstrates that when a variable occurs free
  9551. inside a \code{lambda}, its lifetime becomes indefinite. Thus, the
  9552. value of the variable needs to live on the heap. The verb ``box'' is
  9553. often used for allocating a single value on the heap, producing a
  9554. pointer, and ``unbox'' for dereferencing the pointer.
  9555. We recommend solving these problems by ``boxing'' the local variables
  9556. that are in the intersection of 1) variables that appear on the
  9557. left-hand-side of a \code{set!} and 2) variables that occur free
  9558. inside a \code{lambda}. We shall introduce a new pass named
  9559. \code{convert-assignments} in Section~\ref{sec:convert-assignments} to
  9560. perform this translation. But before diving into the compiler passes,
  9561. we one more problem to discuss.
  9562. \section{Cyclic Control Flow and Dataflow Analysis}
  9563. \label{sec:dataflow-analysis}
  9564. Up until this point the control-flow graphs generated in
  9565. \code{explicate-control} were guaranteed to be acyclic. However, each
  9566. \code{while} loop introduces a cycle in the control-flow graph.
  9567. But does that matter?
  9568. %
  9569. Indeed it does. Recall that for register allocation, the compiler
  9570. performs liveness analysis to determine which variables can share the
  9571. same register. In Section~\ref{sec:liveness-analysis-Rif} we analyze
  9572. the control-flow graph in reverse topological order, but topological
  9573. order is only well-defined for acyclic graphs.
  9574. Let us return to the example of computing the sum of the first five
  9575. positive integers. Here is the program after instruction selection but
  9576. before register allocation.
  9577. \begin{center}
  9578. \begin{minipage}{0.45\textwidth}
  9579. \begin{lstlisting}
  9580. (define (main) : Integer
  9581. mainstart:
  9582. movq $0, sum1
  9583. movq $5, i2
  9584. jmp block5
  9585. block5:
  9586. movq i2, tmp3
  9587. cmpq tmp3, $0
  9588. jl block7
  9589. jmp block8
  9590. \end{lstlisting}
  9591. \end{minipage}
  9592. \begin{minipage}{0.45\textwidth}
  9593. \begin{lstlisting}
  9594. block7:
  9595. addq i2, sum1
  9596. movq $1, tmp4
  9597. negq tmp4
  9598. addq tmp4, i2
  9599. jmp block5
  9600. block8:
  9601. movq $27, %rax
  9602. addq sum1, %rax
  9603. jmp mainconclusion
  9604. )
  9605. \end{lstlisting}
  9606. \end{minipage}
  9607. \end{center}
  9608. Recall that liveness analysis works backwards, starting at the end
  9609. of each function. For this example we could start with \code{block8}
  9610. because we know what is live at the beginning of the conclusion,
  9611. just \code{rax} and \code{rsp}. So the live-before set
  9612. for \code{block8} is $\{\ttm{rsp},\ttm{sum1}\}$.
  9613. %
  9614. Next we might try to analyze \code{block5} or \code{block7}, but
  9615. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9616. we are stuck.
  9617. The way out of this impasse comes from the realization that one can
  9618. perform liveness analysis starting with an empty live-after set to
  9619. compute an under-approximation of the live-before set. By
  9620. \emph{under-approximation}, we mean that the set only contains
  9621. variables that are really live, but it may be missing some. Next, the
  9622. under-approximations for each block can be improved by 1) updating the
  9623. live-after set for each block using the approximate live-before sets
  9624. from the other blocks and 2) perform liveness analysis again on each
  9625. block. In fact, by iterating this process, the under-approximations
  9626. eventually become the correct solutions!
  9627. %
  9628. This approach of iteratively analyzing a control-flow graph is
  9629. applicable to many static analysis problems and goes by the name
  9630. \emph{dataflow analysis}\index{dataflow analysis}. It was invented by
  9631. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  9632. Washington.
  9633. Let us apply this approach to the above example. We use the empty set
  9634. for the initial live-before set for each block. Let $m_0$ be the
  9635. following mapping from label names to sets of locations (variables and
  9636. registers).
  9637. \begin{center}
  9638. \begin{lstlisting}
  9639. mainstart: {}
  9640. block5: {}
  9641. block7: {}
  9642. block8: {}
  9643. \end{lstlisting}
  9644. \end{center}
  9645. Using the above live-before approximations, we determine the
  9646. live-after for each block and then apply liveness analysis to each
  9647. block. This produces our next approximation $m_1$ of the live-before
  9648. sets.
  9649. \begin{center}
  9650. \begin{lstlisting}
  9651. mainstart: {}
  9652. block5: {i2}
  9653. block7: {i2, sum1}
  9654. block8: {rsp, sum1}
  9655. \end{lstlisting}
  9656. \end{center}
  9657. For the second round, the live-after for \code{mainstart} is the
  9658. current live-before for \code{block5}, which is \code{\{i2\}}. So the
  9659. liveness analysis for \code{mainstart} computes the empty set. The
  9660. live-after for \code{block5} is the union of the live-before sets for
  9661. \code{block7} and \code{block8}, which is \code{\{i2 , rsp, sum1\}}.
  9662. So the liveness analysis for \code{block5} computes \code{\{i2 , rsp,
  9663. sum1\}}. The live-after for \code{block7} is the live-before for
  9664. \code{block5} (from the previous iteration), which is \code{\{i2\}}.
  9665. So the liveness analysis for \code{block7} remains \code{\{i2,
  9666. sum1\}}. Together these yield the following approximation $m_2$ of
  9667. the live-before sets.
  9668. \begin{center}
  9669. \begin{lstlisting}
  9670. mainstart: {}
  9671. block5: {i2, rsp, sum1}
  9672. block7: {i2, sum1}
  9673. block8: {rsp, sum1}
  9674. \end{lstlisting}
  9675. \end{center}
  9676. In the preceding iteration, only \code{block5} changed, so we can
  9677. limit our attention to \code{mainstart} and \code{block7}, the two
  9678. blocks that jump to \code{block5}. As a result, the live-before sets
  9679. for \code{mainstart} and \code{block7} are updated to include
  9680. \code{rsp}, yielding the following approximation $m_3$.
  9681. \begin{center}
  9682. \begin{lstlisting}
  9683. mainstart: {rsp}
  9684. block5: {i2, rsp, sum1}
  9685. block7: {i2, rsp, sum1}
  9686. block8: {rsp, sum1}
  9687. \end{lstlisting}
  9688. \end{center}
  9689. Because \code{block7} changed, we analyze \code{block5} once more, but
  9690. its live-before set remains \code{\{ i2, rsp, sum1 \}}. At this point
  9691. our approximations have converged, so $m_3$ is the solution.
  9692. This iteration process is guaranteed to converge to a solution by the
  9693. Kleene Fixed-Point Theorem, a general theorem about functions on
  9694. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9695. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9696. elements, a least element $\bot$ (pronounced bottom), and a join
  9697. operator $\sqcup$.\index{lattice}\index{bottom}\index{partial
  9698. ordering}\index{join}\footnote{Technically speaking, we will be
  9699. working with join semi-lattices.} When two elements are ordered $m_i
  9700. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  9701. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  9702. approximation than $m_i$. The bottom element $\bot$ represents the
  9703. complete lack of information, i.e., the worst approximation. The join
  9704. operator takes two lattice elements and combines their information,
  9705. i.e., it produces the least upper bound of the two.\index{least upper
  9706. bound}
  9707. A dataflow analysis typically involves two lattices: one lattice to
  9708. represent abstract states and another lattice that aggregates the
  9709. abstract states of all the blocks in the control-flow graph. For
  9710. liveness analysis, an abstract state is a set of locations. We form
  9711. the lattice $L$ by taking its elements to be sets of locations, the
  9712. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9713. set, and the join operator to be set union.
  9714. %
  9715. We form a second lattice $M$ by taking its elements to be mappings
  9716. from the block labels to sets of locations (elements of $L$). We
  9717. order the mappings point-wise, using the ordering of $L$. So given any
  9718. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9719. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9720. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9721. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  9722. We can think of one iteration of liveness analysis as being a function
  9723. $f$ on the lattice $M$. It takes a mapping as input and computes a new
  9724. mapping.
  9725. \[
  9726. f(m_i) = m_{i+1}
  9727. \]
  9728. Next let us think for a moment about what a final solution $m_s$
  9729. should look like. If we perform liveness analysis using the solution
  9730. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9731. solution should be a \emph{fixed point} of the function $f$.\index{fixed point}
  9732. \[
  9733. f(m_s) = m_s
  9734. \]
  9735. Furthermore, the solution should only include locations that are
  9736. forced to be there by performing liveness analysis on the program, so
  9737. the solution should be the \emph{least} fixed point.\index{least fixed point}
  9738. The Kleene Fixed-Point Theorem states that if a function $f$ is
  9739. monotone (better inputs produce better outputs), then the least fixed
  9740. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9741. chain} obtained by starting at $\bot$ and iterating $f$ as
  9742. follows.\index{Kleene Fixed-Point Theorem}
  9743. \[
  9744. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9745. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9746. \]
  9747. When a lattice contains only finitely-long ascending chains, then
  9748. every Kleene chain tops out at some fixed point after a number of
  9749. iterations of $f$. So that fixed point is also a least upper
  9750. bound of the chain.
  9751. \[
  9752. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9753. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9754. \]
  9755. The liveness analysis is indeed a monotone function and the lattice
  9756. $M$ only has finitely-long ascending chains because there are only a
  9757. finite number of variables and blocks in the program. Thus we are
  9758. guaranteed that iteratively applying liveness analysis to all blocks
  9759. in the program will eventually produce the least fixed point solution.
  9760. Next let us consider dataflow analysis in general and discuss the
  9761. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  9762. %
  9763. The algorithm has four parameters: the control-flow graph \code{G}, a
  9764. function \code{transfer} that applies the analysis to one block, the
  9765. \code{bottom} and \code{join} operator for the lattice of abstract
  9766. states. The algorithm begins by creating the bottom mapping,
  9767. represented by a hash table. It then pushes all of the nodes in the
  9768. control-flow graph onto the work list (a queue). The algorithm repeats
  9769. the \code{while} loop as long as there are items in the work list. In
  9770. each iteration, a node is popped from the work list and processed. The
  9771. \code{input} for the node is computed by taking the join of the
  9772. abstract states of all the predecessor nodes. The \code{transfer}
  9773. function is then applied to obtain the \code{output} abstract
  9774. state. If the output differs from the previous state for this block,
  9775. the mapping for this block is updated and its successor nodes are
  9776. pushed onto the work list.
  9777. \begin{figure}[tb]
  9778. \begin{lstlisting}
  9779. (define (analyze-dataflow G transfer bottom join)
  9780. (define mapping (make-hash))
  9781. (for ([v (in-vertices G)])
  9782. (dict-set! mapping v bottom))
  9783. (define worklist (make-queue))
  9784. (for ([v (in-vertices G)])
  9785. (enqueue! worklist v))
  9786. (define trans-G (transpose G))
  9787. (while (not (queue-empty? worklist))
  9788. (define node (dequeue! worklist))
  9789. (define input (for/fold ([state bottom])
  9790. ([pred (in-neighbors trans-G node)])
  9791. (join state (dict-ref mapping pred))))
  9792. (define output (transfer node input))
  9793. (cond [(not (equal? output (dict-ref mapping node)))
  9794. (dict-set! mapping node output)
  9795. (for ([v (in-neighbors G node)])
  9796. (enqueue! worklist v))]))
  9797. mapping)
  9798. \end{lstlisting}
  9799. \caption{Generic work list algorithm for dataflow analysis}
  9800. \label{fig:generic-dataflow}
  9801. \end{figure}
  9802. Having discussed the two complications that arise from adding support
  9803. for assignment and loops, we turn to discussing the one new compiler
  9804. pass and the significant changes to existing passes.
  9805. \section{Convert Assignments}
  9806. \label{sec:convert-assignments}
  9807. Recall that in Section~\ref{sec:assignment-scoping} we learned that
  9808. the combination of assignments and lexically-scoped functions requires
  9809. that we box those variables that are both assigned-to and that appear
  9810. free inside a \code{lambda}. The purpose of the
  9811. \code{convert-assignments} pass is to carry out that transformation.
  9812. We recommend placing this pass after \code{uniquify} but before
  9813. \code{reveal-functions}.
  9814. Consider again the first example from
  9815. Section~\ref{sec:assignment-scoping}:
  9816. \begin{lstlisting}
  9817. (let ([x 0])
  9818. (let ([y 0])
  9819. (let ([z 20])
  9820. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  9821. (begin
  9822. (set! x 10)
  9823. (set! y 12)
  9824. (f y))))))
  9825. \end{lstlisting}
  9826. The variables \code{x} and \code{y} are assigned-to. The variables
  9827. \code{x} and \code{z} occur free inside the \code{lambda}. Thus,
  9828. variable \code{x} needs to be boxed but not \code{y} and \code{z}.
  9829. The boxing of \code{x} consists of three transformations: initialize
  9830. \code{x} with a vector, replace reads from \code{x} with
  9831. \code{vector-ref}'s, and replace each \code{set!} on \code{x} with a
  9832. \code{vector-set!}. The output of \code{convert-assignments} for this
  9833. example is as follows.
  9834. \begin{lstlisting}
  9835. (define (main) : Integer
  9836. (let ([x0 (vector 0)])
  9837. (let ([y1 0])
  9838. (let ([z2 20])
  9839. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  9840. (+ a3 (+ (vector-ref x0 0) z2)))])
  9841. (begin
  9842. (vector-set! x0 0 10)
  9843. (set! y1 12)
  9844. (f4 y1)))))))
  9845. \end{lstlisting}
  9846. \paragraph{Assigned \& Free}
  9847. We recommend defining an auxiliary function named
  9848. \code{assigned\&free} that takes an expression and simultaneously
  9849. computes 1) a set of assigned variables $A$, 2) a set $F$ of variables
  9850. that occur free within lambda's, and 3) a new version of the
  9851. expression that records which bound variables occurred in the
  9852. intersection of $A$ and $F$. You can use the struct
  9853. \code{AssignedFree} to do this. Consider the case for
  9854. $\LET{x}{\itm{rhs}}{\itm{body}}$. Suppose the the recursive call on
  9855. $\itm{rhs}$ produces $\itm{rhs}'$, $A_r$, and $F_r$ and the recursive
  9856. call on the $\itm{body}$ produces $\itm{body}'$, $A_b$, and $F_b$. If
  9857. $x$ is in $A_b\cap F_b$, then transforms the \code{Let} as follows.
  9858. \begin{lstlisting}
  9859. (Let |$x$| |$rhs$| |$body$|)
  9860. |$\Rightarrow$|
  9861. (Let (AssignedFree |$x$|) |$rhs'$| |$body'$|)
  9862. \end{lstlisting}
  9863. If $x$ is not in $A_b\cap F_b$ then omit the use of \code{AssignedFree}.
  9864. The set of assigned variables for this \code{Let} is
  9865. $A_r \cup (A_b - \{x\})$
  9866. and the set of variables free in lambda's is
  9867. $F_r \cup (F_b - \{x\})$.
  9868. The case for $\SETBANG{x}{\itm{rhs}}$ is straightforward but
  9869. important. Recursively process \itm{rhs} to obtain \itm{rhs'}, $A_r$,
  9870. and $F_r$. The result is $\SETBANG{x}{\itm{rhs'}}$, $\{x\} \cup A_r$,
  9871. and $F_r$.
  9872. The case for $\LAMBDA{\itm{params}}{T}{\itm{body}}$ is a bit more
  9873. involved. Let \itm{body'}, $A_b$, and $F_b$ be the result of
  9874. recursively processing \itm{body}. Wrap each of parameter that occurs
  9875. in $A_b \cap F_b$ with \code{AssignedFree} to produce \itm{params'}.
  9876. Let $P$ be the set of parameter names in \itm{params}. The result is
  9877. $\LAMBDA{\itm{params'}}{T}{\itm{body'}}$, $A_b - P$, and $(F_b \cup
  9878. \mathrm{FV}(\itm{body})) - P$, where $\mathrm{FV}$ computes the free
  9879. variables of an expression (see Chapter~\ref{ch:lambdas}).
  9880. \paragraph{Convert Assignments}
  9881. Next we discuss the \code{convert-assignment} pass with its auxiliary
  9882. functions for expressions and definitions. The function for
  9883. expressions, \code{cnvt-assign-exp}, should take an expression and a
  9884. set of assigned-and-free variables (obtained from the result of
  9885. \code{assigned\&free}. In the case for $\VAR{x}$, if $x$ is
  9886. assigned-and-free, then unbox it by translating $\VAR{x}$ to a
  9887. \code{vector-ref}.
  9888. \begin{lstlisting}
  9889. (Var |$x$|)
  9890. |$\Rightarrow$|
  9891. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  9892. \end{lstlisting}
  9893. %
  9894. In the case for $\LET{\LP\code{AssignedFree}\,
  9895. x\RP}{\itm{rhs}}{\itm{body}}$, recursively process \itm{rhs} to
  9896. obtain \itm{rhs'}. Next, recursively process \itm{body} to obtain
  9897. \itm{body'} but with $x$ added to the set of assigned-and-free
  9898. variables. Translate the let-expression as follows to bind $x$ to a
  9899. boxed value.
  9900. \begin{lstlisting}
  9901. (Let (AssignedFree |$x$|) |$rhs$| |$body$|)
  9902. |$\Rightarrow$|
  9903. (Let |$x$| (Prim 'vector (list |$rhs'$|)) |$body'$|)
  9904. \end{lstlisting}
  9905. %
  9906. In the case for $\SETBANG{x}{\itm{rhs}}$, recursively process
  9907. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in the assigned-and-free
  9908. variables, translate the \code{set!} into a \code{vector-set!}
  9909. as follows.
  9910. \begin{lstlisting}
  9911. (SetBang |$x$| |$\itm{rhs}$|)
  9912. |$\Rightarrow$|
  9913. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  9914. \end{lstlisting}
  9915. %
  9916. The case for \code{Lambda} is non-trivial, but it is similar to the
  9917. case for function definitions, which we discuss next.
  9918. The auxiliary function for definitions, \code{cnvt-assign-def},
  9919. applies assignment conversion to function definitions.
  9920. We translate a function definition as follows.
  9921. \begin{lstlisting}
  9922. (Def |$f$| |$\itm{params}$| |$T$| |$\itm{info}$| |$\itm{body_1}$|)
  9923. |$\Rightarrow$|
  9924. (Def |$f$| |$\itm{params'}$| |$T$| |$\itm{info}$| |$\itm{body_4}$|)
  9925. \end{lstlisting}
  9926. So it remains to explain \itm{params'} and $\itm{body}_4$.
  9927. Let \itm{body_2}, $A_b$, and $F_b$ be the result of
  9928. \code{assigned\&free} on $\itm{body_1}$.
  9929. Let $P$ be the parameter names in \itm{params}.
  9930. We then apply \code{cnvt-assign-exp} to $\itm{body_2}$ to
  9931. obtain \itm{body_3}, passing $A_b \cap F_b \cap P$
  9932. as the set of assigned-and-free variables.
  9933. Finally, we obtain \itm{body_4} by wrapping \itm{body_3}
  9934. in a sequence of let-expressions that box the parameters
  9935. that are in $A_b \cap F_b$.
  9936. %
  9937. Regarding \itm{params'}, change the names of the parameters that are
  9938. in $A_b \cap F_b$ to maintain uniqueness (and so the let-bound
  9939. variables can retain the original names). Recall the second example in
  9940. Section~\ref{sec:assignment-scoping} involving a counter
  9941. abstraction. The following is the output of assignment version for
  9942. function \code{f}.
  9943. \begin{lstlisting}
  9944. (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  9945. (vector
  9946. (lambda: () : Integer x1)
  9947. (lambda: () : Void (set! x1 (+ 1 x1)))))
  9948. |$\Rightarrow$|
  9949. (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  9950. (let ([x1 (vector param_x1)])
  9951. (vector (lambda: () : Integer (vector-ref x1 0))
  9952. (lambda: () : Void
  9953. (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  9954. \end{lstlisting}
  9955. \section{Remove Complex Operands}
  9956. \label{sec:rco-loop}
  9957. The three new language forms, \code{while}, \code{set!}, and
  9958. \code{begin} are all complex expressions and their subexpressions are
  9959. allowed to be complex. Figure~\ref{fig:Rfun-anf-syntax} defines the
  9960. output language \LangFunANF{} of this pass.
  9961. \begin{figure}[tp]
  9962. \centering
  9963. \fbox{
  9964. \begin{minipage}{0.96\textwidth}
  9965. \small
  9966. \[
  9967. \begin{array}{rcl}
  9968. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  9969. \mid \VOID{} } \\
  9970. \Exp &::=& \ldots \mid \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  9971. &\mid& \WHILE{\Exp}{\Exp} \mid \SETBANG{\Var}{\Exp}
  9972. \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  9973. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  9974. R^{\dagger}_8 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  9975. \end{array}
  9976. \]
  9977. \end{minipage}
  9978. }
  9979. \caption{\LangLoopANF{} is \LangLoop{} in administrative normal form (ANF).}
  9980. \label{fig:r8-anf-syntax}
  9981. \end{figure}
  9982. As usual, when a complex expression appears in a grammar position that
  9983. needs to be atomic, such as the argument of a primitive operator, we
  9984. must introduce a temporary variable and bind it to the complex
  9985. expression. This approach applies, unchanged, to handle the new
  9986. language forms. For example, in the following code there are two
  9987. \code{begin} expressions appearing as arguments to \code{+}. The
  9988. output of \code{rco-exp} is shown below, in which the \code{begin}
  9989. expressions have been bound to temporary variables. Recall that
  9990. \code{let} expressions in \LangLoopANF{} are allowed to have
  9991. arbitrary expressions in their right-hand-side expression, so it is
  9992. fine to place \code{begin} there.
  9993. \begin{lstlisting}
  9994. (let ([x0 10])
  9995. (let ([y1 0])
  9996. (+ (+ (begin (set! y1 (read)) x0)
  9997. (begin (set! x0 (read)) y1))
  9998. x0)))
  9999. |$\Rightarrow$|
  10000. (let ([x0 10])
  10001. (let ([y1 0])
  10002. (let ([tmp2 (begin (set! y1 (read)) x0)])
  10003. (let ([tmp3 (begin (set! x0 (read)) y1)])
  10004. (let ([tmp4 (+ tmp2 tmp3)])
  10005. (+ tmp4 x0))))))
  10006. \end{lstlisting}
  10007. \section{Explicate Control and \LangCLoop{}}
  10008. \label{sec:explicate-loop}
  10009. Recall that in the \code{explicate-control} pass we define one helper
  10010. function for each kind of position in the program. For the \LangVar{}
  10011. language of integers and variables we needed kinds of positions:
  10012. assignment and tail. The \code{if} expressions of \LangIf{} introduced
  10013. predicate positions. For \LangLoop{}, the \code{begin} expression introduces
  10014. yet another kind of position: effect position. Except for the last
  10015. subexpression, the subexpressions inside a \code{begin} are evaluated
  10016. only for their effect. Their result values are discarded. We can
  10017. generate better code by taking this fact into account.
  10018. The output language of \code{explicate-control} is \LangCLoop{}
  10019. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  10020. \LangCLam{}. The only syntactic difference is that \code{Call},
  10021. \code{vector-set!}, and \code{read} may also appear as statements.
  10022. The most significant difference between \LangCLam{} and \LangCLoop{}
  10023. is that the control-flow graphs of the later may contain cycles.
  10024. \begin{figure}[tp]
  10025. \fbox{
  10026. \begin{minipage}{0.96\textwidth}
  10027. \small
  10028. \[
  10029. \begin{array}{lcl}
  10030. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  10031. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  10032. &\mid& \CALL{\Atm}{\LP\Atm\ldots\RP} \mid \READ{}\\
  10033. &\mid& \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP \\
  10034. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  10035. \LangCLoop{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  10036. \end{array}
  10037. \]
  10038. \end{minipage}
  10039. }
  10040. \caption{The abstract syntax of \LangCLoop{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  10041. \label{fig:c7-syntax}
  10042. \end{figure}
  10043. The new auxiliary function \code{explicate-effect} takes an expression
  10044. (in an effect position) and a promise of a continuation block. The
  10045. function returns a promise for a $\Tail$ that includes the generated
  10046. code for the input expression followed by the continuation block. If
  10047. the expression is obviously pure, that is, never causes side effects,
  10048. then the expression can be removed, so the result is just the
  10049. continuation block.
  10050. %
  10051. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  10052. case. First, you will need a fresh label $\itm{loop}$ for the top of
  10053. the loop. Recursively process the \itm{body} (in effect position)
  10054. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  10055. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  10056. \itm{body'} as the then-branch and the continuation block as the
  10057. else-branch. The result should be added to the control-flow graph with
  10058. the label \itm{loop}. The result for the whole \code{while} loop is a
  10059. \code{goto} to the \itm{loop} label. Note that the loop should only be
  10060. added to the control-flow graph if the loop is indeed used, which can
  10061. be accomplished using \code{delay}.
  10062. The auxiliary functions for tail, assignment, and predicate positions
  10063. need to be updated. The three new language forms, \code{while},
  10064. \code{set!}, and \code{begin}, can appear in assignment and tail
  10065. positions. Only \code{begin} may appear in predicate positions; the
  10066. other two have result type \code{Void}.
  10067. \section{Select Instructions}
  10068. \label{sec:select-instructions-loop}
  10069. Only three small additions are needed in the
  10070. \code{select-instructions} pass to handle the changes to \LangCLoop{}. That
  10071. is, \code{Call}, \code{read}, and \code{vector-set!} may now appear as
  10072. stand-alone statements instead of only appearing on the right-hand
  10073. side of an assignment statement. The code generation is nearly
  10074. identical; just leave off the instruction for moving the result into
  10075. the left-hand side.
  10076. \section{Register Allocation}
  10077. \label{sec:register-allocation-loop}
  10078. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  10079. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  10080. which complicates the liveness analysis needed for register
  10081. allocation.
  10082. \subsection{Liveness Analysis}
  10083. \label{sec:liveness-analysis-r8}
  10084. We recommend using the generic \code{analyze-dataflow} function that
  10085. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  10086. perform liveness analysis, replacing the code in
  10087. \code{uncover-live-CFG} that processed the basic blocks in topological
  10088. order (Section~\ref{sec:liveness-analysis-Rif}).
  10089. The \code{analyze-dataflow} function has four parameters.
  10090. \begin{enumerate}
  10091. \item The first parameter \code{G} should be a directed graph from the
  10092. \code{racket/graph} package (see the sidebar in
  10093. Section~\ref{sec:build-interference}) that represents the
  10094. control-flow graph.
  10095. \item The second parameter \code{transfer} is a function that applies
  10096. liveness analysis to a basic block. It takes two parameters: the
  10097. label for the block to analyze and the live-after set for that
  10098. block. The transfer function should return the live-before set for
  10099. the block. Also, as a side-effect, it should update the block's
  10100. $\itm{info}$ with the liveness information for each instruction. To
  10101. implement the \code{transfer} function, you should be able to reuse
  10102. the code you already have for analyzing basic blocks.
  10103. \item The third and fourth parameters of \code{analyze-dataflow} are
  10104. \code{bottom} and \code{join} for the lattice of abstract states,
  10105. i.e. sets of locations. The bottom of the lattice is the empty set
  10106. \code{(set)} and the join operator is \code{set-union}.
  10107. \end{enumerate}
  10108. \begin{figure}[p]
  10109. \begin{tikzpicture}[baseline=(current bounding box.center)]
  10110. \node (Rfun) at (0,2) {\large \LangLoop{}};
  10111. \node (Rfun-2) at (3,2) {\large \LangLoop{}};
  10112. \node (Rfun-3) at (6,2) {\large \LangLoop{}};
  10113. \node (Rfun-4) at (9,2) {\large \LangLoopFunRef{}};
  10114. \node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  10115. \node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  10116. \node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  10117. \node (F1-4) at (3,0) {\large \LangLoopAlloc{}};
  10118. \node (F1-5) at (0,0) {\large \LangLoopAlloc{}};
  10119. \node (C3-2) at (3,-2) {\large \LangCLoop{}};
  10120. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  10121. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  10122. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  10123. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  10124. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  10125. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  10126. %% \path[->,bend left=15] (Rfun) edge [above] node
  10127. %% {\ttfamily\footnotesize type-check} (Rfun-2);
  10128. \path[->,bend left=15] (Rfun) edge [above] node
  10129. {\ttfamily\footnotesize shrink} (Rfun-2);
  10130. \path[->,bend left=15] (Rfun-2) edge [above] node
  10131. {\ttfamily\footnotesize uniquify} (Rfun-3);
  10132. \path[->,bend left=15] (Rfun-3) edge [above] node
  10133. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  10134. \path[->,bend left=15] (Rfun-4) edge [right] node
  10135. {\ttfamily\footnotesize convert-assignments} (F1-1);
  10136. \path[->,bend left=15] (F1-1) edge [below] node
  10137. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  10138. \path[->,bend right=15] (F1-2) edge [above] node
  10139. {\ttfamily\footnotesize limit-fun.} (F1-3);
  10140. \path[->,bend right=15] (F1-3) edge [above] node
  10141. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  10142. \path[->,bend right=15] (F1-4) edge [above] node
  10143. {\ttfamily\footnotesize remove-complex.} (F1-5);
  10144. \path[->,bend right=15] (F1-5) edge [right] node
  10145. {\ttfamily\footnotesize explicate-control} (C3-2);
  10146. \path[->,bend left=15] (C3-2) edge [left] node
  10147. {\ttfamily\footnotesize select-instr.} (x86-2);
  10148. \path[->,bend right=15] (x86-2) edge [left] node
  10149. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  10150. \path[->,bend right=15] (x86-2-1) edge [below] node
  10151. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  10152. \path[->,bend right=15] (x86-2-2) edge [left] node
  10153. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  10154. \path[->,bend left=15] (x86-3) edge [above] node
  10155. {\ttfamily\footnotesize patch-instr.} (x86-4);
  10156. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  10157. \end{tikzpicture}
  10158. \caption{Diagram of the passes for \LangLoop{} (loops and assignment).}
  10159. \label{fig:Rwhile-passes}
  10160. \end{figure}
  10161. Figure~\ref{fig:Rwhile-passes} provides an overview of all the passes needed
  10162. for the compilation of \LangLoop{}.
  10163. % TODO: challenge assignment
  10164. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10165. \chapter{Gradual Typing}
  10166. \label{ch:gradual-typing}
  10167. \index{gradual typing}
  10168. This chapter studies a language, \LangGrad{}, in which the programmer
  10169. can choose between static and dynamic type checking in different parts
  10170. of a program, thereby mixing the statically typed \LangLoop{} language
  10171. with the dynamically typed \LangDyn{}. There are several approaches to
  10172. mixing static and dynamic typing, including multi-language
  10173. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  10174. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  10175. we focus on \emph{gradual typing}\index{gradual typing}, in which the
  10176. programmer controls the amount of static versus dynamic checking by
  10177. adding or removing type annotations on parameters and
  10178. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  10179. %
  10180. The concrete syntax of \LangGrad{} is defined in
  10181. Figure~\ref{fig:r9-concrete-syntax} and its abstract syntax is defined
  10182. in Figure~\ref{fig:r9-syntax}. The main syntactic difference between
  10183. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  10184. non-terminals that make type annotations optional. The return types
  10185. are not optional in the abstract syntax; the parser fills in
  10186. \code{Any} when the return type is not specified in the concrete
  10187. syntax.
  10188. \begin{figure}[tp]
  10189. \centering
  10190. \fbox{
  10191. \begin{minipage}{0.96\textwidth}
  10192. \small
  10193. \[
  10194. \begin{array}{lcl}
  10195. \itm{param} &::=& \Var \mid \LS\Var \key{:} \Type\RS \\
  10196. \itm{ret} &::=& \epsilon \mid \key{:} \Type \\
  10197. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  10198. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  10199. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  10200. &\mid& \gray{\key{\#t} \mid \key{\#f}
  10201. \mid (\key{and}\;\Exp\;\Exp)
  10202. \mid (\key{or}\;\Exp\;\Exp)
  10203. \mid (\key{not}\;\Exp) } \\
  10204. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  10205. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  10206. (\key{vector-ref}\;\Exp\;\Int)} \\
  10207. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  10208. \mid (\Exp \; \Exp\ldots) } \\
  10209. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  10210. \mid \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  10211. &\mid& \gray{ \CSETBANG{\Var}{\Exp}
  10212. \mid \CBEGIN{\Exp\ldots}{\Exp}
  10213. \mid \CWHILE{\Exp}{\Exp} } \\
  10214. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  10215. \LangGrad{} &::=& \gray{\Def\ldots \; \Exp}
  10216. \end{array}
  10217. \]
  10218. \end{minipage}
  10219. }
  10220. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:r8-concrete-syntax}).}
  10221. \label{fig:r9-concrete-syntax}
  10222. \end{figure}
  10223. \begin{figure}[tp]
  10224. \centering
  10225. \fbox{
  10226. \begin{minipage}{0.96\textwidth}
  10227. \small
  10228. \[
  10229. \begin{array}{lcl}
  10230. \itm{param} &::=& \Var \mid \LS\Var \key{:} \Type\RS \\
  10231. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  10232. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  10233. &\mid& \gray{ \BOOL{\itm{bool}}
  10234. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  10235. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  10236. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  10237. &\mid& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  10238. &\mid& \gray{ \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  10239. &\mid& \gray{ \WHILE{\Exp}{\Exp} } \\
  10240. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  10241. \LangGrad{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  10242. \end{array}
  10243. \]
  10244. \end{minipage}
  10245. }
  10246. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:r8-syntax}).}
  10247. \label{fig:r9-syntax}
  10248. \end{figure}
  10249. Both the type checker and the interpreter for \LangGrad{} require some
  10250. interesting changes to enable gradual typing, which we discuss in the
  10251. next two sections in the context of the \code{map-vec} example from
  10252. Chapter~\ref{ch:functions}. In Figure~\ref{fig:gradual-map-vec} we
  10253. revised the \code{map-vec} example, omitting the type annotations from
  10254. the \code{add1} function.
  10255. \begin{figure}[btp]
  10256. % gradual_test_9.rkt
  10257. \begin{lstlisting}
  10258. (define (map-vec [f : (Integer -> Integer)]
  10259. [v : (Vector Integer Integer)])
  10260. : (Vector Integer Integer)
  10261. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10262. (define (add1 x) (+ x 1))
  10263. (vector-ref (map-vec add1 (vector 0 41)) 1)
  10264. \end{lstlisting}
  10265. \caption{A partially-typed version of the \code{map-vec} example.}
  10266. \label{fig:gradual-map-vec}
  10267. \end{figure}
  10268. \section{Type Checking \LangGrad{}, Casts, and \LangCast{}}
  10269. \label{sec:gradual-type-check}
  10270. The type checker for \LangGrad{} uses the \code{Any} type for missing
  10271. parameter and return types. For example, the \code{x} parameter of
  10272. \code{add1} in Figure~\ref{fig:gradual-map-vec} is given the type
  10273. \code{Any} and the return type of \code{add1} is \code{Any}. Next
  10274. consider the \code{+} operator inside \code{add1}. It expects both
  10275. arguments to have type \code{Integer}, but its first argument \code{x}
  10276. has type \code{Any}. In a gradually typed language, such differences
  10277. are allowed so long as the types are \emph{consistent}, that is, they
  10278. are equal except in places where there is an \code{Any} type. The type
  10279. \code{Any} is consistent with every other type.
  10280. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  10281. \begin{figure}[tbp]
  10282. \begin{lstlisting}
  10283. (define/public (consistent? t1 t2)
  10284. (match* (t1 t2)
  10285. [('Integer 'Integer) #t]
  10286. [('Boolean 'Boolean) #t]
  10287. [('Void 'Void) #t]
  10288. [('Any t2) #t]
  10289. [(t1 'Any) #t]
  10290. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10291. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  10292. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10293. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  10294. (consistent? rt1 rt2))]
  10295. [(other wise) #f]))
  10296. \end{lstlisting}
  10297. \caption{The consistency predicate on types, a method in
  10298. \code{type-check-gradual-class}.}
  10299. \label{fig:consistent}
  10300. \end{figure}
  10301. Returning to the \code{map-vec} example of
  10302. Figure~\ref{fig:gradual-map-vec}, the \code{add1} function has type
  10303. \code{(Any -> Any)} but parameter \code{f} of \code{map-vec} has type
  10304. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  10305. because the two types are consistent. In particular, \code{->} is
  10306. equal to \code{->} and because \code{Any} is consistent with
  10307. \code{Integer}.
  10308. Next consider a program with an error, such as applying the
  10309. \code{map-vec} to a function that sometimes returns a Boolean, as
  10310. shown in Figure~\ref{fig:map-vec-maybe-add1}. The type checker for
  10311. \LangGrad{} accepts this program because the type of \code{maybe-add1} is
  10312. consistent with the type of parameter \code{f} of \code{map-vec}, that
  10313. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  10314. Integer)}. One might say that a gradual type checker is optimistic
  10315. in that it accepts programs that might execute without a runtime type
  10316. error.
  10317. %
  10318. Unfortunately, running this program with input \code{1} triggers an
  10319. error when the \code{maybe-add1} function returns \code{\#t}. \LangGrad{}
  10320. performs checking at runtime to ensure the integrity of the static
  10321. types, such as the \code{(Integer -> Integer)} annotation on parameter
  10322. \code{f} of \code{map-vec}. This runtime checking is carried out by a
  10323. new \code{Cast} form that is inserted by the type checker. Thus, the
  10324. output of the type checker is a program in the \LangCast{} language, which
  10325. adds \code{Cast} to \LangLoop{}, as shown in
  10326. Figure~\ref{fig:r9-prime-syntax}.
  10327. \begin{figure}[tp]
  10328. \centering
  10329. \fbox{
  10330. \begin{minipage}{0.96\textwidth}
  10331. \small
  10332. \[
  10333. \begin{array}{lcl}
  10334. \Exp &::=& \ldots \mid \CAST{\Exp}{\Type}{\Type} \\
  10335. \LangCast{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  10336. \end{array}
  10337. \]
  10338. \end{minipage}
  10339. }
  10340. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:r8-syntax}).}
  10341. \label{fig:r9-prime-syntax}
  10342. \end{figure}
  10343. \begin{figure}[tbp]
  10344. \begin{lstlisting}
  10345. (define (map-vec [f : (Integer -> Integer)]
  10346. [v : (Vector Integer Integer)])
  10347. : (Vector Integer Integer)
  10348. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10349. (define (add1 x) (+ x 1))
  10350. (define (true) #t)
  10351. (define (maybe-add1 x) (if (eq? 0 (read)) (add1 x) (true)))
  10352. (vector-ref (map-vec maybe-add1 (vector 0 41)) 0)
  10353. \end{lstlisting}
  10354. \caption{A variant of the \code{map-vec} example with an error.}
  10355. \label{fig:map-vec-maybe-add1}
  10356. \end{figure}
  10357. Figure~\ref{fig:map-vec-cast} shows the output of the type checker for
  10358. \code{map-vec} and \code{maybe-add1}. The idea is that \code{Cast} is
  10359. inserted every time the type checker sees two types that are
  10360. consistent but not equal. In the \code{add1} function, \code{x} is
  10361. cast to \code{Integer} and the result of the \code{+} is cast to
  10362. \code{Any}. In the call to \code{map-vec}, the \code{add1} argument
  10363. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  10364. \begin{figure}[btp]
  10365. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10366. (define (map-vec [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  10367. : (Vector Integer Integer)
  10368. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10369. (define (add1 [x : Any]) : Any
  10370. (cast (+ (cast x Any Integer) 1) Integer Any))
  10371. (define (true) : Any (cast #t Boolean Any))
  10372. (define (maybe-add1 [x : Any]) : Any
  10373. (if (eq? 0 (read)) (add1 x) (true)))
  10374. (vector-ref (map-vec (cast maybe-add1 (Any -> Any) (Integer -> Integer))
  10375. (vector 0 41)) 0)
  10376. \end{lstlisting}
  10377. \caption{Output of type checking \code{map-vec}
  10378. and \code{maybe-add1}.}
  10379. \label{fig:map-vec-cast}
  10380. \end{figure}
  10381. The type checker for \LangGrad{} is defined in
  10382. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  10383. and \ref{fig:type-check-Rgradual-3}.
  10384. \begin{figure}[tbp]
  10385. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10386. (define type-check-gradual-class
  10387. (class type-check-Rwhile-class
  10388. (super-new)
  10389. (inherit operator-types type-predicates)
  10390. (define/override (type-check-exp env)
  10391. (lambda (e)
  10392. (define recur (type-check-exp env))
  10393. (match e
  10394. [(Prim 'vector-length (list e1))
  10395. (define-values (e1^ t) (recur e1))
  10396. (match t
  10397. [`(Vector ,ts ...)
  10398. (values (Prim 'vector-length (list e1^)) 'Integer)]
  10399. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  10400. [(Prim 'vector-ref (list e1 e2))
  10401. (define-values (e1^ t1) (recur e1))
  10402. (define-values (e2^ t2) (recur e2))
  10403. (check-consistent? t2 'Integer e)
  10404. (match t1
  10405. [`(Vector ,ts ...)
  10406. (match e2^
  10407. [(Int i)
  10408. (unless (and (0 . <= . i) (i . < . (length ts)))
  10409. (error 'type-check "invalid index ~a in ~a" i e))
  10410. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10411. [else (define e1^^ (make-cast e1^ t1 'Any))
  10412. (define e2^^ (make-cast e2^ t2 'Integer))
  10413. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  10414. ['Any
  10415. (define e2^^ (make-cast e2^ t2 'Integer))
  10416. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  10417. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  10418. [(Prim 'vector-set! (list e1 e2 e3) )
  10419. (define-values (e1^ t1) (recur e1))
  10420. (define-values (e2^ t2) (recur e2))
  10421. (define-values (e3^ t3) (recur e3))
  10422. (check-consistent? t2 'Integer e)
  10423. (match t1
  10424. [`(Vector ,ts ...)
  10425. (match e2^
  10426. [(Int i)
  10427. (unless (and (0 . <= . i) (i . < . (length ts)))
  10428. (error 'type-check "invalid index ~a in ~a" i e))
  10429. (check-consistent? (list-ref ts i) t3 e)
  10430. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  10431. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  10432. [else
  10433. (define e1^^ (make-cast e1^ t1 'Any))
  10434. (define e2^^ (make-cast e2^ t2 'Integer))
  10435. (define e3^^ (make-cast e3^ t3 'Any))
  10436. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  10437. ['Any
  10438. (define e2^^ (make-cast e2^ t2 'Integer))
  10439. (define e3^^ (make-cast e3^ t3 'Any))
  10440. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  10441. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  10442. \end{lstlisting}
  10443. \caption{Type checker for the \LangGrad{} language, part 1.}
  10444. \label{fig:type-check-Rgradual-1}
  10445. \end{figure}
  10446. \begin{figure}[tbp]
  10447. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10448. [(Prim 'eq? (list e1 e2))
  10449. (define-values (e1^ t1) (recur e1))
  10450. (define-values (e2^ t2) (recur e2))
  10451. (check-consistent? t1 t2 e)
  10452. (define T (meet t1 t2))
  10453. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  10454. 'Boolean)]
  10455. [(Prim 'not (list e1))
  10456. (define-values (e1^ t1) (recur e1))
  10457. (match t1
  10458. ['Any
  10459. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  10460. (Bool #t) (Bool #f)))]
  10461. [else
  10462. (define-values (t-ret new-es^)
  10463. (type-check-op 'not (list t1) (list e1^) e))
  10464. (values (Prim 'not new-es^) t-ret)])]
  10465. [(Prim 'and (list e1 e2))
  10466. (recur (If e1 e2 (Bool #f)))]
  10467. [(Prim 'or (list e1 e2))
  10468. (define tmp (gensym 'tmp))
  10469. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  10470. [(Prim op es)
  10471. #:when (not (set-member? explicit-prim-ops op))
  10472. (define-values (new-es ts)
  10473. (for/lists (exprs types) ([e es])
  10474. (recur e)))
  10475. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  10476. (values (Prim op new-es^) t-ret)]
  10477. [(If e1 e2 e3)
  10478. (define-values (e1^ T1) (recur e1))
  10479. (define-values (e2^ T2) (recur e2))
  10480. (define-values (e3^ T3) (recur e3))
  10481. (check-consistent? T2 T3 e)
  10482. (match T1
  10483. ['Boolean
  10484. (define Tif (join T2 T3))
  10485. (values (If e1^ (make-cast e2^ T2 Tif)
  10486. (make-cast e3^ T3 Tif)) Tif)]
  10487. ['Any
  10488. (define Tif (meet T2 T3))
  10489. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  10490. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  10491. Tif)]
  10492. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  10493. [(HasType e1 T)
  10494. (define-values (e1^ T1) (recur e1))
  10495. (check-consistent? T1 T)
  10496. (values (make-cast e1^ T1 T) T)]
  10497. [(SetBang x e1)
  10498. (define-values (e1^ T1) (recur e1))
  10499. (define varT (dict-ref env x))
  10500. (check-consistent? T1 varT e)
  10501. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  10502. [(WhileLoop e1 e2)
  10503. (define-values (e1^ T1) (recur e1))
  10504. (check-consistent? T1 'Boolean e)
  10505. (define-values (e2^ T2) ((type-check-exp env) e2))
  10506. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  10507. \end{lstlisting}
  10508. \caption{Type checker for the \LangGrad{} language, part 2.}
  10509. \label{fig:type-check-Rgradual-2}
  10510. \end{figure}
  10511. \begin{figure}[tbp]
  10512. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10513. [(Apply e1 e2s)
  10514. (define-values (e1^ T1) (recur e1))
  10515. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  10516. (match T1
  10517. [`(,T1ps ... -> ,T1rt)
  10518. (for ([T2 T2s] [Tp T1ps])
  10519. (check-consistent? T2 Tp e))
  10520. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  10521. (make-cast e2 src tgt)))
  10522. (values (Apply e1^ e2s^^) T1rt)]
  10523. [`Any
  10524. (define e1^^ (make-cast e1^ 'Any
  10525. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  10526. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  10527. (make-cast e2 src 'Any)))
  10528. (values (Apply e1^^ e2s^^) 'Any)]
  10529. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  10530. [(Lambda params Tr e1)
  10531. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  10532. (match p
  10533. [`[,x : ,T] (values x T)]
  10534. [(? symbol? x) (values x 'Any)])))
  10535. (define-values (e1^ T1)
  10536. ((type-check-exp (append (map cons xs Ts) env)) e1))
  10537. (check-consistent? Tr T1 e)
  10538. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  10539. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  10540. [else ((super type-check-exp env) e)]
  10541. )))
  10542. \end{lstlisting}
  10543. \caption{Type checker for the \LangGrad{} language, part 3.}
  10544. \label{fig:type-check-Rgradual-3}
  10545. \end{figure}
  10546. \begin{figure}[tbp]
  10547. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10548. (define/public (join t1 t2)
  10549. (match* (t1 t2)
  10550. [('Integer 'Integer) 'Integer]
  10551. [('Boolean 'Boolean) 'Boolean]
  10552. [('Void 'Void) 'Void]
  10553. [('Any t2) t2]
  10554. [(t1 'Any) t1]
  10555. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10556. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  10557. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10558. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  10559. -> ,(join rt1 rt2))]))
  10560. (define/public (meet t1 t2)
  10561. (match* (t1 t2)
  10562. [('Integer 'Integer) 'Integer]
  10563. [('Boolean 'Boolean) 'Boolean]
  10564. [('Void 'Void) 'Void]
  10565. [('Any t2) 'Any]
  10566. [(t1 'Any) 'Any]
  10567. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10568. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  10569. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10570. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  10571. -> ,(meet rt1 rt2))]))
  10572. (define/public (make-cast e src tgt)
  10573. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  10574. (define/public (check-consistent? t1 t2 e)
  10575. (unless (consistent? t1 t2)
  10576. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  10577. (define/override (type-check-op op arg-types args e)
  10578. (match (dict-ref (operator-types) op)
  10579. [`(,param-types . ,return-type)
  10580. (for ([at arg-types] [pt param-types])
  10581. (check-consistent? at pt e))
  10582. (values return-type
  10583. (for/list ([e args] [s arg-types] [t param-types])
  10584. (make-cast e s t)))]
  10585. [else (error 'type-check-op "unrecognized ~a" op)]))
  10586. (define explicit-prim-ops
  10587. (set-union
  10588. (type-predicates)
  10589. (set 'procedure-arity 'eq?
  10590. 'vector 'vector-length 'vector-ref 'vector-set!
  10591. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  10592. (define/override (fun-def-type d)
  10593. (match d
  10594. [(Def f params rt info body)
  10595. (define ps
  10596. (for/list ([p params])
  10597. (match p
  10598. [`[,x : ,T] T]
  10599. [(? symbol?) 'Any]
  10600. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  10601. `(,@ps -> ,rt)]
  10602. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  10603. \end{lstlisting}
  10604. \caption{Auxiliary functions for type checking \LangGrad{}.}
  10605. \label{fig:type-check-Rgradual-aux}
  10606. \end{figure}
  10607. \clearpage
  10608. \section{Interpreting \LangCast{}}
  10609. \label{sec:interp-casts}
  10610. The runtime behavior of first-order casts is straightforward, that is,
  10611. casts involving simple types such as \code{Integer} and
  10612. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  10613. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  10614. puts the integer into a tagged value
  10615. (Figure~\ref{fig:interp-Rany}). Similarly, a cast from \code{Any} to
  10616. \code{Integer} is accomplished with the \code{Project} operator, that
  10617. is, by checking the value's tag and either retrieving the underlying
  10618. integer or signaling an error if it the tag is not the one for
  10619. integers (Figure~\ref{fig:apply-project}).
  10620. %
  10621. Things get more interesting for higher-order casts, that is, casts
  10622. involving function or vector types.
  10623. Consider the cast of the function \code{maybe-add1} from \code{(Any ->
  10624. Any)} to \code{(Integer -> Integer)}. When a function flows through
  10625. this cast at runtime, we can't know in general whether the function
  10626. will always return an integer.\footnote{Predicting the return value of
  10627. a function is equivalent to the halting problem, which is
  10628. undecidable.} The \LangCast{} interpreter therefore delays the checking
  10629. of the cast until the function is applied. This is accomplished by
  10630. wrapping \code{maybe-add1} in a new function that casts its parameter
  10631. from \code{Integer} to \code{Any}, applies \code{maybe-add1}, and then
  10632. casts the return value from \code{Any} to \code{Integer}.
  10633. Turning our attention to casts involving vector types, we consider the
  10634. example in Figure~\ref{fig:map-vec-bang} that defines a
  10635. partially-typed version of \code{map-vec} whose parameter \code{v} has
  10636. type \code{(Vector Any Any)} and that updates \code{v} in place
  10637. instead of returning a new vector. So we name this function
  10638. \code{map-vec!}. We apply \code{map-vec!} to a vector of integers, so
  10639. the type checker inserts a cast from \code{(Vector Integer Integer)}
  10640. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  10641. cast between vector types would be a build a new vector whose elements
  10642. are the result of casting each of the original elements to the
  10643. appropriate target type. However, this approach is only valid for
  10644. immutable vectors; and our vectors are mutable. In the example of
  10645. Figure~\ref{fig:map-vec-bang}, if the cast created a new vector, then
  10646. the updates inside of \code{map-vec!} would happen to the new vector
  10647. and not the original one.
  10648. \begin{figure}[tbp]
  10649. % gradual_test_11.rkt
  10650. \begin{lstlisting}
  10651. (define (map-vec! [f : (Any -> Any)]
  10652. [v : (Vector Any Any)]) : Void
  10653. (begin
  10654. (vector-set! v 0 (f (vector-ref v 0)))
  10655. (vector-set! v 1 (f (vector-ref v 1)))))
  10656. (define (add1 x) (+ x 1))
  10657. (let ([v (vector 0 41)])
  10658. (begin (map-vec! add1 v) (vector-ref v 1)))
  10659. \end{lstlisting}
  10660. \caption{An example involving casts on vectors.}
  10661. \label{fig:map-vec-bang}
  10662. \end{figure}
  10663. Instead the interpreter needs to create a new kind of value, a
  10664. \emph{vector proxy}, that intercepts every vector operation. On a
  10665. read, the proxy reads from the underlying vector and then applies a
  10666. cast to the resulting value. On a write, the proxy casts the argument
  10667. value and then performs the write to the underlying vector. For the
  10668. first \code{(vector-ref v 0)} in \code{map-vec!}, the proxy casts
  10669. \code{0} from \code{Integer} to \code{Any}. For the first
  10670. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  10671. to \code{Integer}.
  10672. The final category of cast that we need to consider are casts between
  10673. the \code{Any} type and either a function or a vector
  10674. type. Figure~\ref{fig:map-vec-any} shows a variant of \code{map-vec!}
  10675. in which parameter \code{v} does not have a type annotation, so it is
  10676. given type \code{Any}. In the call to \code{map-vec!}, the vector has
  10677. type \code{(Vector Integer Integer)} so the type checker inserts a
  10678. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  10679. thought is to use \code{Inject}, but that doesn't work because
  10680. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  10681. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  10682. to \code{Any}.
  10683. \begin{figure}[tbp]
  10684. \begin{lstlisting}
  10685. (define (map-vec! [f : (Any -> Any)] v) : Void
  10686. (begin
  10687. (vector-set! v 0 (f (vector-ref v 0)))
  10688. (vector-set! v 1 (f (vector-ref v 1)))))
  10689. (define (add1 x) (+ x 1))
  10690. (let ([v (vector 0 41)])
  10691. (begin (map-vec! add1 v) (vector-ref v 1)))
  10692. \end{lstlisting}
  10693. \caption{Casting a vector to \code{Any}.}
  10694. \label{fig:map-vec-any}
  10695. \end{figure}
  10696. The \LangCast{} interpreter uses an auxiliary function named
  10697. \code{apply-cast} to cast a value from a source type to a target type,
  10698. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  10699. of the kinds of casts that we've discussed in this section.
  10700. \begin{figure}[tbp]
  10701. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10702. (define/public (apply-cast v s t)
  10703. (match* (s t)
  10704. [(t1 t2) #:when (equal? t1 t2) v]
  10705. [('Any t2)
  10706. (match t2
  10707. [`(,ts ... -> ,rt)
  10708. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  10709. (define v^ (apply-project v any->any))
  10710. (apply-cast v^ any->any `(,@ts -> ,rt))]
  10711. [`(Vector ,ts ...)
  10712. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  10713. (define v^ (apply-project v vec-any))
  10714. (apply-cast v^ vec-any `(Vector ,@ts))]
  10715. [else (apply-project v t2)])]
  10716. [(t1 'Any)
  10717. (match t1
  10718. [`(,ts ... -> ,rt)
  10719. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  10720. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  10721. (apply-inject v^ (any-tag any->any))]
  10722. [`(Vector ,ts ...)
  10723. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  10724. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  10725. (apply-inject v^ (any-tag vec-any))]
  10726. [else (apply-inject v (any-tag t1))])]
  10727. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10728. (define x (gensym 'x))
  10729. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  10730. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  10731. (define cast-writes
  10732. (for/list ([t1 ts1] [t2 ts2])
  10733. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  10734. `(vector-proxy ,(vector v (apply vector cast-reads)
  10735. (apply vector cast-writes)))]
  10736. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10737. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  10738. `(function ,xs ,(Cast
  10739. (Apply (Value v)
  10740. (for/list ([x xs][t1 ts1][t2 ts2])
  10741. (Cast (Var x) t2 t1)))
  10742. rt1 rt2) ())]
  10743. ))
  10744. \end{lstlisting}
  10745. \caption{The \code{apply-cast} auxiliary method.}
  10746. \label{fig:apply-cast}
  10747. \end{figure}
  10748. The interpreter for \LangCast{} is defined in
  10749. Figure~\ref{fig:interp-Rcast}, with the case for \code{Cast}
  10750. dispatching to \code{apply-cast}. To handle the addition of vector
  10751. proxies, we update the vector primitives in \code{interp-op} using the
  10752. functions in Figure~\ref{fig:guarded-vector}.
  10753. \begin{figure}[tbp]
  10754. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10755. (define interp-Rcast-class
  10756. (class interp-Rwhile-class
  10757. (super-new)
  10758. (inherit apply-fun apply-inject apply-project)
  10759. (define/override (interp-op op)
  10760. (match op
  10761. ['vector-length guarded-vector-length]
  10762. ['vector-ref guarded-vector-ref]
  10763. ['vector-set! guarded-vector-set!]
  10764. ['any-vector-ref (lambda (v i)
  10765. (match v [`(tagged ,v^ ,tg)
  10766. (guarded-vector-ref v^ i)]))]
  10767. ['any-vector-set! (lambda (v i a)
  10768. (match v [`(tagged ,v^ ,tg)
  10769. (guarded-vector-set! v^ i a)]))]
  10770. ['any-vector-length (lambda (v)
  10771. (match v [`(tagged ,v^ ,tg)
  10772. (guarded-vector-length v^)]))]
  10773. [else (super interp-op op)]
  10774. ))
  10775. (define/override ((interp-exp env) e)
  10776. (define (recur e) ((interp-exp env) e))
  10777. (match e
  10778. [(Value v) v]
  10779. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  10780. [else ((super interp-exp env) e)]))
  10781. ))
  10782. (define (interp-Rcast p)
  10783. (send (new interp-Rcast-class) interp-program p))
  10784. \end{lstlisting}
  10785. \caption{The interpreter for \LangCast{}.}
  10786. \label{fig:interp-Rcast}
  10787. \end{figure}
  10788. \begin{figure}[tbp]
  10789. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10790. (define (guarded-vector-ref vec i)
  10791. (match vec
  10792. [`(vector-proxy ,proxy)
  10793. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  10794. (define rd (vector-ref (vector-ref proxy 1) i))
  10795. (apply-fun rd (list val) 'guarded-vector-ref)]
  10796. [else (vector-ref vec i)]))
  10797. (define (guarded-vector-set! vec i arg)
  10798. (match vec
  10799. [`(vector-proxy ,proxy)
  10800. (define wr (vector-ref (vector-ref proxy 2) i))
  10801. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  10802. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  10803. [else (vector-set! vec i arg)]))
  10804. (define (guarded-vector-length vec)
  10805. (match vec
  10806. [`(vector-proxy ,proxy)
  10807. (guarded-vector-length (vector-ref proxy 0))]
  10808. [else (vector-length vec)]))
  10809. \end{lstlisting}
  10810. \caption{The guarded-vector auxiliary functions.}
  10811. \label{fig:guarded-vector}
  10812. \end{figure}
  10813. \section{Lower Casts}
  10814. \label{sec:lower-casts}
  10815. The next step in the journey towards x86 is the \code{lower-casts}
  10816. pass that translates the casts in \LangCast{} to the lower-level
  10817. \code{Inject} and \code{Project} operators and a new operator for
  10818. creating vector proxies, extending the \LangLoop{} language to create
  10819. \LangProxy{}. We recommend creating an auxiliary function named
  10820. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  10821. and a target type, and translates it to expression in \LangProxy{} that has
  10822. the same behavior as casting the expression from the source to the
  10823. target type in the interpreter.
  10824. The \code{lower-cast} function can follow a code structure similar to
  10825. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  10826. the interpreter for \LangCast{} because it must handle the same cases as
  10827. \code{apply-cast} and it needs to mimic the behavior of
  10828. \code{apply-cast}. The most interesting cases are those concerning the
  10829. casts between two vector types and between two function types.
  10830. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  10831. type to another vector type is accomplished by creating a proxy that
  10832. intercepts the operations on the underlying vector. Here we make the
  10833. creation of the proxy explicit with the \code{vector-proxy} primitive
  10834. operation. It takes three arguments, the first is an expression for
  10835. the vector, the second is a vector of functions for casting an element
  10836. that is being read from the vector, and the third is a vector of
  10837. functions for casting an element that is being written to the vector.
  10838. You can create the functions using \code{Lambda}. Also, as we shall
  10839. see in the next section, we need to differentiate these vectors from
  10840. the user-created ones, so we recommend using a new primitive operator
  10841. named \code{raw-vector} instead of \code{vector} to create these
  10842. vectors of functions. Figure~\ref{fig:map-vec-bang-lower-cast} shows
  10843. the output of \code{lower-casts} on the example in
  10844. Figure~\ref{fig:map-vec-bang} that involved casting a vector of
  10845. integers to a vector of \code{Any}.
  10846. \begin{figure}[tbp]
  10847. \begin{lstlisting}
  10848. (define (map-vec! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  10849. (begin
  10850. (vector-set! v 0 (f (vector-ref v 0)))
  10851. (vector-set! v 1 (f (vector-ref v 1)))))
  10852. (define (add1 [x : Any]) : Any
  10853. (inject (+ (project x Integer) 1) Integer))
  10854. (let ([v (vector 0 41)])
  10855. (begin
  10856. (map-vec! add1 (vector-proxy v
  10857. (raw-vector (lambda: ([x9 : Integer]) : Any
  10858. (inject x9 Integer))
  10859. (lambda: ([x9 : Integer]) : Any
  10860. (inject x9 Integer)))
  10861. (raw-vector (lambda: ([x9 : Any]) : Integer
  10862. (project x9 Integer))
  10863. (lambda: ([x9 : Any]) : Integer
  10864. (project x9 Integer)))))
  10865. (vector-ref v 1)))
  10866. \end{lstlisting}
  10867. \caption{Output of \code{lower-casts} on the example in
  10868. Figure~\ref{fig:map-vec-bang}.}
  10869. \label{fig:map-vec-bang-lower-cast}
  10870. \end{figure}
  10871. A cast from one function type to another function type is accomplished
  10872. by generating a \code{Lambda} whose parameter and return types match
  10873. the target function type. The body of the \code{Lambda} should cast
  10874. the parameters from the target type to the source type (yes,
  10875. backwards! functions are contravariant\index{contravariant} in the
  10876. parameters), then call the underlying function, and finally cast the
  10877. result from the source return type to the target return type.
  10878. Figure~\ref{fig:map-vec-lower-cast} shows the output of the
  10879. \code{lower-casts} pass on the \code{map-vec} example in
  10880. Figure~\ref{fig:gradual-map-vec}. Note that the \code{add1} argument
  10881. in the call to \code{map-vec} is wrapped in a \code{lambda}.
  10882. \begin{figure}[tbp]
  10883. \begin{lstlisting}
  10884. (define (map-vec [f : (Integer -> Integer)]
  10885. [v : (Vector Integer Integer)])
  10886. : (Vector Integer Integer)
  10887. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10888. (define (add1 [x : Any]) : Any
  10889. (inject (+ (project x Integer) 1) Integer))
  10890. (vector-ref (map-vec (lambda: ([x9 : Integer]) : Integer
  10891. (project (add1 (inject x9 Integer)) Integer))
  10892. (vector 0 41)) 1)
  10893. \end{lstlisting}
  10894. \caption{Output of \code{lower-casts} on the example in
  10895. Figure~\ref{fig:gradual-map-vec}.}
  10896. \label{fig:map-vec-lower-cast}
  10897. \end{figure}
  10898. \section{Differentiate Proxies}
  10899. \label{sec:differentiate-proxies}
  10900. So far the job of differentiating vectors and vector proxies has been
  10901. the job of the interpreter. For example, the interpreter for \LangCast{}
  10902. implements \code{vector-ref} using the \code{guarded-vector-ref}
  10903. function in Figure~\ref{fig:guarded-vector}. In the
  10904. \code{differentiate-proxies} pass we shift this responsibility to the
  10905. generated code.
  10906. We begin by designing the output language $R^p_8$. In
  10907. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  10908. proxies. In $R^p_8$ we return the \code{Vector} type to
  10909. its original meaning, as the type of real vectors, and we introduce a
  10910. new type, \code{PVector}, whose values can be either real vectors or
  10911. vector proxies. This new type comes with a suite of new primitive
  10912. operations for creating and using values of type \code{PVector}. We
  10913. don't need to introduce a new type to represent vector proxies. A
  10914. proxy is represented by a vector containing three things: 1) the
  10915. underlying vector, 2) a vector of functions for casting elements that
  10916. are read from the vector, and 3) a vector of functions for casting
  10917. values to be written to the vector. So we define the following
  10918. abbreviation for the type of a vector proxy:
  10919. \[
  10920. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  10921. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  10922. \to (\key{PVector}~ T' \ldots)
  10923. \]
  10924. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  10925. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  10926. %
  10927. Next we describe each of the new primitive operations.
  10928. \begin{description}
  10929. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  10930. (\key{PVector} $T \ldots$)]\ \\
  10931. %
  10932. This operation brands a vector as a value of the \code{PVector} type.
  10933. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  10934. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  10935. %
  10936. This operation brands a vector proxy as value of the \code{PVector} type.
  10937. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  10938. \code{Boolean}] \ \\
  10939. %
  10940. returns true if the value is a vector proxy and false if it is a
  10941. real vector.
  10942. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  10943. (\key{Vector} $T \ldots$)]\ \\
  10944. %
  10945. Assuming that the input is a vector (and not a proxy), this
  10946. operation returns the vector.
  10947. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  10948. $\to$ \code{Boolean}]\ \\
  10949. %
  10950. Given a vector proxy, this operation returns the length of the
  10951. underlying vector.
  10952. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  10953. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  10954. %
  10955. Given a vector proxy, this operation returns the $i$th element of
  10956. the underlying vector.
  10957. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  10958. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  10959. proxy, this operation writes a value to the $i$th element of the
  10960. underlying vector.
  10961. \end{description}
  10962. Now to discuss the translation that differentiates vectors from
  10963. proxies. First, every type annotation in the program must be
  10964. translated (recursively) to replace \code{Vector} with \code{PVector}.
  10965. Next, we must insert uses of \code{PVector} operations in the
  10966. appropriate places. For example, we wrap every vector creation with an
  10967. \code{inject-vector}.
  10968. \begin{lstlisting}
  10969. (vector |$e_1 \ldots e_n$|)
  10970. |$\Rightarrow$|
  10971. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  10972. \end{lstlisting}
  10973. The \code{raw-vector} operator that we introduced in the previous
  10974. section does not get injected.
  10975. \begin{lstlisting}
  10976. (raw-vector |$e_1 \ldots e_n$|)
  10977. |$\Rightarrow$|
  10978. (vector |$e'_1 \ldots e'_n$|)
  10979. \end{lstlisting}
  10980. The \code{vector-proxy} primitive translates as follows.
  10981. \begin{lstlisting}
  10982. (vector-proxy |$e_1~e_2~e_3$|)
  10983. |$\Rightarrow$|
  10984. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  10985. \end{lstlisting}
  10986. We translate the vector operations into conditional expressions that
  10987. check whether the value is a proxy and then dispatch to either the
  10988. appropriate proxy vector operation or the regular vector operation.
  10989. For example, the following is the translation for \code{vector-ref}.
  10990. \begin{lstlisting}
  10991. (vector-ref |$e_1$| |$i$|)
  10992. |$\Rightarrow$|
  10993. (let ([|$v~e_1$|])
  10994. (if (proxy? |$v$|)
  10995. (proxy-vector-ref |$v$| |$i$|)
  10996. (vector-ref (project-vector |$v$|) |$i$|)
  10997. \end{lstlisting}
  10998. Note in the case of a real vector, we must apply \code{project-vector}
  10999. before the \code{vector-ref}.
  11000. \section{Reveal Casts}
  11001. \label{sec:reveal-casts-gradual}
  11002. Recall that the \code{reveal-casts} pass
  11003. (Section~\ref{sec:reveal-casts-r6}) is responsible for lowering
  11004. \code{Inject} and \code{Project} into lower-level operations. In
  11005. particular, \code{Project} turns into a conditional expression that
  11006. inspects the tag and retrieves the underlying value. Here we need to
  11007. augment the translation of \code{Project} to handle the situation when
  11008. the target type is \code{PVector}. Instead of using
  11009. \code{vector-length} we need to use \code{proxy-vector-length}.
  11010. \begin{lstlisting}
  11011. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  11012. |$\Rightarrow$|
  11013. (let |$\itm{tmp}$| |$e'$|
  11014. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  11015. (let |$\itm{vec}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  11016. (if (eq? (proxy-vector-length |$\itm{vec}$|) |$n$|) |$\itm{vec}$| (exit)))
  11017. (exit)))
  11018. \end{lstlisting}
  11019. \section{Closure Conversion}
  11020. \label{sec:closure-conversion-gradual}
  11021. The closure conversion pass only requires one minor adjustment. The
  11022. auxiliary function that translates type annotations needs to be
  11023. updated to handle the \code{PVector} type.
  11024. \section{Explicate Control}
  11025. \label{sec:explicate-control-gradual}
  11026. Update the \code{explicate-control} pass to handle the new primitive
  11027. operations on the \code{PVector} type.
  11028. \section{Select Instructions}
  11029. \label{sec:select-instructions-gradual}
  11030. Recall that the \code{select-instructions} pass is responsible for
  11031. lowering the primitive operations into x86 instructions. So we need
  11032. to translate the new \code{PVector} operations to x86. To do so, the
  11033. first question we need to answer is how will we differentiate the two
  11034. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  11035. We need just one bit to accomplish this, so we use the $57$th bit of
  11036. the 64-bit tag at the front of every vector (see
  11037. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  11038. for \code{inject-vector} we leave it that way.
  11039. \begin{lstlisting}
  11040. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  11041. |$\Rightarrow$|
  11042. movq |$e'_1$|, |$\itm{lhs'}$|
  11043. \end{lstlisting}
  11044. On the other hand, \code{inject-proxy} sets the $57$th bit to $1$.
  11045. \begin{lstlisting}
  11046. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  11047. |$\Rightarrow$|
  11048. movq |$e'_1$|, %r11
  11049. movq |$(1 << 57)$|, %rax
  11050. orq 0(%r11), %rax
  11051. movq %rax, 0(%r11)
  11052. movq %r11, |$\itm{lhs'}$|
  11053. \end{lstlisting}
  11054. The \code{proxy?} operation consumes the information so carefully
  11055. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  11056. isolates the $57$th bit to tell whether the value is a real vector or
  11057. a proxy.
  11058. \begin{lstlisting}
  11059. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  11060. |$\Rightarrow$|
  11061. movq |$e_1'$|, %r11
  11062. movq 0(%r11), %rax
  11063. sarq $57, %rax
  11064. andq $1, %rax
  11065. movq %rax, |$\itm{lhs'}$|
  11066. \end{lstlisting}
  11067. The \code{project-vector} operation is straightforward to translate,
  11068. so we leave it up to the reader.
  11069. Regarding the \code{proxy-vector} operations, the runtime provides
  11070. procedures that implement them (they are recursive functions!) so
  11071. here we simply need to translate these vector operations into the
  11072. appropriate function call. For example, here is the translation for
  11073. \code{proxy-vector-ref}.
  11074. \begin{lstlisting}
  11075. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  11076. |$\Rightarrow$|
  11077. movq |$e_1'$|, %rdi
  11078. movq |$e_2'$|, %rsi
  11079. callq proxy_vector_ref
  11080. movq %rax, |$\itm{lhs'}$|
  11081. \end{lstlisting}
  11082. We have another batch of vector operations to deal with, those for the
  11083. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  11084. \code{any-vector-ref} when there is a \code{vector-ref} on something
  11085. of type \code{Any}, and similarly for \code{any-vector-set!} and
  11086. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  11087. Section~\ref{sec:select-r6} we selected instructions for these
  11088. operations based on the idea that the underlying value was a real
  11089. vector. But in the current setting, the underlying value is of type
  11090. \code{PVector}. So \code{any-vector-ref} can be translates to
  11091. pseudo-x86 as follows. We begin by projecting the underlying value out
  11092. of the tagged value and then call the \code{proxy\_vector\_ref}
  11093. procedure in the runtime.
  11094. \begin{lstlisting}
  11095. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  11096. movq |$\neg 111$|, %rdi
  11097. andq |$e_1'$|, %rdi
  11098. movq |$e_2'$|, %rsi
  11099. callq proxy_vector_ref
  11100. movq %rax, |$\itm{lhs'}$|
  11101. \end{lstlisting}
  11102. The \code{any-vector-set!} and \code{any-vector-length} operators can
  11103. be translated in a similar way.
  11104. \begin{exercise}\normalfont
  11105. Implement a compiler for the gradually-typed \LangGrad{} language by
  11106. extending and adapting your compiler for \LangLoop{}. Create 10 new
  11107. partially-typed test programs. In addition to testing with these
  11108. new programs, also test your compiler on all the tests for \LangLoop{}
  11109. and tests for \LangDyn{}. Sometimes you may get a type checking error
  11110. on the \LangDyn{} programs but you can adapt them by inserting
  11111. a cast to the \code{Any} type around each subexpression
  11112. causing a type error. While \LangDyn{} doesn't have explicit casts,
  11113. you can induce one by wrapping the subexpression \code{e}
  11114. with a call to an un-annotated identity function, like this:
  11115. \code{((lambda (x) x) e)}.
  11116. \end{exercise}
  11117. \begin{figure}[p]
  11118. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11119. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  11120. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  11121. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  11122. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  11123. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  11124. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  11125. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  11126. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  11127. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  11128. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  11129. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  11130. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  11131. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  11132. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  11133. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  11134. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  11135. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  11136. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  11137. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  11138. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  11139. \path[->,bend right=15] (Rgradual) edge [above] node
  11140. {\ttfamily\footnotesize type-check} (Rgradualp);
  11141. \path[->,bend right=15] (Rgradualp) edge [above] node
  11142. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  11143. \path[->,bend right=15] (Rwhilepp) edge [right] node
  11144. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  11145. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  11146. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  11147. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  11148. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  11149. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  11150. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  11151. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  11152. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  11153. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  11154. {\ttfamily\footnotesize convert-assignments} (F1-1);
  11155. \path[->,bend left=15] (F1-1) edge [below] node
  11156. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  11157. \path[->,bend right=15] (F1-2) edge [above] node
  11158. {\ttfamily\footnotesize limit-fun.} (F1-3);
  11159. \path[->,bend right=15] (F1-3) edge [above] node
  11160. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  11161. \path[->,bend right=15] (F1-4) edge [above] node
  11162. {\ttfamily\footnotesize remove-complex.} (F1-5);
  11163. \path[->,bend right=15] (F1-5) edge [right] node
  11164. {\ttfamily\footnotesize explicate-control} (C3-2);
  11165. \path[->,bend left=15] (C3-2) edge [left] node
  11166. {\ttfamily\footnotesize select-instr.} (x86-2);
  11167. \path[->,bend right=15] (x86-2) edge [left] node
  11168. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  11169. \path[->,bend right=15] (x86-2-1) edge [below] node
  11170. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  11171. \path[->,bend right=15] (x86-2-2) edge [left] node
  11172. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  11173. \path[->,bend left=15] (x86-3) edge [above] node
  11174. {\ttfamily\footnotesize patch-instr.} (x86-4);
  11175. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  11176. \end{tikzpicture}
  11177. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  11178. \label{fig:Rgradual-passes}
  11179. \end{figure}
  11180. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  11181. for the compilation of \LangGrad{}.
  11182. \section{Further Reading}
  11183. This chapter just scratches the surface of gradual typing. The basic
  11184. approach described here is missing two key ingredients that one would
  11185. want in a implementation of gradual typing: blame
  11186. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  11187. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  11188. problem addressed by blame tracking is that when a cast on a
  11189. higher-order value fails, it often does so at a point in the program
  11190. that is far removed from the original cast. Blame tracking is a
  11191. technique for propagating extra information through casts and proxies
  11192. so that when a cast fails, the error message can point back to the
  11193. original location of the cast in the source program.
  11194. The problem addressed by space-efficient casts also relates to
  11195. higher-order casts. It turns out that in partially typed programs, a
  11196. function or vector can flow through very-many casts at runtime. With
  11197. the approach described in this chapter, each cast adds another
  11198. \code{lambda} wrapper or a vector proxy. Not only does this take up
  11199. considerable space, but it also makes the function calls and vector
  11200. operations slow. For example, a partially-typed version of quicksort
  11201. could, in the worst case, build a chain of proxies of length $O(n)$
  11202. around the vector, changing the overall time complexity of the
  11203. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  11204. solution to this problem by representing casts using the coercion
  11205. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  11206. long chains of proxies by compressing them into a concise normal
  11207. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  11208. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  11209. the Grift compiler.
  11210. \begin{center}
  11211. \url{https://github.com/Gradual-Typing/Grift}
  11212. \end{center}
  11213. There are also interesting interactions between gradual typing and
  11214. other language features, such as parametetric polymorphism,
  11215. information-flow types, and type inference, to name a few. We
  11216. recommend the reader to the online gradual typing bibliography:
  11217. \begin{center}
  11218. \url{http://samth.github.io/gradual-typing-bib/}
  11219. \end{center}
  11220. % TODO: challenge problem:
  11221. % type analysis and type specialization?
  11222. % coercions?
  11223. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11224. \chapter{Parametric Polymorphism}
  11225. \label{ch:parametric-polymorphism}
  11226. \index{parametric polymorphism}
  11227. \index{generics}
  11228. This chapter studies the compilation of parametric
  11229. polymorphism\index{parametric polymorphism}
  11230. (aka. generics\index{generics}) in the subset \LangPoly{} of Typed
  11231. Racket. Parametric polymorphism enables improved code reuse by
  11232. parameterizing functions and data structures with respect to the types
  11233. that they operate on. For example, Figure~\ref{fig:map-vec-poly}
  11234. revisits the \code{map-vec} example but this time gives it a more
  11235. fitting type. This \code{map-vec} function is parameterized with
  11236. respect to the element type of the vector. The type of \code{map-vec}
  11237. is the following polymorphic type as specified by the \code{All} and
  11238. the type parameter \code{a}.
  11239. \begin{lstlisting}
  11240. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  11241. \end{lstlisting}
  11242. The idea is that \code{map-vec} can be used at \emph{all} choices of a
  11243. type for parameter \code{a}. In Figure~\ref{fig:map-vec-poly} we apply
  11244. \code{map-vec} to a vector of integers, a choice of \code{Integer} for
  11245. \code{a}, but we could have just as well applied \code{map-vec} to a
  11246. vector of Booleans (and a function on Booleans).
  11247. \begin{figure}[tbp]
  11248. % poly_test_2.rkt
  11249. \begin{lstlisting}
  11250. (: map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  11251. (define (map-vec f v)
  11252. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11253. (define (add1 [x : Integer]) : Integer (+ x 1))
  11254. (vector-ref (map-vec add1 (vector 0 41)) 1)
  11255. \end{lstlisting}
  11256. \caption{The \code{map-vec} example using parametric polymorphism.}
  11257. \label{fig:map-vec-poly}
  11258. \end{figure}
  11259. Figure~\ref{fig:r10-concrete-syntax} defines the concrete syntax of
  11260. \LangPoly{} and Figure~\ref{fig:r10-syntax} defines the abstract
  11261. syntax. We add a second form for function definitions in which a type
  11262. declaration comes before the \code{define}. In the abstract syntax,
  11263. the return type in the \code{Def} is \code{Any}, but that should be
  11264. ignored in favor of the return type in the type declaration. (The
  11265. \code{Any} comes from using the same parser as in
  11266. Chapter~\ref{ch:type-dynamic}.) The presence of a type declaration
  11267. enables the use of an \code{All} type for a function, thereby making
  11268. it polymorphic. The grammar for types is extended to include
  11269. polymorphic types and type variables.
  11270. \begin{figure}[tp]
  11271. \centering
  11272. \fbox{
  11273. \begin{minipage}{0.96\textwidth}
  11274. \small
  11275. \[
  11276. \begin{array}{lcl}
  11277. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11278. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  11279. &\mid& \LP\key{:}~\Var~\Type\RP \\
  11280. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  11281. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  11282. \end{array}
  11283. \]
  11284. \end{minipage}
  11285. }
  11286. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  11287. (Figure~\ref{fig:r8-concrete-syntax}).}
  11288. \label{fig:r10-concrete-syntax}
  11289. \end{figure}
  11290. \begin{figure}[tp]
  11291. \centering
  11292. \fbox{
  11293. \begin{minipage}{0.96\textwidth}
  11294. \small
  11295. \[
  11296. \begin{array}{lcl}
  11297. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11298. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  11299. &\mid& \DECL{\Var}{\Type} \\
  11300. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  11301. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11302. \end{array}
  11303. \]
  11304. \end{minipage}
  11305. }
  11306. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  11307. (Figure~\ref{fig:r8-syntax}).}
  11308. \label{fig:r10-syntax}
  11309. \end{figure}
  11310. By including polymorphic types in the $\Type$ non-terminal we choose
  11311. to make them first-class which has interesting repercussions on the
  11312. compiler. Many languages with polymorphism, such as
  11313. C++~\citep{stroustrup88:_param_types} and Standard
  11314. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  11315. it is useful to see an example of first-class polymorphism. In
  11316. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  11317. whose parameter is a polymorphic function. The occurrence of a
  11318. polymorphic type underneath a function type is enabled by the normal
  11319. recursive structure of the grammar for $\Type$ and the categorization
  11320. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  11321. applies the polymorphic function to a Boolean and to an integer.
  11322. \begin{figure}[tbp]
  11323. \begin{lstlisting}
  11324. (: apply-twice ((All (b) (b -> b)) -> Integer))
  11325. (define (apply-twice f)
  11326. (if (f #t) (f 42) (f 777)))
  11327. (: id (All (a) (a -> a)))
  11328. (define (id x) x)
  11329. (apply-twice id)
  11330. \end{lstlisting}
  11331. \caption{An example illustrating first-class polymorphism.}
  11332. \label{fig:apply-twice}
  11333. \end{figure}
  11334. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Rvar0} has
  11335. three new responsibilities (compared to \LangLoop{}). The type checking of
  11336. function application is extended to handle the case where the operator
  11337. expression is a polymorphic function. In that case the type arguments
  11338. are deduced by matching the type of the parameters with the types of
  11339. the arguments.
  11340. %
  11341. The \code{match-types} auxiliary function carries out this deduction
  11342. by recursively descending through a parameter type \code{pt} and the
  11343. corresponding argument type \code{at}, making sure that they are equal
  11344. except when there is a type parameter on the left (in the parameter
  11345. type). If it's the first time that the type parameter has been
  11346. encountered, then the algorithm deduces an association of the type
  11347. parameter to the corresponding type on the right (in the argument
  11348. type). If it's not the first time that the type parameter has been
  11349. encountered, the algorithm looks up its deduced type and makes sure
  11350. that it is equal to the type on the right.
  11351. %
  11352. Once the type arguments are deduced, the operator expression is
  11353. wrapped in an \code{Inst} AST node (for instantiate) that records the
  11354. type of the operator, but more importantly, records the deduced type
  11355. arguments. The return type of the application is the return type of
  11356. the polymorphic function, but with the type parameters replaced by the
  11357. deduced type arguments, using the \code{subst-type} function.
  11358. The second responsibility of the type checker is extending the
  11359. function \code{type-equal?} to handle the \code{All} type. This is
  11360. not quite a simple as equal on other types, such as function and
  11361. vector types, because two polymorphic types can be syntactically
  11362. different even though they are equivalent types. For example,
  11363. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  11364. Two polymorphic types should be considered equal if they differ only
  11365. in the choice of the names of the type parameters. The
  11366. \code{type-equal?} function in Figure~\ref{fig:type-check-Rvar0-aux}
  11367. renames the type parameters of the first type to match the type
  11368. parameters of the second type.
  11369. The third responsibility of the type checker is making sure that only
  11370. defined type variables appear in type annotations. The
  11371. \code{check-well-formed} function defined in
  11372. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  11373. sure that each type variable has been defined.
  11374. The output language of the type checker is \LangInst{}, defined in
  11375. Figure~\ref{fig:r10-prime-syntax}. The type checker combines the type
  11376. declaration and polymorphic function into a single definition, using
  11377. the \code{Poly} form, to make polymorphic functions more convenient to
  11378. process in next pass of the compiler.
  11379. \begin{figure}[tp]
  11380. \centering
  11381. \fbox{
  11382. \begin{minipage}{0.96\textwidth}
  11383. \small
  11384. \[
  11385. \begin{array}{lcl}
  11386. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11387. \Exp &::=& \ldots \mid \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  11388. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  11389. &\mid& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  11390. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11391. \end{array}
  11392. \]
  11393. \end{minipage}
  11394. }
  11395. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  11396. (Figure~\ref{fig:r8-syntax}).}
  11397. \label{fig:r10-prime-syntax}
  11398. \end{figure}
  11399. The output of the type checker on the polymorphic \code{map-vec}
  11400. example is listed in Figure~\ref{fig:map-vec-type-check}.
  11401. \begin{figure}[tbp]
  11402. % poly_test_2.rkt
  11403. \begin{lstlisting}
  11404. (poly (a) (define (map-vec [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  11405. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  11406. (define (add1 [x : Integer]) : Integer (+ x 1))
  11407. (vector-ref ((inst map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  11408. (Integer))
  11409. add1 (vector 0 41)) 1)
  11410. \end{lstlisting}
  11411. \caption{Output of the type checker on the \code{map-vec} example.}
  11412. \label{fig:map-vec-type-check}
  11413. \end{figure}
  11414. \begin{figure}[tbp]
  11415. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11416. (define type-check-poly-class
  11417. (class type-check-Rwhile-class
  11418. (super-new)
  11419. (inherit check-type-equal?)
  11420. (define/override (type-check-apply env e1 es)
  11421. (define-values (e^ ty) ((type-check-exp env) e1))
  11422. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  11423. ((type-check-exp env) e)))
  11424. (match ty
  11425. [`(,ty^* ... -> ,rt)
  11426. (for ([arg-ty ty*] [param-ty ty^*])
  11427. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  11428. (values e^ es^ rt)]
  11429. [`(All ,xs (,tys ... -> ,rt))
  11430. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  11431. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  11432. (match-types env^^ param-ty arg-ty)))
  11433. (define targs
  11434. (for/list ([x xs])
  11435. (match (dict-ref env^^ x (lambda () #f))
  11436. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  11437. x (Apply e1 es))]
  11438. [ty ty])))
  11439. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  11440. [else (error 'type-check "expected a function, not ~a" ty)]))
  11441. (define/override ((type-check-exp env) e)
  11442. (match e
  11443. [(Lambda `([,xs : ,Ts] ...) rT body)
  11444. (for ([T Ts]) ((check-well-formed env) T))
  11445. ((check-well-formed env) rT)
  11446. ((super type-check-exp env) e)]
  11447. [(HasType e1 ty)
  11448. ((check-well-formed env) ty)
  11449. ((super type-check-exp env) e)]
  11450. [else ((super type-check-exp env) e)]))
  11451. (define/override ((type-check-def env) d)
  11452. (verbose 'type-check "poly/def" d)
  11453. (match d
  11454. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  11455. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  11456. (for ([p ps]) ((check-well-formed ts-env) p))
  11457. ((check-well-formed ts-env) rt)
  11458. (define new-env (append ts-env (map cons xs ps) env))
  11459. (define-values (body^ ty^) ((type-check-exp new-env) body))
  11460. (check-type-equal? ty^ rt body)
  11461. (Generic ts (Def f p:t* rt info body^))]
  11462. [else ((super type-check-def env) d)]))
  11463. (define/override (type-check-program p)
  11464. (match p
  11465. [(Program info body)
  11466. (type-check-program (ProgramDefsExp info '() body))]
  11467. [(ProgramDefsExp info ds body)
  11468. (define ds^ (combine-decls-defs ds))
  11469. (define new-env (for/list ([d ds^])
  11470. (cons (def-name d) (fun-def-type d))))
  11471. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  11472. (define-values (body^ ty) ((type-check-exp new-env) body))
  11473. (check-type-equal? ty 'Integer body)
  11474. (ProgramDefsExp info ds^^ body^)]))
  11475. ))
  11476. \end{lstlisting}
  11477. \caption{Type checker for the \LangPoly{} language.}
  11478. \label{fig:type-check-Rvar0}
  11479. \end{figure}
  11480. \begin{figure}[tbp]
  11481. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11482. (define/override (type-equal? t1 t2)
  11483. (match* (t1 t2)
  11484. [(`(All ,xs ,T1) `(All ,ys ,T2))
  11485. (define env (map cons xs ys))
  11486. (type-equal? (subst-type env T1) T2)]
  11487. [(other wise)
  11488. (super type-equal? t1 t2)]))
  11489. (define/public (match-types env pt at)
  11490. (match* (pt at)
  11491. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  11492. [('Void 'Void) env] [('Any 'Any) env]
  11493. [(`(Vector ,pts ...) `(Vector ,ats ...))
  11494. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  11495. (match-types env^ pt1 at1))]
  11496. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  11497. (define env^ (match-types env prt art))
  11498. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  11499. (match-types env^^ pt1 at1))]
  11500. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  11501. (define env^ (append (map cons pxs axs) env))
  11502. (match-types env^ pt1 at1)]
  11503. [((? symbol? x) at)
  11504. (match (dict-ref env x (lambda () #f))
  11505. [#f (error 'type-check "undefined type variable ~a" x)]
  11506. ['Type (cons (cons x at) env)]
  11507. [t^ (check-type-equal? at t^ 'matching) env])]
  11508. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  11509. (define/public (subst-type env pt)
  11510. (match pt
  11511. ['Integer 'Integer] ['Boolean 'Boolean]
  11512. ['Void 'Void] ['Any 'Any]
  11513. [`(Vector ,ts ...)
  11514. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  11515. [`(,ts ... -> ,rt)
  11516. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  11517. [`(All ,xs ,t)
  11518. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  11519. [(? symbol? x) (dict-ref env x)]
  11520. [else (error 'type-check "expected a type not ~a" pt)]))
  11521. (define/public (combine-decls-defs ds)
  11522. (match ds
  11523. ['() '()]
  11524. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  11525. (unless (equal? name f)
  11526. (error 'type-check "name mismatch, ~a != ~a" name f))
  11527. (match type
  11528. [`(All ,xs (,ps ... -> ,rt))
  11529. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  11530. (cons (Generic xs (Def name params^ rt info body))
  11531. (combine-decls-defs ds^))]
  11532. [`(,ps ... -> ,rt)
  11533. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  11534. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  11535. [else (error 'type-check "expected a function type, not ~a" type) ])]
  11536. [`(,(Def f params rt info body) . ,ds^)
  11537. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  11538. \end{lstlisting}
  11539. \caption{Auxiliary functions for type checking \LangPoly{}.}
  11540. \label{fig:type-check-Rvar0-aux}
  11541. \end{figure}
  11542. \begin{figure}[tbp]
  11543. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  11544. (define/public ((check-well-formed env) ty)
  11545. (match ty
  11546. ['Integer (void)]
  11547. ['Boolean (void)]
  11548. ['Void (void)]
  11549. [(? symbol? a)
  11550. (match (dict-ref env a (lambda () #f))
  11551. ['Type (void)]
  11552. [else (error 'type-check "undefined type variable ~a" a)])]
  11553. [`(Vector ,ts ...)
  11554. (for ([t ts]) ((check-well-formed env) t))]
  11555. [`(,ts ... -> ,t)
  11556. (for ([t ts]) ((check-well-formed env) t))
  11557. ((check-well-formed env) t)]
  11558. [`(All ,xs ,t)
  11559. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  11560. ((check-well-formed env^) t)]
  11561. [else (error 'type-check "unrecognized type ~a" ty)]))
  11562. \end{lstlisting}
  11563. \caption{Well-formed types.}
  11564. \label{fig:well-formed-types}
  11565. \end{figure}
  11566. % TODO: interpreter for R'_10
  11567. \section{Compiling Polymorphism}
  11568. \label{sec:compiling-poly}
  11569. Broadly speaking, there are four approaches to compiling parametric
  11570. polymorphism, which we describe below.
  11571. \begin{description}
  11572. \item[Monomorphization] generates a different version of a polymorphic
  11573. function for each set of type arguments that it is used with,
  11574. producing type-specialized code. This approach results in the most
  11575. efficient code but requires whole-program compilation (no separate
  11576. compilation) and increases code size. For our current purposes
  11577. monomorphization is a non-starter because, with first-class
  11578. polymorphism, it is sometimes not possible to determine which
  11579. generic functions are used with which type arguments during
  11580. compilation. (It can be done at runtime, with just-in-time
  11581. compilation.) This approach is used to compile C++
  11582. templates~\citep{stroustrup88:_param_types} and polymorphic
  11583. functions in NESL~\citep{Blelloch:1993aa} and
  11584. ML~\citep{Weeks:2006aa}.
  11585. \item[Uniform representation] generates one version of each
  11586. polymorphic function but requires all values have a common ``boxed''
  11587. format, such as the tagged values of type \code{Any} in
  11588. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  11589. similarly to code in a dynamically typed language (like \LangDyn{}), in
  11590. which primitive operators require their arguments to be projected
  11591. from \code{Any} and their results are injected into \code{Any}. (In
  11592. object-oriented languages, the projection is accomplished via
  11593. virtual method dispatch.) The uniform representation approach is
  11594. compatible with separate compilation and with first-class
  11595. polymorphism. However, it produces the least-efficient code because
  11596. it introduces overhead in the entire program, including
  11597. non-polymorphic code. This approach is used in the implementation of
  11598. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  11599. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  11600. Java~\citep{Bracha:1998fk}.
  11601. \item[Mixed representation] generates one version of each polymorphic
  11602. function, using a boxed representation for type
  11603. variables. Monomorphic code is compiled as usual (as in \LangLoop{}) and
  11604. conversions are performed at the boundaries between monomorphic and
  11605. polymorphic (e.g. when a polymorphic function is instantiated and
  11606. called). This approach is compatible with separate compilation and
  11607. first-class polymorphism and maintains the efficiency for
  11608. monomorphic code. The tradeoff is increased overhead at the boundary
  11609. between monomorphic and polymorphic code. This approach is used in
  11610. compilers for variants of ML~\citep{Leroy:1992qb} and starting in
  11611. Java 5 with the addition of autoboxing.
  11612. \item[Type passing] uses the unboxed representation in both
  11613. monomorphic and polymorphic code. Each polymorphic function is
  11614. compiled to a single function with extra parameters that describe
  11615. the type arguments. The type information is used by the generated
  11616. code to direct access of the unboxed values at runtime. This
  11617. approach is used in compilers for the Napier88
  11618. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. This
  11619. approach is compatible with separate compilation and first-class
  11620. polymorphism and maintains the efficiency for monomorphic
  11621. code. There is runtime overhead in polymorphic code from dispatching
  11622. on type information.
  11623. \end{description}
  11624. In this chapter we use the mixed representation approach, partly
  11625. because of its favorable attributes, and partly because it is
  11626. straightforward to implement using the tools that we have already
  11627. built to support gradual typing. To compile polymorphic functions, we
  11628. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  11629. \LangCast{}.
  11630. \section{Erase Types}
  11631. \label{sec:erase-types}
  11632. We use the \code{Any} type from Chapter~\ref{ch:type-dynamic} to
  11633. represent type variables. For example, Figure~\ref{fig:map-vec-erase}
  11634. shows the output of the \code{erase-types} pass on the polymorphic
  11635. \code{map-vec} (Figure~\ref{fig:map-vec-poly}). The occurrences of
  11636. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  11637. \code{All} types are removed from the type of \code{map-vec}.
  11638. \begin{figure}[tbp]
  11639. \begin{lstlisting}
  11640. (define (map-vec [f : (Any -> Any)] [v : (Vector Any Any)])
  11641. : (Vector Any Any)
  11642. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11643. (define (add1 [x : Integer]) : Integer (+ x 1))
  11644. (vector-ref ((cast map-vec
  11645. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  11646. ((Integer -> Integer) (Vector Integer Integer)
  11647. -> (Vector Integer Integer)))
  11648. add1 (vector 0 41)) 1)
  11649. \end{lstlisting}
  11650. \caption{The polymorphic \code{map-vec} example after type erasure.}
  11651. \label{fig:map-vec-erase}
  11652. \end{figure}
  11653. This process of type erasure creates a challenge at points of
  11654. instantiation. For example, consider the instantiation of
  11655. \code{map-vec} in Figure~\ref{fig:map-vec-type-check}.
  11656. The type of \code{map-vec} is
  11657. \begin{lstlisting}
  11658. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  11659. \end{lstlisting}
  11660. and it is instantiated to
  11661. \begin{lstlisting}
  11662. ((Integer -> Integer) (Vector Integer Integer)
  11663. -> (Vector Integer Integer))
  11664. \end{lstlisting}
  11665. After erasure, the type of \code{map-vec} is
  11666. \begin{lstlisting}
  11667. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  11668. \end{lstlisting}
  11669. but we need to convert it to the instantiated type. This is easy to
  11670. do in the target language \LangCast{} with a single \code{cast}. In
  11671. Figure~\ref{fig:map-vec-erase}, the instantiation of \code{map-vec}
  11672. has been compiled to a \code{cast} from the type of \code{map-vec} to
  11673. the instantiated type. The source and target type of a cast must be
  11674. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  11675. because both the source and target are obtained from the same
  11676. polymorphic type of \code{map-vec}, replacing the type parameters with
  11677. \code{Any} in the former and with the deduced type arguments in the
  11678. later. (Recall that the \code{Any} type is consistent with any type.)
  11679. To implement the \code{erase-types} pass, we recommend defining a
  11680. recursive auxiliary function named \code{erase-type} that applies the
  11681. following two transformations. It replaces type variables with
  11682. \code{Any}
  11683. \begin{lstlisting}
  11684. |$x$|
  11685. |$\Rightarrow$|
  11686. Any
  11687. \end{lstlisting}
  11688. and it removes the polymorphic \code{All} types.
  11689. \begin{lstlisting}
  11690. (All |$xs$| |$T_1$|)
  11691. |$\Rightarrow$|
  11692. |$T'_1$|
  11693. \end{lstlisting}
  11694. Apply the \code{erase-type} function to all of the type annotations in
  11695. the program.
  11696. Regarding the translation of expressions, the case for \code{Inst} is
  11697. the interesting one. We translate it into a \code{Cast}, as shown
  11698. below. The type of the subexpression $e$ is the polymorphic type
  11699. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  11700. $T$, the type $T'$. The target type $T''$ is the result of
  11701. substituting the arguments types $ts$ for the type parameters $xs$ in
  11702. $T$ followed by doing type erasure.
  11703. \begin{lstlisting}
  11704. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  11705. |$\Rightarrow$|
  11706. (Cast |$e'$| |$T'$| |$T''$|)
  11707. \end{lstlisting}
  11708. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  11709. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  11710. Finally, each polymorphic function is translated to a regular
  11711. functions in which type erasure has been applied to all the type
  11712. annotations and the body.
  11713. \begin{lstlisting}
  11714. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  11715. |$\Rightarrow$|
  11716. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  11717. \end{lstlisting}
  11718. \begin{exercise}\normalfont
  11719. Implement a compiler for the polymorphic language \LangPoly{} by
  11720. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  11721. programs that use polymorphic functions. Some of them should make
  11722. use of first-class polymorphism.
  11723. \end{exercise}
  11724. \begin{figure}[p]
  11725. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11726. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  11727. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  11728. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  11729. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  11730. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  11731. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  11732. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  11733. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  11734. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  11735. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  11736. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  11737. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  11738. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  11739. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  11740. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  11741. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  11742. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  11743. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  11744. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  11745. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  11746. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  11747. \path[->,bend right=15] (Rpoly) edge [above] node
  11748. {\ttfamily\footnotesize type-check} (Rpolyp);
  11749. \path[->,bend right=15] (Rpolyp) edge [above] node
  11750. {\ttfamily\footnotesize erase-types} (Rgradualp);
  11751. \path[->,bend right=15] (Rgradualp) edge [above] node
  11752. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  11753. \path[->,bend right=15] (Rwhilepp) edge [right] node
  11754. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  11755. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  11756. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  11757. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  11758. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  11759. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  11760. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  11761. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  11762. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  11763. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  11764. {\ttfamily\footnotesize convert-assignments} (F1-1);
  11765. \path[->,bend left=15] (F1-1) edge [below] node
  11766. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  11767. \path[->,bend right=15] (F1-2) edge [above] node
  11768. {\ttfamily\footnotesize limit-fun.} (F1-3);
  11769. \path[->,bend right=15] (F1-3) edge [above] node
  11770. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  11771. \path[->,bend right=15] (F1-4) edge [above] node
  11772. {\ttfamily\footnotesize remove-complex.} (F1-5);
  11773. \path[->,bend right=15] (F1-5) edge [right] node
  11774. {\ttfamily\footnotesize explicate-control} (C3-2);
  11775. \path[->,bend left=15] (C3-2) edge [left] node
  11776. {\ttfamily\footnotesize select-instr.} (x86-2);
  11777. \path[->,bend right=15] (x86-2) edge [left] node
  11778. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  11779. \path[->,bend right=15] (x86-2-1) edge [below] node
  11780. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  11781. \path[->,bend right=15] (x86-2-2) edge [left] node
  11782. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  11783. \path[->,bend left=15] (x86-3) edge [above] node
  11784. {\ttfamily\footnotesize patch-instr.} (x86-4);
  11785. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  11786. \end{tikzpicture}
  11787. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  11788. \label{fig:Rpoly-passes}
  11789. \end{figure}
  11790. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  11791. for the compilation of \LangPoly{}.
  11792. % TODO: challenge problem: specialization of instantiations
  11793. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11794. \chapter{Appendix}
  11795. \section{Interpreters}
  11796. \label{appendix:interp}
  11797. \index{interpreter}
  11798. We provide interpreters for each of the source languages \LangInt{},
  11799. \LangVar{}, $\ldots$ in the files \code{interp-Rint.rkt},
  11800. \code{interp-Rvar.rkt}, etc. The interpreters for the intermediate
  11801. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  11802. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  11803. and x86 are in the \key{interp.rkt} file.
  11804. \section{Utility Functions}
  11805. \label{appendix:utilities}
  11806. The utility functions described in this section are in the
  11807. \key{utilities.rkt} file of the support code.
  11808. \paragraph{\code{interp-tests}}
  11809. The \key{interp-tests} function runs the compiler passes and the
  11810. interpreters on each of the specified tests to check whether each pass
  11811. is correct. The \key{interp-tests} function has the following
  11812. parameters:
  11813. \begin{description}
  11814. \item[name (a string)] a name to identify the compiler,
  11815. \item[typechecker] a function of exactly one argument that either
  11816. raises an error using the \code{error} function when it encounters a
  11817. type error, or returns \code{\#f} when it encounters a type
  11818. error. If there is no type error, the type checker returns the
  11819. program.
  11820. \item[passes] a list with one entry per pass. An entry is a list with
  11821. four things:
  11822. \begin{enumerate}
  11823. \item a string giving the name of the pass,
  11824. \item the function that implements the pass (a translator from AST
  11825. to AST),
  11826. \item a function that implements the interpreter (a function from
  11827. AST to result value) for the output language,
  11828. \item and a type checker for the output language. Type checkers for
  11829. the $R$ and $C$ languages are provided in the support code. For
  11830. example, the type checkers for \LangVar{} and \LangCVar{} are in
  11831. \code{type-check-Rvar.rkt} and \code{type-check-Cvar.rkt}. The
  11832. type checker entry is optional. The support code does not provide
  11833. type checkers for the x86 languages.
  11834. \end{enumerate}
  11835. \item[source-interp] an interpreter for the source language. The
  11836. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  11837. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  11838. \item[tests] a list of test numbers that specifies which tests to
  11839. run. (see below)
  11840. \end{description}
  11841. %
  11842. The \key{interp-tests} function assumes that the subdirectory
  11843. \key{tests} has a collection of Racket programs whose names all start
  11844. with the family name, followed by an underscore and then the test
  11845. number, ending with the file extension \key{.rkt}. Also, for each test
  11846. program that calls \code{read} one or more times, there is a file with
  11847. the same name except that the file extension is \key{.in} that
  11848. provides the input for the Racket program. If the test program is
  11849. expected to fail type checking, then there should be an empty file of
  11850. the same name but with extension \key{.tyerr}.
  11851. \paragraph{\code{compiler-tests}}
  11852. runs the compiler passes to generate x86 (a \key{.s} file) and then
  11853. runs the GNU C compiler (gcc) to generate machine code. It runs the
  11854. machine code and checks that the output is $42$. The parameters to the
  11855. \code{compiler-tests} function are similar to those of the
  11856. \code{interp-tests} function, and consist of
  11857. \begin{itemize}
  11858. \item a compiler name (a string),
  11859. \item a type checker,
  11860. \item description of the passes,
  11861. \item name of a test-family, and
  11862. \item a list of test numbers.
  11863. \end{itemize}
  11864. \paragraph{\code{compile-file}}
  11865. takes a description of the compiler passes (see the comment for
  11866. \key{interp-tests}) and returns a function that, given a program file
  11867. name (a string ending in \key{.rkt}), applies all of the passes and
  11868. writes the output to a file whose name is the same as the program file
  11869. name but with \key{.rkt} replaced with \key{.s}.
  11870. \paragraph{\code{read-program}}
  11871. takes a file path and parses that file (it must be a Racket program)
  11872. into an abstract syntax tree.
  11873. \paragraph{\code{parse-program}}
  11874. takes an S-expression representation of an abstract syntax tree and converts it into
  11875. the struct-based representation.
  11876. \paragraph{\code{assert}}
  11877. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  11878. and displays the message \key{msg} if the Boolean \key{bool} is false.
  11879. \paragraph{\code{lookup}}
  11880. % remove discussion of lookup? -Jeremy
  11881. takes a key and an alist, and returns the first value that is
  11882. associated with the given key, if there is one. If not, an error is
  11883. triggered. The alist may contain both immutable pairs (built with
  11884. \key{cons}) and mutable pairs (built with \key{mcons}).
  11885. %The \key{map2} function ...
  11886. \section{x86 Instruction Set Quick-Reference}
  11887. \label{sec:x86-quick-reference}
  11888. \index{x86}
  11889. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  11890. do. We write $A \to B$ to mean that the value of $A$ is written into
  11891. location $B$. Address offsets are given in bytes. The instruction
  11892. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  11893. registers (such as \code{\%rax}), or memory references (such as
  11894. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  11895. reference per instruction. Other operands must be immediates or
  11896. registers.
  11897. \begin{table}[tbp]
  11898. \centering
  11899. \begin{tabular}{l|l}
  11900. \textbf{Instruction} & \textbf{Operation} \\ \hline
  11901. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  11902. \texttt{negq} $A$ & $- A \to A$ \\
  11903. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  11904. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  11905. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  11906. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  11907. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  11908. \texttt{retq} & Pops the return address and jumps to it \\
  11909. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  11910. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  11911. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  11912. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  11913. be an immediate) \\
  11914. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  11915. matches the condition code of the instruction, otherwise go to the
  11916. next instructions. The condition codes are \key{e} for ``equal'',
  11917. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  11918. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  11919. \texttt{jl} $L$ & \\
  11920. \texttt{jle} $L$ & \\
  11921. \texttt{jg} $L$ & \\
  11922. \texttt{jge} $L$ & \\
  11923. \texttt{jmp} $L$ & Jump to label $L$ \\
  11924. \texttt{movq} $A$, $B$ & $A \to B$ \\
  11925. \texttt{movzbq} $A$, $B$ &
  11926. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  11927. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  11928. and the extra bytes of $B$ are set to zero.} \\
  11929. & \\
  11930. & \\
  11931. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  11932. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  11933. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  11934. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  11935. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  11936. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  11937. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  11938. description of the condition codes. $A$ must be a single byte register
  11939. (e.g., \texttt{al} or \texttt{cl}).} \\
  11940. \texttt{setl} $A$ & \\
  11941. \texttt{setle} $A$ & \\
  11942. \texttt{setg} $A$ & \\
  11943. \texttt{setge} $A$ &
  11944. \end{tabular}
  11945. \vspace{5pt}
  11946. \caption{Quick-reference for the x86 instructions used in this book.}
  11947. \label{tab:x86-instr}
  11948. \end{table}
  11949. \cleardoublepage
  11950. \section{Concrete Syntax for Intermediate Languages}
  11951. The concrete syntax of \LangAny{} is defined in
  11952. Figure~\ref{fig:r6-concrete-syntax}.
  11953. \begin{figure}[tp]
  11954. \centering
  11955. \fbox{
  11956. \begin{minipage}{0.97\textwidth}\small
  11957. \[
  11958. \begin{array}{lcl}
  11959. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  11960. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \key{Void}} \\
  11961. &\mid& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \mid \key{Any} \\
  11962. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void}
  11963. \mid \LP\key{Vector}\; \key{Any}\ldots\RP \\
  11964. &\mid& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  11965. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \mid \CPROJECT{\Exp}{\FType}\\
  11966. &\mid& \LP\key{any-vector-length}\;\Exp\RP
  11967. \mid \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  11968. &\mid& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  11969. &\mid& \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP
  11970. \mid \LP\key{void?}\;\Exp\RP \\
  11971. &\mid& \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \\
  11972. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  11973. \LangAny{} &::=& \gray{\Def\ldots \; \Exp}
  11974. \end{array}
  11975. \]
  11976. \end{minipage}
  11977. }
  11978. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  11979. (Figure~\ref{fig:Rlam-syntax}) with \key{Any}.}
  11980. \label{fig:r6-concrete-syntax}
  11981. \end{figure}
  11982. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and \LangCFun{} is
  11983. defined in Figures~\ref{fig:c0-concrete-syntax},
  11984. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax},
  11985. and \ref{fig:c3-concrete-syntax}, respectively.
  11986. \begin{figure}[tbp]
  11987. \fbox{
  11988. \begin{minipage}{0.96\textwidth}
  11989. \[
  11990. \begin{array}{lcl}
  11991. \Atm &::=& \Int \mid \Var \\
  11992. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  11993. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  11994. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  11995. \LangCVar{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  11996. \end{array}
  11997. \]
  11998. \end{minipage}
  11999. }
  12000. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  12001. \label{fig:c0-concrete-syntax}
  12002. \end{figure}
  12003. \begin{figure}[tbp]
  12004. \fbox{
  12005. \begin{minipage}{0.96\textwidth}
  12006. \small
  12007. \[
  12008. \begin{array}{lcl}
  12009. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  12010. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  12011. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  12012. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  12013. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  12014. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  12015. \mid \key{goto}~\itm{label}\key{;}\\
  12016. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  12017. \LangCIf{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  12018. \end{array}
  12019. \]
  12020. \end{minipage}
  12021. }
  12022. \caption{The concrete syntax of the \LangCIf{} intermediate language.}
  12023. \label{fig:c1-concrete-syntax}
  12024. \end{figure}
  12025. \begin{figure}[tbp]
  12026. \fbox{
  12027. \begin{minipage}{0.96\textwidth}
  12028. \small
  12029. \[
  12030. \begin{array}{lcl}
  12031. \Atm &::=& \gray{ \Int \mid \Var \mid \itm{bool} } \\
  12032. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  12033. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  12034. &\mid& \gray{ \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP } \\
  12035. &\mid& \LP \key{allocate}~\Int~\Type \RP \\
  12036. &\mid& (\key{vector-ref}\;\Atm\;\Int) \mid (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  12037. &\mid& \LP \key{global-value}~\Var \RP \mid \LP \key{void} \RP \\
  12038. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \mid \LP\key{collect}~\Int \RP\\
  12039. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  12040. \mid \gray{ \key{goto}~\itm{label}\key{;} }\\
  12041. &\mid& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  12042. \LangCVec{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  12043. \end{array}
  12044. \]
  12045. \end{minipage}
  12046. }
  12047. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  12048. \label{fig:c2-concrete-syntax}
  12049. \end{figure}
  12050. \begin{figure}[tp]
  12051. \fbox{
  12052. \begin{minipage}{0.96\textwidth}
  12053. \small
  12054. \[
  12055. \begin{array}{lcl}
  12056. \Atm &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  12057. \\
  12058. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  12059. \Exp &::= & \gray{ \Atm \mid \LP\key{read}\RP \mid \LP\key{-}\;\Atm\RP \mid \LP\key{+} \; \Atm\;\Atm\RP
  12060. \mid \LP\key{not}\;\Atm\RP \mid \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  12061. &\mid& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  12062. \mid \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  12063. &\mid& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \mid \LP\key{global-value} \,\itm{name}\RP \mid \LP\key{void}\RP } \\
  12064. &\mid& \LP\key{fun-ref}~\itm{label}\RP \mid \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  12065. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  12066. \mid \LP\key{collect} \,\itm{int}\RP }\\
  12067. \Tail &::= & \gray{\RETURN{\Exp} \mid \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  12068. &\mid& \gray{\LP\key{goto}\,\itm{label}\RP
  12069. \mid \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  12070. &\mid& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  12071. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  12072. \LangCFun{} & ::= & \Def\ldots
  12073. \end{array}
  12074. \]
  12075. \end{minipage}
  12076. }
  12077. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  12078. \label{fig:c3-concrete-syntax}
  12079. \end{figure}
  12080. \cleardoublepage
  12081. \addcontentsline{toc}{chapter}{Index}
  12082. \printindex
  12083. \cleardoublepage
  12084. \bibliographystyle{plainnat}
  12085. \bibliography{all}
  12086. \addcontentsline{toc}{chapter}{Bibliography}
  12087. \end{document}
  12088. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  12089. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  12090. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  12091. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  12092. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator jane
  12093. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  12094. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  12095. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  12096. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs Tt
  12097. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  12098. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  12099. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  12100. %% LocalWords: boolean type-check notq cmpq sete movzbq jmp al xorq
  12101. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  12102. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  12103. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  12104. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  12105. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  12106. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  12107. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  12108. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  12109. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  12110. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  12111. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  12112. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  12113. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  12114. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  12115. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  12116. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  12117. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  12118. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  12119. % LocalWords: struct Friedman's MacOS Nystrom alist sam kate
  12120. % LocalWords: alists arity github unordered pqueue exprs ret param
  12121. % LocalWords: tyerr bytereg dh dl JmpIf HasType Osterlund Jacek TODO
  12122. % LocalWords: Gamari GlobalValue ProgramDefsExp prm ProgramDefs vn
  12123. % LocalWords: FunRef TailCall tailjmp IndirectCallq TailJmp Gilray
  12124. % LocalWords: dereference unbox Dataflow versa dataflow Kildall rhs
  12125. % LocalWords: Kleene enqueue dequeue AssignedFree FV cnvt SetBang tg
  12126. % LocalWords: ValueOf typechecker