book.tex 538 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902
  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. There is a magical moment when a programmer presses the ``run'' button
  147. and the software begins to execute. Somehow a program written in a
  148. high-level language is running on a computer that is only capable of
  149. shuffling bits. This book reveals the wizardry that makes that moment
  150. possible. Beginning with the groundbreaking work of Backus and
  151. colleagues in the 1950s, computer scientists discovered techniques for
  152. constructing programs, called \emph{compilers}, that automatically
  153. translate high-level programs into machine code.
  154. This book guides the reader on the journey of constructing their own
  155. compiler for a small but powerful language. Along the way the reader
  156. learns the essential concepts, algorithms, and data structures that
  157. underlie modern compilers. They develop an understanding of how
  158. programs are mapped onto computer hardware which is helpful when
  159. reasoning about execution time, debugging errors across layers of the
  160. software stack, and finding security vulnerabilities.
  161. %
  162. For readers interested in a career in compiler construction, this book
  163. is a stepping-stone to advanced topics such as just-in-time
  164. compilation, program analysis, and program optimization.
  165. %
  166. For readers interested in the design of programming languages, this
  167. book connects language design choices to their impact on the compiler
  168. and generated code.
  169. A compiler is typically organized as a pipeline with a handful of
  170. passes that translate a program into ever lower levels of
  171. abstraction. We take this approach to the extreme by partitioning our
  172. compiler into a large number of \emph{nanopasses}, each of which
  173. performs a single task. This makes the compiler easier to debug,
  174. because we test the output of each pass, and it makes the compiler
  175. easier to understand, because each pass involves fewer concepts.
  176. Most books about compiler construction are structured like the
  177. compiler, with each chapter describing one pass. The problem with that
  178. structure is that it obfuscates how language features motivate design
  179. choices in the compiler. We take an \emph{incremental} approach in
  180. which we build a complete compiler in each chapter, starting with a
  181. tiny language and adding new features in subsequent chapters.
  182. Our choice of language features is designed to elicit the fundamental
  183. concepts and algorithms used in compilers for modern programming
  184. languages.
  185. \begin{itemize}
  186. \item We begin with integer arithmetic and local variables. The
  187. reader becomes acquainted with the basic tools of compiler
  188. construction, \emph{abstract syntax trees} and \emph{recursive
  189. functions}, in Chapter~\ref{ch:trees-recur} and applies them to a
  190. language with integers and variables in Chapter~\ref{ch:Rvar}. In
  191. Chapter~\ref{ch:register-allocation-Rvar} we apply \emph{graph
  192. coloring} to assign variables to registers.
  193. \item Chapter~\ref{ch:Rif} adds conditional control-flow, which
  194. motivates an elegant recursive algorithm for mapping expressions to
  195. \emph{control-flow graphs}.
  196. \item Chapter~\ref{ch:Rvec} adds heap-allocated tuples, motivating
  197. \emph{garbage collection}.
  198. \item Chapter~\ref{ch:Rfun} adds functions that are first-class values
  199. but lack lexical scoping, similar to the C programming
  200. language~\citep{Kernighan:1988nx} except that we generate efficient
  201. tail calls. The reader learns about the procedure call stack,
  202. \emph{calling conventions}, and their interaction with register
  203. allocation and garbage collection.
  204. \item Chapter~\ref{ch:Rlam} adds anonymous functions with lexical
  205. scoping, i.e., \emph{lambda abstraction}. The reader learns about
  206. \emph{closure conversion}, in which lambdas are translated into a
  207. combination of functions and tuples.
  208. \item Chapter~\ref{ch:Rdyn} adds \emph{dynamic typing}. Prior to this
  209. point the input languages are statically typed. The reader extends
  210. the statically typed language with an \code{Any} type which serves
  211. as a target for compiling the dynamically typed language.
  212. \item Chapter~\ref{ch:Rwhile} fleshes out support for imperative
  213. programming languages with the addition of loops and mutable
  214. variables. These additions elicit the need for \emph{dataflow
  215. analysis} in the register allocator.
  216. \item Chapter~\ref{ch:Rgrad} uses the \code{Any} type of
  217. Chapter~\ref{ch:Rdyn} to implement a \emph{gradually typed language}
  218. in which different regions of a program may be static or dynamically
  219. typed. The reader implements runtime support for \emph{proxies} that
  220. allow values to safely move between regions.
  221. \item Chapter~\ref{ch:Rpoly} adds \emph{generics} with autoboxing,
  222. leveraging the \code{Any} type and type casts developed in Chapters
  223. \ref{ch:Rdyn} and \ref{ch:Rgrad}.
  224. \end{itemize}
  225. There are many language features that we do not include. Our choices
  226. weigh the incidental complexity of a feature against the fundamental
  227. concepts that it exposes. For example, we include tuples and not
  228. records because they both elicit the study of heap allocation and
  229. garbage collection but records come with more incidental complexity.
  230. Since 2016 this book has served as the textbook for the compiler
  231. course at Indiana University, a 16-week course for upper-level
  232. undergraduates and first-year graduate students.
  233. %
  234. Prior to this course, students learn to program in both imperative and
  235. functional languages, study data structures and algorithms, and take
  236. discrete mathematics.
  237. %
  238. At the beginning of the course, students form groups of 2-4 people.
  239. The groups complete one chapter every two weeks, starting with
  240. Chapter~\ref{ch:Rvar} and finishing with Chapter~\ref{ch:Rdyn}. Many
  241. chapters include a challenge problem that we assign to the graduate
  242. students. The last two weeks of the course involve a final project in
  243. which students design and implement a compiler extension of their
  244. choosing. Chapters~\ref{ch:Rwhile}, \ref{ch:Rgrad}, and
  245. \ref{ch:Rpoly} can be used in support of these projects or they can
  246. replace some of the earlier chapters. For example, a course with an
  247. emphasis on statically-typed imperative languages would skip
  248. Chapter~\ref{ch:Rdyn} in favor of
  249. Chapter~\ref{ch:Rwhile}. Figure~\ref{fig:chapter-dependences} depicts
  250. the dependencies between chapters.
  251. This book has also been used in compiler courses at California
  252. Polytechnic State University, Rose–Hulman Institute of Technology, and
  253. University of Massachusetts Lowell.
  254. \begin{figure}[tp]
  255. \begin{tikzpicture}[baseline=(current bounding box.center)]
  256. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  257. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Rvar} Variables};
  258. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Rvar} Registers};
  259. \node (C4) at (0,0) {\small Ch.~\ref{ch:Rif} Control Flow};
  260. \node (C5) at (4,0) {\small Ch.~\ref{ch:Rvec} Tuples};
  261. \node (C6) at (8,0) {\small Ch.~\ref{ch:Rfun} Functions};
  262. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Rwhile} Loops};
  263. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Rdyn} Dynamic};
  264. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Rlam} Lambda};
  265. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Rgrad} Gradual};
  266. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Rpoly} Generics};
  267. \path[->] (C1) edge [above] node {} (C2);
  268. \path[->] (C2) edge [above] node {} (C3);
  269. \path[->] (C3) edge [above] node {} (C4);
  270. \path[->] (C4) edge [above] node {} (C5);
  271. \path[->] (C5) edge [above] node {} (C6);
  272. \path[->] (C6) edge [above] node {} (C7);
  273. \path[->] (C4) edge [above] node {} (C8);
  274. \path[->] (C4) edge [above] node {} (C9);
  275. \path[->] (C8) edge [above] node {} (C10);
  276. \path[->] (C10) edge [above] node {} (C11);
  277. \end{tikzpicture}
  278. \caption{Diagram of chapter dependencies.}
  279. \label{fig:chapter-dependences}
  280. \end{figure}
  281. We use the \href{https://racket-lang.org/}{Racket} language both for
  282. the implementation of the compiler and for the input language, so the
  283. reader should be proficient with Racket or Scheme. There are many
  284. excellent resources for learning Scheme and
  285. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. The
  286. support code for this book is in the \code{github} repository at the
  287. following URL:
  288. \begin{center}\small
  289. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  290. \end{center}
  291. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  292. is helpful but not necessary for the reader to have taken a computer
  293. systems course~\citep{Bryant:2010aa}. This book introduces the parts
  294. of x86-64 assembly language that are needed.
  295. %
  296. We follow the System V calling
  297. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  298. that we generate works with the runtime system (written in C) when it
  299. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  300. operating systems.
  301. %
  302. On the Windows operating system, \code{gcc} uses the Microsoft x64
  303. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  304. assembly code that we generate does \emph{not} work with the runtime
  305. system on Windows. One workaround is to use a virtual machine with
  306. Linux as the guest operating system.
  307. % TODO: point to support code on github
  308. %% The tradition of compiler writing at Indiana University goes back to
  309. %% research and courses on programming languages by Professor Daniel
  310. %% Friedman in the 1970's and 1980's. Friedman conducted research on lazy
  311. %% evaluation~\citep{Friedman:1976aa} in the context of
  312. %% Lisp~\citep{McCarthy:1960dz} and then studied
  313. %% continuations~\citep{Felleisen:kx} and
  314. %% macros~\citep{Kohlbecker:1986dk} in the context of the
  315. %% Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  316. %% of those courses, Kent Dybvig, went on to build Chez
  317. %% Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  318. %% compiler for Scheme. After completing his Ph.D. at the University of
  319. %% North Carolina, he returned to teach at Indiana University.
  320. %% Throughout the 1990's and 2000's, Professor Dybvig continued
  321. %% development of Chez Scheme and taught the compiler course.
  322. %% The compiler course evolved to incorporate novel pedagogical ideas
  323. %% while also including elements of effective real-world compilers. One
  324. %% of Friedman's ideas was to split the compiler into many small
  325. %% ``passes'' so that the code for each pass would be easy to understood
  326. %% in isolation. In contrast, most compilers of the time were organized
  327. %% into only a few monolithic passes for reasons of compile-time
  328. %% efficiency. Another idea, called ``the game'', was to test the code
  329. %% generated by each pass on interpreters for each intermediate language,
  330. %% thereby helping to pinpoint errors in individual passes.
  331. %% %
  332. %% Dybvig, with later help from his students Dipanwita Sarkar and Andrew
  333. %% Keep, developed infrastructure to support this approach and evolved
  334. %% the course, first to use smaller micro-passes and then into even
  335. %% smaller nano-passes~\citep{Sarkar:2004fk,Keep:2012aa}. I was a student
  336. %% in this compiler course in the early 2000's as part of my
  337. %% Ph.D. studies at Indiana University. Needless to say, I enjoyed the
  338. %% course immensely!
  339. %% During that time, another graduate student named Abdulaziz Ghuloum
  340. %% observed that the front-to-back organization of the course made it
  341. %% difficult for students to understand the rationale for the compiler
  342. %% design. Ghuloum proposed an incremental approach in which the students
  343. %% start by implementing a complete compiler for a very small subset of
  344. %% the language. In each subsequent stage they add a feature to the
  345. %% language and then add or modify passes to handle the new
  346. %% feature~\citep{Ghuloum:2006bh}. In this way, the students see how the
  347. %% language features motivate aspects of the compiler design.
  348. %% After graduating from Indiana University in 2005, I went on to teach
  349. %% at the University of Colorado. I adapted the nano-pass and incremental
  350. %% approaches to compiling a subset of the Python
  351. %% language~\citep{Siek:2012ab}.
  352. %% %% Python and Scheme are quite different
  353. %% %% on the surface but there is a large overlap in the compiler techniques
  354. %% %% required for the two languages. Thus, I was able to teach much of the
  355. %% %% same content from the Indiana compiler course.
  356. %% I very much enjoyed teaching the course organized in this way, and
  357. %% even better, many of the students learned a lot and got excited about
  358. %% compilers.
  359. %% I returned to Indiana University in 2013. In my absence the compiler
  360. %% course had switched from the front-to-back organization to a
  361. %% back-to-front~\citep{Dybvig:2010aa}. While that organization also works
  362. %% well, I prefer the incremental approach and started porting and
  363. %% adapting the structure of the Colorado course back into the land of
  364. %% Scheme. In the meantime Indiana University had moved on from Scheme to
  365. %% Racket~\citep{plt-tr}, so the course is now about compiling a subset
  366. %% of Racket (and Typed Racket) to the x86 assembly language.
  367. %% This is the textbook for the incremental version of the compiler
  368. %% course at Indiana University (Spring 2016 - present). With this book
  369. %% I hope to make the Indiana compiler course available to people that
  370. %% have not had the chance to study compilers at Indiana University.
  371. %% %% I have captured what
  372. %% %% I think are the most important topics from \cite{Dybvig:2010aa} but
  373. %% %% have omitted topics that are less interesting conceptually. I have
  374. %% %% also made simplifications to reduce complexity. In this way, this
  375. %% %% book leans more towards pedagogy than towards the efficiency of the
  376. %% %% generated code. Also, the book differs in places where we I the
  377. %% %% opportunity to make the topics more fun, such as in relating register
  378. %% %% allocation to Sudoku (Chapter~\ref{ch:register-allocation-Rvar}).
  379. %% \section*{Prerequisites}
  380. %% The material in this book is challenging but rewarding. It is meant to
  381. %% prepare students for a lifelong career in programming languages.
  382. %% %\section*{Structure of book}
  383. %% % You might want to add short description about each chapter in this book.
  384. %% %\section*{About the companion website}
  385. %% %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  386. %% %\begin{itemize}
  387. %% % \item A link to (freely downlodable) latest version of this document.
  388. %% % \item Link to download LaTeX source for this document.
  389. %% % \item Miscellaneous material (e.g. suggested readings etc).
  390. %% %\end{itemize}
  391. \section*{Acknowledgments}
  392. The tradition of compiler construction at Indiana University goes back
  393. to research and courses on programming languages by Daniel Friedman in
  394. the 1970's and 1980's. One of his students, Kent Dybvig, implemented
  395. Chez Scheme~\citep{Dybvig:2006aa}, a production-quality, efficient
  396. compiler for Scheme. Throughout the 1990's and 2000's, Dybvig taught
  397. the compiler course and continued the development of Chez Scheme.
  398. %
  399. The compiler course evolved to incorporate novel pedagogical ideas
  400. while also including elements of efficient real-world compilers. One
  401. of Friedman's ideas was to split the compiler into many small
  402. passes. Another idea, called ``the game'', was to test the code
  403. generated by each pass on interpreters.
  404. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  405. developed infrastructure to support this approach and evolved the
  406. course to use even smaller
  407. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  408. design decisions in this book are inspired by the assignment
  409. descriptions of \citet{Dybvig:2010aa}. In the mid 2000's a student of
  410. Dybvig's named Abdulaziz Ghuloum observed that the front-to-back
  411. organization of the course made it difficult for students to
  412. understand the rationale for the compiler design. Ghuloum proposed the
  413. incremental approach~\citep{Ghuloum:2006bh}.
  414. We thank Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph Near, Nate
  415. Nystrom, and Michael Wollowski for teaching courses based on early
  416. drafts.
  417. We thank Ronald Garcia for being Jeremy's partner when they took the
  418. compiler course in the early 2000's and especially for finding the bug
  419. that sent the garbage collector on a wild goose chase!
  420. %Oscar Waddell ??
  421. \mbox{}\\
  422. \noindent Jeremy G. Siek \\
  423. Bloomington, Indiana
  424. %\noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  425. %\noindent Spring 2016
  426. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  427. \chapter{Preliminaries}
  428. \label{ch:trees-recur}
  429. In this chapter we review the basic tools that are needed to implement
  430. a compiler. Programs are typically input by a programmer as text,
  431. i.e., a sequence of characters. The program-as-text representation is
  432. called \emph{concrete syntax}. We use concrete syntax to concisely
  433. write down and talk about programs. Inside the compiler, we use
  434. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  435. that efficiently supports the operations that the compiler needs to
  436. perform.\index{concrete syntax}\index{abstract syntax}\index{abstract
  437. syntax tree}\index{AST}\index{program}\index{parse} The translation
  438. from concrete syntax to abstract syntax is a process called
  439. \emph{parsing}~\citep{Aho:1986qf}. We do not cover the theory and
  440. implementation of parsing in this book. A parser is provided in the
  441. support code for translating from concrete to abstract syntax.
  442. ASTs can be represented in many different ways inside the compiler,
  443. depending on the programming language used to write the compiler.
  444. %
  445. We use Racket's
  446. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  447. feature to represent ASTs (Section~\ref{sec:ast}). We use grammars to
  448. define the abstract syntax of programming languages
  449. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  450. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  451. recursive functions to construct and deconstruct ASTs
  452. (Section~\ref{sec:recursion}). This chapter provides an brief
  453. introduction to these ideas. \index{struct}
  454. \section{Abstract Syntax Trees and Racket Structures}
  455. \label{sec:ast}
  456. Compilers use abstract syntax trees to represent programs because they
  457. often need to ask questions like: for a given part of a program, what
  458. kind of language feature is it? What are its sub-parts? Consider the
  459. program on the left and its AST on the right. This program is an
  460. addition operation and it has two sub-parts, a read operation and a
  461. negation. The negation has another sub-part, the integer constant
  462. \code{8}. By using a tree to represent the program, we can easily
  463. follow the links to go from one part of a program to its sub-parts.
  464. \begin{center}
  465. \begin{minipage}{0.4\textwidth}
  466. \begin{lstlisting}
  467. (+ (read) (- 8))
  468. \end{lstlisting}
  469. \end{minipage}
  470. \begin{minipage}{0.4\textwidth}
  471. \begin{equation}
  472. \begin{tikzpicture}
  473. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  474. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  475. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  476. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  477. \draw[->] (plus) to (read);
  478. \draw[->] (plus) to (minus);
  479. \draw[->] (minus) to (8);
  480. \end{tikzpicture}
  481. \label{eq:arith-prog}
  482. \end{equation}
  483. \end{minipage}
  484. \end{center}
  485. We use the standard terminology for trees to describe ASTs: each
  486. circle above is called a \emph{node}. The arrows connect a node to its
  487. \emph{children} (which are also nodes). The top-most node is the
  488. \emph{root}. Every node except for the root has a \emph{parent} (the
  489. node it is the child of). If a node has no children, it is a
  490. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  491. \index{node}
  492. \index{children}
  493. \index{root}
  494. \index{parent}
  495. \index{leaf}
  496. \index{internal node}
  497. %% Recall that an \emph{symbolic expression} (S-expression) is either
  498. %% \begin{enumerate}
  499. %% \item an atom, or
  500. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  501. %% where $e_1$ and $e_2$ are each an S-expression.
  502. %% \end{enumerate}
  503. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  504. %% null value \code{'()}, etc. We can create an S-expression in Racket
  505. %% simply by writing a backquote (called a quasi-quote in Racket)
  506. %% followed by the textual representation of the S-expression. It is
  507. %% quite common to use S-expressions to represent a list, such as $a, b
  508. %% ,c$ in the following way:
  509. %% \begin{lstlisting}
  510. %% `(a . (b . (c . ())))
  511. %% \end{lstlisting}
  512. %% Each element of the list is in the first slot of a pair, and the
  513. %% second slot is either the rest of the list or the null value, to mark
  514. %% the end of the list. Such lists are so common that Racket provides
  515. %% special notation for them that removes the need for the periods
  516. %% and so many parenthesis:
  517. %% \begin{lstlisting}
  518. %% `(a b c)
  519. %% \end{lstlisting}
  520. %% The following expression creates an S-expression that represents AST
  521. %% \eqref{eq:arith-prog}.
  522. %% \begin{lstlisting}
  523. %% `(+ (read) (- 8))
  524. %% \end{lstlisting}
  525. %% When using S-expressions to represent ASTs, the convention is to
  526. %% represent each AST node as a list and to put the operation symbol at
  527. %% the front of the list. The rest of the list contains the children. So
  528. %% in the above case, the root AST node has operation \code{`+} and its
  529. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  530. %% diagram \eqref{eq:arith-prog}.
  531. %% To build larger S-expressions one often needs to splice together
  532. %% several smaller S-expressions. Racket provides the comma operator to
  533. %% splice an S-expression into a larger one. For example, instead of
  534. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  535. %% we could have first created an S-expression for AST
  536. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  537. %% S-expression.
  538. %% \begin{lstlisting}
  539. %% (define ast1.4 `(- 8))
  540. %% (define ast1.1 `(+ (read) ,ast1.4))
  541. %% \end{lstlisting}
  542. %% In general, the Racket expression that follows the comma (splice)
  543. %% can be any expression that produces an S-expression.
  544. We define a Racket \code{struct} for each kind of node. For this
  545. chapter we require just two kinds of nodes: one for integer constants
  546. and one for primitive operations. The following is the \code{struct}
  547. definition for integer constants.
  548. \begin{lstlisting}
  549. (struct Int (value))
  550. \end{lstlisting}
  551. An integer node includes just one thing: the integer value.
  552. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  553. \begin{lstlisting}
  554. (define eight (Int 8))
  555. \end{lstlisting}
  556. We say that the value created by \code{(Int 8)} is an
  557. \emph{instance} of the \code{Int} structure.
  558. The following is the \code{struct} definition for primitives operations.
  559. \begin{lstlisting}
  560. (struct Prim (op args))
  561. \end{lstlisting}
  562. A primitive operation node includes an operator symbol \code{op}
  563. and a list of children \code{args}. For example, to create
  564. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  565. \begin{lstlisting}
  566. (define neg-eight (Prim '- (list eight)))
  567. \end{lstlisting}
  568. Primitive operations may have zero or more children. The \code{read}
  569. operator has zero children:
  570. \begin{lstlisting}
  571. (define rd (Prim 'read '()))
  572. \end{lstlisting}
  573. whereas the addition operator has two children:
  574. \begin{lstlisting}
  575. (define ast1.1 (Prim '+ (list rd neg-eight)))
  576. \end{lstlisting}
  577. We have made a design choice regarding the \code{Prim} structure.
  578. Instead of using one structure for many different operations
  579. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  580. structure for each operation, as follows.
  581. \begin{lstlisting}
  582. (struct Read ())
  583. (struct Add (left right))
  584. (struct Neg (value))
  585. \end{lstlisting}
  586. The reason we choose to use just one structure is that in many parts
  587. of the compiler the code for the different primitive operators is the
  588. same, so we might as well just write that code once, which is enabled
  589. by using a single structure.
  590. When compiling a program such as \eqref{eq:arith-prog}, we need to
  591. know that the operation associated with the root node is addition and
  592. we need to be able to access its two children. Racket provides pattern
  593. matching to support these kinds of queries, as we see in
  594. Section~\ref{sec:pattern-matching}.
  595. In this book, we often write down the concrete syntax of a program
  596. even when we really have in mind the AST because the concrete syntax
  597. is more concise. We recommend that, in your mind, you always think of
  598. programs as abstract syntax trees.
  599. \section{Grammars}
  600. \label{sec:grammar}
  601. \index{integer}
  602. \index{literal}
  603. \index{constant}
  604. A programming language can be thought of as a \emph{set} of programs.
  605. The set is typically infinite (one can always create larger and larger
  606. programs), so one cannot simply describe a language by listing all of
  607. the programs in the language. Instead we write down a set of rules, a
  608. \emph{grammar}, for building programs. Grammars are often used to
  609. define the concrete syntax of a language, but they can also be used to
  610. describe the abstract syntax. We write our rules in a variant of
  611. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  612. \index{Backus-Naur Form}\index{BNF}
  613. As an example, we describe a small language, named \LangInt{}, that consists of
  614. integers and arithmetic operations.
  615. \index{grammar}
  616. The first grammar rule for the abstract syntax of \LangInt{} says that an
  617. instance of the \code{Int} structure is an expression:
  618. \begin{equation}
  619. \Exp ::= \INT{\Int} \label{eq:arith-int}
  620. \end{equation}
  621. %
  622. Each rule has a left-hand-side and a right-hand-side. The way to read
  623. a rule is that if you have an AST node that matches the
  624. right-hand-side, then you can categorize it according to the
  625. left-hand-side.
  626. %
  627. A name such as $\Exp$ that is defined by the grammar rules is a
  628. \emph{non-terminal}. \index{non-terminal}
  629. %
  630. The name $\Int$ is a also a non-terminal, but instead of defining it
  631. with a grammar rule, we define it with the following explanation. We
  632. make the simplifying design decision that all of the languages in this
  633. book only handle machine-representable integers. On most modern
  634. machines this corresponds to integers represented with 64-bits, i.e.,
  635. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  636. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  637. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  638. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  639. that the sequence of decimals represent an integer in range $-2^{62}$
  640. to $2^{62}-1$.
  641. The second grammar rule is the \texttt{read} operation that receives
  642. an input integer from the user of the program.
  643. \begin{equation}
  644. \Exp ::= \READ{} \label{eq:arith-read}
  645. \end{equation}
  646. The third rule says that, given an $\Exp$ node, the negation of that
  647. node is also an $\Exp$.
  648. \begin{equation}
  649. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  650. \end{equation}
  651. Symbols in typewriter font such as \key{-} and \key{read} are
  652. \emph{terminal} symbols and must literally appear in the program for
  653. the rule to be applicable.
  654. \index{terminal}
  655. We can apply these rules to categorize the ASTs that are in the
  656. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  657. \texttt{(Int 8)} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  658. following AST is an $\Exp$.
  659. \begin{center}
  660. \begin{minipage}{0.4\textwidth}
  661. \begin{lstlisting}
  662. (Prim '- (list (Int 8)))
  663. \end{lstlisting}
  664. \end{minipage}
  665. \begin{minipage}{0.25\textwidth}
  666. \begin{equation}
  667. \begin{tikzpicture}
  668. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  669. \node[draw, circle] (8) at (0, -1.2) {$8$};
  670. \draw[->] (minus) to (8);
  671. \end{tikzpicture}
  672. \label{eq:arith-neg8}
  673. \end{equation}
  674. \end{minipage}
  675. \end{center}
  676. The next grammar rule is for addition expressions:
  677. \begin{equation}
  678. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  679. \end{equation}
  680. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  681. \LangInt{}. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  682. \eqref{eq:arith-read} and we have already categorized \code{(Prim '-
  683. (list (Int 8)))} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  684. to show that
  685. \begin{lstlisting}
  686. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  687. \end{lstlisting}
  688. is an $\Exp$ in the \LangInt{} language.
  689. If you have an AST for which the above rules do not apply, then the
  690. AST is not in \LangInt{}. For example, the program \code{(- (read) (+ 8))}
  691. is not in \LangInt{} because there are no rules for \code{+} with only one
  692. argument, nor for \key{-} with two arguments. Whenever we define a
  693. language with a grammar, the language only includes those programs
  694. that are justified by the rules.
  695. The last grammar rule for \LangInt{} states that there is a \code{Program}
  696. node to mark the top of the whole program:
  697. \[
  698. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  699. \]
  700. The \code{Program} structure is defined as follows
  701. \begin{lstlisting}
  702. (struct Program (info body))
  703. \end{lstlisting}
  704. where \code{body} is an expression. In later chapters, the \code{info}
  705. part will be used to store auxiliary information but for now it is
  706. just the empty list.
  707. It is common to have many grammar rules with the same left-hand side
  708. but different right-hand sides, such as the rules for $\Exp$ in the
  709. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  710. combine several right-hand-sides into a single rule.
  711. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  712. in Figure~\ref{fig:r0-syntax}. The concrete syntax for \LangInt{} is
  713. defined in Figure~\ref{fig:r0-concrete-syntax}.
  714. The \code{read-program} function provided in \code{utilities.rkt} of
  715. the support code reads a program in from a file (the sequence of
  716. characters in the concrete syntax of Racket) and parses it into an
  717. abstract syntax tree. See the description of \code{read-program} in
  718. Appendix~\ref{appendix:utilities} for more details.
  719. \begin{figure}[tp]
  720. \fbox{
  721. \begin{minipage}{0.96\textwidth}
  722. \[
  723. \begin{array}{rcl}
  724. \begin{array}{rcl}
  725. \Exp &::=& \Int \mid \LP\key{read}\RP \mid \LP\key{-}\;\Exp\RP \mid \LP\key{+} \; \Exp\;\Exp\RP\\
  726. \LangInt{} &::=& \Exp
  727. \end{array}
  728. \end{array}
  729. \]
  730. \end{minipage}
  731. }
  732. \caption{The concrete syntax of \LangInt{}.}
  733. \label{fig:r0-concrete-syntax}
  734. \end{figure}
  735. \begin{figure}[tp]
  736. \fbox{
  737. \begin{minipage}{0.96\textwidth}
  738. \[
  739. \begin{array}{rcl}
  740. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  741. &\mid& \ADD{\Exp}{\Exp} \\
  742. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  743. \end{array}
  744. \]
  745. \end{minipage}
  746. }
  747. \caption{The abstract syntax of \LangInt{}.}
  748. \label{fig:r0-syntax}
  749. \end{figure}
  750. \section{Pattern Matching}
  751. \label{sec:pattern-matching}
  752. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  753. the parts of an AST node. Racket provides the \texttt{match} form to
  754. access the parts of a structure. Consider the following example and
  755. the output on the right. \index{match} \index{pattern matching}
  756. \begin{center}
  757. \begin{minipage}{0.5\textwidth}
  758. \begin{lstlisting}
  759. (match ast1.1
  760. [(Prim op (list child1 child2))
  761. (print op)])
  762. \end{lstlisting}
  763. \end{minipage}
  764. \vrule
  765. \begin{minipage}{0.25\textwidth}
  766. \begin{lstlisting}
  767. '+
  768. \end{lstlisting}
  769. \end{minipage}
  770. \end{center}
  771. In the above example, the \texttt{match} form takes an AST
  772. \eqref{eq:arith-prog} and binds its parts to the three pattern
  773. variables \texttt{op}, \texttt{child1}, and \texttt{child2}, and then
  774. prints out the operator. In general, a match clause consists of a
  775. \emph{pattern} and a \emph{body}.\index{pattern} Patterns are
  776. recursively defined to be either a pattern variable, a structure name
  777. followed by a pattern for each of the structure's arguments, or an
  778. S-expression (symbols, lists, etc.). (See Chapter 12 of The Racket
  779. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  780. and Chapter 9 of The Racket
  781. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  782. for a complete description of \code{match}.)
  783. %
  784. The body of a match clause may contain arbitrary Racket code. The
  785. pattern variables can be used in the scope of the body, such as
  786. \code{op} in \code{(print op)}.
  787. A \code{match} form may contain several clauses, as in the following
  788. function \code{leaf?} that recognizes when an \LangInt{} node is a leaf in
  789. the AST. The \code{match} proceeds through the clauses in order,
  790. checking whether the pattern can match the input AST. The body of the
  791. first clause that matches is executed. The output of \code{leaf?} for
  792. several ASTs is shown on the right.
  793. \begin{center}
  794. \begin{minipage}{0.6\textwidth}
  795. \begin{lstlisting}
  796. (define (leaf? arith)
  797. (match arith
  798. [(Int n) #t]
  799. [(Prim 'read '()) #t]
  800. [(Prim '- (list e1)) #f]
  801. [(Prim '+ (list e1 e2)) #f]))
  802. (leaf? (Prim 'read '()))
  803. (leaf? (Prim '- (list (Int 8))))
  804. (leaf? (Int 8))
  805. \end{lstlisting}
  806. \end{minipage}
  807. \vrule
  808. \begin{minipage}{0.25\textwidth}
  809. \begin{lstlisting}
  810. #t
  811. #f
  812. #t
  813. \end{lstlisting}
  814. \end{minipage}
  815. \end{center}
  816. When writing a \code{match}, we refer to the grammar definition to
  817. identify which non-terminal we are expecting to match against, then we
  818. make sure that 1) we have one clause for each alternative of that
  819. non-terminal and 2) that the pattern in each clause corresponds to the
  820. corresponding right-hand side of a grammar rule. For the \code{match}
  821. in the \code{leaf?} function, we refer to the grammar for \LangInt{} in
  822. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  823. alternatives, so the \code{match} has 4 clauses. The pattern in each
  824. clause corresponds to the right-hand side of a grammar rule. For
  825. example, the pattern \code{(Prim '+ (list e1 e2))} corresponds to the
  826. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  827. patterns, replace non-terminals such as $\Exp$ with pattern variables
  828. of your choice (e.g. \code{e1} and \code{e2}).
  829. \section{Recursive Functions}
  830. \label{sec:recursion}
  831. \index{recursive function}
  832. Programs are inherently recursive. For example, an \LangInt{} expression is
  833. often made of smaller expressions. Thus, the natural way to process an
  834. entire program is with a recursive function. As a first example of
  835. such a recursive function, we define \texttt{exp?} below, which takes
  836. an arbitrary value and determines whether or not it is an \LangInt{}
  837. expression.
  838. %
  839. We say that a function is defined by \emph{structural recursion} when
  840. it is defined using a sequence of match clauses that correspond to a
  841. grammar, and the body of each clause makes a recursive call on each
  842. child node.\footnote{This principle of structuring code according to
  843. the data definition is advocated in the book \emph{How to Design
  844. Programs} \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}.
  845. Below we also define a second function, named \code{Rint?}, that
  846. determines whether an AST is an \LangInt{} program. In general we can
  847. expect to write one recursive function to handle each non-terminal in
  848. a grammar.\index{structural recursion}
  849. %
  850. \begin{center}
  851. \begin{minipage}{0.7\textwidth}
  852. \begin{lstlisting}
  853. (define (exp? ast)
  854. (match ast
  855. [(Int n) #t]
  856. [(Prim 'read '()) #t]
  857. [(Prim '- (list e)) (exp? e)]
  858. [(Prim '+ (list e1 e2))
  859. (and (exp? e1) (exp? e2))]
  860. [else #f]))
  861. (define (Rint? ast)
  862. (match ast
  863. [(Program '() e) (exp? e)]
  864. [else #f]))
  865. (Rint? (Program '() ast1.1)
  866. (Rint? (Program '()
  867. (Prim '- (list (Prim 'read '())
  868. (Prim '+ (list (Num 8)))))))
  869. \end{lstlisting}
  870. \end{minipage}
  871. \vrule
  872. \begin{minipage}{0.25\textwidth}
  873. \begin{lstlisting}
  874. #t
  875. #f
  876. \end{lstlisting}
  877. \end{minipage}
  878. \end{center}
  879. You may be tempted to merge the two functions into one, like this:
  880. \begin{center}
  881. \begin{minipage}{0.5\textwidth}
  882. \begin{lstlisting}
  883. (define (Rint? ast)
  884. (match ast
  885. [(Int n) #t]
  886. [(Prim 'read '()) #t]
  887. [(Prim '- (list e)) (Rint? e)]
  888. [(Prim '+ (list e1 e2)) (and (Rint? e1) (Rint? e2))]
  889. [(Program '() e) (Rint? e)]
  890. [else #f]))
  891. \end{lstlisting}
  892. \end{minipage}
  893. \end{center}
  894. %
  895. Sometimes such a trick will save a few lines of code, especially when
  896. it comes to the \code{Program} wrapper. Yet this style is generally
  897. \emph{not} recommended because it can get you into trouble.
  898. %
  899. For example, the above function is subtly wrong:
  900. \lstinline{(Rint? (Program '() (Program '() (Int 3))))}
  901. returns true when it should return false.
  902. \section{Interpreters}
  903. \label{sec:interp-Rint}
  904. \index{interpreter}
  905. In general, the intended behavior of a program is defined by the
  906. specification of the language. For example, the Scheme language is
  907. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  908. defined in its reference manual~\citep{plt-tr}. In this book we use
  909. interpreters to specify each language that we consider. An interpreter
  910. that is designated as the definition of a language is called a
  911. \emph{definitional interpreter}~\citep{reynolds72:_def_interp}.
  912. \index{definitional interpreter} We warm up by creating a definitional
  913. interpreter for the \LangInt{} language, which serves as a second example
  914. of structural recursion. The \texttt{interp-Rint} function is defined in
  915. Figure~\ref{fig:interp-Rint}. The body of the function is a match on the
  916. input program followed by a call to the \lstinline{interp-exp} helper
  917. function, which in turn has one match clause per grammar rule for
  918. \LangInt{} expressions.
  919. \begin{figure}[tp]
  920. \begin{lstlisting}
  921. (define (interp-exp e)
  922. (match e
  923. [(Int n) n]
  924. [(Prim 'read '())
  925. (define r (read))
  926. (cond [(fixnum? r) r]
  927. [else (error 'interp-exp "read expected an integer" r)])]
  928. [(Prim '- (list e))
  929. (define v (interp-exp e))
  930. (fx- 0 v)]
  931. [(Prim '+ (list e1 e2))
  932. (define v1 (interp-exp e1))
  933. (define v2 (interp-exp e2))
  934. (fx+ v1 v2)]))
  935. (define (interp-Rint p)
  936. (match p
  937. [(Program '() e) (interp-exp e)]))
  938. \end{lstlisting}
  939. \caption{Interpreter for the \LangInt{} language.}
  940. \label{fig:interp-Rint}
  941. \end{figure}
  942. Let us consider the result of interpreting a few \LangInt{} programs. The
  943. following program adds two integers.
  944. \begin{lstlisting}
  945. (+ 10 32)
  946. \end{lstlisting}
  947. The result is \key{42}, the answer to life, the universe, and
  948. everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to the
  949. Galaxy} by Douglas Adams.}.
  950. %
  951. We wrote the above program in concrete syntax whereas the parsed
  952. abstract syntax is:
  953. \begin{lstlisting}
  954. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  955. \end{lstlisting}
  956. The next example demonstrates that expressions may be nested within
  957. each other, in this case nesting several additions and negations.
  958. \begin{lstlisting}
  959. (+ 10 (- (+ 12 20)))
  960. \end{lstlisting}
  961. What is the result of the above program?
  962. As mentioned previously, the \LangInt{} language does not support
  963. arbitrarily-large integers, but only $63$-bit integers, so we
  964. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  965. in Racket.
  966. Suppose
  967. \[
  968. n = 999999999999999999
  969. \]
  970. which indeed fits in $63$-bits. What happens when we run the
  971. following program in our interpreter?
  972. \begin{lstlisting}
  973. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  974. \end{lstlisting}
  975. It produces an error:
  976. \begin{lstlisting}
  977. fx+: result is not a fixnum
  978. \end{lstlisting}
  979. We establish the convention that if running the definitional
  980. interpreter on a program produces an error then the meaning of that
  981. program is \emph{unspecified}\index{unspecified behavior}, unless the
  982. error is a \code{trapped-error}. A compiler for the language is under
  983. no obligations regarding programs with unspecified behavior; it does
  984. not have to produce an executable, and if it does, that executable can
  985. do anything. On the other hand, if the error is a
  986. \code{trapped-error}, then the compiler must produce an executable and
  987. it is required to report that an error occurred. To signal an error,
  988. exit with a return code of \code{255}. The interpreters in chapters
  989. \ref{ch:type-dynamic} and \ref{ch:Rgrad} use
  990. \code{trapped-error}.
  991. %% This convention applies to the languages defined in this
  992. %% book, as a way to simplify the student's task of implementing them,
  993. %% but this convention is not applicable to all programming languages.
  994. %%
  995. Moving on to the last feature of the \LangInt{} language, the \key{read}
  996. operation prompts the user of the program for an integer. Recall that
  997. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  998. \code{8}. So if we run
  999. \begin{lstlisting}
  1000. (interp-Rint (Program '() ast1.1))
  1001. \end{lstlisting}
  1002. and if the input is \code{50}, the result is \code{42}.
  1003. We include the \key{read} operation in \LangInt{} so a clever student
  1004. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  1005. during compilation to obtain the output and then generates the trivial
  1006. code to produce the output. (Yes, a clever student did this in the
  1007. first instance of this course.)
  1008. The job of a compiler is to translate a program in one language into a
  1009. program in another language so that the output program behaves the
  1010. same way as the input program does. This idea is depicted in the
  1011. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1012. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1013. Given a compiler that translates from language $\mathcal{L}_1$ to
  1014. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1015. compiler must translate it into some program $P_2$ such that
  1016. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1017. same input $i$ yields the same output $o$.
  1018. \begin{equation} \label{eq:compile-correct}
  1019. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1020. \node (p1) at (0, 0) {$P_1$};
  1021. \node (p2) at (3, 0) {$P_2$};
  1022. \node (o) at (3, -2.5) {$o$};
  1023. \path[->] (p1) edge [above] node {compile} (p2);
  1024. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  1025. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  1026. \end{tikzpicture}
  1027. \end{equation}
  1028. In the next section we see our first example of a compiler.
  1029. \section{Example Compiler: a Partial Evaluator}
  1030. \label{sec:partial-evaluation}
  1031. In this section we consider a compiler that translates \LangInt{} programs
  1032. into \LangInt{} programs that may be more efficient, that is, this compiler
  1033. is an optimizer. This optimizer eagerly computes the parts of the
  1034. program that do not depend on any inputs, a process known as
  1035. \emph{partial evaluation}~\citep{Jones:1993uq}.
  1036. \index{partial evaluation}
  1037. For example, given the following program
  1038. \begin{lstlisting}
  1039. (+ (read) (- (+ 5 3)))
  1040. \end{lstlisting}
  1041. our compiler will translate it into the program
  1042. \begin{lstlisting}
  1043. (+ (read) -8)
  1044. \end{lstlisting}
  1045. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1046. evaluator for the \LangInt{} language. The output of the partial evaluator
  1047. is an \LangInt{} program. In Figure~\ref{fig:pe-arith}, the structural
  1048. recursion over $\Exp$ is captured in the \code{pe-exp} function
  1049. whereas the code for partially evaluating the negation and addition
  1050. operations is factored into two separate helper functions:
  1051. \code{pe-neg} and \code{pe-add}. The input to these helper
  1052. functions is the output of partially evaluating the children.
  1053. \begin{figure}[tp]
  1054. \begin{lstlisting}
  1055. (define (pe-neg r)
  1056. (match r
  1057. [(Int n) (Int (fx- 0 n))]
  1058. [else (Prim '- (list r))]))
  1059. (define (pe-add r1 r2)
  1060. (match* (r1 r2)
  1061. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1062. [(_ _) (Prim '+ (list r1 r2))]))
  1063. (define (pe-exp e)
  1064. (match e
  1065. [(Int n) (Int n)]
  1066. [(Prim 'read '()) (Prim 'read '())]
  1067. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  1068. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]))
  1069. (define (pe-Rint p)
  1070. (match p
  1071. [(Program '() e) (Program '() (pe-exp e))]))
  1072. \end{lstlisting}
  1073. \caption{A partial evaluator for \LangInt{}.}
  1074. \label{fig:pe-arith}
  1075. \end{figure}
  1076. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  1077. arguments are integers and if they are, perform the appropriate
  1078. arithmetic. Otherwise, they create an AST node for the arithmetic
  1079. operation.
  1080. To gain some confidence that the partial evaluator is correct, we can
  1081. test whether it produces programs that get the same result as the
  1082. input programs. That is, we can test whether it satisfies Diagram
  1083. \ref{eq:compile-correct}. The following code runs the partial
  1084. evaluator on several examples and tests the output program. The
  1085. \texttt{parse-program} and \texttt{assert} functions are defined in
  1086. Appendix~\ref{appendix:utilities}.\\
  1087. \begin{minipage}{1.0\textwidth}
  1088. \begin{lstlisting}
  1089. (define (test-pe p)
  1090. (assert "testing pe-Rint"
  1091. (equal? (interp-Rint p) (interp-Rint (pe-Rint p)))))
  1092. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1093. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1094. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  1095. \end{lstlisting}
  1096. \end{minipage}
  1097. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1098. \chapter{Integers and Variables}
  1099. \label{ch:Rvar}
  1100. This chapter is about compiling a subset of Racket to x86-64 assembly
  1101. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1102. integer arithmetic and local variable binding. We often refer to
  1103. x86-64 simply as x86. The chapter begins with a description of the
  1104. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  1105. to of x86 assembly (Section~\ref{sec:x86}). The x86 assembly language
  1106. is large so we discuss only the instructions needed for compiling
  1107. \LangVar{}. We introduce more x86 instructions in later chapters.
  1108. After introducing \LangVar{} and x86, we reflect on their differences
  1109. and come up with a plan to break down the translation from \LangVar{}
  1110. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  1111. rest of the sections in this chapter give detailed hints regarding
  1112. each step (Sections~\ref{sec:uniquify-Rvar} through \ref{sec:patch-s0}).
  1113. We hope to give enough hints that the well-prepared reader, together
  1114. with a few friends, can implement a compiler from \LangVar{} to x86 in
  1115. a couple weeks. To give the reader a feeling for the scale of this
  1116. first compiler, the instructor solution for the \LangVar{} compiler is
  1117. approximately 500 lines of code.
  1118. \section{The \LangVar{} Language}
  1119. \label{sec:s0}
  1120. \index{variable}
  1121. The \LangVar{} language extends the \LangInt{} language with variable
  1122. definitions. The concrete syntax of the \LangVar{} language is defined by
  1123. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  1124. syntax is defined in Figure~\ref{fig:r1-syntax}. The non-terminal
  1125. \Var{} may be any Racket identifier. As in \LangInt{}, \key{read} is a
  1126. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  1127. operator. Similar to \LangInt{}, the abstract syntax of \LangVar{} includes the
  1128. \key{Program} struct to mark the top of the program.
  1129. %% The $\itm{info}$
  1130. %% field of the \key{Program} structure contains an \emph{association
  1131. %% list} (a list of key-value pairs) that is used to communicate
  1132. %% auxiliary data from one compiler pass the next.
  1133. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1134. exhibit several compilation techniques.
  1135. \begin{figure}[tp]
  1136. \centering
  1137. \fbox{
  1138. \begin{minipage}{0.96\textwidth}
  1139. \[
  1140. \begin{array}{rcl}
  1141. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp}\\
  1142. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  1143. \LangVar{} &::=& \Exp
  1144. \end{array}
  1145. \]
  1146. \end{minipage}
  1147. }
  1148. \caption{The concrete syntax of \LangVar{}.}
  1149. \label{fig:r1-concrete-syntax}
  1150. \end{figure}
  1151. \begin{figure}[tp]
  1152. \centering
  1153. \fbox{
  1154. \begin{minipage}{0.96\textwidth}
  1155. \[
  1156. \begin{array}{rcl}
  1157. \Exp &::=& \INT{\Int} \mid \READ{} \\
  1158. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  1159. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  1160. \LangVar{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1161. \end{array}
  1162. \]
  1163. \end{minipage}
  1164. }
  1165. \caption{The abstract syntax of \LangVar{}.}
  1166. \label{fig:r1-syntax}
  1167. \end{figure}
  1168. Let us dive further into the syntax and semantics of the \LangVar{}
  1169. language. The \key{let} feature defines a variable for use within its
  1170. body and initializes the variable with the value of an expression.
  1171. The abstract syntax for \key{let} is defined in
  1172. Figure~\ref{fig:r1-syntax}. The concrete syntax for \key{let} is
  1173. \begin{lstlisting}
  1174. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1175. \end{lstlisting}
  1176. For example, the following program initializes \code{x} to $32$ and then
  1177. evaluates the body \code{(+ 10 x)}, producing $42$.
  1178. \begin{lstlisting}
  1179. (let ([x (+ 12 20)]) (+ 10 x))
  1180. \end{lstlisting}
  1181. When there are multiple \key{let}'s for the same variable, the closest
  1182. enclosing \key{let} is used. That is, variable definitions overshadow
  1183. prior definitions. Consider the following program with two \key{let}'s
  1184. that define variables named \code{x}. Can you figure out the result?
  1185. \begin{lstlisting}
  1186. (let ([x 32]) (+ (let ([x 10]) x) x))
  1187. \end{lstlisting}
  1188. For the purposes of depicting which variable uses correspond to which
  1189. definitions, the following shows the \code{x}'s annotated with
  1190. subscripts to distinguish them. Double check that your answer for the
  1191. above is the same as your answer for this annotated version of the
  1192. program.
  1193. \begin{lstlisting}
  1194. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1195. \end{lstlisting}
  1196. The initializing expression is always evaluated before the body of the
  1197. \key{let}, so in the following, the \key{read} for \code{x} is
  1198. performed before the \key{read} for \code{y}. Given the input
  1199. $52$ then $10$, the following produces $42$ (not $-42$).
  1200. \begin{lstlisting}
  1201. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1202. \end{lstlisting}
  1203. \subsection{Extensible Interpreters via Method Overriding}
  1204. \label{sec:extensible-interp}
  1205. To prepare for discussing the interpreter for \LangVar{}, we need to
  1206. explain why we choose to implement the interpreter using
  1207. object-oriented programming, that is, as a collection of methods
  1208. inside of a class. Throughout this book we define many interpreters,
  1209. one for each of the languages that we study. Because each language
  1210. builds on the prior one, there is a lot of commonality between their
  1211. interpreters. We want to write down those common parts just once
  1212. instead of many times. A naive approach would be to have, for example,
  1213. the interpreter for \LangIf{} handle all of the new features in that
  1214. language and then have a default case that dispatches to the
  1215. interpreter for \LangVar{}. The following code sketches this idea.
  1216. \begin{center}
  1217. \begin{minipage}{0.45\textwidth}
  1218. \begin{lstlisting}
  1219. (define (interp-Rvar e)
  1220. (match e
  1221. [(Prim '- (list e))
  1222. (fx- 0 (interp-Rvar e))]
  1223. ...))
  1224. \end{lstlisting}
  1225. \end{minipage}
  1226. \begin{minipage}{0.45\textwidth}
  1227. \begin{lstlisting}
  1228. (define (interp-Rif e)
  1229. (match e
  1230. [(If cnd thn els)
  1231. (match (interp-Rif cnd)
  1232. [#t (interp-Rif thn)]
  1233. [#f (interp-Rif els)])]
  1234. ...
  1235. [else (interp-Rvar e)]))
  1236. \end{lstlisting}
  1237. \end{minipage}
  1238. \end{center}
  1239. The problem with this approach is that it does not handle situations
  1240. in which an \LangIf{} feature, like \code{If}, is nested inside an \LangVar{}
  1241. feature, like the \code{-} operator, as in the following program.
  1242. \begin{lstlisting}
  1243. (Prim '- (list (If (Bool #t) (Int 42) (Int 0))))
  1244. \end{lstlisting}
  1245. If we invoke \code{interp-Rif} on this program, it dispatches to
  1246. \code{interp-Rvar} to handle the \code{-} operator, but then it
  1247. recurisvely calls \code{interp-Rvar} again on the argument of \code{-},
  1248. which is an \code{If}. But there is no case for \code{If} in
  1249. \code{interp-Rvar}, so we get an error!
  1250. To make our interpreters extensible we need something called
  1251. \emph{open recursion}\index{open recursion}, where the tying of the
  1252. recursive knot is delayed to when the functions are
  1253. composed. Object-oriented languages provide open recursion with the
  1254. late-binding of overridden methods\index{method overriding}. The
  1255. following code sketches this idea for interpreting \LangVar{} and
  1256. \LangIf{} using the
  1257. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1258. \index{class} feature of Racket. We define one class for each
  1259. language and define a method for interpreting expressions inside each
  1260. class. The class for \LangIf{} inherits from the class for \LangVar{}
  1261. and the method \code{interp-exp} in \LangIf{} overrides the
  1262. \code{interp-exp} in \LangVar{}. Note that the default case of
  1263. \code{interp-exp} in \LangIf{} uses \code{super} to invoke
  1264. \code{interp-exp}, and because \LangIf{} inherits from \LangVar{},
  1265. that dispatches to the \code{interp-exp} in \LangVar{}.
  1266. \begin{center}
  1267. \begin{minipage}{0.45\textwidth}
  1268. \begin{lstlisting}
  1269. (define interp-Rvar-class
  1270. (class object%
  1271. (define/public (interp-exp e)
  1272. (match e
  1273. [(Prim '- (list e))
  1274. (fx- 0 (interp-exp e))]
  1275. ...))
  1276. ...))
  1277. \end{lstlisting}
  1278. \end{minipage}
  1279. \begin{minipage}{0.45\textwidth}
  1280. \begin{lstlisting}
  1281. (define interp-Rif-class
  1282. (class interp-Rvar-class
  1283. (define/override (interp-exp e)
  1284. (match e
  1285. [(If cnd thn els)
  1286. (match (interp-exp cnd)
  1287. [#t (interp-exp thn)]
  1288. [#f (interp-exp els)])]
  1289. ...
  1290. [else (super interp-exp e)]))
  1291. ...
  1292. ))
  1293. \end{lstlisting}
  1294. \end{minipage}
  1295. \end{center}
  1296. Getting back to the troublesome example, repeated here:
  1297. \begin{lstlisting}
  1298. (define e0 (Prim '- (list (If (Bool #t) (Int 42) (Int 0)))))
  1299. \end{lstlisting}
  1300. We can invoke the \code{interp-exp} method for \LangIf{} on this
  1301. expression by creating an object of the \LangIf{} class and sending it the
  1302. \code{interp-exp} method with the argument \code{e0}.
  1303. \begin{lstlisting}
  1304. (send (new interp-Rif-class) interp-exp e0)
  1305. \end{lstlisting}
  1306. The default case of \code{interp-exp} in \LangIf{} handles it by
  1307. dispatching to the \code{interp-exp} method in \LangVar{}, which
  1308. handles the \code{-} operator. But then for the recursive method call,
  1309. it dispatches back to \code{interp-exp} in \LangIf{}, where the
  1310. \code{If} is handled correctly. Thus, method overriding gives us the
  1311. open recursion that we need to implement our interpreters in an
  1312. extensible way.
  1313. \newpage
  1314. \subsection{Definitional Interpreter for \LangVar{}}
  1315. \begin{wrapfigure}[25]{r}[1.0in]{0.6\textwidth}
  1316. \small
  1317. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1318. An \emph{association list} (alist) is a list of key-value pairs.
  1319. For example, we can map people to their ages with an alist.
  1320. \index{alist}\index{association list}
  1321. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1322. (define ages
  1323. '((jane . 25) (sam . 24) (kate . 45)))
  1324. \end{lstlisting}
  1325. The \emph{dictionary} interface is for mapping keys to values.
  1326. Every alist implements this interface. \index{dictionary} The package
  1327. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1328. provides many functions for working with dictionaries. Here
  1329. are a few of them:
  1330. \begin{description}
  1331. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1332. returns the value associated with the given $\itm{key}$.
  1333. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1334. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1335. but otherwise is the same as $\itm{dict}$.
  1336. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1337. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1338. of keys and values in $\itm{dict}$. For example, the following
  1339. creates a new alist in which the ages are incremented.
  1340. \end{description}
  1341. \vspace{-10pt}
  1342. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1343. (for/list ([(k v) (in-dict ages)])
  1344. (cons k (add1 v)))
  1345. \end{lstlisting}
  1346. \end{tcolorbox}
  1347. \end{wrapfigure}
  1348. Having justified the use of classes and methods to implement
  1349. interpreters, we turn to the definitional interpreter for \LangVar{}
  1350. in Figure~\ref{fig:interp-Rvar}. It is similar to the interpreter for
  1351. \LangInt{} but adds two new \key{match} cases for variables and
  1352. \key{let}. For \key{let} we need a way to communicate the value bound
  1353. to a variable to all the uses of the variable. To accomplish this, we
  1354. maintain a mapping from variables to values. Throughout the compiler
  1355. we often need to map variables to information about them. We refer to
  1356. these mappings as
  1357. \emph{environments}\index{environment}.\footnote{Another common term
  1358. for environment in the compiler literature is \emph{symbol
  1359. table}\index{symbol table}.}
  1360. %
  1361. For simplicity, we use an association list (alist) to represent the
  1362. environment. The sidebar to the right gives a brief introduction to
  1363. alists and the \code{racket/dict} package. The \code{interp-exp}
  1364. function takes the current environment, \code{env}, as an extra
  1365. parameter. When the interpreter encounters a variable, it finds the
  1366. corresponding value using the \code{dict-ref} function. When the
  1367. interpreter encounters a \key{Let}, it evaluates the initializing
  1368. expression, extends the environment with the result value bound to the
  1369. variable, using \code{dict-set}, then evaluates the body of the
  1370. \key{Let}.
  1371. \begin{figure}[tp]
  1372. \begin{lstlisting}
  1373. (define interp-Rvar-class
  1374. (class object%
  1375. (super-new)
  1376. (define/public ((interp-exp env) e)
  1377. (match e
  1378. [(Int n) n]
  1379. [(Prim 'read '())
  1380. (define r (read))
  1381. (cond [(fixnum? r) r]
  1382. [else (error 'interp-exp "expected an integer" r)])]
  1383. [(Prim '- (list e)) (fx- 0 ((interp-exp env) e))]
  1384. [(Prim '+ (list e1 e2))
  1385. (fx+ ((interp-exp env) e1) ((interp-exp env) e2))]
  1386. [(Var x) (dict-ref env x)]
  1387. [(Let x e body)
  1388. (define new-env (dict-set env x ((interp-exp env) e)))
  1389. ((interp-exp new-env) body)]))
  1390. (define/public (interp-program p)
  1391. (match p
  1392. [(Program '() e) ((interp-exp '()) e)]))
  1393. ))
  1394. (define (interp-Rvar p)
  1395. (send (new interp-Rvar-class) interp-program p))
  1396. \end{lstlisting}
  1397. \caption{Interpreter for the \LangVar{} language.}
  1398. \label{fig:interp-Rvar}
  1399. \end{figure}
  1400. The goal for this chapter is to implement a compiler that translates
  1401. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  1402. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1403. computer as the $P_1$ program interpreted by \code{interp-Rvar}. That
  1404. is, they output the same integer $n$. We depict this correctness
  1405. criteria in the following diagram.
  1406. \[
  1407. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1408. \node (p1) at (0, 0) {$P_1$};
  1409. \node (p2) at (4, 0) {$P_2$};
  1410. \node (o) at (4, -2) {$n$};
  1411. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1412. \path[->] (p1) edge [left] node {\footnotesize\code{interp-Rvar}} (o);
  1413. \path[->] (p2) edge [right] node {\footnotesize\code{interp-x86int}} (o);
  1414. \end{tikzpicture}
  1415. \]
  1416. In the next section we introduce the \LangXInt{} subset of x86 that
  1417. suffices for compiling \LangVar{}.
  1418. \section{The \LangXInt{} Assembly Language}
  1419. \label{sec:x86}
  1420. \index{x86}
  1421. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  1422. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  1423. assembler.
  1424. %
  1425. A program begins with a \code{main} label followed by a sequence of
  1426. instructions. The \key{globl} directive says that the \key{main}
  1427. procedure is externally visible, which is necessary so that the
  1428. operating system can call it. In the grammar, ellipses such as
  1429. $\ldots$ are used to indicate a sequence of items, e.g., $\Instr
  1430. \ldots$ is a sequence of instructions.\index{instruction}
  1431. %
  1432. An x86 program is stored in the computer's memory. For our purposes,
  1433. the computer's memory is as a mapping of 64-bit addresses to 64-bit
  1434. values. The computer has a \emph{program counter} (PC)\index{program
  1435. counter}\index{PC} stored in the \code{rip} register that points to
  1436. the address of the next instruction to be executed. For most
  1437. instructions, the program counter is incremented after the instruction
  1438. is executed, so it points to the next instruction in memory. Most x86
  1439. instructions take two operands, where each operand is either an
  1440. integer constant (called \emph{immediate value}\index{immediate
  1441. value}), a \emph{register}\index{register}, or a memory location.
  1442. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1443. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1444. && \key{r8} \mid \key{r9} \mid \key{r10}
  1445. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1446. \mid \key{r14} \mid \key{r15}}
  1447. \begin{figure}[tp]
  1448. \fbox{
  1449. \begin{minipage}{0.96\textwidth}
  1450. \[
  1451. \begin{array}{lcl}
  1452. \Reg &::=& \allregisters{} \\
  1453. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1454. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1455. \key{subq} \; \Arg\key{,} \Arg \mid
  1456. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1457. && \key{callq} \; \mathit{label} \mid
  1458. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} \\
  1459. && \itm{label}\key{:}\; \Instr \\
  1460. \LangXInt{} &::= & \key{.globl main}\\
  1461. & & \key{main:} \; \Instr\ldots
  1462. \end{array}
  1463. \]
  1464. \end{minipage}
  1465. }
  1466. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  1467. \label{fig:x86-int-concrete}
  1468. \end{figure}
  1469. A register is a special kind of variable. Each one holds a 64-bit
  1470. value; there are 16 general-purpose registers in the computer and
  1471. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  1472. is written with a \key{\%} followed by the register name, such as
  1473. \key{\%rax}.
  1474. An immediate value is written using the notation \key{\$}$n$ where $n$
  1475. is an integer.
  1476. %
  1477. %
  1478. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1479. which obtains the address stored in register $r$ and then adds $n$
  1480. bytes to the address. The resulting address is used to load or store
  1481. to memory depending on whether it occurs as a source or destination
  1482. argument of an instruction.
  1483. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1484. source $s$ and destination $d$, applies the arithmetic operation, then
  1485. writes the result back to the destination $d$.
  1486. %
  1487. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1488. stores the result in $d$.
  1489. %
  1490. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  1491. specified by the label and $\key{retq}$ returns from a procedure to
  1492. its caller.
  1493. %
  1494. We discuss procedure calls in more detail later in this chapter and in
  1495. Chapter~\ref{ch:Rfun}. The instruction $\key{jmp}\,\itm{label}$
  1496. updates the program counter to the address of the instruction after
  1497. the specified label.
  1498. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  1499. all of the x86 instructions used in this book.
  1500. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent to
  1501. \code{(+ 10 32)}. The instruction \lstinline{movq $10, %rax}
  1502. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  1503. adds $32$ to the $10$ in \key{rax} and
  1504. puts the result, $42$, back into \key{rax}.
  1505. %
  1506. The last instruction, \key{retq}, finishes the \key{main} function by
  1507. returning the integer in \key{rax} to the operating system. The
  1508. operating system interprets this integer as the program's exit
  1509. code. By convention, an exit code of 0 indicates that a program
  1510. completed successfully, and all other exit codes indicate various
  1511. errors. Nevertheless, in this book we return the result of the program
  1512. as the exit code.
  1513. \begin{figure}[tbp]
  1514. \begin{lstlisting}
  1515. .globl main
  1516. main:
  1517. movq $10, %rax
  1518. addq $32, %rax
  1519. retq
  1520. \end{lstlisting}
  1521. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1522. \label{fig:p0-x86}
  1523. \end{figure}
  1524. The x86 assembly language varies in a couple ways depending on what
  1525. operating system it is assembled in. The code examples shown here are
  1526. correct on Linux and most Unix-like platforms, but when assembled on
  1527. Mac OS X, labels like \key{main} must be prefixed with an underscore,
  1528. as in \key{\_main}.
  1529. We exhibit the use of memory for storing intermediate results in the
  1530. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1531. equivalent to \code{(+ 52 (- 10))}. This program uses a region of
  1532. memory called the \emph{procedure call stack} (or \emph{stack} for
  1533. short). \index{stack}\index{procedure call stack} The stack consists
  1534. of a separate \emph{frame}\index{frame} for each procedure call. The
  1535. memory layout for an individual frame is shown in
  1536. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1537. \emph{stack pointer}\index{stack pointer} and points to the item at
  1538. the top of the stack. The stack grows downward in memory, so we
  1539. increase the size of the stack by subtracting from the stack pointer.
  1540. In the context of a procedure call, the \emph{return
  1541. address}\index{return address} is the instruction after the call
  1542. instruction on the caller side. The function call instruction,
  1543. \code{callq}, pushes the return address onto the stack prior to
  1544. jumping to the procedure. The register \key{rbp} is the \emph{base
  1545. pointer}\index{base pointer} and is used to access variables that
  1546. are stored in the frame of the current procedure call. The base
  1547. pointer of the caller is pushed onto the stack after the return
  1548. address and then the base pointer is set to the location of the old
  1549. base pointer. In Figure~\ref{fig:frame} we number the variables from
  1550. $1$ to $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$,
  1551. variable $2$ at $-16\key{(\%rbp)}$, etc.
  1552. \begin{figure}[tbp]
  1553. \begin{lstlisting}
  1554. start:
  1555. movq $10, -8(%rbp)
  1556. negq -8(%rbp)
  1557. movq -8(%rbp), %rax
  1558. addq $52, %rax
  1559. jmp conclusion
  1560. .globl main
  1561. main:
  1562. pushq %rbp
  1563. movq %rsp, %rbp
  1564. subq $16, %rsp
  1565. jmp start
  1566. conclusion:
  1567. addq $16, %rsp
  1568. popq %rbp
  1569. retq
  1570. \end{lstlisting}
  1571. \caption{An x86 program equivalent to \code{(+ 52 (- 10))}.}
  1572. \label{fig:p1-x86}
  1573. \end{figure}
  1574. \begin{figure}[tbp]
  1575. \centering
  1576. \begin{tabular}{|r|l|} \hline
  1577. Position & Contents \\ \hline
  1578. 8(\key{\%rbp}) & return address \\
  1579. 0(\key{\%rbp}) & old \key{rbp} \\
  1580. -8(\key{\%rbp}) & variable $1$ \\
  1581. -16(\key{\%rbp}) & variable $2$ \\
  1582. \ldots & \ldots \\
  1583. 0(\key{\%rsp}) & variable $n$\\ \hline
  1584. \end{tabular}
  1585. \caption{Memory layout of a frame.}
  1586. \label{fig:frame}
  1587. \end{figure}
  1588. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  1589. control is transferred from the operating system to the \code{main}
  1590. function. The operating system issues a \code{callq main} instruction
  1591. which pushes its return address on the stack and then jumps to
  1592. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  1593. by 16 bytes prior to the execution of any \code{callq} instruction, so
  1594. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  1595. alignment (because the \code{callq} pushed the return address). The
  1596. first three instructions are the typical \emph{prelude}\index{prelude}
  1597. for a procedure. The instruction \code{pushq \%rbp} saves the base
  1598. pointer for the caller onto the stack and subtracts $8$ from the stack
  1599. pointer. The second instruction \code{movq \%rsp, \%rbp} changes the
  1600. base pointer so that it points the location of the old base
  1601. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  1602. pointer down to make enough room for storing variables. This program
  1603. needs one variable ($8$ bytes) but we round up to 16 bytes so that
  1604. \code{rsp} is 16-byte aligned and we're ready to make calls to other
  1605. functions. The last instruction of the prelude is \code{jmp start},
  1606. which transfers control to the instructions that were generated from
  1607. the Racket expression \code{(+ 52 (- 10))}.
  1608. The first instruction under the \code{start} label is
  1609. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  1610. %
  1611. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  1612. %
  1613. The next instruction moves the $-10$ from variable $1$ into the
  1614. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  1615. the value in \code{rax}, updating its contents to $42$.
  1616. The three instructions under the label \code{conclusion} are the
  1617. typical \emph{conclusion}\index{conclusion} of a procedure. The first
  1618. two instructions restore the \code{rsp} and \code{rbp} registers to
  1619. the state they were in at the beginning of the procedure. The
  1620. instruction \key{addq \$16, \%rsp} moves the stack pointer back to
  1621. point at the old base pointer. Then \key{popq \%rbp} returns the old
  1622. base pointer to \key{rbp} and adds $8$ to the stack pointer. The last
  1623. instruction, \key{retq}, jumps back to the procedure that called this
  1624. one and adds $8$ to the stack pointer.
  1625. The compiler needs a convenient representation for manipulating x86
  1626. programs, so we define an abstract syntax for x86 in
  1627. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  1628. \LangXInt{}. The main difference compared to the concrete syntax of
  1629. \LangXInt{} (Figure~\ref{fig:x86-int-concrete}) is that labels are not
  1630. allowed in front of every instructions. Instead instructions are
  1631. grouped into \emph{blocks}\index{block}\index{basic block} with a
  1632. label associated with every block, which is why the \key{X86Program}
  1633. struct includes an alist mapping labels to blocks. The reason for this
  1634. organization becomes apparent in Chapter~\ref{ch:Rif} when we
  1635. introduce conditional branching. The \code{Block} structure includes
  1636. an $\itm{info}$ field that is not needed for this chapter, but becomes
  1637. useful in Chapter~\ref{ch:register-allocation-Rvar}. For now, the
  1638. $\itm{info}$ field should contain an empty list. Also, regarding the
  1639. abstract syntax for \code{callq}, the \code{Callq} struct includes an
  1640. integer for representing the arity of the function, i.e., the number
  1641. of arguments, which is helpful to know during register allocation
  1642. (Chapter~\ref{ch:register-allocation-Rvar}).
  1643. \begin{figure}[tp]
  1644. \fbox{
  1645. \begin{minipage}{0.98\textwidth}
  1646. \small
  1647. \[
  1648. \begin{array}{lcl}
  1649. \Reg &::=& \allregisters{} \\
  1650. \Arg &::=& \IMM{\Int} \mid \REG{\Reg}
  1651. \mid \DEREF{\Reg}{\Int} \\
  1652. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  1653. \mid \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  1654. &\mid& \BININSTR{\code{movq}}{\Arg}{\Arg}
  1655. \mid \UNIINSTR{\code{negq}}{\Arg}\\
  1656. &\mid& \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  1657. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  1658. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP} \\
  1659. \LangXInt{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  1660. \end{array}
  1661. \]
  1662. \end{minipage}
  1663. }
  1664. \caption{The abstract syntax of \LangXInt{} assembly.}
  1665. \label{fig:x86-int-ast}
  1666. \end{figure}
  1667. \section{Planning the trip to x86 via the \LangCVar{} language}
  1668. \label{sec:plan-s0-x86}
  1669. To compile one language to another it helps to focus on the
  1670. differences between the two languages because the compiler will need
  1671. to bridge those differences. What are the differences between \LangVar{}
  1672. and x86 assembly? Here are some of the most important ones:
  1673. \begin{enumerate}
  1674. \item[(a)] x86 arithmetic instructions typically have two arguments
  1675. and update the second argument in place. In contrast, \LangVar{}
  1676. arithmetic operations take two arguments and produce a new value.
  1677. An x86 instruction may have at most one memory-accessing argument.
  1678. Furthermore, some instructions place special restrictions on their
  1679. arguments.
  1680. \item[(b)] An argument of an \LangVar{} operator can be a deeply-nested
  1681. expression, whereas x86 instructions restrict their arguments to be
  1682. integers constants, registers, and memory locations.
  1683. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1684. sequence of instructions and jumps to labeled positions, whereas in
  1685. \LangVar{} the order of evaluation is a left-to-right depth-first
  1686. traversal of the abstract syntax tree.
  1687. \item[(d)] A program in \LangVar{} can have any number of variables
  1688. whereas x86 has 16 registers and the procedure calls stack.
  1689. \item[(e)] Variables in \LangVar{} can overshadow other variables with the
  1690. same name. In x86, registers have unique names and memory locations
  1691. have unique addresses.
  1692. \end{enumerate}
  1693. We ease the challenge of compiling from \LangVar{} to x86 by breaking down
  1694. the problem into several steps, dealing with the above differences one
  1695. at a time. Each of these steps is called a \emph{pass} of the
  1696. compiler.\index{pass}\index{compiler pass}
  1697. %
  1698. This terminology comes from the way each step passes over the AST of
  1699. the program.
  1700. %
  1701. We begin by sketching how we might implement each pass, and give them
  1702. names. We then figure out an ordering of the passes and the
  1703. input/output language for each pass. The very first pass has
  1704. \LangVar{} as its input language and the last pass has \LangXInt{} as
  1705. its output language. In between we can choose whichever language is
  1706. most convenient for expressing the output of each pass, whether that
  1707. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  1708. our own design. Finally, to implement each pass we write one
  1709. recursive function per non-terminal in the grammar of the input
  1710. language of the pass. \index{intermediate language}
  1711. \begin{description}
  1712. \item[\key{select-instructions}] handles the difference between
  1713. \LangVar{} operations and x86 instructions. This pass converts each
  1714. \LangVar{} operation to a short sequence of instructions that
  1715. accomplishes the same task.
  1716. \item[\key{remove-complex-opera*}] ensures that each subexpression of
  1717. a primitive operation is a variable or integer, that is, an
  1718. \emph{atomic} expression. We refer to non-atomic expressions as
  1719. \emph{complex}. This pass introduces temporary variables to hold
  1720. the results of complex subexpressions.\index{atomic
  1721. expression}\index{complex expression}%
  1722. \footnote{The subexpressions of an operation are often called
  1723. operators and operands which explains the presence of
  1724. \code{opera*} in the name of this pass.}
  1725. \item[\key{explicate-control}] makes the execution order of the
  1726. program explicit. It convert the abstract syntax tree representation
  1727. into a control-flow graph in which each node contains a sequence of
  1728. statements and the edges between nodes say which nodes contain jumps
  1729. to other nodes.
  1730. \item[\key{assign-homes}] replaces the variables in \LangVar{} with
  1731. registers or stack locations in x86.
  1732. \item[\key{uniquify}] deals with the shadowing of variables by
  1733. renaming every variable to a unique name.
  1734. \end{description}
  1735. The next question is: in what order should we apply these passes? This
  1736. question can be challenging because it is difficult to know ahead of
  1737. time which orderings will be better (easier to implement, produce more
  1738. efficient code, etc.) so oftentimes trial-and-error is
  1739. involved. Nevertheless, we can try to plan ahead and make educated
  1740. choices regarding the ordering.
  1741. What should be the ordering of \key{explicate-control} with respect to
  1742. \key{uniquify}? The \key{uniquify} pass should come first because
  1743. \key{explicate-control} changes all the \key{let}-bound variables to
  1744. become local variables whose scope is the entire program, which would
  1745. confuse variables with the same name.
  1746. %
  1747. We place \key{remove-complex-opera*} before \key{explicate-control}
  1748. because the later removes the \key{let} form, but it is convenient to
  1749. use \key{let} in the output of \key{remove-complex-opera*}.
  1750. %
  1751. The ordering of \key{uniquify} with respect to
  1752. \key{remove-complex-opera*} does not matter so we arbitrarily choose
  1753. \key{uniquify} to come first.
  1754. Last, we consider \key{select-instructions} and \key{assign-homes}.
  1755. These two passes are intertwined. In Chapter~\ref{ch:Rfun} we
  1756. learn that, in x86, registers are used for passing arguments to
  1757. functions and it is preferable to assign parameters to their
  1758. corresponding registers. On the other hand, by selecting instructions
  1759. first we may run into a dead end in \key{assign-homes}. Recall that
  1760. only one argument of an x86 instruction may be a memory access but
  1761. \key{assign-homes} might fail to assign even one of them to a
  1762. register.
  1763. %
  1764. A sophisticated approach is to iteratively repeat the two passes until
  1765. a solution is found. However, to reduce implementation complexity we
  1766. recommend a simpler approach in which \key{select-instructions} comes
  1767. first, followed by the \key{assign-homes}, then a third pass named
  1768. \key{patch-instructions} that uses a reserved register to fix
  1769. outstanding problems.
  1770. \begin{figure}[tbp]
  1771. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1772. \node (Rvar) at (0,2) {\large \LangVar{}};
  1773. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  1774. \node (Rvar-3) at (6,2) {\large \LangVarANF{}};
  1775. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  1776. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  1777. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  1778. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  1779. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  1780. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  1781. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  1782. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvar-3);
  1783. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate-control} (Cvar-2);
  1784. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1785. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1786. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1787. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1788. \end{tikzpicture}
  1789. \caption{Diagram of the passes for compiling \LangVar{}. }
  1790. \label{fig:Rvar-passes}
  1791. \end{figure}
  1792. Figure~\ref{fig:Rvar-passes} presents the ordering of the compiler
  1793. passes and identifies the input and output language of each pass. The
  1794. last pass, \key{print-x86}, converts from the abstract syntax of
  1795. \LangXInt{} to the concrete syntax. In the following two sections
  1796. we discuss the \LangCVar{} intermediate language and the \LangXVar{}
  1797. dialect of x86. The remainder of this chapter gives hints regarding
  1798. the implementation of each of the compiler passes in
  1799. Figure~\ref{fig:Rvar-passes}.
  1800. %% The output of \key{uniquify} and \key{remove-complex-opera*}
  1801. %% are programs that are still in the \LangVar{} language, though the
  1802. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  1803. %% (Section~\ref{sec:remove-complex-opera-Rvar}).
  1804. %% %
  1805. %% The output of \key{explicate-control} is in an intermediate language
  1806. %% \LangCVar{} designed to make the order of evaluation explicit in its
  1807. %% syntax, which we introduce in the next section. The
  1808. %% \key{select-instruction} pass translates from \LangCVar{} to
  1809. %% \LangXVar{}. The \key{assign-homes} and
  1810. %% \key{patch-instructions}
  1811. %% passes input and output variants of x86 assembly.
  1812. \subsection{The \LangCVar{} Intermediate Language}
  1813. The output of \key{explicate-control} is similar to the $C$
  1814. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1815. categories for expressions and statements, so we name it \LangCVar{}. The
  1816. abstract syntax for \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  1817. (The concrete syntax for \LangCVar{} is in the Appendix,
  1818. Figure~\ref{fig:c0-concrete-syntax}.)
  1819. %
  1820. The \LangCVar{} language supports the same operators as \LangVar{} but
  1821. the arguments of operators are restricted to atomic
  1822. expressions. Instead of \key{let} expressions, \LangCVar{} has
  1823. assignment statements which can be executed in sequence using the
  1824. \key{Seq} form. A sequence of statements always ends with
  1825. \key{Return}, a guarantee that is baked into the grammar rules for
  1826. \itm{tail}. The naming of this non-terminal comes from the term
  1827. \emph{tail position}\index{tail position}, which refers to an
  1828. expression that is the last one to execute within a function.
  1829. A \LangCVar{} program consists of a control-flow graph represented as
  1830. an alist mapping labels to tails. This is more general than necessary
  1831. for the present chapter, as we do not yet introduce \key{goto} for
  1832. jumping to labels, but it saves us from having to change the syntax in
  1833. Chapter~\ref{ch:Rif}. For now there will be just one label,
  1834. \key{start}, and the whole program is its tail.
  1835. %
  1836. The $\itm{info}$ field of the \key{CProgram} form, after the
  1837. \key{explicate-control} pass, contains a mapping from the symbol
  1838. \key{locals} to a list of variables, that is, a list of all the
  1839. variables used in the program. At the start of the program, these
  1840. variables are uninitialized; they become initialized on their first
  1841. assignment.
  1842. \begin{figure}[tbp]
  1843. \fbox{
  1844. \begin{minipage}{0.96\textwidth}
  1845. \[
  1846. \begin{array}{lcl}
  1847. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1848. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1849. &\mid& \ADD{\Atm}{\Atm}\\
  1850. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  1851. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1852. \LangCVar{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  1853. \end{array}
  1854. \]
  1855. \end{minipage}
  1856. }
  1857. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  1858. \label{fig:c0-syntax}
  1859. \end{figure}
  1860. The definitional interpreter for \LangCVar{} is in the support code,
  1861. in the file \code{interp-Cvar.rkt}.
  1862. \subsection{The \LangXVar{} dialect}
  1863. The \LangXVar{} language is the output of the pass
  1864. \key{select-instructions}. It extends \LangXInt{} with an unbounded
  1865. number of program-scope variables and removes the restrictions
  1866. regarding instruction arguments.
  1867. \section{Uniquify Variables}
  1868. \label{sec:uniquify-Rvar}
  1869. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  1870. programs in which every \key{let} binds a unique variable name. For
  1871. example, the \code{uniquify} pass should translate the program on the
  1872. left into the program on the right. \\
  1873. \begin{tabular}{lll}
  1874. \begin{minipage}{0.4\textwidth}
  1875. \begin{lstlisting}
  1876. (let ([x 32])
  1877. (+ (let ([x 10]) x) x))
  1878. \end{lstlisting}
  1879. \end{minipage}
  1880. &
  1881. $\Rightarrow$
  1882. &
  1883. \begin{minipage}{0.4\textwidth}
  1884. \begin{lstlisting}
  1885. (let ([x.1 32])
  1886. (+ (let ([x.2 10]) x.2) x.1))
  1887. \end{lstlisting}
  1888. \end{minipage}
  1889. \end{tabular} \\
  1890. %
  1891. The following is another example translation, this time of a program
  1892. with a \key{let} nested inside the initializing expression of another
  1893. \key{let}.\\
  1894. \begin{tabular}{lll}
  1895. \begin{minipage}{0.4\textwidth}
  1896. \begin{lstlisting}
  1897. (let ([x (let ([x 4])
  1898. (+ x 1))])
  1899. (+ x 2))
  1900. \end{lstlisting}
  1901. \end{minipage}
  1902. &
  1903. $\Rightarrow$
  1904. &
  1905. \begin{minipage}{0.4\textwidth}
  1906. \begin{lstlisting}
  1907. (let ([x.2 (let ([x.1 4])
  1908. (+ x.1 1))])
  1909. (+ x.2 2))
  1910. \end{lstlisting}
  1911. \end{minipage}
  1912. \end{tabular}
  1913. We recommend implementing \code{uniquify} by creating a structurally
  1914. recursive function named \code{uniquify-exp} that mostly just copies
  1915. an expression. However, when encountering a \key{let}, it should
  1916. generate a unique name for the variable and associate the old name
  1917. with the new name in an alist.\footnote{The Racket function
  1918. \code{gensym} is handy for generating unique variable names.} The
  1919. \code{uniquify-exp} function needs to access this alist when it gets
  1920. to a variable reference, so we add a parameter to \code{uniquify-exp}
  1921. for the alist.
  1922. The skeleton of the \code{uniquify-exp} function is shown in
  1923. Figure~\ref{fig:uniquify-Rvar}. The function is curried so that it is
  1924. convenient to partially apply it to an alist and then apply it to
  1925. different expressions, as in the last case for primitive operations in
  1926. Figure~\ref{fig:uniquify-Rvar}. The
  1927. %
  1928. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  1929. %
  1930. form of Racket is useful for transforming each element of a list to
  1931. produce a new list.\index{for/list}
  1932. \begin{exercise}
  1933. \normalfont % I don't like the italics for exercises. -Jeremy
  1934. Complete the \code{uniquify} pass by filling in the blanks in
  1935. Figure~\ref{fig:uniquify-Rvar}, that is, implement the cases for
  1936. variables and for the \key{let} form in the file \code{compiler.rkt}
  1937. in the support code.
  1938. \end{exercise}
  1939. \begin{figure}[tbp]
  1940. \begin{lstlisting}
  1941. (define (uniquify-exp env)
  1942. (lambda (e)
  1943. (match e
  1944. [(Var x) ___]
  1945. [(Int n) (Int n)]
  1946. [(Let x e body) ___]
  1947. [(Prim op es)
  1948. (Prim op (for/list ([e es]) ((uniquify-exp env) e)))])))
  1949. (define (uniquify p)
  1950. (match p
  1951. [(Program '() e) (Program '() ((uniquify-exp '()) e))]))
  1952. \end{lstlisting}
  1953. \caption{Skeleton for the \key{uniquify} pass.}
  1954. \label{fig:uniquify-Rvar}
  1955. \end{figure}
  1956. \begin{exercise}
  1957. \normalfont % I don't like the italics for exercises. -Jeremy
  1958. Create five \LangVar{} programs that exercise the most interesting
  1959. parts of the \key{uniquify} pass, that is, the programs should include
  1960. \key{let} forms, variables, and variables that overshadow each other.
  1961. The five programs should be placed in the subdirectory named
  1962. \key{tests} and the file names should start with \code{var\_test\_}
  1963. followed by a unique integer and end with the file extension
  1964. \key{.rkt}.
  1965. %
  1966. The \key{run-tests.rkt} script in the support code checks whether the
  1967. output programs produce the same result as the input programs. The
  1968. script uses the \key{interp-tests} function
  1969. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1970. your \key{uniquify} pass on the example programs. The \code{passes}
  1971. parameter of \key{interp-tests} is a list that should have one entry
  1972. for each pass in your compiler. For now, define \code{passes} to
  1973. contain just one entry for \code{uniquify} as follows.
  1974. \begin{lstlisting}
  1975. (define passes
  1976. (list (list "uniquify" uniquify interp-Rvar type-check-Rvar)))
  1977. \end{lstlisting}
  1978. Run the \key{run-tests.rkt} script in the support code to check
  1979. whether the output programs produce the same result as the input
  1980. programs.
  1981. \end{exercise}
  1982. \section{Remove Complex Operands}
  1983. \label{sec:remove-complex-opera-Rvar}
  1984. The \code{remove-complex-opera*} pass compiles \LangVar{} programs into
  1985. \LangVar{} programs in which the arguments of operations are atomic
  1986. expressions. Put another way, this pass removes complex
  1987. operands\index{complex operand}, such as the expression \code{(- 10)}
  1988. in the program below. This is accomplished by introducing a new
  1989. \key{let}-bound variable, binding the complex operand to the new
  1990. variable, and then using the new variable in place of the complex
  1991. operand, as shown in the output of \code{remove-complex-opera*} on the
  1992. right.\\
  1993. \begin{tabular}{lll}
  1994. \begin{minipage}{0.4\textwidth}
  1995. % var_test_19.rkt
  1996. \begin{lstlisting}
  1997. (+ 52 (- 10))
  1998. \end{lstlisting}
  1999. \end{minipage}
  2000. &
  2001. $\Rightarrow$
  2002. &
  2003. \begin{minipage}{0.4\textwidth}
  2004. \begin{lstlisting}
  2005. (let ([tmp.1 (- 10)])
  2006. (+ 52 tmp.1))
  2007. \end{lstlisting}
  2008. \end{minipage}
  2009. \end{tabular}
  2010. \begin{figure}[tp]
  2011. \centering
  2012. \fbox{
  2013. \begin{minipage}{0.96\textwidth}
  2014. \[
  2015. \begin{array}{rcl}
  2016. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  2017. \Exp &::=& \Atm \mid \READ{} \\
  2018. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  2019. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  2020. R^{\dagger}_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  2021. \end{array}
  2022. \]
  2023. \end{minipage}
  2024. }
  2025. \caption{\LangVarANF{} is \LangVar{} in administrative normal form (ANF).}
  2026. \label{fig:r1-anf-syntax}
  2027. \end{figure}
  2028. Figure~\ref{fig:r1-anf-syntax} presents the grammar for the output of
  2029. this pass, the language \LangVarANF{}. The only difference is that
  2030. operator arguments are required to be atomic expressions. In the
  2031. literature, this is called \emph{administrative normal form}, or ANF
  2032. for short~\citep{Danvy:1991fk,Flanagan:1993cg}. \index{administrative
  2033. normal form} \index{ANF}
  2034. We recommend implementing this pass with two mutually recursive
  2035. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  2036. \code{rco-atom} to subexpressions that are required to be atomic and
  2037. to apply \code{rco-exp} to subexpressions that can be atomic or
  2038. complex (see Figure~\ref{fig:r1-anf-syntax}). Both functions take an
  2039. \LangVar{} expression as input. The \code{rco-exp} function returns an
  2040. expression. The \code{rco-atom} function returns two things: an
  2041. atomic expression and alist mapping temporary variables to complex
  2042. subexpressions. You can return multiple things from a function using
  2043. Racket's \key{values} form and you can receive multiple things from a
  2044. function call using the \key{define-values} form. If you are not
  2045. familiar with these features, review the Racket documentation. Also,
  2046. 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}}
  2047. form is useful for applying a function to each
  2048. element of a list, in the case where the function returns multiple
  2049. values.
  2050. \index{for/lists}
  2051. The following shows the output of \code{rco-atom} on the expression
  2052. \code{(- 10)} (using concrete syntax to be concise).
  2053. \begin{tabular}{lll}
  2054. \begin{minipage}{0.4\textwidth}
  2055. \begin{lstlisting}
  2056. (- 10)
  2057. \end{lstlisting}
  2058. \end{minipage}
  2059. &
  2060. $\Rightarrow$
  2061. &
  2062. \begin{minipage}{0.4\textwidth}
  2063. \begin{lstlisting}
  2064. tmp.1
  2065. ((tmp.1 . (- 10)))
  2066. \end{lstlisting}
  2067. \end{minipage}
  2068. \end{tabular}
  2069. Take special care of programs such as the following one that binds a
  2070. variable to an atomic expression. You should leave such variable
  2071. bindings unchanged, as shown in to the program on the right \\
  2072. \begin{tabular}{lll}
  2073. \begin{minipage}{0.4\textwidth}
  2074. % var_test_20.rkt
  2075. \begin{lstlisting}
  2076. (let ([a 42])
  2077. (let ([b a])
  2078. b))
  2079. \end{lstlisting}
  2080. \end{minipage}
  2081. &
  2082. $\Rightarrow$
  2083. &
  2084. \begin{minipage}{0.4\textwidth}
  2085. \begin{lstlisting}
  2086. (let ([a 42])
  2087. (let ([b a])
  2088. b))
  2089. \end{lstlisting}
  2090. \end{minipage}
  2091. \end{tabular} \\
  2092. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  2093. produce the following output with unnecessary temporary variables.\\
  2094. \begin{minipage}{0.4\textwidth}
  2095. \begin{lstlisting}
  2096. (let ([tmp.1 42])
  2097. (let ([a tmp.1])
  2098. (let ([tmp.2 a])
  2099. (let ([b tmp.2])
  2100. b))))
  2101. \end{lstlisting}
  2102. \end{minipage}
  2103. \begin{exercise}\normalfont
  2104. %
  2105. Implement the \code{remove-complex-opera*} function in
  2106. \code{compiler.rkt}.
  2107. %
  2108. Create three new \LangInt{} programs that exercise the interesting
  2109. code in the \code{remove-complex-opera*} pass (Following the same file
  2110. name guidelines as before.).
  2111. %
  2112. In the \code{run-tests.rkt} script, add the following entry to the
  2113. list of \code{passes} and then run the script to test your compiler.
  2114. \begin{lstlisting}
  2115. (list "remove-complex" remove-complex-opera* interp-Rvar type-check-Rvar)
  2116. \end{lstlisting}
  2117. While debugging your compiler, it is often useful to see the
  2118. intermediate programs that are output from each pass. To print the
  2119. intermeidate programs, place the following before the call to
  2120. \code{interp-tests} in \code{run-tests.rkt}.
  2121. \begin{lstlisting}
  2122. (debug-level 1)
  2123. \end{lstlisting}
  2124. \end{exercise}
  2125. \section{Explicate Control}
  2126. \label{sec:explicate-control-Rvar}
  2127. The \code{explicate-control} pass compiles \LangVar{} programs into \LangCVar{}
  2128. programs that make the order of execution explicit in their
  2129. syntax. For now this amounts to flattening \key{let} constructs into a
  2130. sequence of assignment statements. For example, consider the following
  2131. \LangVar{} program.\\
  2132. % var_test_11.rkt
  2133. \begin{minipage}{0.96\textwidth}
  2134. \begin{lstlisting}
  2135. (let ([y (let ([x 20])
  2136. (+ x (let ([x 22]) x)))])
  2137. y)
  2138. \end{lstlisting}
  2139. \end{minipage}\\
  2140. %
  2141. The output of the previous pass and of \code{explicate-control} is
  2142. shown below. Recall that the right-hand-side of a \key{let} executes
  2143. before its body, so the order of evaluation for this program is to
  2144. assign \code{20} to \code{x.1}, \code{22} to \code{x.2}, and
  2145. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  2146. output of \code{explicate-control} makes this ordering explicit.\\
  2147. \begin{tabular}{lll}
  2148. \begin{minipage}{0.4\textwidth}
  2149. \begin{lstlisting}
  2150. (let ([y (let ([x.1 20])
  2151. (let ([x.2 22])
  2152. (+ x.1 x.2)))])
  2153. y)
  2154. \end{lstlisting}
  2155. \end{minipage}
  2156. &
  2157. $\Rightarrow$
  2158. &
  2159. \begin{minipage}{0.4\textwidth}
  2160. \begin{lstlisting}[language=C]
  2161. start:
  2162. x.1 = 20;
  2163. x.2 = 22;
  2164. y = (+ x.1 x.2);
  2165. return y;
  2166. \end{lstlisting}
  2167. \end{minipage}
  2168. \end{tabular}
  2169. \begin{figure}[tbp]
  2170. \begin{lstlisting}
  2171. (define (explicate-tail e)
  2172. (match e
  2173. [(Var x) ___]
  2174. [(Int n) (Return (Int n))]
  2175. [(Let x rhs body) ___]
  2176. [(Prim op es) ___]
  2177. [else (error "explicate-tail unhandled case" e)]))
  2178. (define (explicate-assign e x cont)
  2179. (match e
  2180. [(Var x) ___]
  2181. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  2182. [(Let y rhs body) ___]
  2183. [(Prim op es) ___]
  2184. [else (error "explicate-assign unhandled case" e)]))
  2185. (define (explicate-control p)
  2186. (match p
  2187. [(Program info body) ___]))
  2188. \end{lstlisting}
  2189. \caption{Skeleton for the \key{explicate-control} pass.}
  2190. \label{fig:explicate-control-Rvar}
  2191. \end{figure}
  2192. The organization of this pass depends on the notion of tail position
  2193. that we have alluded to earlier. Formally, \emph{tail
  2194. position}\index{tail position} in the context of \LangVar{} is
  2195. defined recursively by the following two rules.
  2196. \begin{enumerate}
  2197. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  2198. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  2199. \end{enumerate}
  2200. We recommend implementing \code{explicate-control} using two mutually
  2201. recursive functions, \code{explicate-tail} and
  2202. \code{explicate-assign}, as suggested in the skeleton code in
  2203. Figure~\ref{fig:explicate-control-Rvar}. The \code{explicate-tail}
  2204. function should be applied to expressions in tail position whereas the
  2205. \code{explicate-assign} should be applied to expressions that occur on
  2206. the right-hand-side of a \key{let}.
  2207. %
  2208. The \code{explicate-tail} function takes an \Exp{} in \LangVar{} as
  2209. input and produces a \Tail{} in \LangCVar{} (see
  2210. Figure~\ref{fig:c0-syntax}).
  2211. %
  2212. The \code{explicate-assign} function takes an \Exp{} in \LangVar{},
  2213. the variable that it is to be assigned to, and a \Tail{} in
  2214. \LangCVar{} for the code that will come after the assignment. The
  2215. \code{explicate-assign} function returns a $\Tail$ in \LangCVar{}.
  2216. The \code{explicate-assign} function is in accumulator-passing style
  2217. in that the \code{cont} parameter is used for accumulating the
  2218. output. The reader might be tempted to instead organize
  2219. \code{explicate-assign} in a more direct fashion, without the
  2220. \code{cont} parameter and perhaps using \code{append} to combine
  2221. statements. We warn against that alternative because the
  2222. accumulator-passing style is key to how we generate high-quality code
  2223. for conditional expressions in Chapter~\ref{ch:Rif}.
  2224. \begin{exercise}\normalfont
  2225. %
  2226. Implement the \code{explicate-control} function in
  2227. \code{compiler.rkt}. Create three new \LangInt{} programs that
  2228. exercise the code in \code{explicate-control}.
  2229. %
  2230. In the \code{run-tests.rkt} script, add the following entry to the
  2231. list of \code{passes} and then run the script to test your compiler.
  2232. \begin{lstlisting}
  2233. (list "explicate control" explicate-control interp-Cvar type-check-Cvar)
  2234. \end{lstlisting}
  2235. \end{exercise}
  2236. \section{Select Instructions}
  2237. \label{sec:select-Rvar}
  2238. \index{instruction selection}
  2239. In the \code{select-instructions} pass we begin the work of
  2240. translating from \LangCVar{} to \LangXVar{}. The target language of
  2241. this pass is a variant of x86 that still uses variables, so we add an
  2242. AST node of the form $\VAR{\itm{var}}$ to the \Arg{} non-terminal of
  2243. the \LangXInt{} abstract syntax (Figure~\ref{fig:x86-int-ast}). We
  2244. recommend implementing the \code{select-instructions} with
  2245. three auxiliary functions, one for each of the non-terminals of
  2246. \LangCVar{}: $\Atm$, $\Stmt$, and $\Tail$.
  2247. The cases for $\Atm$ are straightforward, variables stay
  2248. the same and integer constants are changed to immediates:
  2249. $\INT{n}$ changes to $\IMM{n}$.
  2250. Next we consider the cases for $\Stmt$, starting with arithmetic
  2251. operations. For example, consider the addition operation. We can use
  2252. the \key{addq} instruction, but it performs an in-place update. So we
  2253. could move $\itm{arg}_1$ into the left-hand side \itm{var} and then
  2254. add $\itm{arg}_2$ to \itm{var}. \\
  2255. \begin{tabular}{lll}
  2256. \begin{minipage}{0.4\textwidth}
  2257. \begin{lstlisting}
  2258. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{arg}_2$|);
  2259. \end{lstlisting}
  2260. \end{minipage}
  2261. &
  2262. $\Rightarrow$
  2263. &
  2264. \begin{minipage}{0.4\textwidth}
  2265. \begin{lstlisting}
  2266. movq |$\itm{arg}_1$|, |$\itm{var}$|
  2267. addq |$\itm{arg}_2$|, |$\itm{var}$|
  2268. \end{lstlisting}
  2269. \end{minipage}
  2270. \end{tabular} \\
  2271. %
  2272. There are also cases that require special care to avoid generating
  2273. needlessly complicated code. For example, if one of the arguments of
  2274. the addition is the same variable as the left-hand side of the
  2275. assignment, then there is no need for the extra move instruction. The
  2276. assignment statement can be translated into a single \key{addq}
  2277. instruction as follows.\\
  2278. \begin{tabular}{lll}
  2279. \begin{minipage}{0.4\textwidth}
  2280. \begin{lstlisting}
  2281. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{var}$|);
  2282. \end{lstlisting}
  2283. \end{minipage}
  2284. &
  2285. $\Rightarrow$
  2286. &
  2287. \begin{minipage}{0.4\textwidth}
  2288. \begin{lstlisting}
  2289. addq |$\itm{arg}_1$|, |$\itm{var}$|
  2290. \end{lstlisting}
  2291. \end{minipage}
  2292. \end{tabular}
  2293. The \key{read} operation does not have a direct counterpart in x86
  2294. assembly, so we provide this functionality with the function
  2295. \code{read\_int} in the file \code{runtime.c}, written in
  2296. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  2297. functionality in this file as the \emph{runtime system}\index{runtime
  2298. system}, or simply the \emph{runtime} for short. When compiling your
  2299. generated x86 assembly code, you need to compile \code{runtime.c} to
  2300. \code{runtime.o} (an ``object file'', using \code{gcc} option
  2301. \code{-c}) and link it into the executable. For our purposes of code
  2302. generation, all you need to do is translate an assignment of
  2303. \key{read} into a call to the \code{read\_int} function followed by a
  2304. move from \code{rax} to the left-hand-side variable. (Recall that the
  2305. return value of a function goes into \code{rax}.) \\
  2306. \begin{tabular}{lll}
  2307. \begin{minipage}{0.3\textwidth}
  2308. \begin{lstlisting}
  2309. |$\itm{var}$| = (read);
  2310. \end{lstlisting}
  2311. \end{minipage}
  2312. &
  2313. $\Rightarrow$
  2314. &
  2315. \begin{minipage}{0.3\textwidth}
  2316. \begin{lstlisting}
  2317. callq read_int
  2318. movq %rax, |$\itm{var}$|
  2319. \end{lstlisting}
  2320. \end{minipage}
  2321. \end{tabular}
  2322. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  2323. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  2324. assignment to the \key{rax} register followed by a jump to the
  2325. conclusion of the program (so the conclusion needs to be labeled).
  2326. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  2327. recursively and then append the resulting instructions.
  2328. \begin{exercise}
  2329. \normalfont Implement the \key{select-instructions} pass in
  2330. \code{compiler.rkt}. Create three new example programs that are
  2331. designed to exercise all of the interesting cases in this pass.
  2332. %
  2333. In the \code{run-tests.rkt} script, add the following entry to the
  2334. list of \code{passes} and then run the script to test your compiler.
  2335. \begin{lstlisting}
  2336. (list "instruction selection" select-instructions interp-pseudo-x86-0)
  2337. \end{lstlisting}
  2338. \end{exercise}
  2339. \section{Assign Homes}
  2340. \label{sec:assign-Rvar}
  2341. The \key{assign-homes} pass compiles \LangXVar{} programs to
  2342. \LangXVar{} programs that no longer use program variables.
  2343. Thus, the \key{assign-homes} pass is responsible for placing all of
  2344. the program variables in registers or on the stack. For runtime
  2345. efficiency, it is better to place variables in registers, but as there
  2346. are only 16 registers, some programs must necessarily resort to
  2347. placing some variables on the stack. In this chapter we focus on the
  2348. mechanics of placing variables on the stack. We study an algorithm for
  2349. placing variables in registers in
  2350. Chapter~\ref{ch:register-allocation-Rvar}.
  2351. Consider again the following \LangVar{} program from
  2352. Section~\ref{sec:remove-complex-opera-Rvar}.
  2353. % var_test_20.rkt
  2354. \begin{lstlisting}
  2355. (let ([a 42])
  2356. (let ([b a])
  2357. b))
  2358. \end{lstlisting}
  2359. The output of \code{select-instructions} is shown on the left and the
  2360. output of \code{assign-homes} on the right. In this example, we
  2361. assign variable \code{a} to stack location \code{-8(\%rbp)} and
  2362. variable \code{b} to location \code{-16(\%rbp)}.\\
  2363. \begin{tabular}{l}
  2364. \begin{minipage}{0.4\textwidth}
  2365. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2366. locals-types:
  2367. a : Integer, b : Integer
  2368. start:
  2369. movq $42, a
  2370. movq a, b
  2371. movq b, %rax
  2372. jmp conclusion
  2373. \end{lstlisting}
  2374. \end{minipage}
  2375. {$\Rightarrow$}
  2376. \begin{minipage}{0.4\textwidth}
  2377. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2378. stack-space: 16
  2379. start:
  2380. movq $42, -8(%rbp)
  2381. movq -8(%rbp), -16(%rbp)
  2382. movq -16(%rbp), %rax
  2383. jmp conclusion
  2384. \end{lstlisting}
  2385. \end{minipage}
  2386. \end{tabular}
  2387. The \code{locals-types} entry in the $\itm{info}$ of the
  2388. \code{X86Program} node is an alist mapping all the variables in the
  2389. program to their types (for now just \code{Integer}). The
  2390. \code{assign-homes} pass should replace all uses of those variables
  2391. with stack locations. As an aside, the \code{locals-types} entry is
  2392. computed by \code{type-check-Cvar} in the support code, which installs
  2393. it in the $\itm{info}$ field of the \code{CProgram} node, which should
  2394. be propagated to the \code{X86Program} node.
  2395. In the process of assigning variables to stack locations, it is
  2396. convenient for you to compute and store the size of the frame (in
  2397. bytes) in the $\itm{info}$ field of the \key{X86Program} node, with
  2398. the key \code{stack-space}, which is needed later to generate the
  2399. conclusion of the \code{main} procedure. The x86-64 standard requires
  2400. the frame size to be a multiple of 16 bytes.\index{frame}
  2401. \begin{exercise}\normalfont
  2402. Implement the \key{assign-homes} pass in \code{compiler.rkt}, defining
  2403. auxiliary functions for the non-terminals \Arg{}, \Instr{}, and
  2404. \Block{}. We recommend that the auxiliary functions take an extra
  2405. parameter that is an alist mapping variable names to homes (stack
  2406. locations for now).
  2407. %
  2408. In the \code{run-tests.rkt} script, add the following entry to the
  2409. list of \code{passes} and then run the script to test your compiler.
  2410. \begin{lstlisting}
  2411. (list "assign homes" assign-homes interp-x86-0)
  2412. \end{lstlisting}
  2413. \end{exercise}
  2414. \section{Patch Instructions}
  2415. \label{sec:patch-s0}
  2416. The \code{patch-instructions} pass compiles from \LangXVar{} to
  2417. \LangXInt{} by making sure that each instruction adheres to the
  2418. restriction that at most one argument of an instruction may be a
  2419. memory reference.
  2420. We return to the following example.
  2421. % var_test_20.rkt
  2422. \begin{lstlisting}
  2423. (let ([a 42])
  2424. (let ([b a])
  2425. b))
  2426. \end{lstlisting}
  2427. The \key{assign-homes} pass produces the following output
  2428. for this program. \\
  2429. \begin{minipage}{0.5\textwidth}
  2430. \begin{lstlisting}
  2431. stack-space: 16
  2432. start:
  2433. movq $42, -8(%rbp)
  2434. movq -8(%rbp), -16(%rbp)
  2435. movq -16(%rbp), %rax
  2436. jmp conclusion
  2437. \end{lstlisting}
  2438. \end{minipage}\\
  2439. The second \key{movq} instruction is problematic because both
  2440. arguments are stack locations. We suggest fixing this problem by
  2441. moving from the source location to the register \key{rax} and then
  2442. from \key{rax} to the destination location, as follows.
  2443. \begin{lstlisting}
  2444. movq -8(%rbp), %rax
  2445. movq %rax, -16(%rbp)
  2446. \end{lstlisting}
  2447. \begin{exercise}
  2448. \normalfont Implement the \key{patch-instructions} pass in
  2449. \code{compiler.rkt}. Create three new example programs that are
  2450. designed to exercise all of the interesting cases in this pass.
  2451. %
  2452. In the \code{run-tests.rkt} script, add the following entry to the
  2453. list of \code{passes} and then run the script to test your compiler.
  2454. \begin{lstlisting}
  2455. (list "patch instructions" patch-instructions interp-x86-0)
  2456. \end{lstlisting}
  2457. \end{exercise}
  2458. \section{Print x86}
  2459. \label{sec:print-x86}
  2460. The last step of the compiler from \LangVar{} to x86 is to convert the
  2461. \LangXInt{} AST (defined in Figure~\ref{fig:x86-int-ast}) to the
  2462. string representation (defined in
  2463. Figure~\ref{fig:x86-int-concrete}). The Racket \key{format} and
  2464. \key{string-append} functions are useful in this regard. The main work
  2465. that this step needs to perform is to create the \key{main} function
  2466. and the standard instructions for its prelude and conclusion, as shown
  2467. in Figure~\ref{fig:p1-x86} of Section~\ref{sec:x86}. You will need to
  2468. know the amount of space needed for the stack frame, which you can
  2469. obtain from the \code{stack-space} entry in the $\itm{info}$ field of
  2470. the \key{X86Program} node.
  2471. When running on Mac OS X, you compiler should prefix an underscore to
  2472. labels like \key{main}. The Racket call \code{(system-type 'os)} is
  2473. useful for determining which operating system the compiler is running
  2474. on. It returns \code{'macosx}, \code{'unix}, or \code{'windows}.
  2475. \begin{exercise}\normalfont
  2476. %
  2477. Implement the \key{print-x86} pass in \code{compiler.rkt}.
  2478. %
  2479. In the \code{run-tests.rkt} script, add the following entry to the
  2480. list of \code{passes} and then run the script to test your compiler.
  2481. \begin{lstlisting}
  2482. (list "print x86" print-x86 #f)
  2483. \end{lstlisting}
  2484. %
  2485. Uncomment the call to the \key{compiler-tests} function
  2486. (Appendix~\ref{appendix:utilities}), which tests your complete
  2487. compiler by executing the generated x86 code. Compile the provided
  2488. \key{runtime.c} file to \key{runtime.o} using \key{gcc}. Run the
  2489. script to test your compiler.
  2490. \end{exercise}
  2491. \section{Challenge: Partial Evaluator for \LangVar{}}
  2492. \label{sec:pe-Rvar}
  2493. \index{partial evaluation}
  2494. This section describes optional challenge exercises that involve
  2495. adapting and improving the partial evaluator for \LangInt{} that was
  2496. introduced in Section~\ref{sec:partial-evaluation}.
  2497. \begin{exercise}\label{ex:pe-Rvar}
  2498. \normalfont
  2499. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2500. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  2501. instead of \LangInt{} programs. Recall that \LangVar{} adds \key{let} binding
  2502. and variables to the \LangInt{} language, so you will need to add cases for
  2503. them in the \code{pe-exp} function. Once complete, add the partial
  2504. evaluation pass to the front of your compiler and make sure that your
  2505. compiler still passes all of the tests.
  2506. \end{exercise}
  2507. The next exercise builds on Exercise~\ref{ex:pe-Rvar}.
  2508. \begin{exercise}
  2509. \normalfont
  2510. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2511. \code{pe-add} auxiliary functions with functions that know more about
  2512. arithmetic. For example, your partial evaluator should translate
  2513. \[
  2514. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  2515. \code{(+ 2 (read))}
  2516. \]
  2517. To accomplish this, the \code{pe-exp} function should produce output
  2518. in the form of the $\itm{residual}$ non-terminal of the following
  2519. grammar. The idea is that when processing an addition expression, we
  2520. can always produce either 1) an integer constant, 2) and addition
  2521. expression with an integer constant on the left-hand side but not the
  2522. right-hand side, or 3) or an addition expression in which neither
  2523. subexpression is a constant.
  2524. \[
  2525. \begin{array}{lcl}
  2526. \itm{inert} &::=& \Var \mid \LP\key{read}\RP \mid \LP\key{-} \;\Var\RP
  2527. \mid \LP\key{-} \;\LP\key{read}\RP\RP
  2528. \mid \LP\key{+} \; \itm{inert} \; \itm{inert}\RP\\
  2529. &\mid& \LP\key{let}~\LP\LS\Var~\itm{inert}\RS\RP~ \itm{inert} \RP \\
  2530. \itm{residual} &::=& \Int \mid \LP\key{+}\; \Int\; \itm{inert}\RP \mid \itm{inert}
  2531. \end{array}
  2532. \]
  2533. The \code{pe-add} and \code{pe-neg} functions may assume that their
  2534. inputs are $\itm{residual}$ expressions and they should return
  2535. $\itm{residual}$ expressions. Once the improvements are complete,
  2536. make sure that your compiler still passes all of the tests. After
  2537. all, fast code is useless if it produces incorrect results!
  2538. \end{exercise}
  2539. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2540. \chapter{Register Allocation}
  2541. \label{ch:register-allocation-Rvar}
  2542. \index{register allocation}
  2543. In Chapter~\ref{ch:Rvar} we learned how to store variables on the
  2544. stack. In this Chapter we learn how to improve the performance of the
  2545. generated code by placing some variables into registers. The CPU can
  2546. access a register in a single cycle, whereas accessing the stack can
  2547. take 10s to 100s of cycles. The program in Figure~\ref{fig:reg-eg}
  2548. serves as a running example. The source program is on the left and the
  2549. output of instruction selection is on the right. The program is almost
  2550. in the x86 assembly language but it still uses variables.
  2551. \begin{figure}
  2552. \begin{minipage}{0.45\textwidth}
  2553. Example \LangVar{} program:
  2554. % var_test_28.rkt
  2555. \begin{lstlisting}
  2556. (let ([v 1])
  2557. (let ([w 42])
  2558. (let ([x (+ v 7)])
  2559. (let ([y x])
  2560. (let ([z (+ x w)])
  2561. (+ z (- y)))))))
  2562. \end{lstlisting}
  2563. \end{minipage}
  2564. \begin{minipage}{0.45\textwidth}
  2565. After instruction selection:
  2566. \begin{lstlisting}
  2567. locals-types:
  2568. x : Integer, y : Integer,
  2569. z : Integer, t : Integer,
  2570. v : Integer, w : Integer
  2571. start:
  2572. movq $1, v
  2573. movq $42, w
  2574. movq v, x
  2575. addq $7, x
  2576. movq x, y
  2577. movq x, z
  2578. addq w, z
  2579. movq y, t
  2580. negq t
  2581. movq z, %rax
  2582. addq t, %rax
  2583. jmp conclusion
  2584. \end{lstlisting}
  2585. \end{minipage}
  2586. \caption{A running example for register allocation.}
  2587. \label{fig:reg-eg}
  2588. \end{figure}
  2589. The goal of register allocation is to fit as many variables into
  2590. registers as possible. Some programs have more variables than
  2591. registers so we cannot always map each variable to a different
  2592. register. Fortunately, it is common for different variables to be
  2593. needed during different periods of time during program execution, and
  2594. in such cases several variables can be mapped to the same register.
  2595. Consider variables \code{x} and \code{z} in Figure~\ref{fig:reg-eg}.
  2596. After the variable \code{x} is moved to \code{z} it is no longer
  2597. needed. Variable \code{z}, on the other hand, is used only after this
  2598. point, so \code{x} and \code{z} could share the same register. The
  2599. topic of Section~\ref{sec:liveness-analysis-Rvar} is how to compute
  2600. where a variable is needed. Once we have that information, we compute
  2601. which variables are needed at the same time, i.e., which ones
  2602. \emph{interfere} with each other, and represent this relation as an
  2603. undirected graph whose vertices are variables and edges indicate when
  2604. two variables interfere (Section~\ref{sec:build-interference}). We
  2605. then model register allocation as a graph coloring problem
  2606. (Section~\ref{sec:graph-coloring}).
  2607. If we run out of registers despite these efforts, we place the
  2608. remaining variables on the stack, similar to what we did in
  2609. Chapter~\ref{ch:Rvar}. It is common to use the verb \emph{spill}
  2610. for assigning a variable to a stack location. The decision to spill a
  2611. variable is handled as part of the graph coloring process
  2612. (Section~\ref{sec:graph-coloring}).
  2613. We make the simplifying assumption that each variable is assigned to
  2614. one location (a register or stack address). A more sophisticated
  2615. approach is to assign a variable to one or more locations in different
  2616. regions of the program. For example, if a variable is used many times
  2617. in short sequence and then only used again after many other
  2618. instructions, it could be more efficient to assign the variable to a
  2619. register during the initial sequence and then move it to the stack for
  2620. the rest of its lifetime. We refer the interested reader to
  2621. \citet{Cooper:2011aa} for more information about that approach.
  2622. % discuss prioritizing variables based on how much they are used.
  2623. \section{Registers and Calling Conventions}
  2624. \label{sec:calling-conventions}
  2625. \index{calling conventions}
  2626. As we perform register allocation, we need to be aware of the
  2627. \emph{calling conventions} \index{calling conventions} that govern how
  2628. functions calls are performed in x86.
  2629. %
  2630. Even though \LangVar{} does not include programmer-defined functions,
  2631. our generated code includes a \code{main} function that is called by
  2632. the operating system and our generated code contains calls to the
  2633. \code{read\_int} function.
  2634. Function calls require coordination between two pieces of code that
  2635. may be written by different programmers or generated by different
  2636. compilers. Here we follow the System V calling conventions that are
  2637. used by the GNU C compiler on Linux and
  2638. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  2639. %
  2640. The calling conventions include rules about how functions share the
  2641. use of registers. In particular, the caller is responsible for freeing
  2642. up some registers prior to the function call for use by the callee.
  2643. These are called the \emph{caller-saved registers}
  2644. \index{caller-saved registers}
  2645. and they are
  2646. \begin{lstlisting}
  2647. rax rcx rdx rsi rdi r8 r9 r10 r11
  2648. \end{lstlisting}
  2649. On the other hand, the callee is responsible for preserving the values
  2650. of the \emph{callee-saved registers}, \index{callee-saved registers}
  2651. which are
  2652. \begin{lstlisting}
  2653. rsp rbp rbx r12 r13 r14 r15
  2654. \end{lstlisting}
  2655. We can think about this caller/callee convention from two points of
  2656. view, the caller view and the callee view:
  2657. \begin{itemize}
  2658. \item The caller should assume that all the caller-saved registers get
  2659. overwritten with arbitrary values by the callee. On the other hand,
  2660. the caller can safely assume that all the callee-saved registers
  2661. contain the same values after the call that they did before the
  2662. call.
  2663. \item The callee can freely use any of the caller-saved registers.
  2664. However, if the callee wants to use a callee-saved register, the
  2665. callee must arrange to put the original value back in the register
  2666. prior to returning to the caller. This can be accomplished by saving
  2667. the value to the stack in the prelude of the function and restoring
  2668. the value in the conclusion of the function.
  2669. \end{itemize}
  2670. In x86, registers are also used for passing arguments to a function
  2671. and for the return value. In particular, the first six arguments to a
  2672. function are passed in the following six registers, in this order.
  2673. \begin{lstlisting}
  2674. rdi rsi rdx rcx r8 r9
  2675. \end{lstlisting}
  2676. If there are more than six arguments, then the convention is to use
  2677. space on the frame of the caller for the rest of the
  2678. arguments. However, in Chapter~\ref{ch:Rfun} we arrange never to
  2679. need more than six arguments. For now, the only function we care about
  2680. is \code{read\_int} and it takes zero arguments.
  2681. %
  2682. The register \code{rax} is used for the return value of a function.
  2683. The next question is how these calling conventions impact register
  2684. allocation. Consider the \LangVar{} program in
  2685. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  2686. example from the caller point of view and then from the callee point
  2687. of view.
  2688. The program makes two calls to the \code{read} function. Also, the
  2689. variable \code{x} is in use during the second call to \code{read}, so
  2690. we need to make sure that the value in \code{x} does not get
  2691. accidentally wiped out by the call to \code{read}. One obvious
  2692. approach is to save all the values in caller-saved registers to the
  2693. stack prior to each function call, and restore them after each
  2694. call. That way, if the register allocator chooses to assign \code{x}
  2695. to a caller-saved register, its value will be preserved across the
  2696. call to \code{read}. However, saving and restoring to the stack is
  2697. relatively slow. If \code{x} is not used many times, it may be better
  2698. to assign \code{x} to a stack location in the first place. Or better
  2699. yet, if we can arrange for \code{x} to be placed in a callee-saved
  2700. register, then it won't need to be saved and restored during function
  2701. calls.
  2702. The approach that we recommend for variables that are in use during a
  2703. function call is to either assign them to callee-saved registers or to
  2704. spill them to the stack. On the other hand, for variables that are not
  2705. in use during a function call, we try the following alternatives in
  2706. order 1) look for an available caller-saved register (to leave room
  2707. for other variables in the callee-saved register), 2) look for a
  2708. callee-saved register, and 3) spill the variable to the stack.
  2709. It is straightforward to implement this approach in a graph coloring
  2710. register allocator. First, we know which variables are in use during
  2711. every function call because we compute that information for every
  2712. instruction (Section~\ref{sec:liveness-analysis-Rvar}). Second, when we
  2713. build the interference graph (Section~\ref{sec:build-interference}),
  2714. we can place an edge between each of these variables and the
  2715. caller-saved registers in the interference graph. This will prevent
  2716. the graph coloring algorithm from assigning those variables to
  2717. caller-saved registers.
  2718. Returning to the example in
  2719. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  2720. generated x86 code on the right-hand side, focusing on the
  2721. \code{start} block. Notice that variable \code{x} is assigned to
  2722. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  2723. place during the second call to \code{read\_int}. Next, notice that
  2724. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  2725. because there are no function calls in the remainder of the block.
  2726. Next we analyze the example from the callee point of view, focusing on
  2727. the prelude and conclusion of the \code{main} function. As usual the
  2728. prelude begins with saving the \code{rbp} register to the stack and
  2729. setting the \code{rbp} to the current stack pointer. We now know why
  2730. it is necessary to save the \code{rbp}: it is a callee-saved register.
  2731. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  2732. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  2733. (\code{x}). The other callee-saved registers are not saved in the
  2734. prelude because they are not used. The prelude subtracts 8 bytes from
  2735. the \code{rsp} to make it 16-byte aligned and then jumps to the
  2736. \code{start} block. Shifting attention to the \code{conclusion}, we
  2737. see that \code{rbx} is restored from the stack with a \code{popq}
  2738. instruction. \index{prelude}\index{conclusion}
  2739. \begin{figure}[tp]
  2740. \begin{minipage}{0.45\textwidth}
  2741. Example \LangVar{} program:
  2742. %var_test_14.rkt
  2743. \begin{lstlisting}
  2744. (let ([x (read)])
  2745. (let ([y (read)])
  2746. (+ (+ x y) 42)))
  2747. \end{lstlisting}
  2748. \end{minipage}
  2749. \begin{minipage}{0.45\textwidth}
  2750. Generated x86 assembly:
  2751. \begin{lstlisting}
  2752. start:
  2753. callq read_int
  2754. movq %rax, %rbx
  2755. callq read_int
  2756. movq %rax, %rcx
  2757. addq %rcx, %rbx
  2758. movq %rbx, %rax
  2759. addq $42, %rax
  2760. jmp _conclusion
  2761. .globl main
  2762. main:
  2763. pushq %rbp
  2764. movq %rsp, %rbp
  2765. pushq %rbx
  2766. subq $8, %rsp
  2767. jmp start
  2768. conclusion:
  2769. addq $8, %rsp
  2770. popq %rbx
  2771. popq %rbp
  2772. retq
  2773. \end{lstlisting}
  2774. \end{minipage}
  2775. \caption{An example with function calls.}
  2776. \label{fig:example-calling-conventions}
  2777. \end{figure}
  2778. \clearpage
  2779. \section{Liveness Analysis}
  2780. \label{sec:liveness-analysis-Rvar}
  2781. \index{liveness analysis}
  2782. The \code{uncover-live} pass performs \emph{liveness analysis}, that
  2783. is, it discovers which variables are in-use in different regions of a
  2784. program.
  2785. %
  2786. A variable or register is \emph{live} at a program point if its
  2787. current value is used at some later point in the program. We
  2788. refer to variables and registers collectively as \emph{locations}.
  2789. %
  2790. Consider the following code fragment in which there are two writes to
  2791. \code{b}. Are \code{a} and \code{b} both live at the same time?
  2792. \begin{center}
  2793. \begin{minipage}{0.96\textwidth}
  2794. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2795. movq $5, a
  2796. movq $30, b
  2797. movq a, c
  2798. movq $10, b
  2799. addq b, c
  2800. \end{lstlisting}
  2801. \end{minipage}
  2802. \end{center}
  2803. The answer is no because \code{a} is live from line 1 to 3 and
  2804. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  2805. line 2 is never used because it is overwritten (line 4) before the
  2806. next read (line 5).
  2807. \begin{wrapfigure}[19]{l}[1.0in]{0.6\textwidth}
  2808. \small
  2809. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  2810. A \emph{set} is an unordered collection of elements without duplicates.
  2811. \index{set}
  2812. \begin{description}
  2813. \item[$\LP\code{set}\,v\,\ldots\RP$] constructs a set containing the specified elements.
  2814. \item[$\LP\code{set-union}\,set_1\,set_2\RP$] returns the union of the two sets.
  2815. \item[$\LP\code{set-subtract}\,set_1\,set_2\RP$] returns the difference of the two sets.
  2816. \item[$\LP\code{set-member?}\,set\,v\RP$] is element $v$ in $set$?
  2817. \item[$\LP\code{set-count}\,set\RP$] how many unique elements are in $set$?
  2818. \item[$\LP\code{set->list}\,set\RP$] converts the set to a list.
  2819. \end{description}
  2820. \end{tcolorbox}
  2821. \end{wrapfigure}
  2822. The live locations can be computed by traversing the instruction
  2823. sequence back to front (i.e., backwards in execution order). Let
  2824. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2825. $L_{\mathsf{after}}(k)$ for the set of live locations after
  2826. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2827. locations before instruction $I_k$. The live locations after an
  2828. instruction are always the same as the live locations before the next
  2829. instruction. \index{live-after} \index{live-before}
  2830. \begin{equation} \label{eq:live-after-before-next}
  2831. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2832. \end{equation}
  2833. To start things off, there are no live locations after the last
  2834. instruction, so
  2835. \begin{equation}\label{eq:live-last-empty}
  2836. L_{\mathsf{after}}(n) = \emptyset
  2837. \end{equation}
  2838. We then apply the following rule repeatedly, traversing the
  2839. instruction sequence back to front.
  2840. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2841. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2842. \end{equation}
  2843. where $W(k)$ are the locations written to by instruction $I_k$ and
  2844. $R(k)$ are the locations read by instruction $I_k$.
  2845. There is a special case for \code{jmp} instructions. The locations
  2846. that are live before a \code{jmp} should be the locations in
  2847. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  2848. maintaining an alist named \code{label->live} that maps each label to
  2849. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  2850. now the only \code{jmp} in a \LangXVar{} program is the one at the
  2851. end, to the conclusion. (For example, see Figure~\ref{fig:reg-eg}.)
  2852. The conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should
  2853. map \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  2854. Let us walk through the above example, applying these formulas
  2855. starting with the instruction on line 5. We collect the answers in
  2856. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  2857. \code{addq b, c} instruction is $\emptyset$ because it is the last
  2858. instruction (formula~\ref{eq:live-last-empty}). The
  2859. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  2860. because it reads from variables \code{b} and \code{c}
  2861. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  2862. \[
  2863. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  2864. \]
  2865. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2866. the live-before set from line 5 to be the live-after set for this
  2867. instruction (formula~\ref{eq:live-after-before-next}).
  2868. \[
  2869. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  2870. \]
  2871. This move instruction writes to \code{b} and does not read from any
  2872. variables, so we have the following live-before set
  2873. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2874. \[
  2875. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  2876. \]
  2877. The live-before for instruction \code{movq a, c}
  2878. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  2879. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2880. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  2881. variable that is not live and does not read from a variable.
  2882. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2883. because it writes to variable \code{a}.
  2884. \begin{figure}[tbp]
  2885. \begin{minipage}{0.45\textwidth}
  2886. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2887. movq $5, a
  2888. movq $30, b
  2889. movq a, c
  2890. movq $10, b
  2891. addq b, c
  2892. \end{lstlisting}
  2893. \end{minipage}
  2894. \vrule\hspace{10pt}
  2895. \begin{minipage}{0.45\textwidth}
  2896. \begin{align*}
  2897. L_{\mathsf{before}}(1)= \emptyset,
  2898. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  2899. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  2900. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  2901. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  2902. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  2903. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  2904. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  2905. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  2906. L_{\mathsf{after}}(5)= \emptyset
  2907. \end{align*}
  2908. \end{minipage}
  2909. \caption{Example output of liveness analysis on a short example.}
  2910. \label{fig:liveness-example-0}
  2911. \end{figure}
  2912. \begin{exercise}\normalfont
  2913. Perform liveness analysis on the running example in
  2914. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  2915. sets for each instruction. Compare your answers to the solution
  2916. shown in Figure~\ref{fig:live-eg}.
  2917. \end{exercise}
  2918. \begin{figure}[tp]
  2919. \hspace{20pt}
  2920. \begin{minipage}{0.45\textwidth}
  2921. \begin{lstlisting}
  2922. |$\{\ttm{rsp}\}$|
  2923. movq $1, v
  2924. |$\{\ttm{v},\ttm{rsp}\}$|
  2925. movq $42, w
  2926. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  2927. movq v, x
  2928. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  2929. addq $7, x
  2930. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  2931. movq x, y
  2932. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  2933. movq x, z
  2934. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  2935. addq w, z
  2936. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  2937. movq y, t
  2938. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  2939. negq t
  2940. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  2941. movq z, %rax
  2942. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  2943. addq t, %rax
  2944. |$\{\ttm{rax},\ttm{rsp}\}$|
  2945. jmp conclusion
  2946. \end{lstlisting}
  2947. \end{minipage}
  2948. \caption{The running example annotated with live-after sets.}
  2949. \label{fig:live-eg}
  2950. \end{figure}
  2951. \begin{exercise}\normalfont
  2952. Implement the \code{uncover-live} pass. Store the sequence of
  2953. live-after sets in the $\itm{info}$ field of the \code{Block}
  2954. structure.
  2955. %
  2956. We recommend creating an auxiliary function that takes a list of
  2957. instructions and an initial live-after set (typically empty) and
  2958. returns the list of live-after sets.
  2959. %
  2960. We also recommend creating auxiliary functions to 1) compute the set
  2961. of locations that appear in an \Arg{}, 2) compute the locations read
  2962. by an instruction (the $R$ function), and 3) the locations written by
  2963. an instruction (the $W$ function). The \code{callq} instruction should
  2964. include all of the caller-saved registers in its write-set $W$ because
  2965. the calling convention says that those registers may be written to
  2966. during the function call. Likewise, the \code{callq} instruction
  2967. should include the appropriate argument-passing registers in its
  2968. read-set $R$, depending on the arity of the function being
  2969. called. (This is why the abstract syntax for \code{callq} includes the
  2970. arity.)
  2971. \end{exercise}
  2972. \clearpage
  2973. \section{Build the Interference Graph}
  2974. \label{sec:build-interference}
  2975. \begin{wrapfigure}[25]{r}[1.0in]{0.6\textwidth}
  2976. \small
  2977. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  2978. A \emph{graph} is a collection of vertices and edges where each
  2979. edge connects two vertices. A graph is \emph{directed} if each
  2980. edge points from a source to a target. Otherwise the graph is
  2981. \emph{undirected}.
  2982. \index{graph}\index{directed graph}\index{undirected graph}
  2983. \begin{description}
  2984. %% We currently don't use directed graphs. We instead use
  2985. %% directed multi-graphs. -Jeremy
  2986. %% \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  2987. %% directed graph from a list of edges. Each edge is a list
  2988. %% containing the source and target vertex.
  2989. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  2990. undirected graph from a list of edges. Each edge is represented by
  2991. a list containing two vertices.
  2992. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  2993. inserts a vertex into the graph.
  2994. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  2995. inserts an edge between the two vertices into the graph.
  2996. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  2997. returns a sequence of all the neighbors of the given vertex.
  2998. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  2999. returns a sequence of all the vertices in the graph.
  3000. \end{description}
  3001. \end{tcolorbox}
  3002. \end{wrapfigure}
  3003. Based on the liveness analysis, we know where each location is live.
  3004. However, during register allocation, we need to answer questions of
  3005. the specific form: are locations $u$ and $v$ live at the same time?
  3006. (And therefore cannot be assigned to the same register.) To make this
  3007. question more efficient to answer, we create an explicit data
  3008. structure, an \emph{interference graph}\index{interference graph}. An
  3009. interference graph is an undirected graph that has an edge between two
  3010. locations if they are live at the same time, that is, if they
  3011. interfere with each other.
  3012. An obvious way to compute the interference graph is to look at the set
  3013. of live locations between each instruction and the next and add an edge to the graph
  3014. for every pair of variables in the same set. This approach is less
  3015. than ideal for two reasons. First, it can be expensive because it
  3016. takes $O(n^2)$ time to consider at every pair in a set of $n$ live
  3017. locations. Second, in the special case where two locations hold the
  3018. same value (because one was assigned to the other), they can be live
  3019. at the same time without interfering with each other.
  3020. A better way to compute the interference graph is to focus on
  3021. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  3022. must not overwrite something in a live location. So for each
  3023. instruction, we create an edge between the locations being written to
  3024. and the live locations. (Except that one should not create self
  3025. edges.) Note that for the \key{callq} instruction, we consider all of
  3026. the caller-saved registers as being written to, so an edge is added
  3027. between every live variable and every caller-saved register. For
  3028. \key{movq}, we deal with the above-mentioned special case by not
  3029. adding an edge between a live variable $v$ and the destination if $v$
  3030. matches the source. So we have the following two rules.
  3031. \begin{enumerate}
  3032. \item If instruction $I_k$ is a move such as \key{movq} $s$\key{,}
  3033. $d$, then add the edge $(d,v)$ for every $v \in
  3034. L_{\mathsf{after}}(k)$ unless $v = d$ or $v = s$.
  3035. \item For any other instruction $I_k$, for every $d \in W(k)$
  3036. add an edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  3037. %% \item If instruction $I_k$ is an arithmetic instruction such as
  3038. %% \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  3039. %% L_{\mathsf{after}}(k)$ unless $v = d$.
  3040. %% \item If instruction $I_k$ is of the form \key{callq}
  3041. %% $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  3042. %% register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  3043. \end{enumerate}
  3044. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  3045. the above rules to each instruction. We highlight a few of the
  3046. instructions. The first instruction is \lstinline{movq $1, v} and the
  3047. live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies, so \code{v}
  3048. interferes with \code{rsp}.
  3049. %
  3050. The fourth instruction is \lstinline{addq $7, x} and the live-after
  3051. set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so $\ttm{x}$
  3052. interferes with \ttm{w} and \ttm{rsp}.
  3053. %
  3054. The next instruction is \lstinline{movq x, y} and the live-after set
  3055. is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1 applies, so \ttm{y}
  3056. interferes with \ttm{w} and \ttm{rsp} but not \ttm{x} because \ttm{x}
  3057. is the source of the move and therefore \ttm{x} and \ttm{y} hold the
  3058. same value. Figure~\ref{fig:interference-results} lists the
  3059. interference results for all of the instructions and the resulting
  3060. interference graph is shown in Figure~\ref{fig:interfere}.
  3061. \begin{figure}[tbp]
  3062. \begin{quote}
  3063. \begin{tabular}{ll}
  3064. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  3065. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  3066. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  3067. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  3068. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  3069. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  3070. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  3071. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  3072. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  3073. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  3074. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  3075. \lstinline!jmp conclusion!& no interference.
  3076. \end{tabular}
  3077. \end{quote}
  3078. \caption{Interference results for the running example.}
  3079. \label{fig:interference-results}
  3080. \end{figure}
  3081. \begin{figure}[tbp]
  3082. \large
  3083. \[
  3084. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3085. \node (rax) at (0,0) {$\ttm{rax}$};
  3086. \node (rsp) at (9,2) {$\ttm{rsp}$};
  3087. \node (t1) at (0,2) {$\ttm{t}$};
  3088. \node (z) at (3,2) {$\ttm{z}$};
  3089. \node (x) at (6,2) {$\ttm{x}$};
  3090. \node (y) at (3,0) {$\ttm{y}$};
  3091. \node (w) at (6,0) {$\ttm{w}$};
  3092. \node (v) at (9,0) {$\ttm{v}$};
  3093. \draw (t1) to (rax);
  3094. \draw (t1) to (z);
  3095. \draw (z) to (y);
  3096. \draw (z) to (w);
  3097. \draw (x) to (w);
  3098. \draw (y) to (w);
  3099. \draw (v) to (w);
  3100. \draw (v) to (rsp);
  3101. \draw (w) to (rsp);
  3102. \draw (x) to (rsp);
  3103. \draw (y) to (rsp);
  3104. \path[-.,bend left=15] (z) edge node {} (rsp);
  3105. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3106. \draw (rax) to (rsp);
  3107. \end{tikzpicture}
  3108. \]
  3109. \caption{The interference graph of the example program.}
  3110. \label{fig:interfere}
  3111. \end{figure}
  3112. %% Our next concern is to choose a data structure for representing the
  3113. %% interference graph. There are many choices for how to represent a
  3114. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  3115. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  3116. %% data structure is to study the algorithm that uses the data structure,
  3117. %% determine what operations need to be performed, and then choose the
  3118. %% data structure that provide the most efficient implementations of
  3119. %% those operations. Often times the choice of data structure can have an
  3120. %% effect on the time complexity of the algorithm, as it does here. If
  3121. %% you skim the next section, you will see that the register allocation
  3122. %% algorithm needs to ask the graph for all of its vertices and, given a
  3123. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  3124. %% correct choice of graph representation is that of an adjacency
  3125. %% list. There are helper functions in \code{utilities.rkt} for
  3126. %% representing graphs using the adjacency list representation:
  3127. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  3128. %% (Appendix~\ref{appendix:utilities}).
  3129. %% %
  3130. %% \margincomment{\footnotesize To do: change to use the
  3131. %% Racket graph library. \\ --Jeremy}
  3132. %% %
  3133. %% In particular, those functions use a hash table to map each vertex to
  3134. %% the set of adjacent vertices, and the sets are represented using
  3135. %% Racket's \key{set}, which is also a hash table.
  3136. \begin{exercise}\normalfont
  3137. Implement the compiler pass named \code{build-interference} according
  3138. to the algorithm suggested above. We recommend using the \code{graph}
  3139. package to create and inspect the interference graph. The output
  3140. graph of this pass should be stored in the $\itm{info}$ field of the
  3141. program, under the key \code{conflicts}.
  3142. \end{exercise}
  3143. \section{Graph Coloring via Sudoku}
  3144. \label{sec:graph-coloring}
  3145. \index{graph coloring}
  3146. \index{Sudoku}
  3147. \index{color}
  3148. We come to the main event, mapping variables to registers and stack
  3149. locations. Variables that interfere with each other must be mapped to
  3150. different locations. In terms of the interference graph, this means
  3151. that adjacent vertices must be mapped to different locations. If we
  3152. think of locations as colors, the register allocation problem becomes
  3153. the graph coloring problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  3154. The reader may be more familiar with the graph coloring problem than he
  3155. or she realizes; the popular game of Sudoku is an instance of the
  3156. graph coloring problem. The following describes how to build a graph
  3157. out of an initial Sudoku board.
  3158. \begin{itemize}
  3159. \item There is one vertex in the graph for each Sudoku square.
  3160. \item There is an edge between two vertices if the corresponding squares
  3161. are in the same row, in the same column, or if the squares are in
  3162. the same $3\times 3$ region.
  3163. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  3164. \item Based on the initial assignment of numbers to squares in the
  3165. Sudoku board, assign the corresponding colors to the corresponding
  3166. vertices in the graph.
  3167. \end{itemize}
  3168. If you can color the remaining vertices in the graph with the nine
  3169. colors, then you have also solved the corresponding game of Sudoku.
  3170. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  3171. the corresponding graph with colored vertices. We map the Sudoku
  3172. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  3173. sampling of the vertices (the colored ones) because showing edges for
  3174. all of the vertices would make the graph unreadable.
  3175. \begin{figure}[tbp]
  3176. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  3177. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  3178. \caption{A Sudoku game board and the corresponding colored graph.}
  3179. \label{fig:sudoku-graph}
  3180. \end{figure}
  3181. It turns out that some techniques for playing Sudoku correspond to
  3182. heuristics used in graph coloring algorithms. For example, one of the
  3183. basic techniques for Sudoku is called Pencil Marks. The idea is to use
  3184. a process of elimination to determine what numbers are no longer
  3185. available for a square and write down those numbers in the square
  3186. (writing very small). For example, if the number $1$ is assigned to a
  3187. square, then write the pencil mark $1$ in all the squares in the same
  3188. row, column, and region.
  3189. %
  3190. The Pencil Marks technique corresponds to the notion of
  3191. \emph{saturation}\index{saturation} due to \cite{Brelaz:1979eu}. The
  3192. saturation of a vertex, in Sudoku terms, is the set of numbers that
  3193. are no longer available. In graph terminology, we have the following
  3194. definition:
  3195. \begin{equation*}
  3196. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  3197. \text{ and } \mathrm{color}(v) = c \}
  3198. \end{equation*}
  3199. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  3200. edge with $u$.
  3201. Using the Pencil Marks technique leads to a simple strategy for
  3202. filling in numbers: if there is a square with only one possible number
  3203. left, then choose that number! But what if there are no squares with
  3204. only one possibility left? One brute-force approach is to try them
  3205. all: choose the first one and if it ultimately leads to a solution,
  3206. great. If not, backtrack and choose the next possibility. One good
  3207. thing about Pencil Marks is that it reduces the degree of branching in
  3208. the search tree. Nevertheless, backtracking can be horribly time
  3209. consuming. One way to reduce the amount of backtracking is to use the
  3210. most-constrained-first heuristic. That is, when choosing a square,
  3211. always choose one with the fewest possibilities left (the vertex with
  3212. the highest saturation). The idea is that choosing highly constrained
  3213. squares earlier rather than later is better because later on there may
  3214. not be any possibilities left in the highly saturated squares.
  3215. However, register allocation is easier than Sudoku because the
  3216. register allocator can map variables to stack locations when the
  3217. registers run out. Thus, it makes sense to replace backtracking with
  3218. greedy search: make the best choice at the time and keep going. We
  3219. still wish to minimize the number of colors needed, so we use the
  3220. most-constrained-first heuristic in the greedy search.
  3221. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  3222. algorithm for register allocation based on saturation and the
  3223. most-constrained-first heuristic. It is roughly equivalent to the
  3224. DSATUR
  3225. algorithm~\citep{Brelaz:1979eu,Gebremedhin:1999fk,Omari:2006uq}. Just
  3226. as in Sudoku, the algorithm represents colors with integers. The
  3227. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  3228. for register allocation. The integers $k$ and larger correspond to
  3229. stack locations. The registers that are not used for register
  3230. allocation, such as \code{rax}, are assigned to negative integers. In
  3231. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  3232. %% One might wonder why we include registers at all in the liveness
  3233. %% analysis and interference graph. For example, we never allocate a
  3234. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  3235. %% leave them out. As we see in Chapter~\ref{ch:Rvec}, when we begin
  3236. %% to use register for passing arguments to functions, it will be
  3237. %% necessary for those registers to appear in the interference graph
  3238. %% because those registers will also be assigned to variables, and we
  3239. %% don't want those two uses to encroach on each other. Regarding
  3240. %% registers such as \code{rax} and \code{rsp} that are not used for
  3241. %% variables, we could omit them from the interference graph but that
  3242. %% would require adding special cases to our algorithm, which would
  3243. %% complicate the logic for little gain.
  3244. \begin{figure}[btp]
  3245. \centering
  3246. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  3247. Algorithm: DSATUR
  3248. Input: a graph |$G$|
  3249. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  3250. |$W \gets \mathrm{vertices}(G)$|
  3251. while |$W \neq \emptyset$| do
  3252. pick a vertex |$u$| from |$W$| with the highest saturation,
  3253. breaking ties randomly
  3254. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  3255. |$\mathrm{color}[u] \gets c$|
  3256. |$W \gets W - \{u\}$|
  3257. \end{lstlisting}
  3258. \caption{The saturation-based greedy graph coloring algorithm.}
  3259. \label{fig:satur-algo}
  3260. \end{figure}
  3261. With the DSATUR algorithm in hand, let us return to the running
  3262. example and consider how to color the interference graph in
  3263. Figure~\ref{fig:interfere}.
  3264. %
  3265. We start by assigning the register nodes to their own color. For
  3266. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  3267. assigned $-2$. The variables are not yet colored, so they are
  3268. annotated with a dash. We then update the saturation for vertices that
  3269. are adjacent to a register, obtaining the following annotated
  3270. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  3271. it interferes with both \code{rax} and \code{rsp}.
  3272. \[
  3273. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3274. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  3275. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  3276. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  3277. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  3278. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3279. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3280. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3281. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3282. \draw (t1) to (rax);
  3283. \draw (t1) to (z);
  3284. \draw (z) to (y);
  3285. \draw (z) to (w);
  3286. \draw (x) to (w);
  3287. \draw (y) to (w);
  3288. \draw (v) to (w);
  3289. \draw (v) to (rsp);
  3290. \draw (w) to (rsp);
  3291. \draw (x) to (rsp);
  3292. \draw (y) to (rsp);
  3293. \path[-.,bend left=15] (z) edge node {} (rsp);
  3294. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3295. \draw (rax) to (rsp);
  3296. \end{tikzpicture}
  3297. \]
  3298. The algorithm says to select a maximally saturated vertex. So we pick
  3299. $\ttm{t}$ and color it with the first available integer, which is
  3300. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  3301. and \ttm{rsp} because they interfere with $\ttm{t}$.
  3302. \[
  3303. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3304. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3305. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  3306. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  3307. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  3308. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3309. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3310. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3311. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3312. \draw (t1) to (rax);
  3313. \draw (t1) to (z);
  3314. \draw (z) to (y);
  3315. \draw (z) to (w);
  3316. \draw (x) to (w);
  3317. \draw (y) to (w);
  3318. \draw (v) to (w);
  3319. \draw (v) to (rsp);
  3320. \draw (w) to (rsp);
  3321. \draw (x) to (rsp);
  3322. \draw (y) to (rsp);
  3323. \path[-.,bend left=15] (z) edge node {} (rsp);
  3324. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3325. \draw (rax) to (rsp);
  3326. \end{tikzpicture}
  3327. \]
  3328. We repeat the process, selecting the next maximally saturated vertex,
  3329. which is \code{z}, and color it with the first available number, which
  3330. is $1$. We add $1$ to the saturation for the neighboring vertices
  3331. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  3332. \[
  3333. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3334. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3335. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3336. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3337. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3338. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3339. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3340. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3341. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3342. \draw (t1) to (rax);
  3343. \draw (t1) to (z);
  3344. \draw (z) to (y);
  3345. \draw (z) to (w);
  3346. \draw (x) to (w);
  3347. \draw (y) to (w);
  3348. \draw (v) to (w);
  3349. \draw (v) to (rsp);
  3350. \draw (w) to (rsp);
  3351. \draw (x) to (rsp);
  3352. \draw (y) to (rsp);
  3353. \path[-.,bend left=15] (z) edge node {} (rsp);
  3354. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3355. \draw (rax) to (rsp);
  3356. \end{tikzpicture}
  3357. \]
  3358. The most saturated vertices are now \code{w} and \code{y}. We color
  3359. \code{w} with the first available color, which is $0$.
  3360. \[
  3361. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3362. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3363. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3364. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3365. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3366. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3367. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  3368. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  3369. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  3370. \draw (t1) to (rax);
  3371. \draw (t1) to (z);
  3372. \draw (z) to (y);
  3373. \draw (z) to (w);
  3374. \draw (x) to (w);
  3375. \draw (y) to (w);
  3376. \draw (v) to (w);
  3377. \draw (v) to (rsp);
  3378. \draw (w) to (rsp);
  3379. \draw (x) to (rsp);
  3380. \draw (y) to (rsp);
  3381. \path[-.,bend left=15] (z) edge node {} (rsp);
  3382. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3383. \draw (rax) to (rsp);
  3384. \end{tikzpicture}
  3385. \]
  3386. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  3387. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  3388. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  3389. and \code{z}, whose colors are $0$ and $1$ respectively.
  3390. \[
  3391. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3392. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3393. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3394. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3395. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3396. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3397. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3398. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3399. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  3400. \draw (t1) to (rax);
  3401. \draw (t1) to (z);
  3402. \draw (z) to (y);
  3403. \draw (z) to (w);
  3404. \draw (x) to (w);
  3405. \draw (y) to (w);
  3406. \draw (v) to (w);
  3407. \draw (v) to (rsp);
  3408. \draw (w) to (rsp);
  3409. \draw (x) to (rsp);
  3410. \draw (y) to (rsp);
  3411. \path[-.,bend left=15] (z) edge node {} (rsp);
  3412. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3413. \draw (rax) to (rsp);
  3414. \end{tikzpicture}
  3415. \]
  3416. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  3417. \[
  3418. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3419. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3420. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3421. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3422. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3423. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3424. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3425. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3426. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3427. \draw (t1) to (rax);
  3428. \draw (t1) to (z);
  3429. \draw (z) to (y);
  3430. \draw (z) to (w);
  3431. \draw (x) to (w);
  3432. \draw (y) to (w);
  3433. \draw (v) to (w);
  3434. \draw (v) to (rsp);
  3435. \draw (w) to (rsp);
  3436. \draw (x) to (rsp);
  3437. \draw (y) to (rsp);
  3438. \path[-.,bend left=15] (z) edge node {} (rsp);
  3439. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3440. \draw (rax) to (rsp);
  3441. \end{tikzpicture}
  3442. \]
  3443. In the last step of the algorithm, we color \code{x} with $1$.
  3444. \[
  3445. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3446. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3447. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3448. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3449. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3450. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  3451. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3452. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3453. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3454. \draw (t1) to (rax);
  3455. \draw (t1) to (z);
  3456. \draw (z) to (y);
  3457. \draw (z) to (w);
  3458. \draw (x) to (w);
  3459. \draw (y) to (w);
  3460. \draw (v) to (w);
  3461. \draw (v) to (rsp);
  3462. \draw (w) to (rsp);
  3463. \draw (x) to (rsp);
  3464. \draw (y) to (rsp);
  3465. \path[-.,bend left=15] (z) edge node {} (rsp);
  3466. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3467. \draw (rax) to (rsp);
  3468. \end{tikzpicture}
  3469. \]
  3470. \begin{wrapfigure}[25]{r}[1.0in]{0.6\textwidth}
  3471. \small
  3472. \begin{tcolorbox}[title=Priority Queue]
  3473. A \emph{priority queue} is a collection of items in which the
  3474. removal of items is governed by priority. In a ``min'' queue,
  3475. lower priority items are removed first. An implementation is in
  3476. \code{priority\_queue.rkt} of the support code. \index{priority
  3477. queue} \index{minimum priority queue}
  3478. \begin{description}
  3479. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  3480. priority queue that uses the $\itm{cmp}$ predicate to determine
  3481. whether its first argument has lower or equal priority to its
  3482. second argument.
  3483. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  3484. items in the queue.
  3485. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  3486. the item into the queue and returns a handle for the item in the
  3487. queue.
  3488. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  3489. the lowest priority.
  3490. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  3491. notifies the queue that the priority has decreased for the item
  3492. associated with the given handle.
  3493. \end{description}
  3494. \end{tcolorbox}
  3495. \end{wrapfigure}
  3496. We recommend creating an auxiliary function named \code{color-graph}
  3497. that takes an interference graph and a list of all the variables in
  3498. the program. This function should return a mapping of variables to
  3499. their colors (represented as natural numbers). By creating this helper
  3500. function, you will be able to reuse it in Chapter~\ref{ch:Rfun}
  3501. when we add support for functions.
  3502. To prioritize the processing of highly saturated nodes inside the
  3503. \code{color-graph} function, we recommend using the priority queue
  3504. data structure (see the side bar on the right). In addition, you will
  3505. need to maintain a mapping from variables to their ``handles'' in the
  3506. priority queue so that you can notify the priority queue when their
  3507. saturation changes.
  3508. With the coloring complete, we finalize the assignment of variables to
  3509. registers and stack locations. We map the first $k$ colors to the $k$
  3510. registers and the rest of the colors to stack locations. Suppose for
  3511. the moment that we have just one register to use for register
  3512. allocation, \key{rcx}. Then we have the following map from colors to
  3513. locations.
  3514. \[
  3515. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  3516. \]
  3517. Composing this mapping with the coloring, we arrive at the following
  3518. assignment of variables to locations.
  3519. \begin{gather*}
  3520. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  3521. \ttm{w} \mapsto \key{\%rcx}, \,
  3522. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  3523. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  3524. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  3525. \ttm{t} \mapsto \key{\%rcx} \}
  3526. \end{gather*}
  3527. Adapt the code from the \code{assign-homes} pass
  3528. (Section~\ref{sec:assign-Rvar}) to replace the variables with their
  3529. assigned location. Applying the above assignment to our running
  3530. example, on the left, yields the program on the right.
  3531. % why frame size of 32? -JGS
  3532. \begin{center}
  3533. \begin{minipage}{0.3\textwidth}
  3534. \begin{lstlisting}
  3535. movq $1, v
  3536. movq $42, w
  3537. movq v, x
  3538. addq $7, x
  3539. movq x, y
  3540. movq x, z
  3541. addq w, z
  3542. movq y, t
  3543. negq t
  3544. movq z, %rax
  3545. addq t, %rax
  3546. jmp conclusion
  3547. \end{lstlisting}
  3548. \end{minipage}
  3549. $\Rightarrow\qquad$
  3550. \begin{minipage}{0.45\textwidth}
  3551. \begin{lstlisting}
  3552. movq $1, -8(%rbp)
  3553. movq $42, %rcx
  3554. movq -8(%rbp), -8(%rbp)
  3555. addq $7, -8(%rbp)
  3556. movq -8(%rbp), -16(%rbp)
  3557. movq -8(%rbp), -8(%rbp)
  3558. addq %rcx, -8(%rbp)
  3559. movq -16(%rbp), %rcx
  3560. negq %rcx
  3561. movq -8(%rbp), %rax
  3562. addq %rcx, %rax
  3563. jmp conclusion
  3564. \end{lstlisting}
  3565. \end{minipage}
  3566. \end{center}
  3567. \begin{exercise}\normalfont
  3568. %
  3569. Implement the compiler pass \code{allocate-registers}.
  3570. %
  3571. Create five programs that exercise all of the register allocation
  3572. algorithm, including spilling variables to the stack.
  3573. %
  3574. Replace \code{assign-homes} in the list of \code{passes} in the
  3575. \code{run-tests.rkt} script with the three new passes:
  3576. \code{uncover-live}, \code{build-interference}, and
  3577. \code{allocate-registers}.
  3578. %
  3579. Temporarily remove the \code{print-x86} pass from the list of passes
  3580. and the call to \code{compiler-tests}.
  3581. %
  3582. Run the script to test the register allocator.
  3583. \end{exercise}
  3584. \section{Patch Instructions}
  3585. \label{sec:patch-instructions}
  3586. The remaining step in the compilation to x86 is to ensure that the
  3587. instructions have at most one argument that is a memory access.
  3588. In the running example, the instruction \code{movq -8(\%rbp), -16(\%rbp)}
  3589. is problematic. The fix is to first move \code{-8(\%rbp)}
  3590. into \code{rax} and then move \code{rax} into \code{-16(\%rbp)}.
  3591. %
  3592. The two moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  3593. problematic, but they can be fixed by simply deleting them. In
  3594. general, we recommend deleting all the trivial moves whose source and
  3595. destination are the same location.
  3596. %
  3597. The following is the output of \code{patch-instructions} on the
  3598. running example.
  3599. \begin{center}
  3600. \begin{minipage}{0.4\textwidth}
  3601. \begin{lstlisting}
  3602. movq $1, -8(%rbp)
  3603. movq $42, %rcx
  3604. movq -8(%rbp), -8(%rbp)
  3605. addq $7, -8(%rbp)
  3606. movq -8(%rbp), -16(%rbp)
  3607. movq -8(%rbp), -8(%rbp)
  3608. addq %rcx, -8(%rbp)
  3609. movq -16(%rbp), %rcx
  3610. negq %rcx
  3611. movq -8(%rbp), %rax
  3612. addq %rcx, %rax
  3613. jmp conclusion
  3614. \end{lstlisting}
  3615. \end{minipage}
  3616. $\Rightarrow\qquad$
  3617. \begin{minipage}{0.45\textwidth}
  3618. \begin{lstlisting}
  3619. movq $1, -8(%rbp)
  3620. movq $42, %rcx
  3621. addq $7, -8(%rbp)
  3622. movq -8(%rbp), %rax
  3623. movq %rax, -16(%rbp)
  3624. addq %rcx, -8(%rbp)
  3625. movq -16(%rbp), %rcx
  3626. negq %rcx
  3627. movq -8(%rbp), %rax
  3628. addq %rcx, %rax
  3629. jmp conclusion
  3630. \end{lstlisting}
  3631. \end{minipage}
  3632. \end{center}
  3633. \begin{exercise}\normalfont
  3634. %
  3635. Implement the \code{patch-instructions} compiler pass.
  3636. %
  3637. Insert it after \code{allocate-registers} in the list of \code{passes}
  3638. in the \code{run-tests.rkt} script.
  3639. %
  3640. Run the script to test the \code{patch-instructions} pass.
  3641. \end{exercise}
  3642. \section{Print x86}
  3643. \label{sec:print-x86-reg-alloc}
  3644. \index{calling conventions}
  3645. \index{prelude}\index{conclusion}
  3646. Recall that the \code{print-x86} pass generates the prelude and
  3647. conclusion instructions to satisfy the x86 calling conventions
  3648. (Section~\ref{sec:calling-conventions}). With the addition of the
  3649. register allocator, the callee-saved registers used by the register
  3650. allocator must be saved in the prelude and restored in the conclusion.
  3651. In the \code{allocate-registers} pass, add an entry to the \itm{info}
  3652. of \code{X86Program} named \code{used-callee} that stores the set of
  3653. callee-saved registers that were assigned to variables. The
  3654. \code{print-x86} pass can then access this information to decide which
  3655. callee-saved registers need to be saved and restored.
  3656. %
  3657. When calculating the size of the frame to adjust the \code{rsp} in the
  3658. prelude, make sure to take into account the space used for saving the
  3659. callee-saved registers. Also, don't forget that the frame needs to be
  3660. a multiple of 16 bytes!
  3661. An overview of all of the passes involved in register allocation is
  3662. shown in Figure~\ref{fig:reg-alloc-passes}.
  3663. \begin{figure}[tbp]
  3664. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3665. \node (Rvar) at (0,2) {\large \LangVar{}};
  3666. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  3667. \node (Rvar-3) at (6,2) {\large \LangVar{}};
  3668. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  3669. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  3670. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  3671. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  3672. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  3673. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  3674. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  3675. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  3676. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvar-3);
  3677. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate-control} (Cvar-1);
  3678. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  3679. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  3680. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  3681. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  3682. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  3683. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  3684. \end{tikzpicture}
  3685. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  3686. \label{fig:reg-alloc-passes}
  3687. \end{figure}
  3688. \begin{exercise}\normalfont
  3689. Update the \code{print-x86} pass as described in this section.
  3690. %
  3691. In the \code{run-tests.rkt} script, reinstate \code{print-x86} in the
  3692. list of passes and the call to \code{compiler-tests}.
  3693. %
  3694. Run the script to test the complete compiler for \LangVar{} that
  3695. performs register allocation.
  3696. \end{exercise}
  3697. \section{Challenge: Move Biasing}
  3698. \label{sec:move-biasing}
  3699. \index{move biasing}
  3700. This section describes an enhancement to the register allocator for
  3701. students looking for an extra challenge or who have a deeper interest
  3702. in register allocation.
  3703. To motivate the need for move biasing we return to the running example
  3704. but this time use all of the general purpose registers. So we have
  3705. the following mapping of color numbers to registers.
  3706. \[
  3707. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi} \}
  3708. \]
  3709. Using the same assignment of variables to color numbers that was
  3710. produced by the register allocator described in the last section, we
  3711. get the following program.
  3712. \begin{center}
  3713. \begin{minipage}{0.3\textwidth}
  3714. \begin{lstlisting}
  3715. movq $1, v
  3716. movq $42, w
  3717. movq v, x
  3718. addq $7, x
  3719. movq x, y
  3720. movq x, z
  3721. addq w, z
  3722. movq y, t
  3723. negq t
  3724. movq z, %rax
  3725. addq t, %rax
  3726. jmp conclusion
  3727. \end{lstlisting}
  3728. \end{minipage}
  3729. $\Rightarrow\qquad$
  3730. \begin{minipage}{0.45\textwidth}
  3731. \begin{lstlisting}
  3732. movq $1, %rdx
  3733. movq $42, %rcx
  3734. movq %rdx, %rdx
  3735. addq $7, %rdx
  3736. movq %rdx, %rsi
  3737. movq %rdx, %rdx
  3738. addq %rcx, %rdx
  3739. movq %rsi, %rcx
  3740. negq %rcx
  3741. movq %rdx, %rax
  3742. addq %rcx, %rax
  3743. jmp conclusion
  3744. \end{lstlisting}
  3745. \end{minipage}
  3746. \end{center}
  3747. In the above output code there are two \key{movq} instructions that
  3748. can be removed because their source and target are the same. However,
  3749. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  3750. register, we could instead remove three \key{movq} instructions. We
  3751. can accomplish this by taking into account which variables appear in
  3752. \key{movq} instructions with which other variables.
  3753. We say that two variables $p$ and $q$ are \emph{move
  3754. related}\index{move related} if they participate together in a
  3755. \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  3756. \key{movq} $q$\key{,} $p$. When the register allocator chooses a color
  3757. for a variable, it should prefer a color that has already been used
  3758. for a move-related variable (assuming that they do not interfere). Of
  3759. course, this preference should not override the preference for
  3760. registers over stack locations. This preference should be used as a
  3761. tie breaker when choosing between registers or when choosing between
  3762. stack locations.
  3763. We recommend representing the move relationships in a graph, similar
  3764. to how we represented interference. The following is the \emph{move
  3765. graph} for our running example.
  3766. \[
  3767. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3768. \node (rax) at (0,0) {$\ttm{rax}$};
  3769. \node (rsp) at (9,2) {$\ttm{rsp}$};
  3770. \node (t) at (0,2) {$\ttm{t}$};
  3771. \node (z) at (3,2) {$\ttm{z}$};
  3772. \node (x) at (6,2) {$\ttm{x}$};
  3773. \node (y) at (3,0) {$\ttm{y}$};
  3774. \node (w) at (6,0) {$\ttm{w}$};
  3775. \node (v) at (9,0) {$\ttm{v}$};
  3776. \draw (v) to (x);
  3777. \draw (x) to (y);
  3778. \draw (x) to (z);
  3779. \draw (y) to (t);
  3780. \end{tikzpicture}
  3781. \]
  3782. Now we replay the graph coloring, pausing to see the coloring of
  3783. \code{y}. Recall the following configuration. The most saturated vertices
  3784. were \code{w} and \code{y}.
  3785. \[
  3786. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3787. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3788. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3789. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3790. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3791. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3792. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3793. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3794. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  3795. \draw (t1) to (rax);
  3796. \draw (t1) to (z);
  3797. \draw (z) to (y);
  3798. \draw (z) to (w);
  3799. \draw (x) to (w);
  3800. \draw (y) to (w);
  3801. \draw (v) to (w);
  3802. \draw (v) to (rsp);
  3803. \draw (w) to (rsp);
  3804. \draw (x) to (rsp);
  3805. \draw (y) to (rsp);
  3806. \path[-.,bend left=15] (z) edge node {} (rsp);
  3807. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3808. \draw (rax) to (rsp);
  3809. \end{tikzpicture}
  3810. \]
  3811. %
  3812. Last time we chose to color \code{w} with $0$. But this time we see
  3813. that \code{w} is not move related to any vertex, but \code{y} is move
  3814. related to \code{t}. So we choose to color \code{y} the same color as
  3815. \code{t}, $0$.
  3816. \[
  3817. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3818. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3819. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3820. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3821. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3822. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3823. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  3824. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  3825. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  3826. \draw (t1) to (rax);
  3827. \draw (t1) to (z);
  3828. \draw (z) to (y);
  3829. \draw (z) to (w);
  3830. \draw (x) to (w);
  3831. \draw (y) to (w);
  3832. \draw (v) to (w);
  3833. \draw (v) to (rsp);
  3834. \draw (w) to (rsp);
  3835. \draw (x) to (rsp);
  3836. \draw (y) to (rsp);
  3837. \path[-.,bend left=15] (z) edge node {} (rsp);
  3838. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3839. \draw (rax) to (rsp);
  3840. \end{tikzpicture}
  3841. \]
  3842. Now \code{w} is the most saturated, so we color it $2$.
  3843. \[
  3844. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3845. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3846. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3847. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3848. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3849. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  3850. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  3851. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  3852. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  3853. \draw (t1) to (rax);
  3854. \draw (t1) to (z);
  3855. \draw (z) to (y);
  3856. \draw (z) to (w);
  3857. \draw (x) to (w);
  3858. \draw (y) to (w);
  3859. \draw (v) to (w);
  3860. \draw (v) to (rsp);
  3861. \draw (w) to (rsp);
  3862. \draw (x) to (rsp);
  3863. \draw (y) to (rsp);
  3864. \path[-.,bend left=15] (z) edge node {} (rsp);
  3865. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3866. \draw (rax) to (rsp);
  3867. \end{tikzpicture}
  3868. \]
  3869. At this point, vertices \code{x} and \code{v} are most saturated, but
  3870. \code{x} is move related to \code{y} and \code{z}, so we color
  3871. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  3872. \[
  3873. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3874. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3875. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3876. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3877. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3878. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  3879. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  3880. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  3881. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  3882. \draw (t1) to (rax);
  3883. \draw (t) to (z);
  3884. \draw (z) to (y);
  3885. \draw (z) to (w);
  3886. \draw (x) to (w);
  3887. \draw (y) to (w);
  3888. \draw (v) to (w);
  3889. \draw (v) to (rsp);
  3890. \draw (w) to (rsp);
  3891. \draw (x) to (rsp);
  3892. \draw (y) to (rsp);
  3893. \path[-.,bend left=15] (z) edge node {} (rsp);
  3894. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3895. \draw (rax) to (rsp);
  3896. \end{tikzpicture}
  3897. \]
  3898. So we have the following assignment of variables to registers.
  3899. \begin{gather*}
  3900. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  3901. \ttm{w} \mapsto \key{\%rsi}, \,
  3902. \ttm{x} \mapsto \key{\%rcx}, \,
  3903. \ttm{y} \mapsto \key{\%rcx}, \,
  3904. \ttm{z} \mapsto \key{\%rdx}, \,
  3905. \ttm{t} \mapsto \key{\%rcx} \}
  3906. \end{gather*}
  3907. We apply this register assignment to the running example, on the left,
  3908. to obtain the code in the middle. The \code{patch-instructions} then
  3909. removes the three trivial moves to obtain the code on the right.
  3910. \begin{minipage}{0.25\textwidth}
  3911. \begin{lstlisting}
  3912. movq $1, v
  3913. movq $42, w
  3914. movq v, x
  3915. addq $7, x
  3916. movq x, y
  3917. movq x, z
  3918. addq w, z
  3919. movq y, t
  3920. negq t
  3921. movq z, %rax
  3922. addq t, %rax
  3923. jmp conclusion
  3924. \end{lstlisting}
  3925. \end{minipage}
  3926. $\Rightarrow\qquad$
  3927. \begin{minipage}{0.25\textwidth}
  3928. \begin{lstlisting}
  3929. movq $1, %rcx
  3930. movq $42, %rsi
  3931. movq %rcx, %rcx
  3932. addq $7, %rcx
  3933. movq %rcx, %rcx
  3934. movq %rcx, %rdx
  3935. addq %rsi, %rdx
  3936. movq %rcx, %rcx
  3937. negq %rcx
  3938. movq %rdx, %rax
  3939. addq %rcx, %rax
  3940. jmp conclusion
  3941. \end{lstlisting}
  3942. \end{minipage}
  3943. $\Rightarrow\qquad$
  3944. \begin{minipage}{0.25\textwidth}
  3945. \begin{lstlisting}
  3946. movq $1, %rcx
  3947. movq $42, %rsi
  3948. addq $7, %rcx
  3949. movq %rcx, %rdx
  3950. addq %rsi, %rdx
  3951. negq %rcx
  3952. movq %rdx, %rax
  3953. addq %rcx, %rax
  3954. jmp conclusion
  3955. \end{lstlisting}
  3956. \end{minipage}
  3957. \begin{exercise}\normalfont
  3958. Change your implementation of \code{allocate-registers} to take move
  3959. biasing into account. Create two new tests that include at least one
  3960. opportunity for move biasing and visually inspect the output x86
  3961. programs to make sure that your move biasing is working properly. Make
  3962. sure that your compiler still passes all of the tests.
  3963. \end{exercise}
  3964. \margincomment{\footnotesize To do: another neat challenge would be to do
  3965. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3966. %% \subsection{Output of the Running Example}
  3967. %% \label{sec:reg-alloc-output}
  3968. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  3969. the running example (Figure~\ref{fig:reg-eg}) with register allocation
  3970. and move biasing. To demonstrate both the use of registers and the
  3971. stack, we have limited the register allocator to use just two
  3972. registers: \code{rbx} and \code{rcx}. In the prelude\index{prelude}
  3973. of the \code{main} function, we push \code{rbx} onto the stack because
  3974. it is a callee-saved register and it was assigned to variable by the
  3975. register allocator. We subtract \code{8} from the \code{rsp} at the
  3976. end of the prelude to reserve space for the one spilled variable.
  3977. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  3978. Moving on the the \code{start} block, we see how the registers were
  3979. allocated. Variables \code{v}, \code{x}, and \code{y} were assigned to
  3980. \code{rbx} and variable \code{z} was assigned to \code{rcx}. Variable
  3981. \code{w} was spilled to the stack location \code{-16(\%rbp)}. Recall
  3982. that the prelude saved the callee-save register \code{rbx} onto the
  3983. stack. The spilled variables must be placed lower on the stack than
  3984. the saved callee-save registers, so in this case \code{w} is placed at
  3985. \code{-16(\%rbp)}.
  3986. In the \code{conclusion}\index{conclusion}, we undo the work that was
  3987. done in the prelude. We move the stack pointer up by \code{8} bytes
  3988. (the room for spilled variables), then we pop the old values of
  3989. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  3990. \code{retq} to return control to the operating system.
  3991. \begin{figure}[tbp]
  3992. % var_test_28.rkt
  3993. % (use-minimal-set-of-registers! #t)
  3994. % and only rbx rcx
  3995. % tmp 0 rbx
  3996. % z 1 rcx
  3997. % y 0 rbx
  3998. % w 2 16(%rbp)
  3999. % v 0 rbx
  4000. % x 0 rbx
  4001. \begin{lstlisting}
  4002. start:
  4003. movq $1, %rbx
  4004. movq $42, -16(%rbp)
  4005. addq $7, %rbx
  4006. movq %rbx, %rcx
  4007. addq -16(%rbp), %rcx
  4008. negq %rbx
  4009. movq %rcx, %rax
  4010. addq %rbx, %rax
  4011. jmp conclusion
  4012. .globl main
  4013. main:
  4014. pushq %rbp
  4015. movq %rsp, %rbp
  4016. pushq %rbx
  4017. subq $8, %rsp
  4018. jmp start
  4019. conclusion:
  4020. addq $8, %rsp
  4021. popq %rbx
  4022. popq %rbp
  4023. retq
  4024. \end{lstlisting}
  4025. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  4026. \label{fig:running-example-x86}
  4027. \end{figure}
  4028. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4029. \chapter{Booleans and Control Flow}
  4030. \label{ch:Rif}
  4031. \index{Boolean}
  4032. \index{control flow}
  4033. \index{conditional expression}
  4034. The \LangInt{} and \LangVar{} languages only have a single kind of
  4035. value, integers. In this chapter we add a second kind of value, the
  4036. Booleans, to create the \LangIf{} language. The Boolean values
  4037. \emph{true} and \emph{false} are written \key{\#t} and \key{\#f}
  4038. respectively in Racket. The \LangIf{} language includes several
  4039. operations that involve Booleans (\key{and}, \key{not}, \key{eq?},
  4040. \key{<}, etc.) and the conditional \key{if} expression. With the
  4041. addition of \key{if}, programs can have non-trivial control flow which
  4042. impacts \code{explicate-control} and liveness analysis. Also, because
  4043. we now have two kinds of values, we need to handle programs that apply
  4044. an operation to the wrong kind of value, such as \code{(not 1)}.
  4045. There are two language design options for such situations. One option
  4046. is to signal an error and the other is to provide a wider
  4047. interpretation of the operation. The Racket language uses a mixture of
  4048. these two options, depending on the operation and the kind of
  4049. value. For example, the result of \code{(not 1)} in Racket is
  4050. \code{\#f} because Racket treats non-zero integers as if they were
  4051. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  4052. error in Racket because \code{car} expects a pair.
  4053. Typed Racket makes similar design choices as Racket, except much of
  4054. the error detection happens at compile time instead of run time. Typed
  4055. Racket accepts and runs \code{(not 1)}, producing \code{\#f}. But in
  4056. the case of \code{(car 1)}, Typed Racket reports a compile-time error
  4057. because Typed Racket expects the type of the argument to be of the
  4058. form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  4059. The \LangIf{} language performs type checking during compilation like
  4060. Typed Racket. In Chapter~\ref{ch:type-dynamic} we study the
  4061. alternative choice, that is, a dynamically typed language like Racket.
  4062. The \LangIf{} language is a subset of Typed Racket; for some
  4063. operations we are more restrictive, for example, rejecting
  4064. \code{(not 1)}.
  4065. This chapter is organized as follows. We begin by defining the syntax
  4066. and interpreter for the \LangIf{} language
  4067. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  4068. checking and build a type checker for \LangIf{}
  4069. (Section~\ref{sec:type-check-Rif}). To compile \LangIf{} we need to
  4070. enlarge the intermediate language \LangCVar{} into \LangCIf{}
  4071. (Section~\ref{sec:Cif}) and \LangXInt{} into \LangXIf{}
  4072. (Section~\ref{sec:x86-if}). The remaining sections of this chapter
  4073. discuss how our compiler passes change to accommodate Booleans and
  4074. conditional control flow. There is one new pass, named \code{shrink},
  4075. that translates some operators into others, thereby reducing the
  4076. number of operators that need to be handled in later passes. The
  4077. largest changes occur in \code{explicate-control}, to translate
  4078. \code{if} expressions into control-flow graphs
  4079. (Section~\ref{sec:explicate-control-Rif}). Regarding register
  4080. allocation, the liveness analysis now has multiple basic blocks to
  4081. process and there is the interesting question of how to handle
  4082. conditional jumps.
  4083. \section{The \LangIf{} Language}
  4084. \label{sec:lang-if}
  4085. The concrete syntax of the \LangIf{} language is defined in
  4086. Figure~\ref{fig:Rif-concrete-syntax} and the abstract syntax is defined
  4087. in Figure~\ref{fig:Rif-syntax}. The \LangIf{} language includes all of
  4088. \LangVar{} (shown in gray), the Boolean literals \code{\#t} and
  4089. \code{\#f}, and the conditional \code{if} expression. We expand the
  4090. operators to include
  4091. \begin{enumerate}
  4092. \item subtraction on integers,
  4093. \item the logical operators \key{and}, \key{or} and \key{not},
  4094. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  4095. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  4096. comparing integers.
  4097. \end{enumerate}
  4098. We reorganize the abstract syntax for the primitive operations in
  4099. Figure~\ref{fig:Rif-syntax}, using only one grammar rule for all of
  4100. them. This means that the grammar no longer checks whether the arity
  4101. of an operators matches the number of arguments. That responsibility
  4102. is moved to the type checker for \LangIf{}, which we introduce in
  4103. Section~\ref{sec:type-check-Rif}.
  4104. \begin{figure}[tp]
  4105. \centering
  4106. \fbox{
  4107. \begin{minipage}{0.96\textwidth}
  4108. \[
  4109. \begin{array}{lcl}
  4110. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  4111. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  4112. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} } \mid \CSUB{\Exp}{\Exp} \\
  4113. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} } \\
  4114. &\mid& \itm{bool}
  4115. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  4116. \mid (\key{not}\;\Exp) \\
  4117. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} \\
  4118. \LangIf{} &::=& \Exp
  4119. \end{array}
  4120. \]
  4121. \end{minipage}
  4122. }
  4123. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  4124. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  4125. \label{fig:Rif-concrete-syntax}
  4126. \end{figure}
  4127. \begin{figure}[tp]
  4128. \centering
  4129. \fbox{
  4130. \begin{minipage}{0.96\textwidth}
  4131. \[
  4132. \begin{array}{lcl}
  4133. \itm{bool} &::=& \code{\#t} \mid \code{\#f} \\
  4134. \itm{cmp} &::= & \code{eq?} \mid \code{<} \mid \code{<=} \mid \code{>} \mid \code{>=} \\
  4135. \itm{op} &::= & \itm{cmp} \mid \code{read} \mid \code{+} \mid \code{-}
  4136. \mid \code{and} \mid \code{or} \mid \code{not} \\
  4137. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  4138. &\mid& \PRIM{\itm{op}}{\Exp\ldots}\\
  4139. &\mid& \BOOL{\itm{bool}} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4140. \LangIf{} &::=& \PROGRAM{\code{'()}}{\Exp}
  4141. \end{array}
  4142. \]
  4143. \end{minipage}
  4144. }
  4145. \caption{The abstract syntax of \LangIf{}.}
  4146. \label{fig:Rif-syntax}
  4147. \end{figure}
  4148. Figure~\ref{fig:interp-Rif} defines the interpreter for \LangIf{},
  4149. which inherits from the interpreter for \LangVar{}
  4150. (Figure~\ref{fig:interp-Rvar}). The literals \code{\#t} and \code{\#f}
  4151. evaluate to the corresponding Boolean values. The conditional
  4152. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  4153. \itm{cnd} and then either evaluates \itm{thn} or \itm{els} depending
  4154. on whether \itm{cnd} produced \code{\#t} or \code{\#f}. The logical
  4155. operations \code{not} and \code{and} behave as you might expect, but
  4156. note that the \code{and} operation is short-circuiting. That is, given
  4157. the expression $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not
  4158. evaluated if $e_1$ evaluates to \code{\#f}.
  4159. With the increase in the number of primitive operations, the
  4160. interpreter would become repetitive without some care. We refactor
  4161. the case for \code{Prim}, moving the code that differs with each
  4162. operation into the \code{interp-op} method shown in in
  4163. Figure~\ref{fig:interp-op-Rif}. We handle the \code{and} operation
  4164. separately because of its short-circuiting behavior.
  4165. \begin{figure}[tbp]
  4166. \begin{lstlisting}
  4167. (define interp-Rif-class
  4168. (class interp-Rvar-class
  4169. (super-new)
  4170. (define/public (interp-op op) ...)
  4171. (define/override ((interp-exp env) e)
  4172. (define recur (interp-exp env))
  4173. (match e
  4174. [(Bool b) b]
  4175. [(If cnd thn els)
  4176. (match (recur cnd)
  4177. [#t (recur thn)]
  4178. [#f (recur els)])]
  4179. [(Prim 'and (list e1 e2))
  4180. (match (recur e1)
  4181. [#t (match (recur e2) [#t #t] [#f #f])]
  4182. [#f #f])]
  4183. [(Prim op args)
  4184. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  4185. [else ((super interp-exp env) e)]))
  4186. ))
  4187. (define (interp-Rif p)
  4188. (send (new interp-Rif-class) interp-program p))
  4189. \end{lstlisting}
  4190. \caption{Interpreter for the \LangIf{} language. (See
  4191. Figure~\ref{fig:interp-op-Rif} for \code{interp-op}.)}
  4192. \label{fig:interp-Rif}
  4193. \end{figure}
  4194. \begin{figure}[tbp]
  4195. \begin{lstlisting}
  4196. (define/public (interp-op op)
  4197. (match op
  4198. ['+ fx+]
  4199. ['- fx-]
  4200. ['read read-fixnum]
  4201. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  4202. ['or (lambda (v1 v2)
  4203. (cond [(and (boolean? v1) (boolean? v2))
  4204. (or v1 v2)]))]
  4205. ['eq? (lambda (v1 v2)
  4206. (cond [(or (and (fixnum? v1) (fixnum? v2))
  4207. (and (boolean? v1) (boolean? v2))
  4208. (and (vector? v1) (vector? v2)))
  4209. (eq? v1 v2)]))]
  4210. ['< (lambda (v1 v2)
  4211. (cond [(and (fixnum? v1) (fixnum? v2))
  4212. (< v1 v2)]))]
  4213. ['<= (lambda (v1 v2)
  4214. (cond [(and (fixnum? v1) (fixnum? v2))
  4215. (<= v1 v2)]))]
  4216. ['> (lambda (v1 v2)
  4217. (cond [(and (fixnum? v1) (fixnum? v2))
  4218. (> v1 v2)]))]
  4219. ['>= (lambda (v1 v2)
  4220. (cond [(and (fixnum? v1) (fixnum? v2))
  4221. (>= v1 v2)]))]
  4222. [else (error 'interp-op "unknown operator")]))
  4223. \end{lstlisting}
  4224. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  4225. \label{fig:interp-op-Rif}
  4226. \end{figure}
  4227. \section{Type Checking \LangIf{} Programs}
  4228. \label{sec:type-check-Rif}
  4229. \index{type checking}
  4230. \index{semantic analysis}
  4231. It is helpful to think about type checking in two complementary
  4232. ways. A type checker predicts the type of value that will be produced
  4233. by each expression in the program. For \LangIf{}, we have just two types,
  4234. \key{Integer} and \key{Boolean}. So a type checker should predict that
  4235. \begin{lstlisting}
  4236. (+ 10 (- (+ 12 20)))
  4237. \end{lstlisting}
  4238. produces an \key{Integer} while
  4239. \begin{lstlisting}
  4240. (and (not #f) #t)
  4241. \end{lstlisting}
  4242. produces a \key{Boolean}.
  4243. Another way to think about type checking is that it enforces a set of
  4244. rules about which operators can be applied to which kinds of
  4245. values. For example, our type checker for \LangIf{} signals an error
  4246. for the below expression
  4247. \begin{lstlisting}
  4248. (not (+ 10 (- (+ 12 20))))
  4249. \end{lstlisting}
  4250. The subexpression \code{(+ 10 (- (+ 12 20)))} has type \key{Integer}
  4251. but the type checker enforces the rule that the argument of \code{not}
  4252. must be a \key{Boolean}.
  4253. We implement type checking using classes and methods because they
  4254. provide the open recursion needed to reuse code as we extend the type
  4255. checker in later chapters, analogous to the use of classes and methods
  4256. for the interpreters (Section~\ref{sec:extensible-interp}).
  4257. We separate the type checker for the \LangVar{} fragment into its own
  4258. class, shown in Figure~\ref{fig:type-check-Rvar}. The type checker for
  4259. \LangIf{} is shown in Figure~\ref{fig:type-check-Rif} and it inherits
  4260. from the type checker for \LangVar{}. These type checkers are in the
  4261. files \code{type-check-Rvar.rkt} and \code{type-check-Rif.rkt} of the
  4262. support code.
  4263. %
  4264. Each type checker is a structurally recursive function over the AST.
  4265. Given an input expression \code{e}, the type checker either signals an
  4266. error or returns an expression and its type (\key{Integer} or
  4267. \key{Boolean}). It returns an expression because there are situations
  4268. in which we want to change or update the expression.
  4269. Next we discuss the \code{match} cases in \code{type-check-exp} of
  4270. Figure~\ref{fig:type-check-Rvar}. The type of an integer constant is
  4271. \code{Integer}. To handle variables, the type checker uses the
  4272. environment \code{env} to map variables to types. Consider the case
  4273. for \key{let}. We type check the initializing expression to obtain
  4274. its type \key{T} and then associate type \code{T} with the variable
  4275. \code{x} in the environment used to type check the body of the
  4276. \key{let}. Thus, when the type checker encounters a use of variable
  4277. \code{x}, it can find its type in the environment. Regarding
  4278. primitive operators, we recursively analyze the arguments and then
  4279. invoke \code{type-check-op} to check whether the argument types are
  4280. allowed.
  4281. Several auxiliary methods are used in the type checker. The method
  4282. \code{operator-types} defines a dictionary that maps the operator
  4283. names to their parameter and return types. The \code{type-equal?}
  4284. method determines whether two types are equal, which for now simply
  4285. dispatches to \code{equal?} (deep equality). The
  4286. \code{check-type-equal?} method triggers an error if the two types are
  4287. not equal. The \code{type-check-op} method looks up the operator in
  4288. the \code{operator-types} dictionary and then checks whether the
  4289. argument types are equal to the parameter types. The result is the
  4290. return type of the operator.
  4291. \begin{figure}[tbp]
  4292. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4293. (define type-check-Rvar-class
  4294. (class object%
  4295. (super-new)
  4296. (define/public (operator-types)
  4297. '((+ . ((Integer Integer) . Integer))
  4298. (- . ((Integer) . Integer))
  4299. (read . (() . Integer))))
  4300. (define/public (type-equal? t1 t2) (equal? t1 t2))
  4301. (define/public (check-type-equal? t1 t2 e)
  4302. (unless (type-equal? t1 t2)
  4303. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  4304. (define/public (type-check-op op arg-types e)
  4305. (match (dict-ref (operator-types) op)
  4306. [`(,param-types . ,return-type)
  4307. (for ([at arg-types] [pt param-types])
  4308. (check-type-equal? at pt e))
  4309. return-type]
  4310. [else (error 'type-check-op "unrecognized ~a" op)]))
  4311. (define/public (type-check-exp env)
  4312. (lambda (e)
  4313. (match e
  4314. [(Int n) (values (Int n) 'Integer)]
  4315. [(Var x) (values (Var x) (dict-ref env x))]
  4316. [(Let x e body)
  4317. (define-values (e^ Te) ((type-check-exp env) e))
  4318. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  4319. (values (Let x e^ b) Tb)]
  4320. [(Prim op es)
  4321. (define-values (new-es ts)
  4322. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  4323. (values (Prim op new-es) (type-check-op op ts e))]
  4324. [else (error 'type-check-exp "couldn't match" e)])))
  4325. (define/public (type-check-program e)
  4326. (match e
  4327. [(Program info body)
  4328. (define-values (body^ Tb) ((type-check-exp '()) body))
  4329. (check-type-equal? Tb 'Integer body)
  4330. (Program info body^)]
  4331. [else (error 'type-check-Rvar "couldn't match ~a" e)]))
  4332. ))
  4333. (define (type-check-Rvar p)
  4334. (send (new type-check-Rvar-class) type-check-program p))
  4335. \end{lstlisting}
  4336. \caption{Type checker for the \LangVar{} language.}
  4337. \label{fig:type-check-Rvar}
  4338. \end{figure}
  4339. \begin{figure}[tbp]
  4340. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4341. (define type-check-Rif-class
  4342. (class type-check-Rvar-class
  4343. (super-new)
  4344. (inherit check-type-equal?)
  4345. (define/override (operator-types)
  4346. (append '((- . ((Integer Integer) . Integer))
  4347. (and . ((Boolean Boolean) . Boolean))
  4348. (or . ((Boolean Boolean) . Boolean))
  4349. (< . ((Integer Integer) . Boolean))
  4350. (<= . ((Integer Integer) . Boolean))
  4351. (> . ((Integer Integer) . Boolean))
  4352. (>= . ((Integer Integer) . Boolean))
  4353. (not . ((Boolean) . Boolean))
  4354. )
  4355. (super operator-types)))
  4356. (define/override (type-check-exp env)
  4357. (lambda (e)
  4358. (match e
  4359. [(Prim 'eq? (list e1 e2))
  4360. (define-values (e1^ T1) ((type-check-exp env) e1))
  4361. (define-values (e2^ T2) ((type-check-exp env) e2))
  4362. (check-type-equal? T1 T2 e)
  4363. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  4364. [(Bool b) (values (Bool b) 'Boolean)]
  4365. [(If cnd thn els)
  4366. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  4367. (define-values (thn^ Tt) ((type-check-exp env) thn))
  4368. (define-values (els^ Te) ((type-check-exp env) els))
  4369. (check-type-equal? Tc 'Boolean e)
  4370. (check-type-equal? Tt Te e)
  4371. (values (If cnd^ thn^ els^) Te)]
  4372. [else ((super type-check-exp env) e)])))
  4373. ))
  4374. (define (type-check-Rif p)
  4375. (send (new type-check-Rif-class) type-check-program p))
  4376. \end{lstlisting}
  4377. \caption{Type checker for the \LangIf{} language.}
  4378. \label{fig:type-check-Rif}
  4379. \end{figure}
  4380. Next we discuss the type checker for \LangIf{} in
  4381. Figure~\ref{fig:type-check-Rif}. The operator \code{eq?} requires the
  4382. two arguments to have the same type. The type of a Boolean constant is
  4383. \code{Boolean}. The condition of an \code{if} must be of
  4384. \code{Boolean} type and the two branches must have the same type. The
  4385. \code{operator-types} function adds dictionary entries for the other
  4386. new operators.
  4387. \begin{exercise}\normalfont
  4388. Create 10 new test programs in \LangIf{}. Half of the programs should
  4389. have a type error. For those programs, create an empty file with the
  4390. same base name but with file extension \code{.tyerr}. For example, if
  4391. the test \code{cond\_test\_14.rkt} is expected to error, then create
  4392. an empty file named \code{cond\_test\_14.tyerr}. This indicates to
  4393. \code{interp-tests} and \code{compiler-tests} that a type error is
  4394. expected. The other half of the test programs should not have type
  4395. errors.
  4396. In the \code{run-tests.rkt} script, change the second argument of
  4397. \code{interp-tests} and \code{compiler-tests} to
  4398. \code{type-check-Rif}, which causes the type checker to run prior to
  4399. the compiler passes. Temporarily change the \code{passes} to an empty
  4400. list and run the script, thereby checking that the new test programs
  4401. either type check or not as intended.
  4402. \end{exercise}
  4403. \section{The \LangCIf{} Intermediate Language}
  4404. \label{sec:Cif}
  4405. Figure~\ref{fig:c1-syntax} defines the abstract syntax of the
  4406. \LangCIf{} intermediate language. (The concrete syntax is in the
  4407. Appendix, Figure~\ref{fig:c1-concrete-syntax}.) Compared to
  4408. \LangCVar{}, the \LangCIf{} language adds logical and comparison
  4409. operators to the \Exp{} non-terminal and the literals \key{\#t} and
  4410. \key{\#f} to the \Arg{} non-terminal.
  4411. Regarding control flow, \LangCIf{} adds \key{goto} and \code{if}
  4412. statements to the \Tail{} non-terminal. The condition of an \code{if}
  4413. statement is a comparison operation and the branches are \code{goto}
  4414. statements, making it straightforward to compile \code{if} statements
  4415. to x86.
  4416. \begin{figure}[tp]
  4417. \fbox{
  4418. \begin{minipage}{0.96\textwidth}
  4419. \small
  4420. \[
  4421. \begin{array}{lcl}
  4422. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  4423. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  4424. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  4425. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4426. &\mid& \UNIOP{\key{'not}}{\Atm}
  4427. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  4428. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  4429. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  4430. \mid \GOTO{\itm{label}} \\
  4431. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  4432. \LangCIf{} & ::= & \gray{\CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}}
  4433. \end{array}
  4434. \]
  4435. \end{minipage}
  4436. }
  4437. \caption{The abstract syntax of \LangCIf{}, an extension of \LangCVar{}
  4438. (Figure~\ref{fig:c0-syntax}).}
  4439. \label{fig:c1-syntax}
  4440. \end{figure}
  4441. \section{The \LangXIf{} Language}
  4442. \label{sec:x86-if}
  4443. \index{x86} To implement the new logical operations, the comparison
  4444. operations, and the \key{if} expression, we need to delve further into
  4445. the x86 language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1}
  4446. define the concrete and abstract syntax for the \LangXIf{} subset
  4447. of x86, which includes instructions for logical operations,
  4448. comparisons, and conditional jumps.
  4449. One challenge is that x86 does not provide an instruction that
  4450. directly implements logical negation (\code{not} in \LangIf{} and
  4451. \LangCIf{}). However, the \code{xorq} instruction can be used to
  4452. encode \code{not}. The \key{xorq} instruction takes two arguments,
  4453. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  4454. bit of its arguments, and writes the results into its second argument.
  4455. Recall the truth table for exclusive-or:
  4456. \begin{center}
  4457. \begin{tabular}{l|cc}
  4458. & 0 & 1 \\ \hline
  4459. 0 & 0 & 1 \\
  4460. 1 & 1 & 0
  4461. \end{tabular}
  4462. \end{center}
  4463. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  4464. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  4465. for the bit $1$, the result is the opposite of the second bit. Thus,
  4466. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  4467. the first argument:
  4468. \[
  4469. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  4470. \qquad\Rightarrow\qquad
  4471. \begin{array}{l}
  4472. \key{movq}~ \Arg\key{,} \Var\\
  4473. \key{xorq}~ \key{\$1,} \Var
  4474. \end{array}
  4475. \]
  4476. \begin{figure}[tp]
  4477. \fbox{
  4478. \begin{minipage}{0.96\textwidth}
  4479. \[
  4480. \begin{array}{lcl}
  4481. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  4482. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4483. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} } \mid \key{\%}\itm{bytereg}\\
  4484. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4485. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \mid
  4486. \key{subq} \; \Arg\key{,} \Arg \mid
  4487. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid } \\
  4488. && \gray{ \key{callq} \; \itm{label} \mid
  4489. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} } \\
  4490. && \gray{ \itm{label}\key{:}\; \Instr }
  4491. \mid \key{xorq}~\Arg\key{,}~\Arg
  4492. \mid \key{cmpq}~\Arg\key{,}~\Arg \mid \\
  4493. && \key{set}cc~\Arg
  4494. \mid \key{movzbq}~\Arg\key{,}~\Arg
  4495. \mid \key{j}cc~\itm{label}
  4496. \\
  4497. \LangXIf{} &::= & \gray{ \key{.globl main} }\\
  4498. & & \gray{ \key{main:} \; \Instr\ldots }
  4499. \end{array}
  4500. \]
  4501. \end{minipage}
  4502. }
  4503. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  4504. \label{fig:x86-1-concrete}
  4505. \end{figure}
  4506. \begin{figure}[tp]
  4507. \fbox{
  4508. \begin{minipage}{0.98\textwidth}
  4509. \small
  4510. \[
  4511. \begin{array}{lcl}
  4512. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  4513. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4514. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}}
  4515. \mid \BYTEREG{\itm{bytereg}} \\
  4516. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4517. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  4518. \mid \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  4519. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  4520. \mid \UNIINSTR{\code{negq}}{\Arg} } \\
  4521. &\mid& \gray{ \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  4522. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  4523. &\mid& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  4524. \mid \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  4525. &\mid& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  4526. \mid \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  4527. &\mid& \JMPIF{\itm{cc}}{\itm{label}} \\
  4528. \Block &::= & \gray{\BLOCK{\itm{info}}{\LP\Instr\ldots\RP}} \\
  4529. \LangXIf{} &::= & \gray{\XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}}
  4530. \end{array}
  4531. \]
  4532. \end{minipage}
  4533. }
  4534. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  4535. \label{fig:x86-1}
  4536. \end{figure}
  4537. Next we consider the x86 instructions that are relevant for compiling
  4538. the comparison operations. The \key{cmpq} instruction compares its two
  4539. arguments to determine whether one argument is less than, equal, or
  4540. greater than the other argument. The \key{cmpq} instruction is unusual
  4541. regarding the order of its arguments and where the result is
  4542. placed. The argument order is backwards: if you want to test whether
  4543. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  4544. \key{cmpq} is placed in the special EFLAGS register. This register
  4545. cannot be accessed directly but it can be queried by a number of
  4546. instructions, including the \key{set} instruction. The instruction
  4547. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  4548. depending on whether the comparison comes out according to the
  4549. condition code \itm{cc} (\key{e} for equal, \key{l} for less, \key{le}
  4550. for less-or-equal, \key{g} for greater, \key{ge} for
  4551. greater-or-equal). The \key{set} instruction has an annoying quirk in
  4552. that its destination argument must be single byte register, such as
  4553. \code{al} (L for lower bits) or \code{ah} (H for higher bits), which
  4554. are part of the \code{rax} register. Thankfully, the \key{movzbq}
  4555. instruction can be used to move from a single byte register to a
  4556. normal 64-bit register. The abstract syntax for the \code{set}
  4557. instruction differs from the concrete syntax in that it separates the
  4558. instruction name from the condition code.
  4559. The x86 instruction for conditional jump is relevant to the
  4560. compilation of \key{if} expressions. The instruction
  4561. $\key{j}\itm{cc}~\itm{label}$ updates the program counter to point to
  4562. the instruction after \itm{label} depending on whether the result in
  4563. the EFLAGS register matches the condition code \itm{cc}, otherwise the
  4564. jump instruction falls through to the next instruction. Like the
  4565. abstract syntax for \code{set}, the abstract syntax for conditional
  4566. jump separates the instruction name from the condition code. For
  4567. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  4568. the conditional jump instruction relies on the EFLAGS register, it is
  4569. common for it to be immediately preceded by a \key{cmpq} instruction
  4570. to set the EFLAGS register.
  4571. \section{Shrink the \LangIf{} Language}
  4572. \label{sec:shrink-Rif}
  4573. The \LangIf{} language includes several operators that are easily
  4574. expressible with other operators. For example, subtraction is
  4575. expressible using addition and negation.
  4576. \[
  4577. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  4578. \]
  4579. Several of the comparison operations are expressible using less-than
  4580. and logical negation.
  4581. \[
  4582. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  4583. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  4584. \]
  4585. The \key{let} is needed in the above translation to ensure that
  4586. expression $e_1$ is evaluated before $e_2$.
  4587. By performing these translations in the front-end of the compiler, the
  4588. later passes of the compiler do not need to deal with these operators,
  4589. making the passes shorter.
  4590. %% On the other hand, sometimes
  4591. %% these translations make it more difficult to generate the most
  4592. %% efficient code with respect to the number of instructions. However,
  4593. %% these differences typically do not affect the number of accesses to
  4594. %% memory, which is the primary factor that determines execution time on
  4595. %% modern computer architectures.
  4596. \begin{exercise}\normalfont
  4597. Implement the pass \code{shrink} to remove subtraction, \key{and},
  4598. \key{or}, \key{<=}, \key{>}, and \key{>=} from the language by
  4599. translating them to other constructs in \LangIf{}.
  4600. %
  4601. Create six test programs that involve these operators.
  4602. %
  4603. In the \code{run-tests.rkt} script, add the following entry for
  4604. \code{shrink} to the list of passes (it should be the only pass at
  4605. this point).
  4606. \begin{lstlisting}
  4607. (list "shrink" shrink interp-Rif type-check-Rif)
  4608. \end{lstlisting}
  4609. This instructs \code{interp-tests} to run the intepreter
  4610. \code{interp-Rif} and the type checker \code{type-check-Rif} on the
  4611. output of \code{shrink}.
  4612. %
  4613. Run the script to test your compiler on all the test programs.
  4614. \end{exercise}
  4615. \section{Uniquify Variables}
  4616. \label{sec:uniquify-Rif}
  4617. Add cases to \code{uniquify-exp} to handle Boolean constants and
  4618. \code{if} expressions.
  4619. \begin{exercise}\normalfont
  4620. Update the \code{uniquify-exp} for \LangIf{} and add the following
  4621. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  4622. \begin{lstlisting}
  4623. (list "uniquify" uniquify interp-Rif type-check-Rif)
  4624. \end{lstlisting}
  4625. Run the script to test your compiler.
  4626. \end{exercise}
  4627. \section{Remove Complex Operands}
  4628. \label{sec:remove-complex-opera-Rif}
  4629. The output language for this pass is \LangIfANF{}
  4630. (Figure~\ref{fig:Rif-anf-syntax}), the administrative normal form of
  4631. \LangIf{}. The \code{Bool} form is an atomic expressions but
  4632. \code{If} is not. All three sub-expressions of an \code{If} are
  4633. allowed to be complex expressions but the operands of \code{not} and
  4634. the comparisons must be atoms.
  4635. Add cases for \code{Bool} and \code{If} to the \code{rco-exp} and
  4636. \code{rco-atom} functions according to whether the output needs to be
  4637. \Exp{} or \Atm{} as specified in the grammar for \LangIfANF{}.
  4638. Regarding \code{If}, it is particularly important to \textbf{not}
  4639. replace its condition with a temporary variable because that would
  4640. interfere with the generation of high-quality output in the
  4641. \code{explicate-control} pass.
  4642. \begin{figure}[tp]
  4643. \centering
  4644. \fbox{
  4645. \begin{minipage}{0.96\textwidth}
  4646. \[
  4647. \begin{array}{rcl}
  4648. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} } \mid \BOOL{\itm{bool}}\\
  4649. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  4650. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4651. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  4652. &\mid& \UNIOP{\key{not}}{\Atm} \\
  4653. &\mid& \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4654. R^{\dagger}_2 &::=& \PROGRAM{\code{()}}{\Exp}
  4655. \end{array}
  4656. \]
  4657. \end{minipage}
  4658. }
  4659. \caption{\LangIfANF{} is \LangIf{} in administrative normal form (ANF).}
  4660. \label{fig:Rif-anf-syntax}
  4661. \end{figure}
  4662. \begin{exercise}\normalfont
  4663. %
  4664. Add cases for Boolean constants and \code{if} to the \code{rco-atom}
  4665. and \code{rco-exp} functions in \code{compiler.rkt}.
  4666. %
  4667. Create three new \LangInt{} programs that exercise the interesting
  4668. code in this pass.
  4669. %
  4670. In the \code{run-tests.rkt} script, add the following entry to the
  4671. list of \code{passes} and then run the script to test your compiler.
  4672. \begin{lstlisting}
  4673. (list "remove-complex" remove-complex-opera* interp-Rif type-check-Rif)
  4674. \end{lstlisting}
  4675. \end{exercise}
  4676. \section{Explicate Control}
  4677. \label{sec:explicate-control-Rif}
  4678. Recall that the purpose of \code{explicate-control} is to make the
  4679. order of evaluation explicit in the syntax of the program. With the
  4680. addition of \key{if} this get more interesting.
  4681. As a motivating example, consider the following program that has an
  4682. \key{if} expression nested in the predicate of another \key{if}.
  4683. % cond_test_41.rkt
  4684. \begin{center}
  4685. \begin{minipage}{0.96\textwidth}
  4686. \begin{lstlisting}
  4687. (let ([x (read)])
  4688. (let ([y (read)])
  4689. (if (if (< x 1) (eq? x 0) (eq? x 2))
  4690. (+ y 2)
  4691. (+ y 10))))
  4692. \end{lstlisting}
  4693. \end{minipage}
  4694. \end{center}
  4695. %
  4696. The naive way to compile \key{if} and the comparison would be to
  4697. handle each of them in isolation, regardless of their context. Each
  4698. comparison would be translated into a \key{cmpq} instruction followed
  4699. by a couple instructions to move the result from the EFLAGS register
  4700. into a general purpose register or stack location. Each \key{if} would
  4701. be translated into a \key{cmpq} instruction followed by a conditional
  4702. jump. The generated code for the inner \key{if} in the above example
  4703. would be as follows.
  4704. \begin{center}
  4705. \begin{minipage}{0.96\textwidth}
  4706. \begin{lstlisting}
  4707. ...
  4708. cmpq $1, x ;; (< x 1)
  4709. setl %al
  4710. movzbq %al, tmp
  4711. cmpq $1, tmp ;; (if ...)
  4712. je then_branch_1
  4713. jmp else_branch_1
  4714. ...
  4715. \end{lstlisting}
  4716. \end{minipage}
  4717. \end{center}
  4718. However, if we take context into account we can do better and reduce
  4719. the use of \key{cmpq} instructions for accessing the EFLAG register.
  4720. Our goal will be compile \key{if} expressions so that the relevant
  4721. comparison instruction appears directly before the conditional jump.
  4722. For example, we want to generate the following code for the inner
  4723. \code{if}.
  4724. \begin{center}
  4725. \begin{minipage}{0.96\textwidth}
  4726. \begin{lstlisting}
  4727. ...
  4728. cmpq $1, x
  4729. je then_branch_1
  4730. jmp else_branch_1
  4731. ...
  4732. \end{lstlisting}
  4733. \end{minipage}
  4734. \end{center}
  4735. One way to achieve this is to reorganize the code at the level of
  4736. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  4737. the following code.
  4738. \begin{center}
  4739. \begin{minipage}{0.96\textwidth}
  4740. \begin{lstlisting}
  4741. (let ([x (read)])
  4742. (let ([y (read)])
  4743. (if (< x 1)
  4744. (if (eq? x 0)
  4745. (+ y 2)
  4746. (+ y 10))
  4747. (if (eq? x 2)
  4748. (+ y 2)
  4749. (+ y 10)))))
  4750. \end{lstlisting}
  4751. \end{minipage}
  4752. \end{center}
  4753. Unfortunately, this approach duplicates the two branches from the
  4754. outer \code{if} and a compiler must never duplicate code!
  4755. We need a way to perform the above transformation but without
  4756. duplicating code. That is, we need a way for different parts of a
  4757. program to refer to the same piece of code. At the level of x86
  4758. assembly this is straightforward because we can label the code for
  4759. each branch and insert jumps in all the places that need to execute
  4760. the branch. In our intermediate language, we need to move away from
  4761. abstract syntax \emph{trees} and instead use \emph{graphs}. In
  4762. particular, we use a standard program representation called a
  4763. \emph{control flow graph} (CFG), due to Frances Elizabeth
  4764. \citet{Allen:1970uq}. \index{control-flow graph} Each vertex is a
  4765. labeled sequence of code, called a \emph{basic block}, and each edge
  4766. represents a jump to another block. The \key{CProgram} construct of
  4767. \LangCVar{} and \LangCIf{} contains a control flow graph represented
  4768. as an alist mapping labels to basic blocks. Each basic block is
  4769. represented by the $\Tail$ non-terminal.
  4770. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  4771. \code{remove-complex-opera*} pass and then the
  4772. \code{explicate-control} pass on the example program. We walk through
  4773. the output program and then discuss the algorithm.
  4774. %
  4775. Following the order of evaluation in the output of
  4776. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  4777. and then the comparison \lstinline{(< x 1)} in the predicate of the
  4778. inner \key{if}. In the output of \code{explicate-control}, in the
  4779. block labeled \code{start}, is two assignment statements followed by a
  4780. \code{if} statement that branches to \code{block40} or
  4781. \code{block41}. The blocks associated with those labels contain the
  4782. translations of the code \lstinline{(eq? x 0)} and \lstinline{(eq? x 2)},
  4783. respectively. In particular, we start \code{block40} with the
  4784. comparison \lstinline{(eq? x 0)} and then branch to \code{block38} or
  4785. \code{block39}, the two branches of the outer \key{if}, i.e.,
  4786. \lstinline{(+ y 2)} and \lstinline{(+ y 10)}. The story for
  4787. \code{block41} is similar.
  4788. \begin{figure}[tbp]
  4789. \begin{tabular}{lll}
  4790. \begin{minipage}{0.4\textwidth}
  4791. % cond_test_41.rkt
  4792. \begin{lstlisting}
  4793. (let ([x (read)])
  4794. (let ([y (read)])
  4795. (if (if (< x 1)
  4796. (eq? x 0)
  4797. (eq? x 2))
  4798. (+ y 2)
  4799. (+ y 10))))
  4800. \end{lstlisting}
  4801. \hspace{40pt}$\Downarrow$
  4802. \begin{lstlisting}
  4803. (let ([x (read)])
  4804. (let ([y (read)])
  4805. (if (if (< x 1)
  4806. (eq? x 0)
  4807. (eq? x 2))
  4808. (+ y 2)
  4809. (+ y 10))))
  4810. \end{lstlisting}
  4811. \end{minipage}
  4812. &
  4813. $\Rightarrow$
  4814. &
  4815. \begin{minipage}{0.55\textwidth}
  4816. \begin{lstlisting}
  4817. start:
  4818. x = (read);
  4819. y = (read);
  4820. if (< x 1) goto block40;
  4821. else goto block41;
  4822. block40:
  4823. if (eq? x 0) goto block38;
  4824. else goto block39;
  4825. block41:
  4826. if (eq? x 2) goto block38;
  4827. else goto block39;
  4828. block38:
  4829. return (+ y 2);
  4830. block39:
  4831. return (+ y 10);
  4832. \end{lstlisting}
  4833. \end{minipage}
  4834. \end{tabular}
  4835. \caption{Translation from \LangIf{} to \LangCIf{}
  4836. via the \code{explicate-control}.}
  4837. \label{fig:explicate-control-s1-38}
  4838. \end{figure}
  4839. %% The nice thing about the output of \code{explicate-control} is that
  4840. %% there are no unnecessary comparisons and every comparison is part of a
  4841. %% conditional jump.
  4842. %% The down-side of this output is that it includes
  4843. %% trivial blocks, such as the blocks labeled \code{block92} through
  4844. %% \code{block95}, that only jump to another block. We discuss a solution
  4845. %% to this problem in Section~\ref{sec:opt-jumps}.
  4846. Recall that in Section~\ref{sec:explicate-control-Rvar} we implement
  4847. \code{explicate-control} for \LangVar{} using two mutually recursive
  4848. functions, \code{explicate-tail} and \code{explicate-assign}. The
  4849. former function translates expressions in tail position whereas the
  4850. later function translates expressions on the right-hand-side of a
  4851. \key{let}. With the addition of \key{if} expression in \LangIf{} we
  4852. have a new kind of position to deal with: the predicate position of
  4853. the \key{if}. We need another function, \code{explicate-pred}, that
  4854. takes an \LangIf{} expression and two blocks for the then-branch and
  4855. else-branch. The output of \code{explicate-pred} is a block.
  4856. %
  4857. In the following paragraphs we discuss specific cases in the
  4858. \code{explicate-pred} function as well as additions to the
  4859. \code{explicate-tail} and \code{explicate-assign} functions.
  4860. \begin{figure}[tbp]
  4861. \begin{lstlisting}
  4862. (define (explicate-pred cnd thn els)
  4863. (match cnd
  4864. [(Var x) ___]
  4865. [(Let x rhs body) ___]
  4866. [(Prim 'not (list e)) ___]
  4867. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  4868. (IfStmt (Prim op arg*) (force (block->goto thn))
  4869. (force (block->goto els)))]
  4870. [(Bool b) (if b thn els)]
  4871. [(If cnd^ thn^ els^) ___]
  4872. [else (error "explicate-pred unhandled case" cnd)]))
  4873. \end{lstlisting}
  4874. \caption{Skeleton for the \key{explicate-pred} auxiliary function.}
  4875. \label{fig:explicate-pred}
  4876. \end{figure}
  4877. The skeleton for the \code{explicate-pred} function is given in
  4878. Figure~\ref{fig:explicate-pred}. It has a case for every expression
  4879. that can have type \code{Boolean}. We detail a few cases here and
  4880. leave the rest for the reader. The input to this function is an
  4881. expression and two blocks, \code{thn} and \code{els}, for the two
  4882. branches of the enclosing \key{if}.
  4883. %
  4884. Consider the case for Boolean constants in
  4885. Figure~\ref{fig:explicate-pred}. We perform a kind of partial
  4886. evaluation\index{partial evaluation} and output either the \code{thn}
  4887. or \code{els} branch depending on whether the constant is true or
  4888. false. This case demonstrates that we sometimes discard the \code{thn}
  4889. or \code{els} blocks that are input to \code{explicate-pred}.
  4890. The case for \key{if} in \code{explicate-pred} is particularly
  4891. illuminating because it deals with the challenges we discussed above
  4892. regarding nested \key{if} expressions
  4893. (Figure~\ref{fig:explicate-control-s1-38}). The \lstinline{thn^} and
  4894. \lstinline{els^} branches of the \key{if} inherit their context from
  4895. the current one, that is, predicate context. So you should recursively
  4896. apply \code{explicate-pred} to the \lstinline{thn^} and
  4897. \lstinline{els^} branches. For both of those recursive calls, pass
  4898. \code{thn} and \code{els} as the extra parameters. Thus, \code{thn}
  4899. and \code{els} may get used twice, once inside each recursive call. As
  4900. discussed above, to avoid duplicating code, we need to add them to the
  4901. control-flow graph so that we can instead refer to them by name and
  4902. execute them with a \key{goto}. However, as we saw in the cases above
  4903. for Boolean constants, the blocks \code{thn} and \code{els} may not
  4904. get used at all and we don't want to prematurely add them to the
  4905. control-flow graph if they end up being discarded.
  4906. The solution to this conundrum is to use \emph{lazy
  4907. evaluation}\index{lazy evaluation}\citep{Friedman:1976aa} to delay
  4908. adding the blocks to the control-flow graph until the points where we
  4909. know they will be used. Racket provides support for lazy evaluation
  4910. with the
  4911. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  4912. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  4913. \index{delay} creates a \emph{promise}\index{promise} in which the
  4914. evaluation of the expressions is postponed. When \key{(force}
  4915. $p$\key{)}\index{force} is applied to a promise $p$ for the first
  4916. time, the expressions $e_1 \ldots e_n$ are evaluated and the result of
  4917. $e_n$ is cached in the promise and returned. If \code{force} is
  4918. applied again to the same promise, then the cached result is returned.
  4919. If \code{force} is applied to an argument that is not a promise,
  4920. \code{force} simply returns the argument.
  4921. We use lazy evaluation for the input and output blocks of the
  4922. functions \code{explicate-pred} and \code{explicate-assign} and for
  4923. the output block of \code{explicate-tail}. So instead of taking and
  4924. returning blocks, they take and return promises. Furthermore, when we
  4925. come to a situation in which we a block might be used more than once,
  4926. as in the case for \code{if} in \code{explicate-pred}, we transform
  4927. the promise into a new promise that will add the block to the
  4928. control-flow graph and return a \code{goto}. The following auxiliary
  4929. function named \code{block->goto} accomplishes this task. It begins
  4930. with \code{delay} to create a promise. When forced, this promise will
  4931. force the original promise. If that returns a \code{goto} (because the
  4932. block was already added to the control-flow graph), then we return the
  4933. \code{goto}. Otherwise we add the block to the control-flow graph with
  4934. another auxiliary function named \code{add-node}. That function
  4935. returns the label for the new block, which we use to create a
  4936. \code{goto}.
  4937. \begin{lstlisting}
  4938. (define (block->goto block)
  4939. (delay
  4940. (define b (force block))
  4941. (match b
  4942. [(Goto label) (Goto label)]
  4943. [else (Goto (add-node b))])))
  4944. \end{lstlisting}
  4945. Returning to the discussion of \code{explicate-pred}
  4946. (Figure~\ref{fig:explicate-pred}), consider the case for comparison
  4947. operators. This is one of the base cases of the recursive function so
  4948. we translate the comparison to an \code{if} statement. We apply
  4949. \code{block->goto} to \code{thn} and \code{els} to obtain two promises
  4950. that will add then to the control-flow graph, which we can immediately
  4951. \code{force} to obtain the two goto's that form the branches of the
  4952. \code{if} statement.
  4953. %% Getting back to the case for \code{if} in \code{explicate-pred}, we
  4954. %% make the recursive calls to \code{explicate-pred} on the ``then'' and
  4955. %% ``else'' branches with the arguments \code{(block->goto} $B_1$\code{)}
  4956. %% and \code{(block->goto} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  4957. %% results from the two recursive calls. We complete the case for
  4958. %% \code{if} by recursively apply \code{explicate-pred} to the condition
  4959. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  4960. %% the result $B_5$.
  4961. %% \[
  4962. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  4963. %% \quad\Rightarrow\quad
  4964. %% B_5
  4965. %% \]
  4966. The \code{explicate-tail} and \code{explicate-assign} functions need
  4967. additional cases for Boolean constants and \key{if}.
  4968. %
  4969. In the cases for \code{if}, the two branches inherit the current
  4970. context, so in \code{explicate-tail} they are in tail position and in
  4971. \code{explicate-assign} they are in assignment position. The
  4972. \code{cont} parameter of \code{explicate-assign} is used in both
  4973. recursive calls, so make sure to use \code{block->goto} on it.
  4974. %% In the case for \code{if} in \code{explicate-tail}, the two branches
  4975. %% inherit the current context, so they are in tail position. Thus, the
  4976. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  4977. %% \code{explicate-tail}.
  4978. %% %
  4979. %% We need to pass $B_0$ as the accumulator argument for both of these
  4980. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  4981. %% Thus, we first apply \code{block->goto} to $B_0$ so that it gets added
  4982. %% to the control-flow graph and obtain a promised goto $G_0$.
  4983. %% %
  4984. %% Let $B_1$ be the result of \code{explicate-tail} on the ``then''
  4985. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate-tail}
  4986. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  4987. %% \code{explicate-pred} to the condition of the \key{if}, $B_1$, and
  4988. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  4989. %% \[
  4990. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  4991. %% \]
  4992. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  4993. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  4994. %% should not be confused with the labels for the blocks that appear in
  4995. %% the generated code. We initially construct unlabeled blocks; we only
  4996. %% attach labels to blocks when we add them to the control-flow graph, as
  4997. %% we see in the next case.
  4998. %% Next consider the case for \key{if} in the \code{explicate-assign}
  4999. %% function. The context of the \key{if} is an assignment to some
  5000. %% variable $x$ and then the control continues to some promised block
  5001. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  5002. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  5003. %% apply \code{block->goto} to it and obtain a promised goto $G_1$. The
  5004. %% branches of the \key{if} inherit the current context, so they are in
  5005. %% assignment positions. Let $B_2$ be the result of applying
  5006. %% \code{explicate-assign} to the ``then'' branch, variable $x$, and
  5007. %% $G_1$. Let $B_3$ be the result of applying \code{explicate-assign} to
  5008. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  5009. %% the result of applying \code{explicate-pred} to the predicate
  5010. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  5011. %% translates to the promise $B_4$.
  5012. %% \[
  5013. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  5014. %% \]
  5015. %% This completes the description of \code{explicate-control} for \LangIf{}.
  5016. The way in which the \code{shrink} pass transforms logical operations
  5017. such as \code{and} and \code{or} can impact the quality of code
  5018. generated by \code{explicate-control}. For example, consider the
  5019. following program.
  5020. % cond_test_21.rkt
  5021. \begin{lstlisting}
  5022. (if (and (eq? (read) 0) (eq? (read) 1))
  5023. 0
  5024. 42)
  5025. \end{lstlisting}
  5026. The \code{and} operation should transform into something that the
  5027. \code{explicate-pred} function can still analyze and descend through to
  5028. reach the underlying \code{eq?} conditions. Ideally, your
  5029. \code{explicate-control} pass should generate code similar to the
  5030. following for the above program.
  5031. \begin{center}
  5032. \begin{lstlisting}
  5033. start:
  5034. tmp1 = (read);
  5035. if (eq? tmp1 0) goto block40;
  5036. else goto block39;
  5037. block40:
  5038. tmp2 = (read);
  5039. if (eq? tmp2 1) goto block38;
  5040. else goto block39;
  5041. block38:
  5042. return 0;
  5043. block39:
  5044. return 42;
  5045. \end{lstlisting}
  5046. \end{center}
  5047. \begin{exercise}\normalfont
  5048. Implement the pass \code{explicate-control} by adding the cases for
  5049. Boolean constants and \key{if} to the \code{explicate-tail} and
  5050. \code{explicate-assign}. Implement the auxiliary function
  5051. \code{explicate-pred} for predicate contexts.
  5052. %
  5053. Create test cases that exercise all of the new cases in the code for
  5054. this pass.
  5055. %
  5056. Add the following entry to the list of \code{passes} in
  5057. \code{run-tests.rkt} and then run this script to test your compiler.
  5058. \begin{lstlisting}
  5059. (list "explicate-control" explicate-control interp-Cif type-check-Cif)
  5060. \end{lstlisting}
  5061. \end{exercise}
  5062. \section{Select Instructions}
  5063. \label{sec:select-Rif}
  5064. \index{instruction selection}
  5065. The \code{select-instructions} pass translate \LangCIf{} to
  5066. \LangXIfVar{}. Recall that we implement this pass using three
  5067. auxiliary functions, one for each of the non-terminals $\Atm$,
  5068. $\Stmt$, and $\Tail$.
  5069. For $\Atm$, we have new cases for the Booleans. We take the usual
  5070. approach of encoding them as integers, with true as 1 and false as 0.
  5071. \[
  5072. \key{\#t} \Rightarrow \key{1}
  5073. \qquad
  5074. \key{\#f} \Rightarrow \key{0}
  5075. \]
  5076. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  5077. be implemented in terms of \code{xorq} as we discussed at the
  5078. beginning of this section. Given an assignment
  5079. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  5080. if the left-hand side $\itm{var}$ is
  5081. the same as $\Atm$, then just the \code{xorq} suffices.
  5082. \[
  5083. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  5084. \quad\Rightarrow\quad
  5085. \key{xorq}~\key{\$}1\key{,}~\Var
  5086. \]
  5087. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  5088. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  5089. x86. Then we have
  5090. \[
  5091. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  5092. \quad\Rightarrow\quad
  5093. \begin{array}{l}
  5094. \key{movq}~\Arg\key{,}~\Var\\
  5095. \key{xorq}~\key{\$}1\key{,}~\Var
  5096. \end{array}
  5097. \]
  5098. Next consider the cases for \code{eq?} and less-than comparison.
  5099. Translating these operations to x86 is slightly involved due to the
  5100. unusual nature of the \key{cmpq} instruction discussed above. We
  5101. recommend translating an assignment from \code{eq?} into the following
  5102. sequence of three instructions. \\
  5103. \begin{tabular}{lll}
  5104. \begin{minipage}{0.4\textwidth}
  5105. \begin{lstlisting}
  5106. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  5107. \end{lstlisting}
  5108. \end{minipage}
  5109. &
  5110. $\Rightarrow$
  5111. &
  5112. \begin{minipage}{0.4\textwidth}
  5113. \begin{lstlisting}
  5114. cmpq |$\Arg_2$|, |$\Arg_1$|
  5115. sete %al
  5116. movzbq %al, |$\Var$|
  5117. \end{lstlisting}
  5118. \end{minipage}
  5119. \end{tabular} \\
  5120. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  5121. and \key{if} statements. Both are straightforward to translate to
  5122. x86. A \key{goto} becomes a jump instruction.
  5123. \[
  5124. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  5125. \]
  5126. An \key{if} statement becomes a compare instruction followed by a
  5127. conditional jump (for the ``then'' branch) and the fall-through is to
  5128. a regular jump (for the ``else'' branch).\\
  5129. \begin{tabular}{lll}
  5130. \begin{minipage}{0.4\textwidth}
  5131. \begin{lstlisting}
  5132. if (eq? |$\Atm_1$| |$\Atm_2$|) goto |$\ell_1$|;
  5133. else goto |$\ell_2$|;
  5134. \end{lstlisting}
  5135. \end{minipage}
  5136. &
  5137. $\Rightarrow$
  5138. &
  5139. \begin{minipage}{0.4\textwidth}
  5140. \begin{lstlisting}
  5141. cmpq |$\Arg_2$|, |$\Arg_1$|
  5142. je |$\ell_1$|
  5143. jmp |$\ell_2$|
  5144. \end{lstlisting}
  5145. \end{minipage}
  5146. \end{tabular} \\
  5147. \begin{exercise}\normalfont
  5148. Expand your \code{select-instructions} pass to handle the new features
  5149. of the \LangIf{} language.
  5150. %
  5151. Add the following entry to the list of \code{passes} in
  5152. \code{run-tests.rkt}
  5153. \begin{lstlisting}
  5154. (list "select-instructions" select-instructions interp-pseudo-x86-1)
  5155. \end{lstlisting}
  5156. %
  5157. Run the script to test your compiler on all the test programs.
  5158. \end{exercise}
  5159. \section{Register Allocation}
  5160. \label{sec:register-allocation-Rif}
  5161. \index{register allocation}
  5162. The changes required for \LangIf{} affect liveness analysis, building the
  5163. interference graph, and assigning homes, but the graph coloring
  5164. algorithm itself does not change.
  5165. \subsection{Liveness Analysis}
  5166. \label{sec:liveness-analysis-Rif}
  5167. \index{liveness analysis}
  5168. Recall that for \LangVar{} we implemented liveness analysis for a single
  5169. basic block (Section~\ref{sec:liveness-analysis-Rvar}). With the
  5170. addition of \key{if} expressions to \LangIf{}, \code{explicate-control}
  5171. produces many basic blocks arranged in a control-flow graph. We
  5172. recommend that you create a new auxiliary function named
  5173. \code{uncover-live-CFG} that applies liveness analysis to a
  5174. control-flow graph.
  5175. The first question we is: what order should we process the basic
  5176. blocks in the control-flow graph? Recall that to perform liveness
  5177. analysis on a basic block we need to know its live-after set. If a
  5178. basic block has no successors (i.e. no out-edges in the control flow
  5179. graph), then it has an empty live-after set and we can immediately
  5180. apply liveness analysis to it. If a basic block has some successors,
  5181. then we need to complete liveness analysis on those blocks first. In
  5182. graph theory, a sequence of nodes is in \emph{topological
  5183. order}\index{topological order} if each vertex comes before its
  5184. successors. We need the opposite, so we can transpose the graph
  5185. before computing a topological order.
  5186. %
  5187. Use the \code{tsort} and \code{transpose} functions of the Racket
  5188. \code{graph} package to accomplish this.
  5189. %
  5190. As an aside, a topological ordering is only guaranteed to exist if the
  5191. graph does not contain any cycles. That is indeed the case for the
  5192. control-flow graphs that we generate from \LangIf{} programs.
  5193. However, in Chapter~\ref{ch:Rwhile} we add loops to \LangLoop{} and
  5194. learn how to handle cycles in the control-flow graph.
  5195. You'll need to construct a directed graph to represent the
  5196. control-flow graph. Do not use the \code{directed-graph} of the
  5197. \code{graph} package because that only allows at most one edge between
  5198. each pair of vertices, but a control-flow graph may have multiple
  5199. edges between a pair of vertices. The \code{multigraph.rkt} file in
  5200. the support code implements a graph representation that allows
  5201. multiple edges between a pair of vertices.
  5202. The next question is how to analyze jump instructions. Recall that in
  5203. Section~\ref{sec:liveness-analysis-Rvar} we maintain an alist named
  5204. \code{label->live} that maps each label to the set of live locations
  5205. at the beginning of its block. We use \code{label->live} to determine
  5206. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  5207. that we have many basic blocks, \code{label->live} needs to be updated
  5208. as we process the blocks. In particular, after performing liveness
  5209. analysis on a block, we take the live-before set of its first
  5210. instruction and associate that with the block's label in the
  5211. \code{label->live}.
  5212. In \LangXIfVar{} we also have the conditional jump
  5213. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  5214. this instruction is particularly interesting because during
  5215. compilation we do not know which way a conditional jump will go. So
  5216. we do not know whether to use the live-before set for the following
  5217. instruction or the live-before set for the $\itm{label}$. However,
  5218. there is no harm to the correctness of the compiler if we classify
  5219. more locations as live than the ones that are truly live during a
  5220. particular execution of the instruction. Thus, we can take the union
  5221. of the live-before sets from the following instruction and from the
  5222. mapping for $\itm{label}$ in \code{label->live}.
  5223. The auxiliary functions for computing the variables in an
  5224. instruction's argument and for computing the variables read-from ($R$)
  5225. or written-to ($W$) by an instruction need to be updated to handle the
  5226. new kinds of arguments and instructions in \LangXIfVar{}.
  5227. \begin{exercise}\normalfont
  5228. Update the \code{uncover-live} pass and implement the
  5229. \code{uncover-live-CFG} auxiliary function to apply liveness analysis
  5230. to the control-flow graph. Add the following entry to the list of
  5231. \code{passes} in the \code{run-tests.rkt} script.
  5232. \begin{lstlisting}
  5233. (list "uncover-live" uncover-live interp-pseudo-x86-1)
  5234. \end{lstlisting}
  5235. \end{exercise}
  5236. \subsection{Build the Interference Graph}
  5237. \label{sec:build-interference-Rif}
  5238. Many of the new instructions in \LangXIfVar{} can be handled in the
  5239. same way as the instructions in \LangXVar{}. Thus, if your code was
  5240. already quite general, it will not need to be changed to handle the
  5241. new instructions. If you code is not general enough, we recommend that
  5242. you change your code to be more general. For example, you can factor
  5243. out the computing of the the read and write sets for each kind of
  5244. instruction into two auxiliary functions.
  5245. Note that the \key{movzbq} instruction requires some special care,
  5246. similar to the \key{movq} instruction. See rule number 1 in
  5247. Section~\ref{sec:build-interference}.
  5248. \begin{exercise}\normalfont
  5249. Update the \code{build-interference} pass for \LangXIfVar{} and add the
  5250. following entries to the list of \code{passes} in the
  5251. \code{run-tests.rkt} script.
  5252. \begin{lstlisting}
  5253. (list "build-interference" build-interference interp-pseudo-x86-1)
  5254. (list "allocate-registers" allocate-registers interp-x86-1)
  5255. \end{lstlisting}
  5256. Run the script to test your compiler on all the \LangIf{} test
  5257. programs.
  5258. \end{exercise}
  5259. \section{Patch Instructions}
  5260. The second argument of the \key{cmpq} instruction must not be an
  5261. immediate value (such as an integer). So if you are comparing two
  5262. immediates, we recommend inserting a \key{movq} instruction to put the
  5263. second argument in \key{rax}. Also, recall that instructions may have
  5264. at most one memory reference.
  5265. %
  5266. The second argument of the \key{movzbq} must be a register.
  5267. %
  5268. There are no special restrictions on the jump instructions.
  5269. \begin{exercise}\normalfont
  5270. %
  5271. Update \code{patch-instructions} pass for \LangXIfVar{}.
  5272. %
  5273. Add the following entry to the list of \code{passes} in
  5274. \code{run-tests.rkt} and then run this script to test your compiler.
  5275. \begin{lstlisting}
  5276. (list "patch-instructions" patch-instructions interp-x86-1)
  5277. \end{lstlisting}
  5278. \end{exercise}
  5279. \begin{figure}[tbp]
  5280. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5281. \node (Rif) at (0,2) {\large \LangIf{}};
  5282. \node (Rif-2) at (3,2) {\large \LangIf{}};
  5283. \node (Rif-3) at (6,2) {\large \LangIf{}};
  5284. \node (Rif-4) at (9,2) {\large \LangIf{}};
  5285. \node (Rif-5) at (12,2) {\large \LangIf{}};
  5286. \node (C1-1) at (3,0) {\large \LangCIf{}};
  5287. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  5288. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  5289. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  5290. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  5291. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  5292. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  5293. \path[->,bend left=15] (Rif) edge [above] node {\ttfamily\footnotesize type-check} (Rif-2);
  5294. \path[->,bend left=15] (Rif-2) edge [above] node {\ttfamily\footnotesize shrink} (Rif-3);
  5295. \path[->,bend left=15] (Rif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Rif-4);
  5296. \path[->,bend left=15] (Rif-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rif-5);
  5297. \path[->,bend left=15] (Rif-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C1-1);
  5298. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select-instructions} (x86-2);
  5299. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  5300. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  5301. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  5302. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  5303. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86 } (x86-5);
  5304. \end{tikzpicture}
  5305. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  5306. \label{fig:Rif-passes}
  5307. \end{figure}
  5308. Figure~\ref{fig:Rif-passes} lists all the passes needed for the
  5309. compilation of \LangIf{}.
  5310. \section{An Example Translation}
  5311. Figure~\ref{fig:if-example-x86} shows a simple example program in
  5312. \LangIf{} translated to x86, showing the results of
  5313. \code{explicate-control}, \code{select-instructions}, and the final
  5314. x86 assembly code.
  5315. \begin{figure}[tbp]
  5316. \begin{tabular}{lll}
  5317. \begin{minipage}{0.4\textwidth}
  5318. % cond_test_20.rkt
  5319. \begin{lstlisting}
  5320. (if (eq? (read) 1) 42 0)
  5321. \end{lstlisting}
  5322. $\Downarrow$
  5323. \begin{lstlisting}
  5324. start:
  5325. tmp7951 = (read);
  5326. if (eq? tmp7951 1)
  5327. goto block7952;
  5328. else
  5329. goto block7953;
  5330. block7952:
  5331. return 42;
  5332. block7953:
  5333. return 0;
  5334. \end{lstlisting}
  5335. $\Downarrow$
  5336. \begin{lstlisting}
  5337. start:
  5338. callq read_int
  5339. movq %rax, tmp7951
  5340. cmpq $1, tmp7951
  5341. je block7952
  5342. jmp block7953
  5343. block7953:
  5344. movq $0, %rax
  5345. jmp conclusion
  5346. block7952:
  5347. movq $42, %rax
  5348. jmp conclusion
  5349. \end{lstlisting}
  5350. \end{minipage}
  5351. &
  5352. $\Rightarrow\qquad$
  5353. \begin{minipage}{0.4\textwidth}
  5354. \begin{lstlisting}
  5355. start:
  5356. callq read_int
  5357. movq %rax, %rcx
  5358. cmpq $1, %rcx
  5359. je block7952
  5360. jmp block7953
  5361. block7953:
  5362. movq $0, %rax
  5363. jmp conclusion
  5364. block7952:
  5365. movq $42, %rax
  5366. jmp conclusion
  5367. .globl main
  5368. main:
  5369. pushq %rbp
  5370. movq %rsp, %rbp
  5371. pushq %r13
  5372. pushq %r12
  5373. pushq %rbx
  5374. pushq %r14
  5375. subq $0, %rsp
  5376. jmp start
  5377. conclusion:
  5378. addq $0, %rsp
  5379. popq %r14
  5380. popq %rbx
  5381. popq %r12
  5382. popq %r13
  5383. popq %rbp
  5384. retq
  5385. \end{lstlisting}
  5386. \end{minipage}
  5387. \end{tabular}
  5388. \caption{Example compilation of an \key{if} expression to x86.}
  5389. \label{fig:if-example-x86}
  5390. \end{figure}
  5391. \section{Challenge: Remove Jumps}
  5392. \label{sec:opt-jumps}
  5393. %% Recall that in the example output of \code{explicate-control} in
  5394. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  5395. %% \code{block60} are trivial blocks, they do nothing but jump to another
  5396. %% block. The first goal of this challenge assignment is to remove those
  5397. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  5398. %% \code{explicate-control} on the left and shows the result of bypassing
  5399. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  5400. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  5401. %% \code{block55}. The optimized code on the right of
  5402. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  5403. %% \code{then} branch jumping directly to \code{block55}. The story is
  5404. %% similar for the \code{else} branch, as well as for the two branches in
  5405. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  5406. %% have been optimized in this way, there are no longer any jumps to
  5407. %% blocks \code{block57} through \code{block60}, so they can be removed.
  5408. %% \begin{figure}[tbp]
  5409. %% \begin{tabular}{lll}
  5410. %% \begin{minipage}{0.4\textwidth}
  5411. %% \begin{lstlisting}
  5412. %% block62:
  5413. %% tmp54 = (read);
  5414. %% if (eq? tmp54 2) then
  5415. %% goto block59;
  5416. %% else
  5417. %% goto block60;
  5418. %% block61:
  5419. %% tmp53 = (read);
  5420. %% if (eq? tmp53 0) then
  5421. %% goto block57;
  5422. %% else
  5423. %% goto block58;
  5424. %% block60:
  5425. %% goto block56;
  5426. %% block59:
  5427. %% goto block55;
  5428. %% block58:
  5429. %% goto block56;
  5430. %% block57:
  5431. %% goto block55;
  5432. %% block56:
  5433. %% return (+ 700 77);
  5434. %% block55:
  5435. %% return (+ 10 32);
  5436. %% start:
  5437. %% tmp52 = (read);
  5438. %% if (eq? tmp52 1) then
  5439. %% goto block61;
  5440. %% else
  5441. %% goto block62;
  5442. %% \end{lstlisting}
  5443. %% \end{minipage}
  5444. %% &
  5445. %% $\Rightarrow$
  5446. %% &
  5447. %% \begin{minipage}{0.55\textwidth}
  5448. %% \begin{lstlisting}
  5449. %% block62:
  5450. %% tmp54 = (read);
  5451. %% if (eq? tmp54 2) then
  5452. %% goto block55;
  5453. %% else
  5454. %% goto block56;
  5455. %% block61:
  5456. %% tmp53 = (read);
  5457. %% if (eq? tmp53 0) then
  5458. %% goto block55;
  5459. %% else
  5460. %% goto block56;
  5461. %% block56:
  5462. %% return (+ 700 77);
  5463. %% block55:
  5464. %% return (+ 10 32);
  5465. %% start:
  5466. %% tmp52 = (read);
  5467. %% if (eq? tmp52 1) then
  5468. %% goto block61;
  5469. %% else
  5470. %% goto block62;
  5471. %% \end{lstlisting}
  5472. %% \end{minipage}
  5473. %% \end{tabular}
  5474. %% \caption{Optimize jumps by removing trivial blocks.}
  5475. %% \label{fig:optimize-jumps}
  5476. %% \end{figure}
  5477. %% The name of this pass is \code{optimize-jumps}. We recommend
  5478. %% implementing this pass in two phases. The first phrase builds a hash
  5479. %% table that maps labels to possibly improved labels. The second phase
  5480. %% changes the target of each \code{goto} to use the improved label. If
  5481. %% the label is for a trivial block, then the hash table should map the
  5482. %% label to the first non-trivial block that can be reached from this
  5483. %% label by jumping through trivial blocks. If the label is for a
  5484. %% non-trivial block, then the hash table should map the label to itself;
  5485. %% we do not want to change jumps to non-trivial blocks.
  5486. %% The first phase can be accomplished by constructing an empty hash
  5487. %% table, call it \code{short-cut}, and then iterating over the control
  5488. %% flow graph. Each time you encouter a block that is just a \code{goto},
  5489. %% then update the hash table, mapping the block's source to the target
  5490. %% of the \code{goto}. Also, the hash table may already have mapped some
  5491. %% labels to the block's source, to you must iterate through the hash
  5492. %% table and update all of those so that they instead map to the target
  5493. %% of the \code{goto}.
  5494. %% For the second phase, we recommend iterating through the $\Tail$ of
  5495. %% each block in the program, updating the target of every \code{goto}
  5496. %% according to the mapping in \code{short-cut}.
  5497. %% \begin{exercise}\normalfont
  5498. %% Implement the \code{optimize-jumps} pass as a transformation from
  5499. %% \LangCIf{} to \LangCIf{}, coming after the \code{explicate-control} pass.
  5500. %% Check that \code{optimize-jumps} removes trivial blocks in a few
  5501. %% example programs. Then check that your compiler still passes all of
  5502. %% your tests.
  5503. %% \end{exercise}
  5504. There is an opportunity for optimizing jumps that is apparent in the
  5505. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  5506. ends with a jump to \code{block7953} and there are no other jumps to
  5507. \code{block7953} in the rest of the program. In this situation we can
  5508. avoid the runtime overhead of this jump by merging \code{block7953}
  5509. into the preceding block, in this case the \code{start} block.
  5510. Figure~\ref{fig:remove-jumps} shows the output of
  5511. \code{select-instructions} on the left and the result of this
  5512. optimization on the right.
  5513. \begin{figure}[tbp]
  5514. \begin{tabular}{lll}
  5515. \begin{minipage}{0.5\textwidth}
  5516. % cond_test_20.rkt
  5517. \begin{lstlisting}
  5518. start:
  5519. callq read_int
  5520. movq %rax, tmp7951
  5521. cmpq $1, tmp7951
  5522. je block7952
  5523. jmp block7953
  5524. block7953:
  5525. movq $0, %rax
  5526. jmp conclusion
  5527. block7952:
  5528. movq $42, %rax
  5529. jmp conclusion
  5530. \end{lstlisting}
  5531. \end{minipage}
  5532. &
  5533. $\Rightarrow\qquad$
  5534. \begin{minipage}{0.4\textwidth}
  5535. \begin{lstlisting}
  5536. start:
  5537. callq read_int
  5538. movq %rax, tmp7951
  5539. cmpq $1, tmp7951
  5540. je block7952
  5541. movq $0, %rax
  5542. jmp conclusion
  5543. block7952:
  5544. movq $42, %rax
  5545. jmp conclusion
  5546. \end{lstlisting}
  5547. \end{minipage}
  5548. \end{tabular}
  5549. \caption{Merging basic blocks by removing unnecessary jumps.}
  5550. \label{fig:remove-jumps}
  5551. \end{figure}
  5552. \begin{exercise}\normalfont
  5553. %
  5554. Implement a pass named \code{remove-jumps} that merges basic blocks
  5555. into their preceding basic block, when there is only one preceding
  5556. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  5557. %
  5558. In the \code{run-tests.rkt} script, add the following entry to the
  5559. list of \code{passes} between \code{allocate-registers}
  5560. and \code{patch-instructions}.
  5561. \begin{lstlisting}
  5562. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  5563. \end{lstlisting}
  5564. Run this script to test your compiler.
  5565. %
  5566. Check that \code{remove-jumps} accomplishes the goal of merging basic
  5567. blocks on several test programs.
  5568. \end{exercise}
  5569. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5570. \chapter{Tuples and Garbage Collection}
  5571. \label{ch:Rvec}
  5572. \index{tuple}
  5573. \index{vector}
  5574. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  5575. all the IR grammars are spelled out! \\ --Jeremy}
  5576. \margincomment{\scriptsize Be more explicit about how to deal with
  5577. the root stack. \\ --Jeremy}
  5578. In this chapter we study the implementation of mutable tuples, called
  5579. vectors in Racket. This language feature is the first to use the
  5580. computer's \emph{heap}\index{heap} because the lifetime of a Racket
  5581. tuple is indefinite, that is, a tuple lives forever from the
  5582. programmer's viewpoint. Of course, from an implementer's viewpoint, it
  5583. is important to reclaim the space associated with a tuple when it is
  5584. no longer needed, which is why we also study \emph{garbage collection}
  5585. \emph{garbage collection} techniques in this chapter.
  5586. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  5587. interpreter and type checker. The \LangVec{} language extends the \LangIf{}
  5588. language of Chapter~\ref{ch:Rif} with vectors and Racket's
  5589. \code{void} value. The reason for including the later is that the
  5590. \code{vector-set!} operation returns a value of type
  5591. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  5592. called the \code{Unit} type in the programming languages
  5593. literature. Racket's \code{Void} type is inhabited by a single value
  5594. \code{void} which corresponds to \code{unit} or \code{()} in the
  5595. literature~\citep{Pierce:2002hj}.}.
  5596. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  5597. copying live objects back and forth between two halves of the
  5598. heap. The garbage collector requires coordination with the compiler so
  5599. that it can see all of the \emph{root} pointers, that is, pointers in
  5600. registers or on the procedure call stack.
  5601. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  5602. discuss all the necessary changes and additions to the compiler
  5603. passes, including a new compiler pass named \code{expose-allocation}.
  5604. \section{The \LangVec{} Language}
  5605. \label{sec:r3}
  5606. Figure~\ref{fig:Rvec-concrete-syntax} defines the concrete syntax for
  5607. \LangVec{} and Figure~\ref{fig:Rvec-syntax} defines the abstract syntax. The
  5608. \LangVec{} language includes three new forms: \code{vector} for creating a
  5609. tuple, \code{vector-ref} for reading an element of a tuple, and
  5610. \code{vector-set!} for writing to an element of a tuple. The program
  5611. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  5612. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  5613. the 3-tuple, demonstrating that tuples are first-class values. The
  5614. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  5615. of the \key{if} is taken. The element at index $0$ of \code{t} is
  5616. \code{40}, to which we add \code{2}, the element at index $0$ of the
  5617. 1-tuple. So the result of the program is \code{42}.
  5618. \begin{figure}[tbp]
  5619. \centering
  5620. \fbox{
  5621. \begin{minipage}{0.96\textwidth}
  5622. \[
  5623. \begin{array}{lcl}
  5624. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  5625. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \key{Void}\\
  5626. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  5627. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  5628. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5629. \mid \LP\key{and}\;\Exp\;\Exp\RP
  5630. \mid \LP\key{or}\;\Exp\;\Exp\RP
  5631. \mid \LP\key{not}\;\Exp\RP } \\
  5632. &\mid& \gray{ \LP\itm{cmp}\;\Exp\;\Exp\RP
  5633. \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  5634. &\mid& \LP\key{vector}\;\Exp\ldots\RP
  5635. \mid \LP\key{vector-length}\;\Exp\RP \\
  5636. &\mid& \LP\key{vector-ref}\;\Exp\;\Int\RP
  5637. \mid \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP \\
  5638. &\mid& \LP\key{void}\RP \mid \LP\key{has-type}~\Exp~\Type\RP\\
  5639. \LangVec{} &::=& \Exp
  5640. \end{array}
  5641. \]
  5642. \end{minipage}
  5643. }
  5644. \caption{The concrete syntax of \LangVec{}, extending \LangIf{}
  5645. (Figure~\ref{fig:Rif-concrete-syntax}).}
  5646. \label{fig:Rvec-concrete-syntax}
  5647. \end{figure}
  5648. \begin{figure}[tbp]
  5649. \begin{lstlisting}
  5650. (let ([t (vector 40 #t (vector 2))])
  5651. (if (vector-ref t 1)
  5652. (+ (vector-ref t 0)
  5653. (vector-ref (vector-ref t 2) 0))
  5654. 44))
  5655. \end{lstlisting}
  5656. \caption{Example program that creates tuples and reads from them.}
  5657. \label{fig:vector-eg}
  5658. \end{figure}
  5659. \begin{figure}[tp]
  5660. \centering
  5661. \fbox{
  5662. \begin{minipage}{0.96\textwidth}
  5663. \[
  5664. \begin{array}{lcl}
  5665. \itm{op} &::=& \ldots \mid \code{vector} \mid \code{vector-length} \\
  5666. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  5667. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots}
  5668. \mid \BOOL{\itm{bool}}
  5669. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  5670. &\mid& \VECREF{\Exp}{\INT{\Int}}\\
  5671. &\mid& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  5672. &\mid& \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP \\
  5673. \LangVec{} &::=& \PROGRAM{\key{'()}}{\Exp}
  5674. \end{array}
  5675. \]
  5676. \end{minipage}
  5677. }
  5678. \caption{The abstract syntax of \LangVec{}.}
  5679. \label{fig:Rvec-syntax}
  5680. \end{figure}
  5681. \index{allocate}
  5682. \index{heap allocate}
  5683. Tuples are our first encounter with heap-allocated data, which raises
  5684. several interesting issues. First, variable binding performs a
  5685. shallow-copy when dealing with tuples, which means that different
  5686. variables can refer to the same tuple, that is, different variables
  5687. can be \emph{aliases} for the same entity. Consider the following
  5688. example in which both \code{t1} and \code{t2} refer to the same tuple.
  5689. Thus, the mutation through \code{t2} is visible when referencing the
  5690. tuple from \code{t1}, so the result of this program is \code{42}.
  5691. \index{alias}\index{mutation}
  5692. \begin{center}
  5693. \begin{minipage}{0.96\textwidth}
  5694. \begin{lstlisting}
  5695. (let ([t1 (vector 3 7)])
  5696. (let ([t2 t1])
  5697. (let ([_ (vector-set! t2 0 42)])
  5698. (vector-ref t1 0))))
  5699. \end{lstlisting}
  5700. \end{minipage}
  5701. \end{center}
  5702. The next issue concerns the lifetime of tuples. Of course, they are
  5703. created by the \code{vector} form, but when does their lifetime end?
  5704. Notice that \LangVec{} does not include an operation for deleting
  5705. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  5706. of static scoping. For example, the following program returns
  5707. \code{42} even though the variable \code{w} goes out of scope prior to
  5708. the \code{vector-ref} that reads from the vector it was bound to.
  5709. \begin{center}
  5710. \begin{minipage}{0.96\textwidth}
  5711. \begin{lstlisting}
  5712. (let ([v (vector (vector 44))])
  5713. (let ([x (let ([w (vector 42)])
  5714. (let ([_ (vector-set! v 0 w)])
  5715. 0))])
  5716. (+ x (vector-ref (vector-ref v 0) 0))))
  5717. \end{lstlisting}
  5718. \end{minipage}
  5719. \end{center}
  5720. From the perspective of programmer-observable behavior, tuples live
  5721. forever. Of course, if they really lived forever, then many programs
  5722. would run out of memory.\footnote{The \LangVec{} language does not have
  5723. looping or recursive functions, so it is nigh impossible to write a
  5724. program in \LangVec{} that will run out of memory. However, we add
  5725. recursive functions in the next Chapter!} A Racket implementation
  5726. must therefore perform automatic garbage collection.
  5727. Figure~\ref{fig:interp-Rvec} shows the definitional interpreter for the
  5728. \LangVec{} language. We define the \code{vector}, \code{vector-length},
  5729. \code{vector-ref}, and \code{vector-set!} operations for \LangVec{} in
  5730. terms of the corresponding operations in Racket. One subtle point is
  5731. that the \code{vector-set!} operation returns the \code{\#<void>}
  5732. value. The \code{\#<void>} value can be passed around just like other
  5733. values inside an \LangVec{} program and a \code{\#<void>} value can be
  5734. compared for equality with another \code{\#<void>} value. However,
  5735. there are no other operations specific to the the \code{\#<void>}
  5736. value in \LangVec{}. In contrast, Racket defines the \code{void?} predicate
  5737. that returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  5738. otherwise.
  5739. \begin{figure}[tbp]
  5740. \begin{lstlisting}
  5741. (define interp-Rvec-class
  5742. (class interp-Rif-class
  5743. (super-new)
  5744. (define/override (interp-op op)
  5745. (match op
  5746. ['eq? (lambda (v1 v2)
  5747. (cond [(or (and (fixnum? v1) (fixnum? v2))
  5748. (and (boolean? v1) (boolean? v2))
  5749. (and (vector? v1) (vector? v2))
  5750. (and (void? v1) (void? v2)))
  5751. (eq? v1 v2)]))]
  5752. ['vector vector]
  5753. ['vector-length vector-length]
  5754. ['vector-ref vector-ref]
  5755. ['vector-set! vector-set!]
  5756. [else (super interp-op op)]
  5757. ))
  5758. (define/override ((interp-exp env) e)
  5759. (define recur (interp-exp env))
  5760. (match e
  5761. [(HasType e t) (recur e)]
  5762. [(Void) (void)]
  5763. [else ((super interp-exp env) e)]
  5764. ))
  5765. ))
  5766. (define (interp-Rvec p)
  5767. (send (new interp-Rvec-class) interp-program p))
  5768. \end{lstlisting}
  5769. \caption{Interpreter for the \LangVec{} language.}
  5770. \label{fig:interp-Rvec}
  5771. \end{figure}
  5772. Figure~\ref{fig:type-check-Rvec} shows the type checker for \LangVec{}, which
  5773. deserves some explanation. When allocating a vector, we need to know
  5774. which elements of the vector are pointers (i.e. are also vectors). We
  5775. can obtain this information during type checking. The type checker in
  5776. Figure~\ref{fig:type-check-Rvec} not only computes the type of an
  5777. expression, it also wraps every \key{vector} creation with the form
  5778. $(\key{HasType}~e~T)$, where $T$ is the vector's type.
  5779. %
  5780. To create the s-expression for the \code{Vector} type in
  5781. Figure~\ref{fig:type-check-Rvec}, we use the
  5782. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  5783. operator} \code{,@} to insert the list \code{t*} without its usual
  5784. start and end parentheses. \index{unquote-slicing}
  5785. \begin{figure}[tp]
  5786. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5787. (define type-check-Rvec-class
  5788. (class type-check-Rif-class
  5789. (super-new)
  5790. (inherit check-type-equal?)
  5791. (define/override (type-check-exp env)
  5792. (lambda (e)
  5793. (define recur (type-check-exp env))
  5794. (match e
  5795. [(Void) (values (Void) 'Void)]
  5796. [(Prim 'vector es)
  5797. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  5798. (define t `(Vector ,@t*))
  5799. (values (HasType (Prim 'vector e*) t) t)]
  5800. [(Prim 'vector-ref (list e1 (Int i)))
  5801. (define-values (e1^ t) (recur e1))
  5802. (match t
  5803. [`(Vector ,ts ...)
  5804. (unless (and (0 . <= . i) (i . < . (length ts)))
  5805. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  5806. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  5807. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  5808. [(Prim 'vector-set! (list e1 (Int i) arg) )
  5809. (define-values (e-vec t-vec) (recur e1))
  5810. (define-values (e-arg^ t-arg) (recur arg))
  5811. (match t-vec
  5812. [`(Vector ,ts ...)
  5813. (unless (and (0 . <= . i) (i . < . (length ts)))
  5814. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  5815. (check-type-equal? (list-ref ts i) t-arg e)
  5816. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  5817. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  5818. [(Prim 'vector-length (list e))
  5819. (define-values (e^ t) (recur e))
  5820. (match t
  5821. [`(Vector ,ts ...)
  5822. (values (Prim 'vector-length (list e^)) 'Integer)]
  5823. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  5824. [(Prim 'eq? (list arg1 arg2))
  5825. (define-values (e1 t1) (recur arg1))
  5826. (define-values (e2 t2) (recur arg2))
  5827. (match* (t1 t2)
  5828. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  5829. [(other wise) (check-type-equal? t1 t2 e)])
  5830. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  5831. [(HasType (Prim 'vector es) t)
  5832. ((type-check-exp env) (Prim 'vector es))]
  5833. [(HasType e1 t)
  5834. (define-values (e1^ t^) (recur e1))
  5835. (check-type-equal? t t^ e)
  5836. (values (HasType e1^ t) t)]
  5837. [else ((super type-check-exp env) e)]
  5838. )))
  5839. ))
  5840. (define (type-check-Rvec p)
  5841. (send (new type-check-Rvec-class) type-check-program p))
  5842. \end{lstlisting}
  5843. \caption{Type checker for the \LangVec{} language.}
  5844. \label{fig:type-check-Rvec}
  5845. \end{figure}
  5846. \section{Garbage Collection}
  5847. \label{sec:GC}
  5848. Here we study a relatively simple algorithm for garbage collection
  5849. that is the basis of state-of-the-art garbage
  5850. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  5851. particular, we describe a two-space copying
  5852. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  5853. perform the
  5854. copy~\citep{Cheney:1970aa}.
  5855. \index{copying collector}
  5856. \index{two-space copying collector}
  5857. Figure~\ref{fig:copying-collector} gives a
  5858. coarse-grained depiction of what happens in a two-space collector,
  5859. showing two time steps, prior to garbage collection (on the top) and
  5860. after garbage collection (on the bottom). In a two-space collector,
  5861. the heap is divided into two parts named the FromSpace and the
  5862. ToSpace. Initially, all allocations go to the FromSpace until there is
  5863. not enough room for the next allocation request. At that point, the
  5864. garbage collector goes to work to make more room.
  5865. \index{ToSpace}
  5866. \index{FromSpace}
  5867. The garbage collector must be careful not to reclaim tuples that will
  5868. be used by the program in the future. Of course, it is impossible in
  5869. general to predict what a program will do, but we can over approximate
  5870. the will-be-used tuples by preserving all tuples that could be
  5871. accessed by \emph{any} program given the current computer state. A
  5872. program could access any tuple whose address is in a register or on
  5873. the procedure call stack. These addresses are called the \emph{root
  5874. set}\index{root set}. In addition, a program could access any tuple that is
  5875. transitively reachable from the root set. Thus, it is safe for the
  5876. garbage collector to reclaim the tuples that are not reachable in this
  5877. way.
  5878. So the goal of the garbage collector is twofold:
  5879. \begin{enumerate}
  5880. \item preserve all tuple that are reachable from the root set via a
  5881. path of pointers, that is, the \emph{live} tuples, and
  5882. \item reclaim the memory of everything else, that is, the
  5883. \emph{garbage}.
  5884. \end{enumerate}
  5885. A copying collector accomplishes this by copying all of the live
  5886. objects from the FromSpace into the ToSpace and then performs a sleight
  5887. of hand, treating the ToSpace as the new FromSpace and the old
  5888. FromSpace as the new ToSpace. In the example of
  5889. Figure~\ref{fig:copying-collector}, there are three pointers in the
  5890. root set, one in a register and two on the stack. All of the live
  5891. objects have been copied to the ToSpace (the right-hand side of
  5892. Figure~\ref{fig:copying-collector}) in a way that preserves the
  5893. pointer relationships. For example, the pointer in the register still
  5894. points to a 2-tuple whose first element is a 3-tuple and whose second
  5895. element is a 2-tuple. There are four tuples that are not reachable
  5896. from the root set and therefore do not get copied into the ToSpace.
  5897. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  5898. created by a well-typed program in \LangVec{} because it contains a
  5899. cycle. However, creating cycles will be possible once we get to \LangAny{}.
  5900. We design the garbage collector to deal with cycles to begin with so
  5901. we will not need to revisit this issue.
  5902. \begin{figure}[tbp]
  5903. \centering
  5904. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  5905. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  5906. \caption{A copying collector in action.}
  5907. \label{fig:copying-collector}
  5908. \end{figure}
  5909. There are many alternatives to copying collectors (and their bigger
  5910. siblings, the generational collectors) when its comes to garbage
  5911. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  5912. reference counting~\citep{Collins:1960aa}. The strengths of copying
  5913. collectors are that allocation is fast (just a comparison and pointer
  5914. increment), there is no fragmentation, cyclic garbage is collected,
  5915. and the time complexity of collection only depends on the amount of
  5916. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  5917. main disadvantages of a two-space copying collector is that it uses a
  5918. lot of space and takes a long time to perform the copy, though these
  5919. problems are ameliorated in generational collectors. Racket and
  5920. Scheme programs tend to allocate many small objects and generate a lot
  5921. of garbage, so copying and generational collectors are a good fit.
  5922. Garbage collection is an active research topic, especially concurrent
  5923. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  5924. developing new techniques and revisiting old
  5925. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  5926. meet every year at the International Symposium on Memory Management to
  5927. present these findings.
  5928. \subsection{Graph Copying via Cheney's Algorithm}
  5929. \label{sec:cheney}
  5930. \index{Cheney's algorithm}
  5931. Let us take a closer look at the copying of the live objects. The
  5932. allocated objects and pointers can be viewed as a graph and we need to
  5933. copy the part of the graph that is reachable from the root set. To
  5934. make sure we copy all of the reachable vertices in the graph, we need
  5935. an exhaustive graph traversal algorithm, such as depth-first search or
  5936. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  5937. such algorithms take into account the possibility of cycles by marking
  5938. which vertices have already been visited, so as to ensure termination
  5939. of the algorithm. These search algorithms also use a data structure
  5940. such as a stack or queue as a to-do list to keep track of the vertices
  5941. that need to be visited. We use breadth-first search and a trick
  5942. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  5943. and copying tuples into the ToSpace.
  5944. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  5945. copy progresses. The queue is represented by a chunk of contiguous
  5946. memory at the beginning of the ToSpace, using two pointers to track
  5947. the front and the back of the queue. The algorithm starts by copying
  5948. all tuples that are immediately reachable from the root set into the
  5949. ToSpace to form the initial queue. When we copy a tuple, we mark the
  5950. old tuple to indicate that it has been visited. We discuss how this
  5951. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  5952. pointers inside the copied tuples in the queue still point back to the
  5953. FromSpace. Once the initial queue has been created, the algorithm
  5954. enters a loop in which it repeatedly processes the tuple at the front
  5955. of the queue and pops it off the queue. To process a tuple, the
  5956. algorithm copies all the tuple that are directly reachable from it to
  5957. the ToSpace, placing them at the back of the queue. The algorithm then
  5958. updates the pointers in the popped tuple so they point to the newly
  5959. copied tuples.
  5960. \begin{figure}[tbp]
  5961. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  5962. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  5963. \label{fig:cheney}
  5964. \end{figure}
  5965. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  5966. tuple whose second element is $42$ to the back of the queue. The other
  5967. pointer goes to a tuple that has already been copied, so we do not
  5968. need to copy it again, but we do need to update the pointer to the new
  5969. location. This can be accomplished by storing a \emph{forwarding
  5970. pointer} to the new location in the old tuple, back when we initially
  5971. copied the tuple into the ToSpace. This completes one step of the
  5972. algorithm. The algorithm continues in this way until the front of the
  5973. queue is empty, that is, until the front catches up with the back.
  5974. \subsection{Data Representation}
  5975. \label{sec:data-rep-gc}
  5976. The garbage collector places some requirements on the data
  5977. representations used by our compiler. First, the garbage collector
  5978. needs to distinguish between pointers and other kinds of data. There
  5979. are several ways to accomplish this.
  5980. \begin{enumerate}
  5981. \item Attached a tag to each object that identifies what type of
  5982. object it is~\citep{McCarthy:1960dz}.
  5983. \item Store different types of objects in different
  5984. regions~\citep{Steele:1977ab}.
  5985. \item Use type information from the program to either generate
  5986. type-specific code for collecting or to generate tables that can
  5987. guide the
  5988. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  5989. \end{enumerate}
  5990. Dynamically typed languages, such as Lisp, need to tag objects
  5991. anyways, so option 1 is a natural choice for those languages.
  5992. However, \LangVec{} is a statically typed language, so it would be
  5993. unfortunate to require tags on every object, especially small and
  5994. pervasive objects like integers and Booleans. Option 3 is the
  5995. best-performing choice for statically typed languages, but comes with
  5996. a relatively high implementation complexity. To keep this chapter
  5997. within a 2-week time budget, we recommend a combination of options 1
  5998. and 2, using separate strategies for the stack and the heap.
  5999. Regarding the stack, we recommend using a separate stack for pointers,
  6000. which we call a \emph{root stack}\index{root stack} (a.k.a. ``shadow
  6001. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  6002. is, when a local variable needs to be spilled and is of type
  6003. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  6004. stack instead of the normal procedure call stack. Furthermore, we
  6005. always spill vector-typed variables if they are live during a call to
  6006. the collector, thereby ensuring that no pointers are in registers
  6007. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  6008. example from Figure~\ref{fig:copying-collector} and contrasts it with
  6009. the data layout using a root stack. The root stack contains the two
  6010. pointers from the regular stack and also the pointer in the second
  6011. register.
  6012. \begin{figure}[tbp]
  6013. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  6014. \caption{Maintaining a root stack to facilitate garbage collection.}
  6015. \label{fig:shadow-stack}
  6016. \end{figure}
  6017. The problem of distinguishing between pointers and other kinds of data
  6018. also arises inside of each tuple on the heap. We solve this problem by
  6019. attaching a tag, an extra 64-bits, to each
  6020. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  6021. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  6022. that we have drawn the bits in a big-endian way, from right-to-left,
  6023. with bit location 0 (the least significant bit) on the far right,
  6024. which corresponds to the direction of the x86 shifting instructions
  6025. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  6026. is dedicated to specifying which elements of the tuple are pointers,
  6027. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  6028. indicates there is a pointer and a 0 bit indicates some other kind of
  6029. data. The pointer mask starts at bit location 7. We have limited
  6030. tuples to a maximum size of 50 elements, so we just need 50 bits for
  6031. the pointer mask. The tag also contains two other pieces of
  6032. information. The length of the tuple (number of elements) is stored in
  6033. bits location 1 through 6. Finally, the bit at location 0 indicates
  6034. whether the tuple has yet to be copied to the ToSpace. If the bit has
  6035. value 1, then this tuple has not yet been copied. If the bit has
  6036. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  6037. of a pointer are always zero anyways because our tuples are 8-byte
  6038. aligned.)
  6039. \begin{figure}[tbp]
  6040. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  6041. \caption{Representation of tuples in the heap.}
  6042. \label{fig:tuple-rep}
  6043. \end{figure}
  6044. \subsection{Implementation of the Garbage Collector}
  6045. \label{sec:organize-gz}
  6046. \index{prelude}
  6047. An implementation of the copying collector is provided in the
  6048. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  6049. interface to the garbage collector that is used by the compiler. The
  6050. \code{initialize} function creates the FromSpace, ToSpace, and root
  6051. stack and should be called in the prelude of the \code{main}
  6052. function. The arguments of \code{initialize} are the root stack size
  6053. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  6054. good choice for both. The \code{initialize} function puts the address
  6055. of the beginning of the FromSpace into the global variable
  6056. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  6057. the address that is 1-past the last element of the FromSpace. (We use
  6058. half-open intervals to represent chunks of
  6059. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  6060. points to the first element of the root stack.
  6061. As long as there is room left in the FromSpace, your generated code
  6062. can allocate tuples simply by moving the \code{free\_ptr} forward.
  6063. %
  6064. The amount of room left in FromSpace is the difference between the
  6065. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  6066. function should be called when there is not enough room left in the
  6067. FromSpace for the next allocation. The \code{collect} function takes
  6068. a pointer to the current top of the root stack (one past the last item
  6069. that was pushed) and the number of bytes that need to be
  6070. allocated. The \code{collect} function performs the copying collection
  6071. and leaves the heap in a state such that the next allocation will
  6072. succeed.
  6073. \begin{figure}[tbp]
  6074. \begin{lstlisting}
  6075. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  6076. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  6077. int64_t* free_ptr;
  6078. int64_t* fromspace_begin;
  6079. int64_t* fromspace_end;
  6080. int64_t** rootstack_begin;
  6081. \end{lstlisting}
  6082. \caption{The compiler's interface to the garbage collector.}
  6083. \label{fig:gc-header}
  6084. \end{figure}
  6085. %% \begin{exercise}
  6086. %% In the file \code{runtime.c} you will find the implementation of
  6087. %% \code{initialize} and a partial implementation of \code{collect}.
  6088. %% The \code{collect} function calls another function, \code{cheney},
  6089. %% to perform the actual copy, and that function is left to the reader
  6090. %% to implement. The following is the prototype for \code{cheney}.
  6091. %% \begin{lstlisting}
  6092. %% static void cheney(int64_t** rootstack_ptr);
  6093. %% \end{lstlisting}
  6094. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  6095. %% rootstack (which is an array of pointers). The \code{cheney} function
  6096. %% also communicates with \code{collect} through the global
  6097. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  6098. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  6099. %% the ToSpace:
  6100. %% \begin{lstlisting}
  6101. %% static int64_t* tospace_begin;
  6102. %% static int64_t* tospace_end;
  6103. %% \end{lstlisting}
  6104. %% The job of the \code{cheney} function is to copy all the live
  6105. %% objects (reachable from the root stack) into the ToSpace, update
  6106. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  6107. %% update the root stack so that it points to the objects in the
  6108. %% ToSpace, and finally to swap the global pointers for the FromSpace
  6109. %% and ToSpace.
  6110. %% \end{exercise}
  6111. %% \section{Compiler Passes}
  6112. %% \label{sec:code-generation-gc}
  6113. The introduction of garbage collection has a non-trivial impact on our
  6114. compiler passes. We introduce a new compiler pass named
  6115. \code{expose-allocation}. We make
  6116. significant changes to \code{select-instructions},
  6117. \code{build-interference}, \code{allocate-registers}, and
  6118. \code{print-x86} and make minor changes in several more passes. The
  6119. following program will serve as our running example. It creates two
  6120. tuples, one nested inside the other. Both tuples have length one. The
  6121. program accesses the element in the inner tuple tuple via two vector
  6122. references.
  6123. % tests/s2_17.rkt
  6124. \begin{lstlisting}
  6125. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  6126. \end{lstlisting}
  6127. \section{Shrink}
  6128. \label{sec:shrink-Rvec}
  6129. Recall that the \code{shrink} pass translates the primitives operators
  6130. into a smaller set of primitives. Because this pass comes after type
  6131. checking, but before the passes that require the type information in
  6132. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  6133. to wrap \code{HasType} around each AST node that it generates.
  6134. \section{Expose Allocation}
  6135. \label{sec:expose-allocation}
  6136. The pass \code{expose-allocation} lowers the \code{vector} creation
  6137. form into a conditional call to the collector followed by the
  6138. allocation. We choose to place the \code{expose-allocation} pass
  6139. before \code{remove-complex-opera*} because the code generated by
  6140. \code{expose-allocation} contains complex operands. We also place
  6141. \code{expose-allocation} before \code{explicate-control} because
  6142. \code{expose-allocation} introduces new variables using \code{let},
  6143. but \code{let} is gone after \code{explicate-control}.
  6144. The output of \code{expose-allocation} is a language \LangAlloc{} that
  6145. extends \LangVec{} with the three new forms that we use in the translation
  6146. of the \code{vector} form.
  6147. \[
  6148. \begin{array}{lcl}
  6149. \Exp &::=& \cdots
  6150. \mid (\key{collect} \,\itm{int})
  6151. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  6152. \mid (\key{global-value} \,\itm{name})
  6153. \end{array}
  6154. \]
  6155. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  6156. $n$ bytes. It will become a call to the \code{collect} function in
  6157. \code{runtime.c} in \code{select-instructions}. The
  6158. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  6159. \index{allocate}
  6160. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  6161. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  6162. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  6163. a global variable, such as \code{free\_ptr}.
  6164. In the following, we show the transformation for the \code{vector}
  6165. form into 1) a sequence of let-bindings for the initializing
  6166. expressions, 2) a conditional call to \code{collect}, 3) a call to
  6167. \code{allocate}, and 4) the initialization of the vector. In the
  6168. following, \itm{len} refers to the length of the vector and
  6169. \itm{bytes} is how many total bytes need to be allocated for the
  6170. vector, which is 8 for the tag plus \itm{len} times 8.
  6171. \begin{lstlisting}
  6172. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  6173. |$\Longrightarrow$|
  6174. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  6175. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  6176. (global-value fromspace_end))
  6177. (void)
  6178. (collect |\itm{bytes}|))])
  6179. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  6180. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  6181. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  6182. |$v$|) ... )))) ...)
  6183. \end{lstlisting}
  6184. In the above, we suppressed all of the \code{has-type} forms in the
  6185. output for the sake of readability. The placement of the initializing
  6186. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  6187. sequence of \code{vector-set!} is important, as those expressions may
  6188. trigger garbage collection and we cannot have an allocated but
  6189. uninitialized tuple on the heap during a collection.
  6190. Figure~\ref{fig:expose-alloc-output} shows the output of the
  6191. \code{expose-allocation} pass on our running example.
  6192. \begin{figure}[tbp]
  6193. % tests/s2_17.rkt
  6194. \begin{lstlisting}
  6195. (vector-ref
  6196. (vector-ref
  6197. (let ([vecinit7976
  6198. (let ([vecinit7972 42])
  6199. (let ([collectret7974
  6200. (if (< (+ (global-value free_ptr) 16)
  6201. (global-value fromspace_end))
  6202. (void)
  6203. (collect 16)
  6204. )])
  6205. (let ([alloc7971 (allocate 1 (Vector Integer))])
  6206. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  6207. alloc7971)
  6208. )
  6209. )
  6210. )
  6211. ])
  6212. (let ([collectret7978
  6213. (if (< (+ (global-value free_ptr) 16)
  6214. (global-value fromspace_end))
  6215. (void)
  6216. (collect 16)
  6217. )])
  6218. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  6219. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  6220. alloc7975)
  6221. )
  6222. )
  6223. )
  6224. 0)
  6225. 0)
  6226. \end{lstlisting}
  6227. \caption{Output of the \code{expose-allocation} pass, minus
  6228. all of the \code{has-type} forms.}
  6229. \label{fig:expose-alloc-output}
  6230. \end{figure}
  6231. \section{Remove Complex Operands}
  6232. \label{sec:remove-complex-opera-Rvec}
  6233. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  6234. should all be treated as complex operands.
  6235. %% A new case for
  6236. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  6237. %% handled carefully to prevent the \code{Prim} node from being separated
  6238. %% from its enclosing \code{HasType}.
  6239. Figure~\ref{fig:Rvec-anf-syntax}
  6240. shows the grammar for the output language \LangVecANF{} of this
  6241. pass, which is \LangVec{} in administrative normal form.
  6242. \begin{figure}[tp]
  6243. \centering
  6244. \fbox{
  6245. \begin{minipage}{0.96\textwidth}
  6246. \small
  6247. \[
  6248. \begin{array}{rcl}
  6249. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }
  6250. \mid \VOID{} \\
  6251. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  6252. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  6253. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  6254. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  6255. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  6256. &\mid& \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  6257. \mid \LP\key{GlobalValue}~\Var\RP\\
  6258. % &\mid& \LP\key{HasType}~\Exp~\Type\RP \\
  6259. R^{\dagger}_3 &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  6260. \end{array}
  6261. \]
  6262. \end{minipage}
  6263. }
  6264. \caption{\LangVecANF{} is \LangVec{} in administrative normal form (ANF).}
  6265. \label{fig:Rvec-anf-syntax}
  6266. \end{figure}
  6267. \section{Explicate Control and the \LangCVec{} language}
  6268. \label{sec:explicate-control-r3}
  6269. \begin{figure}[tp]
  6270. \fbox{
  6271. \begin{minipage}{0.96\textwidth}
  6272. \small
  6273. \[
  6274. \begin{array}{lcl}
  6275. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  6276. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  6277. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  6278. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  6279. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  6280. &\mid& \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  6281. &\mid& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  6282. &\mid& \LP\key{Prim}~\key{'vector-set!}\,\LP\Atm\,\INT{\Int}\,\Atm\RP\RP\\
  6283. &\mid& \LP\key{GlobalValue} \,\Var\RP \mid \LP\key{Void}\RP\\
  6284. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  6285. \mid \LP\key{Collect} \,\itm{int}\RP \\
  6286. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  6287. \mid \GOTO{\itm{label}} } \\
  6288. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  6289. \LangCVec{} & ::= & \gray{ \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }
  6290. \end{array}
  6291. \]
  6292. \end{minipage}
  6293. }
  6294. \caption{The abstract syntax of \LangCVec{}, extending \LangCIf{}
  6295. (Figure~\ref{fig:c1-syntax}).}
  6296. \label{fig:c2-syntax}
  6297. \end{figure}
  6298. The output of \code{explicate-control} is a program in the
  6299. intermediate language \LangCVec{}, whose abstract syntax is defined in
  6300. Figure~\ref{fig:c2-syntax}. (The concrete syntax is defined in
  6301. Figure~\ref{fig:c2-concrete-syntax} of the Appendix.) The new forms
  6302. of \LangCVec{} include the \key{allocate}, \key{vector-ref}, and
  6303. \key{vector-set!}, and \key{global-value} expressions and the
  6304. \code{collect} statement. The \code{explicate-control} pass can treat
  6305. these new forms much like the other expression forms that we've
  6306. already encoutered.
  6307. \section{Select Instructions and the \LangXGlobal{} Language}
  6308. \label{sec:select-instructions-gc}
  6309. \index{instruction selection}
  6310. %% void (rep as zero)
  6311. %% allocate
  6312. %% collect (callq collect)
  6313. %% vector-ref
  6314. %% vector-set!
  6315. %% global (postpone)
  6316. In this pass we generate x86 code for most of the new operations that
  6317. were needed to compile tuples, including \code{Allocate},
  6318. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  6319. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  6320. the later has a different concrete syntax (see
  6321. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  6322. \index{x86}
  6323. The \code{vector-ref} and \code{vector-set!} forms translate into
  6324. \code{movq} instructions. (The plus one in the offset is to get past
  6325. the tag at the beginning of the tuple representation.)
  6326. \begin{lstlisting}
  6327. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  6328. |$\Longrightarrow$|
  6329. movq |$\itm{vec}'$|, %r11
  6330. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  6331. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  6332. |$\Longrightarrow$|
  6333. movq |$\itm{vec}'$|, %r11
  6334. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  6335. movq $0, |$\itm{lhs'}$|
  6336. \end{lstlisting}
  6337. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  6338. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  6339. register \code{r11} ensures that offset expression
  6340. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  6341. removing \code{r11} from consideration by the register allocating.
  6342. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  6343. \code{rax}. Then the generated code for \code{vector-set!} would be
  6344. \begin{lstlisting}
  6345. movq |$\itm{vec}'$|, %rax
  6346. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  6347. movq $0, |$\itm{lhs}'$|
  6348. \end{lstlisting}
  6349. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  6350. \code{patch-instructions} would insert a move through \code{rax}
  6351. as follows.
  6352. \begin{lstlisting}
  6353. movq |$\itm{vec}'$|, %rax
  6354. movq |$\itm{arg}'$|, %rax
  6355. movq %rax, |$8(n+1)$|(%rax)
  6356. movq $0, |$\itm{lhs}'$|
  6357. \end{lstlisting}
  6358. But the above sequence of instructions does not work because we're
  6359. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  6360. $\itm{arg}'$) at the same time!
  6361. We compile the \code{allocate} form to operations on the
  6362. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  6363. is the next free address in the FromSpace, so we copy it into
  6364. \code{r11} and then move it forward by enough space for the tuple
  6365. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  6366. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  6367. initialize the \itm{tag} and finally copy the address in \code{r11} to
  6368. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  6369. tag is organized. We recommend using the Racket operations
  6370. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  6371. during compilation. The type annotation in the \code{vector} form is
  6372. used to determine the pointer mask region of the tag.
  6373. \begin{lstlisting}
  6374. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  6375. |$\Longrightarrow$|
  6376. movq free_ptr(%rip), %r11
  6377. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  6378. movq $|$\itm{tag}$|, 0(%r11)
  6379. movq %r11, |$\itm{lhs}'$|
  6380. \end{lstlisting}
  6381. The \code{collect} form is compiled to a call to the \code{collect}
  6382. function in the runtime. The arguments to \code{collect} are 1) the
  6383. top of the root stack and 2) the number of bytes that need to be
  6384. allocated. We use another dedicated register, \code{r15}, to
  6385. store the pointer to the top of the root stack. So \code{r15} is not
  6386. available for use by the register allocator.
  6387. \begin{lstlisting}
  6388. (collect |$\itm{bytes}$|)
  6389. |$\Longrightarrow$|
  6390. movq %r15, %rdi
  6391. movq $|\itm{bytes}|, %rsi
  6392. callq collect
  6393. \end{lstlisting}
  6394. \begin{figure}[tp]
  6395. \fbox{
  6396. \begin{minipage}{0.96\textwidth}
  6397. \[
  6398. \begin{array}{lcl}
  6399. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)} \\
  6400. \LangXGlobal{} &::= & \gray{ \key{.globl main} }\\
  6401. & & \gray{ \key{main:} \; \Instr\ldots }
  6402. \end{array}
  6403. \]
  6404. \end{minipage}
  6405. }
  6406. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  6407. \label{fig:x86-2-concrete}
  6408. \end{figure}
  6409. \begin{figure}[tp]
  6410. \fbox{
  6411. \begin{minipage}{0.96\textwidth}
  6412. \small
  6413. \[
  6414. \begin{array}{lcl}
  6415. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  6416. \mid \BYTEREG{\Reg}} \\
  6417. &\mid& (\key{Global}~\Var) \\
  6418. \LangXGlobal{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  6419. \end{array}
  6420. \]
  6421. \end{minipage}
  6422. }
  6423. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  6424. \label{fig:x86-2}
  6425. \end{figure}
  6426. The concrete and abstract syntax of the \LangXGlobal{} language is
  6427. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  6428. differs from \LangXIf{} just in the addition of the form for global
  6429. variables.
  6430. %
  6431. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  6432. \code{select-instructions} pass on the running example.
  6433. \begin{figure}[tbp]
  6434. \centering
  6435. % tests/s2_17.rkt
  6436. \begin{minipage}[t]{0.5\textwidth}
  6437. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6438. block35:
  6439. movq free_ptr(%rip), alloc9024
  6440. addq $16, free_ptr(%rip)
  6441. movq alloc9024, %r11
  6442. movq $131, 0(%r11)
  6443. movq alloc9024, %r11
  6444. movq vecinit9025, 8(%r11)
  6445. movq $0, initret9026
  6446. movq alloc9024, %r11
  6447. movq 8(%r11), tmp9034
  6448. movq tmp9034, %r11
  6449. movq 8(%r11), %rax
  6450. jmp conclusion
  6451. block36:
  6452. movq $0, collectret9027
  6453. jmp block35
  6454. block38:
  6455. movq free_ptr(%rip), alloc9020
  6456. addq $16, free_ptr(%rip)
  6457. movq alloc9020, %r11
  6458. movq $3, 0(%r11)
  6459. movq alloc9020, %r11
  6460. movq vecinit9021, 8(%r11)
  6461. movq $0, initret9022
  6462. movq alloc9020, vecinit9025
  6463. movq free_ptr(%rip), tmp9031
  6464. movq tmp9031, tmp9032
  6465. addq $16, tmp9032
  6466. movq fromspace_end(%rip), tmp9033
  6467. cmpq tmp9033, tmp9032
  6468. jl block36
  6469. jmp block37
  6470. block37:
  6471. movq %r15, %rdi
  6472. movq $16, %rsi
  6473. callq 'collect
  6474. jmp block35
  6475. block39:
  6476. movq $0, collectret9023
  6477. jmp block38
  6478. \end{lstlisting}
  6479. \end{minipage}
  6480. \begin{minipage}[t]{0.45\textwidth}
  6481. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6482. start:
  6483. movq $42, vecinit9021
  6484. movq free_ptr(%rip), tmp9028
  6485. movq tmp9028, tmp9029
  6486. addq $16, tmp9029
  6487. movq fromspace_end(%rip), tmp9030
  6488. cmpq tmp9030, tmp9029
  6489. jl block39
  6490. jmp block40
  6491. block40:
  6492. movq %r15, %rdi
  6493. movq $16, %rsi
  6494. callq 'collect
  6495. jmp block38
  6496. \end{lstlisting}
  6497. \end{minipage}
  6498. \caption{Output of the \code{select-instructions} pass.}
  6499. \label{fig:select-instr-output-gc}
  6500. \end{figure}
  6501. \clearpage
  6502. \section{Register Allocation}
  6503. \label{sec:reg-alloc-gc}
  6504. \index{register allocation}
  6505. As discussed earlier in this chapter, the garbage collector needs to
  6506. access all the pointers in the root set, that is, all variables that
  6507. are vectors. It will be the responsibility of the register allocator
  6508. to make sure that:
  6509. \begin{enumerate}
  6510. \item the root stack is used for spilling vector-typed variables, and
  6511. \item if a vector-typed variable is live during a call to the
  6512. collector, it must be spilled to ensure it is visible to the
  6513. collector.
  6514. \end{enumerate}
  6515. The later responsibility can be handled during construction of the
  6516. interference graph, by adding interference edges between the call-live
  6517. vector-typed variables and all the callee-saved registers. (They
  6518. already interfere with the caller-saved registers.) The type
  6519. information for variables is in the \code{Program} form, so we
  6520. recommend adding another parameter to the \code{build-interference}
  6521. function to communicate this alist.
  6522. The spilling of vector-typed variables to the root stack can be
  6523. handled after graph coloring, when choosing how to assign the colors
  6524. (integers) to registers and stack locations. The \code{Program} output
  6525. of this pass changes to also record the number of spills to the root
  6526. stack.
  6527. % build-interference
  6528. %
  6529. % callq
  6530. % extra parameter for var->type assoc. list
  6531. % update 'program' and 'if'
  6532. % allocate-registers
  6533. % allocate spilled vectors to the rootstack
  6534. % don't change color-graph
  6535. \section{Print x86}
  6536. \label{sec:print-x86-gc}
  6537. \index{prelude}\index{conclusion}
  6538. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  6539. \code{print-x86} pass on the running example. In the prelude and
  6540. conclusion of the \code{main} function, we treat the root stack very
  6541. much like the regular stack in that we move the root stack pointer
  6542. (\code{r15}) to make room for the spills to the root stack, except
  6543. that the root stack grows up instead of down. For the running
  6544. example, there was just one spill so we increment \code{r15} by 8
  6545. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  6546. One issue that deserves special care is that there may be a call to
  6547. \code{collect} prior to the initializing assignments for all the
  6548. variables in the root stack. We do not want the garbage collector to
  6549. accidentally think that some uninitialized variable is a pointer that
  6550. needs to be followed. Thus, we zero-out all locations on the root
  6551. stack in the prelude of \code{main}. In
  6552. Figure~\ref{fig:print-x86-output-gc}, the instruction
  6553. %
  6554. \lstinline{movq $0, (%r15)}
  6555. %
  6556. accomplishes this task. The garbage collector tests each root to see
  6557. if it is null prior to dereferencing it.
  6558. \begin{figure}[htbp]
  6559. \begin{minipage}[t]{0.5\textwidth}
  6560. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6561. block35:
  6562. movq free_ptr(%rip), %rcx
  6563. addq $16, free_ptr(%rip)
  6564. movq %rcx, %r11
  6565. movq $131, 0(%r11)
  6566. movq %rcx, %r11
  6567. movq -8(%r15), %rax
  6568. movq %rax, 8(%r11)
  6569. movq $0, %rdx
  6570. movq %rcx, %r11
  6571. movq 8(%r11), %rcx
  6572. movq %rcx, %r11
  6573. movq 8(%r11), %rax
  6574. jmp conclusion
  6575. block36:
  6576. movq $0, %rcx
  6577. jmp block35
  6578. block38:
  6579. movq free_ptr(%rip), %rcx
  6580. addq $16, free_ptr(%rip)
  6581. movq %rcx, %r11
  6582. movq $3, 0(%r11)
  6583. movq %rcx, %r11
  6584. movq %rbx, 8(%r11)
  6585. movq $0, %rdx
  6586. movq %rcx, -8(%r15)
  6587. movq free_ptr(%rip), %rcx
  6588. addq $16, %rcx
  6589. movq fromspace_end(%rip), %rdx
  6590. cmpq %rdx, %rcx
  6591. jl block36
  6592. movq %r15, %rdi
  6593. movq $16, %rsi
  6594. callq collect
  6595. jmp block35
  6596. block39:
  6597. movq $0, %rcx
  6598. jmp block38
  6599. \end{lstlisting}
  6600. \end{minipage}
  6601. \begin{minipage}[t]{0.45\textwidth}
  6602. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6603. start:
  6604. movq $42, %rbx
  6605. movq free_ptr(%rip), %rdx
  6606. addq $16, %rdx
  6607. movq fromspace_end(%rip), %rcx
  6608. cmpq %rcx, %rdx
  6609. jl block39
  6610. movq %r15, %rdi
  6611. movq $16, %rsi
  6612. callq collect
  6613. jmp block38
  6614. .globl main
  6615. main:
  6616. pushq %rbp
  6617. movq %rsp, %rbp
  6618. pushq %r13
  6619. pushq %r12
  6620. pushq %rbx
  6621. pushq %r14
  6622. subq $0, %rsp
  6623. movq $16384, %rdi
  6624. movq $16384, %rsi
  6625. callq initialize
  6626. movq rootstack_begin(%rip), %r15
  6627. movq $0, (%r15)
  6628. addq $8, %r15
  6629. jmp start
  6630. conclusion:
  6631. subq $8, %r15
  6632. addq $0, %rsp
  6633. popq %r14
  6634. popq %rbx
  6635. popq %r12
  6636. popq %r13
  6637. popq %rbp
  6638. retq
  6639. \end{lstlisting}
  6640. \end{minipage}
  6641. \caption{Output of the \code{print-x86} pass.}
  6642. \label{fig:print-x86-output-gc}
  6643. \end{figure}
  6644. \begin{figure}[p]
  6645. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6646. \node (Rvec) at (0,2) {\large \LangVec{}};
  6647. \node (Rvec-2) at (3,2) {\large \LangVec{}};
  6648. \node (Rvec-3) at (6,2) {\large \LangVec{}};
  6649. \node (Rvec-4) at (9,2) {\large \LangVec{}};
  6650. \node (Rvec-5) at (12,2) {\large \LangAlloc{}};
  6651. \node (C2-4) at (3,0) {\large \LangCVec{}};
  6652. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  6653. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  6654. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  6655. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  6656. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  6657. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  6658. %\path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize type-check} (Rvec-2);
  6659. \path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize shrink} (Rvec-2);
  6660. \path[->,bend left=15] (Rvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Rvec-3);
  6661. \path[->,bend left=15] (Rvec-3) edge [above] node {\ttfamily\footnotesize expose-alloc.} (Rvec-4);
  6662. \path[->,bend left=15] (Rvec-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvec-5);
  6663. \path[->,bend left=20] (Rvec-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-4);
  6664. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select-instr.} (x86-2);
  6665. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6666. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  6667. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6668. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  6669. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  6670. \end{tikzpicture}
  6671. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  6672. \label{fig:Rvec-passes}
  6673. \end{figure}
  6674. Figure~\ref{fig:Rvec-passes} gives an overview of all the passes needed
  6675. for the compilation of \LangVec{}.
  6676. \section{Challenge: Simple Structures}
  6677. \label{sec:simple-structures}
  6678. \index{struct}
  6679. \index{structure}
  6680. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  6681. \LangStruct{}, which extends \LangVec{} with support for simple structures.
  6682. Recall that a \code{struct} in Typed Racket is a user-defined data
  6683. type that contains named fields and that is heap allocated, similar to
  6684. a vector. The following is an example of a structure definition, in
  6685. this case the definition of a \code{point} type.
  6686. \begin{lstlisting}
  6687. (struct point ([x : Integer] [y : Integer]) #:mutable)
  6688. \end{lstlisting}
  6689. \begin{figure}[tbp]
  6690. \centering
  6691. \fbox{
  6692. \begin{minipage}{0.96\textwidth}
  6693. \[
  6694. \begin{array}{lcl}
  6695. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6696. \mid (\key{Vector}\;\Type \ldots) \mid \key{Void} } \mid \Var \\
  6697. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6698. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  6699. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  6700. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6701. \mid (\key{and}\;\Exp\;\Exp)
  6702. \mid (\key{or}\;\Exp\;\Exp)
  6703. \mid (\key{not}\;\Exp) } \\
  6704. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  6705. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  6706. &\mid& \gray{ (\key{vector}\;\Exp \ldots)
  6707. \mid (\key{vector-ref}\;\Exp\;\Int) } \\
  6708. &\mid& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  6709. &\mid& \gray{ (\key{void}) } \mid (\Var\;\Exp \ldots)\\
  6710. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  6711. \LangStruct{} &::=& \Def \ldots \; \Exp
  6712. \end{array}
  6713. \]
  6714. \end{minipage}
  6715. }
  6716. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  6717. (Figure~\ref{fig:Rvec-concrete-syntax}).}
  6718. \label{fig:r3s-concrete-syntax}
  6719. \end{figure}
  6720. An instance of a structure is created using function call syntax, with
  6721. the name of the structure in the function position:
  6722. \begin{lstlisting}
  6723. (point 7 12)
  6724. \end{lstlisting}
  6725. Function-call syntax is also used to read the value in a field of a
  6726. structure. The function name is formed by the structure name, a dash,
  6727. and the field name. The following example uses \code{point-x} and
  6728. \code{point-y} to access the \code{x} and \code{y} fields of two point
  6729. instances.
  6730. \begin{center}
  6731. \begin{lstlisting}
  6732. (let ([pt1 (point 7 12)])
  6733. (let ([pt2 (point 4 3)])
  6734. (+ (- (point-x pt1) (point-x pt2))
  6735. (- (point-y pt1) (point-y pt2)))))
  6736. \end{lstlisting}
  6737. \end{center}
  6738. Similarly, to write to a field of a structure, use its set function,
  6739. whose name starts with \code{set-}, followed by the structure name,
  6740. then a dash, then the field name, and concluded with an exclamation
  6741. mark. The following example uses \code{set-point-x!} to change the
  6742. \code{x} field from \code{7} to \code{42}.
  6743. \begin{center}
  6744. \begin{lstlisting}
  6745. (let ([pt (point 7 12)])
  6746. (let ([_ (set-point-x! pt 42)])
  6747. (point-x pt)))
  6748. \end{lstlisting}
  6749. \end{center}
  6750. \begin{exercise}\normalfont
  6751. Extend your compiler with support for simple structures, compiling
  6752. \LangStruct{} to x86 assembly code. Create five new test cases that use
  6753. structures and test your compiler.
  6754. \end{exercise}
  6755. \section{Challenge: Generational Collection}
  6756. The copying collector described in Section~\ref{sec:GC} can incur
  6757. significant runtime overhead because the call to \code{collect} takes
  6758. time proportional to all of the live data. One way to reduce this
  6759. overhead is to reduce how much data is inspected in each call to
  6760. \code{collect}. In particular, researchers have observed that recently
  6761. allocated data is more likely to become garbage then data that has
  6762. survived one or more previous calls to \code{collect}. This insight
  6763. motivated the creation of \emph{generational garbage collectors}
  6764. \index{generational garbage collector} that
  6765. 1) segregates data according to its age into two or more generations,
  6766. 2) allocates less space for younger generations, so collecting them is
  6767. faster, and more space for the older generations, and 3) performs
  6768. collection on the younger generations more frequently then for older
  6769. generations~\citep{Wilson:1992fk}.
  6770. For this challenge assignment, the goal is to adapt the copying
  6771. collector implemented in \code{runtime.c} to use two generations, one
  6772. for young data and one for old data. Each generation consists of a
  6773. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  6774. \code{collect} function to use the two generations.
  6775. \begin{enumerate}
  6776. \item Copy the young generation's FromSpace to its ToSpace then switch
  6777. the role of the ToSpace and FromSpace
  6778. \item If there is enough space for the requested number of bytes in
  6779. the young FromSpace, then return from \code{collect}.
  6780. \item If there is not enough space in the young FromSpace for the
  6781. requested bytes, then move the data from the young generation to the
  6782. old one with the following steps:
  6783. \begin{enumerate}
  6784. \item If there is enough room in the old FromSpace, copy the young
  6785. FromSpace to the old FromSpace and then return.
  6786. \item If there is not enough room in the old FromSpace, then collect
  6787. the old generation by copying the old FromSpace to the old ToSpace
  6788. and swap the roles of the old FromSpace and ToSpace.
  6789. \item If there is enough room now, copy the young FromSpace to the
  6790. old FromSpace and return. Otherwise, allocate a larger FromSpace
  6791. and ToSpace for the old generation. Copy the young FromSpace and
  6792. the old FromSpace into the larger FromSpace for the old
  6793. generation and then return.
  6794. \end{enumerate}
  6795. \end{enumerate}
  6796. We recommend that you generalize the \code{cheney} function so that it
  6797. can be used for all the copies mentioned above: between the young
  6798. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  6799. between the young FromSpace and old FromSpace. This can be
  6800. accomplished by adding parameters to \code{cheney} that replace its
  6801. use of the global variables \code{fromspace\_begin},
  6802. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  6803. Note that the collection of the young generation does not traverse the
  6804. old generation. This introduces a potential problem: there may be
  6805. young data that is only reachable through pointers in the old
  6806. generation. If these pointers are not taken into account, the
  6807. collector could throw away young data that is live! One solution,
  6808. called \emph{pointer recording}, is to maintain a set of all the
  6809. pointers from the old generation into the new generation and consider
  6810. this set as part of the root set. To maintain this set, the compiler
  6811. must insert extra instructions around every \code{vector-set!}. If the
  6812. vector being modified is in the old generation, and if the value being
  6813. written is a pointer into the new generation, than that pointer must
  6814. be added to the set. Also, if the value being overwritten was a
  6815. pointer into the new generation, then that pointer should be removed
  6816. from the set.
  6817. \begin{exercise}\normalfont
  6818. Adapt the \code{collect} function in \code{runtime.c} to implement
  6819. generational garbage collection, as outlined in this section.
  6820. Update the code generation for \code{vector-set!} to implement
  6821. pointer recording. Make sure that your new compiler and runtime
  6822. passes your test suite.
  6823. \end{exercise}
  6824. % TODO: challenge, implement homogeneous vectors
  6825. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6826. \chapter{Functions}
  6827. \label{ch:Rfun}
  6828. \index{function}
  6829. This chapter studies the compilation of functions similar to those
  6830. found in the C language. This corresponds to a subset of Typed Racket
  6831. in which only top-level function definitions are allowed. This kind of
  6832. function is an important stepping stone to implementing
  6833. lexically-scoped functions, that is, \key{lambda} abstractions, which
  6834. is the topic of Chapter~\ref{ch:Rlam}.
  6835. \section{The \LangFun{} Language}
  6836. The concrete and abstract syntax for function definitions and function
  6837. application is shown in Figures~\ref{fig:Rfun-concrete-syntax} and
  6838. \ref{fig:Rfun-syntax}, where we define the \LangFun{} language. Programs in
  6839. \LangFun{} begin with zero or more function definitions. The function
  6840. names from these definitions are in-scope for the entire program,
  6841. including all other function definitions (so the ordering of function
  6842. definitions does not matter). The concrete syntax for function
  6843. application\index{function application} is $(\Exp \; \Exp \ldots)$
  6844. where the first expression must
  6845. evaluate to a function and the rest are the arguments.
  6846. The abstract syntax for function application is
  6847. $\APPLY{\Exp}{\Exp\ldots}$.
  6848. %% The syntax for function application does not include an explicit
  6849. %% keyword, which is error prone when using \code{match}. To alleviate
  6850. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  6851. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  6852. Functions are first-class in the sense that a function pointer
  6853. \index{function pointer} is data and can be stored in memory or passed
  6854. as a parameter to another function. Thus, we introduce a function
  6855. type, written
  6856. \begin{lstlisting}
  6857. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  6858. \end{lstlisting}
  6859. for a function whose $n$ parameters have the types $\Type_1$ through
  6860. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  6861. these functions (with respect to Racket functions) is that they are
  6862. not lexically scoped. That is, the only external entities that can be
  6863. referenced from inside a function body are other globally-defined
  6864. functions. The syntax of \LangFun{} prevents functions from being nested
  6865. inside each other.
  6866. \begin{figure}[tp]
  6867. \centering
  6868. \fbox{
  6869. \begin{minipage}{0.96\textwidth}
  6870. \small
  6871. \[
  6872. \begin{array}{lcl}
  6873. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  6874. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void} } \mid (\Type \ldots \; \key{->}\; \Type) \\
  6875. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6876. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  6877. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  6878. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6879. \mid (\key{and}\;\Exp\;\Exp)
  6880. \mid (\key{or}\;\Exp\;\Exp)
  6881. \mid (\key{not}\;\Exp)} \\
  6882. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  6883. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  6884. (\key{vector-ref}\;\Exp\;\Int)} \\
  6885. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  6886. \mid \LP\key{has-type}~\Exp~\Type\RP } \\
  6887. &\mid& \LP\Exp \; \Exp \ldots\RP \\
  6888. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  6889. \LangFun{} &::=& \Def \ldots \; \Exp
  6890. \end{array}
  6891. \]
  6892. \end{minipage}
  6893. }
  6894. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-concrete-syntax}).}
  6895. \label{fig:Rfun-concrete-syntax}
  6896. \end{figure}
  6897. \begin{figure}[tp]
  6898. \centering
  6899. \fbox{
  6900. \begin{minipage}{0.96\textwidth}
  6901. \small
  6902. \[
  6903. \begin{array}{lcl}
  6904. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6905. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  6906. &\mid& \gray{ \BOOL{\itm{bool}}
  6907. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6908. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP }
  6909. \mid \APPLY{\Exp}{\Exp\ldots}\\
  6910. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}\\
  6911. \LangFun{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  6912. \end{array}
  6913. \]
  6914. \end{minipage}
  6915. }
  6916. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-syntax}).}
  6917. \label{fig:Rfun-syntax}
  6918. \end{figure}
  6919. The program in Figure~\ref{fig:Rfun-function-example} is a
  6920. representative example of defining and using functions in \LangFun{}. We
  6921. define a function \code{map-vec} that applies some other function
  6922. \code{f} to both elements of a vector and returns a new
  6923. vector containing the results. We also define a function \code{add1}.
  6924. The program applies
  6925. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  6926. \code{(vector 1 42)}, from which we return the \code{42}.
  6927. \begin{figure}[tbp]
  6928. \begin{lstlisting}
  6929. (define (map-vec [f : (Integer -> Integer)]
  6930. [v : (Vector Integer Integer)])
  6931. : (Vector Integer Integer)
  6932. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  6933. (define (add1 [x : Integer]) : Integer
  6934. (+ x 1))
  6935. (vector-ref (map-vec add1 (vector 0 41)) 1)
  6936. \end{lstlisting}
  6937. \caption{Example of using functions in \LangFun{}.}
  6938. \label{fig:Rfun-function-example}
  6939. \end{figure}
  6940. The definitional interpreter for \LangFun{} is in
  6941. Figure~\ref{fig:interp-Rfun}. The case for the \code{ProgramDefsExp} form is
  6942. responsible for setting up the mutual recursion between the top-level
  6943. function definitions. We use the classic back-patching \index{back-patching}
  6944. approach that uses mutable variables and makes two passes over the function
  6945. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  6946. top-level environment using a mutable cons cell for each function
  6947. definition. Note that the \code{lambda} value for each function is
  6948. incomplete; it does not yet include the environment. Once the
  6949. top-level environment is constructed, we then iterate over it and
  6950. update the \code{lambda} values to use the top-level environment.
  6951. \begin{figure}[tp]
  6952. \begin{lstlisting}
  6953. (define interp-Rfun-class
  6954. (class interp-Rvec-class
  6955. (super-new)
  6956. (define/override ((interp-exp env) e)
  6957. (define recur (interp-exp env))
  6958. (match e
  6959. [(Var x) (unbox (dict-ref env x))]
  6960. [(Let x e body)
  6961. (define new-env (dict-set env x (box (recur e))))
  6962. ((interp-exp new-env) body)]
  6963. [(Apply fun args)
  6964. (define fun-val (recur fun))
  6965. (define arg-vals (for/list ([e args]) (recur e)))
  6966. (match fun-val
  6967. [`(function (,xs ...) ,body ,fun-env)
  6968. (define params-args (for/list ([x xs] [arg arg-vals])
  6969. (cons x (box arg))))
  6970. (define new-env (append params-args fun-env))
  6971. ((interp-exp new-env) body)]
  6972. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  6973. [else ((super interp-exp env) e)]
  6974. ))
  6975. (define/public (interp-def d)
  6976. (match d
  6977. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  6978. (cons f (box `(function ,xs ,body ())))]))
  6979. (define/override (interp-program p)
  6980. (match p
  6981. [(ProgramDefsExp info ds body)
  6982. (let ([top-level (for/list ([d ds]) (interp-def d))])
  6983. (for/list ([f (in-dict-values top-level)])
  6984. (set-box! f (match (unbox f)
  6985. [`(function ,xs ,body ())
  6986. `(function ,xs ,body ,top-level)])))
  6987. ((interp-exp top-level) body))]))
  6988. ))
  6989. (define (interp-Rfun p)
  6990. (send (new interp-Rfun-class) interp-program p))
  6991. \end{lstlisting}
  6992. \caption{Interpreter for the \LangFun{} language.}
  6993. \label{fig:interp-Rfun}
  6994. \end{figure}
  6995. \margincomment{TODO: explain type checker}
  6996. The type checker for \LangFun{} is is in Figure~\ref{fig:type-check-Rfun}.
  6997. \begin{figure}[tp]
  6998. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6999. (define type-check-Rfun-class
  7000. (class type-check-Rvec-class
  7001. (super-new)
  7002. (inherit check-type-equal?)
  7003. (define/public (type-check-apply env e es)
  7004. (define-values (e^ ty) ((type-check-exp env) e))
  7005. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  7006. ((type-check-exp env) e)))
  7007. (match ty
  7008. [`(,ty^* ... -> ,rt)
  7009. (for ([arg-ty ty*] [param-ty ty^*])
  7010. (check-type-equal? arg-ty param-ty (Apply e es)))
  7011. (values e^ e* rt)]))
  7012. (define/override (type-check-exp env)
  7013. (lambda (e)
  7014. (match e
  7015. [(FunRef f)
  7016. (values (FunRef f) (dict-ref env f))]
  7017. [(Apply e es)
  7018. (define-values (e^ es^ rt) (type-check-apply env e es))
  7019. (values (Apply e^ es^) rt)]
  7020. [(Call e es)
  7021. (define-values (e^ es^ rt) (type-check-apply env e es))
  7022. (values (Call e^ es^) rt)]
  7023. [else ((super type-check-exp env) e)])))
  7024. (define/public (type-check-def env)
  7025. (lambda (e)
  7026. (match e
  7027. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  7028. (define new-env (append (map cons xs ps) env))
  7029. (define-values (body^ ty^) ((type-check-exp new-env) body))
  7030. (check-type-equal? ty^ rt body)
  7031. (Def f p:t* rt info body^)])))
  7032. (define/public (fun-def-type d)
  7033. (match d
  7034. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  7035. (define/override (type-check-program e)
  7036. (match e
  7037. [(ProgramDefsExp info ds body)
  7038. (define new-env (for/list ([d ds])
  7039. (cons (Def-name d) (fun-def-type d))))
  7040. (define ds^ (for/list ([d ds]) ((type-check-def new-env) d)))
  7041. (define-values (body^ ty) ((type-check-exp new-env) body))
  7042. (check-type-equal? ty 'Integer body)
  7043. (ProgramDefsExp info ds^ body^)]))))
  7044. (define (type-check-Rfun p)
  7045. (send (new type-check-Rfun-class) type-check-program p))
  7046. \end{lstlisting}
  7047. \caption{Type checker for the \LangFun{} language.}
  7048. \label{fig:type-check-Rfun}
  7049. \end{figure}
  7050. \section{Functions in x86}
  7051. \label{sec:fun-x86}
  7052. \margincomment{\tiny Make sure callee-saved registers are discussed
  7053. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  7054. \margincomment{\tiny Talk about the return address on the
  7055. stack and what callq and retq does.\\ --Jeremy }
  7056. The x86 architecture provides a few features to support the
  7057. implementation of functions. We have already seen that x86 provides
  7058. labels so that one can refer to the location of an instruction, as is
  7059. needed for jump instructions. Labels can also be used to mark the
  7060. beginning of the instructions for a function. Going further, we can
  7061. obtain the address of a label by using the \key{leaq} instruction and
  7062. PC-relative addressing. For example, the following puts the
  7063. address of the \code{add1} label into the \code{rbx} register.
  7064. \begin{lstlisting}
  7065. leaq add1(%rip), %rbx
  7066. \end{lstlisting}
  7067. The instruction pointer register \key{rip} (aka. the program counter
  7068. \index{program counter}) always points to the next instruction to be
  7069. executed. When combined with an label, as in \code{add1(\%rip)}, the
  7070. linker computes the distance $d$ between the address of \code{add1}
  7071. and where the \code{rip} would be at that moment and then changes
  7072. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  7073. the address of \code{add1}.
  7074. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  7075. jump to a function whose location is given by a label. To support
  7076. function calls in this chapter we instead will be jumping to a
  7077. function whose location is given by an address in a register, that is,
  7078. we need to make an \emph{indirect function call}. The x86 syntax for
  7079. this is a \code{callq} instruction but with an asterisk before the
  7080. register name.\index{indirect function call}
  7081. \begin{lstlisting}
  7082. callq *%rbx
  7083. \end{lstlisting}
  7084. \subsection{Calling Conventions}
  7085. \index{calling conventions}
  7086. The \code{callq} instruction provides partial support for implementing
  7087. functions: it pushes the return address on the stack and it jumps to
  7088. the target. However, \code{callq} does not handle
  7089. \begin{enumerate}
  7090. \item parameter passing,
  7091. \item pushing frames on the procedure call stack and popping them off,
  7092. or
  7093. \item determining how registers are shared by different functions.
  7094. \end{enumerate}
  7095. Regarding (1) parameter passing, recall that the following six
  7096. registers are used to pass arguments to a function, in this order.
  7097. \begin{lstlisting}
  7098. rdi rsi rdx rcx r8 r9
  7099. \end{lstlisting}
  7100. If there are
  7101. more than six arguments, then the convention is to use space on the
  7102. frame of the caller for the rest of the arguments. However, to ease
  7103. the implementation of efficient tail calls
  7104. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  7105. arguments.
  7106. %
  7107. Also recall that the register \code{rax} is for the return value of
  7108. the function.
  7109. \index{prelude}\index{conclusion}
  7110. Regarding (2) frames \index{frame} and the procedure call stack,
  7111. \index{procedure call stack} recall from Section~\ref{sec:x86} that
  7112. the stack grows down, with each function call using a chunk of space
  7113. called a frame. The caller sets the stack pointer, register
  7114. \code{rsp}, to the last data item in its frame. The callee must not
  7115. change anything in the caller's frame, that is, anything that is at or
  7116. above the stack pointer. The callee is free to use locations that are
  7117. below the stack pointer.
  7118. Recall that we are storing variables of vector type on the root stack.
  7119. So the prelude needs to move the root stack pointer \code{r15} up and
  7120. the conclusion needs to move the root stack pointer back down. Also,
  7121. the prelude must initialize to \code{0} this frame's slots in the root
  7122. stack to signal to the garbage collector that those slots do not yet
  7123. contain a pointer to a vector. Otherwise the garbage collector will
  7124. interpret the garbage bits in those slots as memory addresses and try
  7125. to traverse them, causing serious mayhem!
  7126. Regarding (3) the sharing of registers between different functions,
  7127. recall from Section~\ref{sec:calling-conventions} that the registers
  7128. are divided into two groups, the caller-saved registers and the
  7129. callee-saved registers. The caller should assume that all the
  7130. caller-saved registers get overwritten with arbitrary values by the
  7131. callee. That is why we recommend in
  7132. Section~\ref{sec:calling-conventions} that variables that are live
  7133. during a function call should not be assigned to caller-saved
  7134. registers.
  7135. On the flip side, if the callee wants to use a callee-saved register,
  7136. the callee must save the contents of those registers on their stack
  7137. frame and then put them back prior to returning to the caller. That
  7138. is why we recommended in Section~\ref{sec:calling-conventions} that if
  7139. the register allocator assigns a variable to a callee-saved register,
  7140. then the prelude of the \code{main} function must save that register
  7141. to the stack and the conclusion of \code{main} must restore it. This
  7142. recommendation now generalizes to all functions.
  7143. Also recall that the base pointer, register \code{rbp}, is used as a
  7144. point-of-reference within a frame, so that each local variable can be
  7145. accessed at a fixed offset from the base pointer
  7146. (Section~\ref{sec:x86}).
  7147. %
  7148. Figure~\ref{fig:call-frames} shows the general layout of the caller
  7149. and callee frames.
  7150. \begin{figure}[tbp]
  7151. \centering
  7152. \begin{tabular}{r|r|l|l} \hline
  7153. Caller View & Callee View & Contents & Frame \\ \hline
  7154. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  7155. 0(\key{\%rbp}) & & old \key{rbp} \\
  7156. -8(\key{\%rbp}) & & callee-saved $1$ \\
  7157. \ldots & & \ldots \\
  7158. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  7159. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  7160. \ldots & & \ldots \\
  7161. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  7162. %% & & \\
  7163. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  7164. %% & \ldots & \ldots \\
  7165. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  7166. \hline
  7167. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  7168. & 0(\key{\%rbp}) & old \key{rbp} \\
  7169. & -8(\key{\%rbp}) & callee-saved $1$ \\
  7170. & \ldots & \ldots \\
  7171. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  7172. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  7173. & \ldots & \ldots \\
  7174. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  7175. \end{tabular}
  7176. \caption{Memory layout of caller and callee frames.}
  7177. \label{fig:call-frames}
  7178. \end{figure}
  7179. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  7180. %% local variables and for storing the values of callee-saved registers
  7181. %% (we shall refer to all of these collectively as ``locals''), and that
  7182. %% at the beginning of a function we move the stack pointer \code{rsp}
  7183. %% down to make room for them.
  7184. %% We recommend storing the local variables
  7185. %% first and then the callee-saved registers, so that the local variables
  7186. %% can be accessed using \code{rbp} the same as before the addition of
  7187. %% functions.
  7188. %% To make additional room for passing arguments, we shall
  7189. %% move the stack pointer even further down. We count how many stack
  7190. %% arguments are needed for each function call that occurs inside the
  7191. %% body of the function and find their maximum. Adding this number to the
  7192. %% number of locals gives us how much the \code{rsp} should be moved at
  7193. %% the beginning of the function. In preparation for a function call, we
  7194. %% offset from \code{rsp} to set up the stack arguments. We put the first
  7195. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  7196. %% so on.
  7197. %% Upon calling the function, the stack arguments are retrieved by the
  7198. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  7199. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  7200. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  7201. %% the layout of the caller and callee frames. Notice how important it is
  7202. %% that we correctly compute the maximum number of arguments needed for
  7203. %% function calls; if that number is too small then the arguments and
  7204. %% local variables will smash into each other!
  7205. \subsection{Efficient Tail Calls}
  7206. \label{sec:tail-call}
  7207. In general, the amount of stack space used by a program is determined
  7208. by the longest chain of nested function calls. That is, if function
  7209. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  7210. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  7211. $n$ can grow quite large in the case of recursive or mutually
  7212. recursive functions. However, in some cases we can arrange to use only
  7213. constant space, i.e. $O(1)$, instead of $O(n)$.
  7214. If a function call is the last action in a function body, then that
  7215. call is said to be a \emph{tail call}\index{tail call}.
  7216. For example, in the following
  7217. program, the recursive call to \code{tail-sum} is a tail call.
  7218. \begin{center}
  7219. \begin{lstlisting}
  7220. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  7221. (if (eq? n 0)
  7222. r
  7223. (tail-sum (- n 1) (+ n r))))
  7224. (+ (tail-sum 5 0) 27)
  7225. \end{lstlisting}
  7226. \end{center}
  7227. At a tail call, the frame of the caller is no longer needed, so we
  7228. can pop the caller's frame before making the tail call. With this
  7229. approach, a recursive function that only makes tail calls will only
  7230. use $O(1)$ stack space. Functional languages like Racket typically
  7231. rely heavily on recursive functions, so they typically guarantee that
  7232. all tail calls will be optimized in this way.
  7233. \index{frame}
  7234. However, some care is needed with regards to argument passing in tail
  7235. calls. As mentioned above, for arguments beyond the sixth, the
  7236. convention is to use space in the caller's frame for passing
  7237. arguments. But for a tail call we pop the caller's frame and can no
  7238. longer use it. Another alternative is to use space in the callee's
  7239. frame for passing arguments. However, this option is also problematic
  7240. because the caller and callee's frame overlap in memory. As we begin
  7241. to copy the arguments from their sources in the caller's frame, the
  7242. target locations in the callee's frame might overlap with the sources
  7243. for later arguments! We solve this problem by not using the stack for
  7244. passing more than six arguments but instead using the heap, as we
  7245. describe in the Section~\ref{sec:limit-functions-r4}.
  7246. As mentioned above, for a tail call we pop the caller's frame prior to
  7247. making the tail call. The instructions for popping a frame are the
  7248. instructions that we usually place in the conclusion of a
  7249. function. Thus, we also need to place such code immediately before
  7250. each tail call. These instructions include restoring the callee-saved
  7251. registers, so it is good that the argument passing registers are all
  7252. caller-saved registers.
  7253. One last note regarding which instruction to use to make the tail
  7254. call. When the callee is finished, it should not return to the current
  7255. function, but it should return to the function that called the current
  7256. one. Thus, the return address that is already on the stack is the
  7257. right one, and we should not use \key{callq} to make the tail call, as
  7258. that would unnecessarily overwrite the return address. Instead we can
  7259. simply use the \key{jmp} instruction. Like the indirect function call,
  7260. we write an \emph{indirect jump}\index{indirect jump} with a register
  7261. prefixed with an asterisk. We recommend using \code{rax} to hold the
  7262. jump target because the preceding conclusion overwrites just about
  7263. everything else.
  7264. \begin{lstlisting}
  7265. jmp *%rax
  7266. \end{lstlisting}
  7267. \section{Shrink \LangFun{}}
  7268. \label{sec:shrink-r4}
  7269. The \code{shrink} pass performs a minor modification to ease the
  7270. later passes. This pass introduces an explicit \code{main} function
  7271. and changes the top \code{ProgramDefsExp} form to
  7272. \code{ProgramDefs} as follows.
  7273. \begin{lstlisting}
  7274. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  7275. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  7276. \end{lstlisting}
  7277. where $\itm{mainDef}$ is
  7278. \begin{lstlisting}
  7279. (Def 'main '() 'Integer '() |$\Exp'$|)
  7280. \end{lstlisting}
  7281. \section{Reveal Functions and the \LangFunRef{} language}
  7282. \label{sec:reveal-functions-r4}
  7283. The syntax of \LangFun{} is inconvenient for purposes of compilation in one
  7284. respect: it conflates the use of function names and local
  7285. variables. This is a problem because we need to compile the use of a
  7286. function name differently than the use of a local variable; we need to
  7287. use \code{leaq} to convert the function name (a label in x86) to an
  7288. address in a register. Thus, it is a good idea to create a new pass
  7289. that changes function references from just a symbol $f$ to
  7290. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  7291. output language, \LangFunRef{}, is defined in Figure~\ref{fig:f1-syntax}.
  7292. The concrete syntax for a function reference is $\CFUNREF{f}$.
  7293. \begin{figure}[tp]
  7294. \centering
  7295. \fbox{
  7296. \begin{minipage}{0.96\textwidth}
  7297. \[
  7298. \begin{array}{lcl}
  7299. \Exp &::=& \ldots \mid \FUNREF{\Var}\\
  7300. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7301. \LangFunRef{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  7302. \end{array}
  7303. \]
  7304. \end{minipage}
  7305. }
  7306. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  7307. (Figure~\ref{fig:Rfun-syntax}).}
  7308. \label{fig:f1-syntax}
  7309. \end{figure}
  7310. %% Distinguishing between calls in tail position and non-tail position
  7311. %% requires the pass to have some notion of context. We recommend using
  7312. %% two mutually recursive functions, one for processing expressions in
  7313. %% tail position and another for the rest.
  7314. Placing this pass after \code{uniquify} will make sure that there are
  7315. no local variables and functions that share the same name. On the
  7316. other hand, \code{reveal-functions} needs to come before the
  7317. \code{explicate-control} pass because that pass helps us compile
  7318. \code{FunRef} forms into assignment statements.
  7319. \section{Limit Functions}
  7320. \label{sec:limit-functions-r4}
  7321. Recall that we wish to limit the number of function parameters to six
  7322. so that we do not need to use the stack for argument passing, which
  7323. makes it easier to implement efficient tail calls. However, because
  7324. the input language \LangFun{} supports arbitrary numbers of function
  7325. arguments, we have some work to do!
  7326. This pass transforms functions and function calls that involve more
  7327. than six arguments to pass the first five arguments as usual, but it
  7328. packs the rest of the arguments into a vector and passes it as the
  7329. sixth argument.
  7330. Each function definition with too many parameters is transformed as
  7331. follows.
  7332. \begin{lstlisting}
  7333. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  7334. |$\Rightarrow$|
  7335. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  7336. \end{lstlisting}
  7337. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  7338. the occurrences of the later parameters with vector references.
  7339. \begin{lstlisting}
  7340. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  7341. \end{lstlisting}
  7342. For function calls with too many arguments, the \code{limit-functions}
  7343. pass transforms them in the following way.
  7344. \begin{tabular}{lll}
  7345. \begin{minipage}{0.2\textwidth}
  7346. \begin{lstlisting}
  7347. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  7348. \end{lstlisting}
  7349. \end{minipage}
  7350. &
  7351. $\Rightarrow$
  7352. &
  7353. \begin{minipage}{0.4\textwidth}
  7354. \begin{lstlisting}
  7355. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  7356. \end{lstlisting}
  7357. \end{minipage}
  7358. \end{tabular}
  7359. \section{Remove Complex Operands}
  7360. \label{sec:rco-r4}
  7361. The primary decisions to make for this pass is whether to classify
  7362. \code{FunRef} and \code{Apply} as either atomic or complex
  7363. expressions. Recall that a simple expression will eventually end up as
  7364. just an immediate argument of an x86 instruction. Function
  7365. application will be translated to a sequence of instructions, so
  7366. \code{Apply} must be classified as complex expression.
  7367. On the other hand, the arguments of \code{Apply} should be
  7368. atomic expressions.
  7369. %
  7370. Regarding \code{FunRef}, as discussed above, the function label needs
  7371. to be converted to an address using the \code{leaq} instruction. Thus,
  7372. even though \code{FunRef} seems rather simple, it needs to be
  7373. classified as a complex expression so that we generate an assignment
  7374. statement with a left-hand side that can serve as the target of the
  7375. \code{leaq}. Figure~\ref{fig:Rfun-anf-syntax} defines the
  7376. output language \LangFunANF{} of this pass.
  7377. \begin{figure}[tp]
  7378. \centering
  7379. \fbox{
  7380. \begin{minipage}{0.96\textwidth}
  7381. \small
  7382. \[
  7383. \begin{array}{rcl}
  7384. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  7385. \mid \VOID{} } \\
  7386. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  7387. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  7388. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  7389. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  7390. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  7391. &\mid& \gray{ \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  7392. \mid \LP\key{GlobalValue}~\Var\RP }\\
  7393. &\mid& \FUNREF{\Var} \mid \APPLY{\Atm}{\Atm\ldots}\\
  7394. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7395. R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  7396. \end{array}
  7397. \]
  7398. \end{minipage}
  7399. }
  7400. \caption{\LangFunANF{} is \LangFun{} in administrative normal form (ANF).}
  7401. \label{fig:Rfun-anf-syntax}
  7402. \end{figure}
  7403. \section{Explicate Control and the \LangCFun{} language}
  7404. \label{sec:explicate-control-r4}
  7405. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  7406. output of \key{explicate-control}. (The concrete syntax is given in
  7407. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.) The auxiliary
  7408. functions for assignment and tail contexts should be updated with
  7409. cases for \code{Apply} and \code{FunRef} and the function for
  7410. predicate context should be updated for \code{Apply} but not
  7411. \code{FunRef}. (A \code{FunRef} can't be a Boolean.) In assignment
  7412. and predicate contexts, \code{Apply} becomes \code{Call}, whereas in
  7413. tail position \code{Apply} becomes \code{TailCall}. We recommend
  7414. defining a new auxiliary function for processing function definitions.
  7415. This code is similar to the case for \code{Program} in \LangVec{}. The
  7416. top-level \code{explicate-control} function that handles the
  7417. \code{ProgramDefs} form of \LangFun{} can then apply this new function to
  7418. all the function definitions.
  7419. \begin{figure}[tp]
  7420. \fbox{
  7421. \begin{minipage}{0.96\textwidth}
  7422. \small
  7423. \[
  7424. \begin{array}{lcl}
  7425. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  7426. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  7427. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  7428. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  7429. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  7430. &\mid& \gray{ \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP } \\
  7431. &\mid& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  7432. &\mid& \gray{ \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP }\\
  7433. &\mid& \gray{ \LP\key{GlobalValue} \,\Var\RP \mid \LP\key{Void}\RP }\\
  7434. &\mid& \FUNREF{\itm{label}} \mid \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  7435. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  7436. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  7437. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  7438. \mid \GOTO{\itm{label}} } \\
  7439. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  7440. &\mid& \TAILCALL{\Atm}{\Atm\ldots} \\
  7441. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  7442. \LangCFun{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  7443. \end{array}
  7444. \]
  7445. \end{minipage}
  7446. }
  7447. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  7448. \label{fig:c3-syntax}
  7449. \end{figure}
  7450. \section{Select Instructions and the \LangXIndCall{} Language}
  7451. \label{sec:select-r4}
  7452. \index{instruction selection}
  7453. The output of select instructions is a program in the \LangXIndCall{}
  7454. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  7455. \index{x86}
  7456. \begin{figure}[tp]
  7457. \fbox{
  7458. \begin{minipage}{0.96\textwidth}
  7459. \small
  7460. \[
  7461. \begin{array}{lcl}
  7462. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)}
  7463. \mid \LP\key{fun-ref}\; \itm{label}\RP\\
  7464. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  7465. \Instr &::=& \ldots
  7466. \mid \key{callq}\;\key{*}\Arg \mid \key{tailjmp}\;\Arg
  7467. \mid \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  7468. \Block &::= & \Instr\ldots \\
  7469. \Def &::= & \LP\key{define} \; \LP\itm{label}\RP \;\LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\RP\\
  7470. \LangXIndCall{} &::= & \Def\ldots
  7471. \end{array}
  7472. \]
  7473. \end{minipage}
  7474. }
  7475. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  7476. \label{fig:x86-3-concrete}
  7477. \end{figure}
  7478. \begin{figure}[tp]
  7479. \fbox{
  7480. \begin{minipage}{0.96\textwidth}
  7481. \small
  7482. \[
  7483. \begin{array}{lcl}
  7484. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  7485. \mid \BYTEREG{\Reg} } \\
  7486. &\mid& \gray{ (\key{Global}~\Var) } \mid \FUNREF{\itm{label}} \\
  7487. \Instr &::=& \ldots \mid \INDCALLQ{\Arg}{\itm{int}}
  7488. \mid \TAILJMP{\Arg}{\itm{int}}\\
  7489. &\mid& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  7490. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  7491. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  7492. \LangXIndCall{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  7493. \end{array}
  7494. \]
  7495. \end{minipage}
  7496. }
  7497. \caption{The abstract syntax of \LangXIndCall{} (extends
  7498. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  7499. \label{fig:x86-3}
  7500. \end{figure}
  7501. An assignment of a function reference to a variable becomes a
  7502. load-effective-address instruction as follows: \\
  7503. \begin{tabular}{lcl}
  7504. \begin{minipage}{0.35\textwidth}
  7505. \begin{lstlisting}
  7506. |$\itm{lhs}$| = (fun-ref |$f$|);
  7507. \end{lstlisting}
  7508. \end{minipage}
  7509. &
  7510. $\Rightarrow$\qquad\qquad
  7511. &
  7512. \begin{minipage}{0.3\textwidth}
  7513. \begin{lstlisting}
  7514. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  7515. \end{lstlisting}
  7516. \end{minipage}
  7517. \end{tabular} \\
  7518. Regarding function definitions, we need to remove the parameters and
  7519. instead perform parameter passing using the conventions discussed in
  7520. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  7521. registers. We recommend turning the parameters into local variables
  7522. and generating instructions at the beginning of the function to move
  7523. from the argument passing registers to these local variables.
  7524. \begin{lstlisting}
  7525. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  7526. |$\Rightarrow$|
  7527. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  7528. \end{lstlisting}
  7529. The $G'$ control-flow graph is the same as $G$ except that the
  7530. \code{start} block is modified to add the instructions for moving from
  7531. the argument registers to the parameter variables. So the \code{start}
  7532. block of $G$ shown on the left is changed to the code on the right.
  7533. \begin{center}
  7534. \begin{minipage}{0.3\textwidth}
  7535. \begin{lstlisting}
  7536. start:
  7537. |$\itm{instr}_1$|
  7538. |$\vdots$|
  7539. |$\itm{instr}_n$|
  7540. \end{lstlisting}
  7541. \end{minipage}
  7542. $\Rightarrow$
  7543. \begin{minipage}{0.3\textwidth}
  7544. \begin{lstlisting}
  7545. start:
  7546. movq %rdi, |$x_1$|
  7547. movq %rsi, |$x_2$|
  7548. |$\vdots$|
  7549. |$\itm{instr}_1$|
  7550. |$\vdots$|
  7551. |$\itm{instr}_n$|
  7552. \end{lstlisting}
  7553. \end{minipage}
  7554. \end{center}
  7555. By changing the parameters to local variables, we are giving the
  7556. register allocator control over which registers or stack locations to
  7557. use for them. If you implemented the move-biasing challenge
  7558. (Section~\ref{sec:move-biasing}), the register allocator will try to
  7559. assign the parameter variables to the corresponding argument register,
  7560. in which case the \code{patch-instructions} pass will remove the
  7561. \code{movq} instruction. This happens in the example translation in
  7562. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  7563. the \code{add} function.
  7564. %
  7565. Also, note that the register allocator will perform liveness analysis
  7566. on this sequence of move instructions and build the interference
  7567. graph. So, for example, $x_1$ will be marked as interfering with
  7568. \code{rsi} and that will prevent the assignment of $x_1$ to
  7569. \code{rsi}, which is good, because that would overwrite the argument
  7570. that needs to move into $x_2$.
  7571. Next, consider the compilation of function calls. In the mirror image
  7572. of handling the parameters of function definitions, the arguments need
  7573. to be moved to the argument passing registers. The function call
  7574. itself is performed with an indirect function call. The return value
  7575. from the function is stored in \code{rax}, so it needs to be moved
  7576. into the \itm{lhs}.
  7577. \begin{lstlisting}
  7578. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  7579. |$\Rightarrow$|
  7580. movq |$\itm{arg}_1$|, %rdi
  7581. movq |$\itm{arg}_2$|, %rsi
  7582. |$\vdots$|
  7583. callq *|\itm{fun}|
  7584. movq %rax, |\itm{lhs}|
  7585. \end{lstlisting}
  7586. The \code{IndirectCallq} AST node includes an integer for the arity of
  7587. the function, i.e., the number of parameters. That information is
  7588. useful in the \code{uncover-live} pass for determining which
  7589. argument-passing registers are potentially read during the call.
  7590. For tail calls, the parameter passing is the same as non-tail calls:
  7591. generate instructions to move the arguments into to the argument
  7592. passing registers. After that we need to pop the frame from the
  7593. procedure call stack. However, we do not yet know how big the frame
  7594. is; that gets determined during register allocation. So instead of
  7595. generating those instructions here, we invent a new instruction that
  7596. means ``pop the frame and then do an indirect jump'', which we name
  7597. \code{TailJmp}. The abstract syntax for this instruction includes an
  7598. argument that specifies where to jump and an integer that represents
  7599. the arity of the function being called.
  7600. Recall that in Section~\ref{sec:explicate-control-Rvar} we recommended
  7601. using the label \code{start} for the initial block of a program, and
  7602. in Section~\ref{sec:select-Rvar} we recommended labeling the conclusion
  7603. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  7604. can be compiled to an assignment to \code{rax} followed by a jump to
  7605. \code{conclusion}. With the addition of function definitions, we will
  7606. have a starting block and conclusion for each function, but their
  7607. labels need to be unique. We recommend prepending the function's name
  7608. to \code{start} and \code{conclusion}, respectively, to obtain unique
  7609. labels. (Alternatively, one could \code{gensym} labels for the start
  7610. and conclusion and store them in the $\itm{info}$ field of the
  7611. function definition.)
  7612. \section{Register Allocation}
  7613. \label{sec:register-allocation-r4}
  7614. \subsection{Liveness Analysis}
  7615. \label{sec:liveness-analysis-r4}
  7616. \index{liveness analysis}
  7617. %% The rest of the passes need only minor modifications to handle the new
  7618. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  7619. %% \code{leaq}.
  7620. The \code{IndirectCallq} instruction should be treated like
  7621. \code{Callq} regarding its written locations $W$, in that they should
  7622. include all the caller-saved registers. Recall that the reason for
  7623. that is to force call-live variables to be assigned to callee-saved
  7624. registers or to be spilled to the stack.
  7625. Regarding the set of read locations $R$ the arity field of
  7626. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  7627. argument-passing registers should be considered as read by those
  7628. instructions.
  7629. \subsection{Build Interference Graph}
  7630. \label{sec:build-interference-r4}
  7631. With the addition of function definitions, we compute an interference
  7632. graph for each function (not just one for the whole program).
  7633. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  7634. spill vector-typed variables that are live during a call to the
  7635. \code{collect}. With the addition of functions to our language, we
  7636. need to revisit this issue. Many functions perform allocation and
  7637. therefore have calls to the collector inside of them. Thus, we should
  7638. not only spill a vector-typed variable when it is live during a call
  7639. to \code{collect}, but we should spill the variable if it is live
  7640. during any function call. Thus, in the \code{build-interference} pass,
  7641. we recommend adding interference edges between call-live vector-typed
  7642. variables and the callee-saved registers (in addition to the usual
  7643. addition of edges between call-live variables and the caller-saved
  7644. registers).
  7645. \subsection{Allocate Registers}
  7646. The primary change to the \code{allocate-registers} pass is adding an
  7647. auxiliary function for handling definitions (the \Def{} non-terminal
  7648. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  7649. logic is the same as described in
  7650. Chapter~\ref{ch:register-allocation-Rvar}, except now register
  7651. allocation is performed many times, once for each function definition,
  7652. instead of just once for the whole program.
  7653. \section{Patch Instructions}
  7654. In \code{patch-instructions}, you should deal with the x86
  7655. idiosyncrasy that the destination argument of \code{leaq} must be a
  7656. register. Additionally, you should ensure that the argument of
  7657. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  7658. code generation more convenient, because we trample many registers
  7659. before the tail call (as explained in the next section).
  7660. \section{Print x86}
  7661. For the \code{print-x86} pass, the cases for \code{FunRef} and
  7662. \code{IndirectCallq} are straightforward: output their concrete
  7663. syntax.
  7664. \begin{lstlisting}
  7665. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  7666. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  7667. \end{lstlisting}
  7668. The \code{TailJmp} node requires a bit work. A straightforward
  7669. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  7670. before the jump we need to pop the current frame. This sequence of
  7671. instructions is the same as the code for the conclusion of a function,
  7672. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  7673. Regarding function definitions, you will need to generate a prelude
  7674. and conclusion for each one. This code is similar to the prelude and
  7675. conclusion that you generated for the \code{main} function in
  7676. Chapter~\ref{ch:Rvec}. To review, the prelude of every function
  7677. should carry out the following steps.
  7678. \begin{enumerate}
  7679. \item Start with \code{.global} and \code{.align} directives followed
  7680. by the label for the function. (See Figure~\ref{fig:add-fun} for an
  7681. example.)
  7682. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  7683. pointer.
  7684. \item Push to the stack all of the callee-saved registers that were
  7685. used for register allocation.
  7686. \item Move the stack pointer \code{rsp} down by the size of the stack
  7687. frame for this function, which depends on the number of regular
  7688. spills. (Aligned to 16 bytes.)
  7689. \item Move the root stack pointer \code{r15} up by the size of the
  7690. root-stack frame for this function, which depends on the number of
  7691. spilled vectors. \label{root-stack-init}
  7692. \item Initialize to zero all of the entries in the root-stack frame.
  7693. \item Jump to the start block.
  7694. \end{enumerate}
  7695. The prelude of the \code{main} function has one additional task: call
  7696. the \code{initialize} function to set up the garbage collector and
  7697. move the value of the global \code{rootstack\_begin} in
  7698. \code{r15}. This should happen before step \ref{root-stack-init}
  7699. above, which depends on \code{r15}.
  7700. The conclusion of every function should do the following.
  7701. \begin{enumerate}
  7702. \item Move the stack pointer back up by the size of the stack frame
  7703. for this function.
  7704. \item Restore the callee-saved registers by popping them from the
  7705. stack.
  7706. \item Move the root stack pointer back down by the size of the
  7707. root-stack frame for this function.
  7708. \item Restore \code{rbp} by popping it from the stack.
  7709. \item Return to the caller with the \code{retq} instruction.
  7710. \end{enumerate}
  7711. \begin{exercise}\normalfont
  7712. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  7713. Create 5 new programs that use functions, including examples that pass
  7714. functions and return functions from other functions, recursive
  7715. functions, functions that create vectors, and functions that make tail
  7716. calls. Test your compiler on these new programs and all of your
  7717. previously created test programs.
  7718. \end{exercise}
  7719. \begin{figure}[tbp]
  7720. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7721. \node (Rfun) at (0,2) {\large \LangFun{}};
  7722. \node (Rfun-1) at (3,2) {\large \LangFun{}};
  7723. \node (Rfun-2) at (6,2) {\large \LangFun{}};
  7724. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  7725. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  7726. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  7727. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  7728. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  7729. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  7730. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  7731. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  7732. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  7733. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  7734. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  7735. \path[->,bend left=15] (Rfun) edge [above] node
  7736. {\ttfamily\footnotesize shrink} (Rfun-1);
  7737. \path[->,bend left=15] (Rfun-1) edge [above] node
  7738. {\ttfamily\footnotesize uniquify} (Rfun-2);
  7739. \path[->,bend left=15] (Rfun-2) edge [right] node
  7740. {\ttfamily\footnotesize ~~reveal-functions} (F1-1);
  7741. \path[->,bend left=15] (F1-1) edge [below] node
  7742. {\ttfamily\footnotesize limit-functions} (F1-2);
  7743. \path[->,bend right=15] (F1-2) edge [above] node
  7744. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  7745. \path[->,bend right=15] (F1-3) edge [above] node
  7746. {\ttfamily\footnotesize remove-complex.} (F1-4);
  7747. \path[->,bend left=15] (F1-4) edge [right] node
  7748. {\ttfamily\footnotesize explicate-control} (C3-2);
  7749. \path[->,bend right=15] (C3-2) edge [left] node
  7750. {\ttfamily\footnotesize select-instr.} (x86-2);
  7751. \path[->,bend left=15] (x86-2) edge [left] node
  7752. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  7753. \path[->,bend right=15] (x86-2-1) edge [below] node
  7754. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  7755. \path[->,bend right=15] (x86-2-2) edge [left] node
  7756. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7757. \path[->,bend left=15] (x86-3) edge [above] node
  7758. {\ttfamily\footnotesize patch-instr.} (x86-4);
  7759. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  7760. \end{tikzpicture}
  7761. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  7762. \label{fig:Rfun-passes}
  7763. \end{figure}
  7764. Figure~\ref{fig:Rfun-passes} gives an overview of the passes for
  7765. compiling \LangFun{} to x86.
  7766. \section{An Example Translation}
  7767. \label{sec:functions-example}
  7768. Figure~\ref{fig:add-fun} shows an example translation of a simple
  7769. function in \LangFun{} to x86. The figure also includes the results of the
  7770. \code{explicate-control} and \code{select-instructions} passes.
  7771. \begin{figure}[htbp]
  7772. \begin{tabular}{ll}
  7773. \begin{minipage}{0.5\textwidth}
  7774. % s3_2.rkt
  7775. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7776. (define (add [x : Integer] [y : Integer])
  7777. : Integer
  7778. (+ x y))
  7779. (add 40 2)
  7780. \end{lstlisting}
  7781. $\Downarrow$
  7782. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7783. (define (add86 [x87 : Integer]
  7784. [y88 : Integer]) : Integer
  7785. add86start:
  7786. return (+ x87 y88);
  7787. )
  7788. (define (main) : Integer ()
  7789. mainstart:
  7790. tmp89 = (fun-ref add86);
  7791. (tail-call tmp89 40 2)
  7792. )
  7793. \end{lstlisting}
  7794. \end{minipage}
  7795. &
  7796. $\Rightarrow$
  7797. \begin{minipage}{0.5\textwidth}
  7798. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7799. (define (add86) : Integer
  7800. add86start:
  7801. movq %rdi, x87
  7802. movq %rsi, y88
  7803. movq x87, %rax
  7804. addq y88, %rax
  7805. jmp add11389conclusion
  7806. )
  7807. (define (main) : Integer
  7808. mainstart:
  7809. leaq (fun-ref add86), tmp89
  7810. movq $40, %rdi
  7811. movq $2, %rsi
  7812. tail-jmp tmp89
  7813. )
  7814. \end{lstlisting}
  7815. $\Downarrow$
  7816. \end{minipage}
  7817. \end{tabular}
  7818. \begin{tabular}{ll}
  7819. \begin{minipage}{0.3\textwidth}
  7820. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7821. .globl add86
  7822. .align 16
  7823. add86:
  7824. pushq %rbp
  7825. movq %rsp, %rbp
  7826. jmp add86start
  7827. add86start:
  7828. movq %rdi, %rax
  7829. addq %rsi, %rax
  7830. jmp add86conclusion
  7831. add86conclusion:
  7832. popq %rbp
  7833. retq
  7834. \end{lstlisting}
  7835. \end{minipage}
  7836. &
  7837. \begin{minipage}{0.5\textwidth}
  7838. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7839. .globl main
  7840. .align 16
  7841. main:
  7842. pushq %rbp
  7843. movq %rsp, %rbp
  7844. movq $16384, %rdi
  7845. movq $16384, %rsi
  7846. callq initialize
  7847. movq rootstack_begin(%rip), %r15
  7848. jmp mainstart
  7849. mainstart:
  7850. leaq add86(%rip), %rcx
  7851. movq $40, %rdi
  7852. movq $2, %rsi
  7853. movq %rcx, %rax
  7854. popq %rbp
  7855. jmp *%rax
  7856. mainconclusion:
  7857. popq %rbp
  7858. retq
  7859. \end{lstlisting}
  7860. \end{minipage}
  7861. \end{tabular}
  7862. \caption{Example compilation of a simple function to x86.}
  7863. \label{fig:add-fun}
  7864. \end{figure}
  7865. % Challenge idea: inlining! (simple version)
  7866. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7867. \chapter{Lexically Scoped Functions}
  7868. \label{ch:Rlam}
  7869. \index{lambda}
  7870. \index{lexical scoping}
  7871. This chapter studies lexically scoped functions as they appear in
  7872. functional languages such as Racket. By lexical scoping we mean that a
  7873. function's body may refer to variables whose binding site is outside
  7874. of the function, in an enclosing scope.
  7875. %
  7876. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  7877. \LangLam{}, which extends \LangFun{} with anonymous functions using the
  7878. \key{lambda} form. The body of the \key{lambda}, refers to three
  7879. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  7880. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  7881. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  7882. parameter of function \code{f}. The \key{lambda} is returned from the
  7883. function \code{f}. The main expression of the program includes two
  7884. calls to \code{f} with different arguments for \code{x}, first
  7885. \code{5} then \code{3}. The functions returned from \code{f} are bound
  7886. to variables \code{g} and \code{h}. Even though these two functions
  7887. were created by the same \code{lambda}, they are really different
  7888. functions because they use different values for \code{x}. Applying
  7889. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  7890. \code{15} produces \code{22}. The result of this program is \code{42}.
  7891. \begin{figure}[btp]
  7892. % s4_6.rkt
  7893. \begin{lstlisting}
  7894. (define (f [x : Integer]) : (Integer -> Integer)
  7895. (let ([y 4])
  7896. (lambda: ([z : Integer]) : Integer
  7897. (+ x (+ y z)))))
  7898. (let ([g (f 5)])
  7899. (let ([h (f 3)])
  7900. (+ (g 11) (h 15))))
  7901. \end{lstlisting}
  7902. \caption{Example of a lexically scoped function.}
  7903. \label{fig:lexical-scoping}
  7904. \end{figure}
  7905. The approach that we take for implementing lexically scoped
  7906. functions is to compile them into top-level function definitions,
  7907. translating from \LangLam{} into \LangFun{}. However, the compiler will need to
  7908. provide special treatment for variable occurrences such as \code{x}
  7909. and \code{y} in the body of the \code{lambda} of
  7910. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function may not
  7911. refer to variables defined outside of it. To identify such variable
  7912. occurrences, we review the standard notion of free variable.
  7913. \begin{definition}
  7914. A variable is \emph{free in expression} $e$ if the variable occurs
  7915. inside $e$ but does not have an enclosing binding in $e$.\index{free
  7916. variable}
  7917. \end{definition}
  7918. For example, in the expression \code{(+ x (+ y z))} the variables
  7919. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  7920. only \code{x} and \code{y} are free in the following expression
  7921. because \code{z} is bound by the \code{lambda}.
  7922. \begin{lstlisting}
  7923. (lambda: ([z : Integer]) : Integer
  7924. (+ x (+ y z)))
  7925. \end{lstlisting}
  7926. So the free variables of a \code{lambda} are the ones that will need
  7927. special treatment. We need to arrange for some way to transport, at
  7928. runtime, the values of those variables from the point where the
  7929. \code{lambda} was created to the point where the \code{lambda} is
  7930. applied. An efficient solution to the problem, due to
  7931. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  7932. free variables together with the function pointer for the lambda's
  7933. code, an arrangement called a \emph{flat closure} (which we shorten to
  7934. just ``closure''). \index{closure}\index{flat closure} Fortunately,
  7935. we have all the ingredients to make closures, Chapter~\ref{ch:Rvec}
  7936. gave us vectors and Chapter~\ref{ch:Rfun} gave us function
  7937. pointers. The function pointer resides at index $0$ and the
  7938. values for the free variables will fill in the rest of the vector.
  7939. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  7940. how closures work. It's a three-step dance. The program first calls
  7941. function \code{f}, which creates a closure for the \code{lambda}. The
  7942. closure is a vector whose first element is a pointer to the top-level
  7943. function that we will generate for the \code{lambda}, the second
  7944. element is the value of \code{x}, which is \code{5}, and the third
  7945. element is \code{4}, the value of \code{y}. The closure does not
  7946. contain an element for \code{z} because \code{z} is not a free
  7947. variable of the \code{lambda}. Creating the closure is step 1 of the
  7948. dance. The closure is returned from \code{f} and bound to \code{g}, as
  7949. shown in Figure~\ref{fig:closures}.
  7950. %
  7951. The second call to \code{f} creates another closure, this time with
  7952. \code{3} in the second slot (for \code{x}). This closure is also
  7953. returned from \code{f} but bound to \code{h}, which is also shown in
  7954. Figure~\ref{fig:closures}.
  7955. \begin{figure}[tbp]
  7956. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  7957. \caption{Example closure representation for the \key{lambda}'s
  7958. in Figure~\ref{fig:lexical-scoping}.}
  7959. \label{fig:closures}
  7960. \end{figure}
  7961. Continuing with the example, consider the application of \code{g} to
  7962. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  7963. obtain the function pointer in the first element of the closure and
  7964. call it, passing in the closure itself and then the regular arguments,
  7965. in this case \code{11}. This technique for applying a closure is step
  7966. 2 of the dance.
  7967. %
  7968. But doesn't this \code{lambda} only take 1 argument, for parameter
  7969. \code{z}? The third and final step of the dance is generating a
  7970. top-level function for a \code{lambda}. We add an additional
  7971. parameter for the closure and we insert a \code{let} at the beginning
  7972. of the function for each free variable, to bind those variables to the
  7973. appropriate elements from the closure parameter.
  7974. %
  7975. This three-step dance is known as \emph{closure conversion}. We
  7976. discuss the details of closure conversion in
  7977. Section~\ref{sec:closure-conversion} and the code generated from the
  7978. example in Section~\ref{sec:example-lambda}. But first we define the
  7979. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  7980. \section{The \LangLam{} Language}
  7981. \label{sec:r5}
  7982. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  7983. functions and lexical scoping, is defined in
  7984. Figures~\ref{fig:Rlam-concrete-syntax} and ~\ref{fig:Rlam-syntax}. It adds
  7985. the \key{lambda} form to the grammar for \LangFun{}, which already has
  7986. syntax for function application.
  7987. \begin{figure}[tp]
  7988. \centering
  7989. \fbox{
  7990. \begin{minipage}{0.96\textwidth}
  7991. \small
  7992. \[
  7993. \begin{array}{lcl}
  7994. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7995. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}
  7996. \mid (\Type\ldots \; \key{->}\; \Type)} \\
  7997. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  7998. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  7999. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  8000. &\mid& \gray{\key{\#t} \mid \key{\#f}
  8001. \mid (\key{and}\;\Exp\;\Exp)
  8002. \mid (\key{or}\;\Exp\;\Exp)
  8003. \mid (\key{not}\;\Exp) } \\
  8004. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  8005. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  8006. (\key{vector-ref}\;\Exp\;\Int)} \\
  8007. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  8008. \mid (\Exp \; \Exp\ldots) } \\
  8009. &\mid& \LP \key{procedure-arity}~\Exp\RP \\
  8010. &\mid& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  8011. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  8012. \LangLam{} &::=& \gray{\Def\ldots \; \Exp}
  8013. \end{array}
  8014. \]
  8015. \end{minipage}
  8016. }
  8017. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-concrete-syntax})
  8018. with \key{lambda}.}
  8019. \label{fig:Rlam-concrete-syntax}
  8020. \end{figure}
  8021. \begin{figure}[tp]
  8022. \centering
  8023. \fbox{
  8024. \begin{minipage}{0.96\textwidth}
  8025. \small
  8026. \[
  8027. \begin{array}{lcl}
  8028. \itm{op} &::=& \ldots \mid \code{procedure-arity} \\
  8029. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  8030. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  8031. &\mid& \gray{ \BOOL{\itm{bool}}
  8032. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  8033. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  8034. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  8035. &\mid& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  8036. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  8037. \LangLam{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  8038. \end{array}
  8039. \]
  8040. \end{minipage}
  8041. }
  8042. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-syntax}).}
  8043. \label{fig:Rlam-syntax}
  8044. \end{figure}
  8045. \index{interpreter}
  8046. \label{sec:interp-Rlambda}
  8047. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  8048. \LangLam{}. The case for \key{lambda} saves the current environment
  8049. inside the returned \key{lambda}. Then the case for \key{Apply} uses
  8050. the environment from the \key{lambda}, the \code{lam-env}, when
  8051. interpreting the body of the \key{lambda}. The \code{lam-env}
  8052. environment is extended with the mapping of parameters to argument
  8053. values.
  8054. \begin{figure}[tbp]
  8055. \begin{lstlisting}
  8056. (define interp-Rlambda-class
  8057. (class interp-Rfun-class
  8058. (super-new)
  8059. (define/override (interp-op op)
  8060. (match op
  8061. ['procedure-arity
  8062. (lambda (v)
  8063. (match v
  8064. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  8065. [else (error 'interp-op "expected a function, not ~a" v)]))]
  8066. [else (super interp-op op)]))
  8067. (define/override ((interp-exp env) e)
  8068. (define recur (interp-exp env))
  8069. (match e
  8070. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  8071. `(function ,xs ,body ,env)]
  8072. [else ((super interp-exp env) e)]))
  8073. ))
  8074. (define (interp-Rlambda p)
  8075. (send (new interp-Rlambda-class) interp-program p))
  8076. \end{lstlisting}
  8077. \caption{Interpreter for \LangLam{}.}
  8078. \label{fig:interp-Rlambda}
  8079. \end{figure}
  8080. \label{sec:type-check-r5}
  8081. \index{type checking}
  8082. Figure~\ref{fig:type-check-Rlambda} shows how to type check the new
  8083. \key{lambda} form. The body of the \key{lambda} is checked in an
  8084. environment that includes the current environment (because it is
  8085. lexically scoped) and also includes the \key{lambda}'s parameters. We
  8086. require the body's type to match the declared return type.
  8087. \begin{figure}[tbp]
  8088. \begin{lstlisting}
  8089. (define (type-check-Rlambda env)
  8090. (lambda (e)
  8091. (match e
  8092. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  8093. (define-values (new-body bodyT)
  8094. ((type-check-exp (append (map cons xs Ts) env)) body))
  8095. (define ty `(,@Ts -> ,rT))
  8096. (cond
  8097. [(equal? rT bodyT)
  8098. (values (HasType (Lambda params rT new-body) ty) ty)]
  8099. [else
  8100. (error "mismatch in return type" bodyT rT)])]
  8101. ...
  8102. )))
  8103. \end{lstlisting}
  8104. \caption{Type checking the \key{lambda}'s in \LangLam{}.}
  8105. \label{fig:type-check-Rlambda}
  8106. \end{figure}
  8107. \section{Reveal Functions and the $F_2$ language}
  8108. \label{sec:reveal-functions-r5}
  8109. To support the \code{procedure-arity} operator we need to communicate
  8110. the arity of a function to the point of closure creation. We can
  8111. accomplish this by replacing the $\FUNREF{\Var}$ struct with one that
  8112. has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$. The
  8113. output of this pass is the language $F_2$, whose syntax is defined in
  8114. Figure~\ref{fig:f2-syntax}.
  8115. \begin{figure}[tp]
  8116. \centering
  8117. \fbox{
  8118. \begin{minipage}{0.96\textwidth}
  8119. \[
  8120. \begin{array}{lcl}
  8121. \Exp &::=& \ldots \mid \FUNREFARITY{\Var}{\Int}\\
  8122. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  8123. F_2 &::=& \gray{\PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}}
  8124. \end{array}
  8125. \]
  8126. \end{minipage}
  8127. }
  8128. \caption{The abstract syntax $F_2$, an extension of \LangLam{}
  8129. (Figure~\ref{fig:Rlam-syntax}).}
  8130. \label{fig:f2-syntax}
  8131. \end{figure}
  8132. \section{Closure Conversion}
  8133. \label{sec:closure-conversion}
  8134. \index{closure conversion}
  8135. The compiling of lexically-scoped functions into top-level function
  8136. definitions is accomplished in the pass \code{convert-to-closures}
  8137. that comes after \code{reveal-functions} and before
  8138. \code{limit-functions}.
  8139. As usual, we implement the pass as a recursive function over the
  8140. AST. All of the action is in the cases for \key{Lambda} and
  8141. \key{Apply}. We transform a \key{Lambda} expression into an expression
  8142. that creates a closure, that is, a vector whose first element is a
  8143. function pointer and the rest of the elements are the free variables
  8144. of the \key{Lambda}. We use the struct \code{Closure} here instead of
  8145. using \code{vector} so that we can distinguish closures from vectors
  8146. in Section~\ref{sec:optimize-closures} and to record the arity. In
  8147. the generated code below, the \itm{name} is a unique symbol generated
  8148. to identify the function and the \itm{arity} is the number of
  8149. parameters (the length of \itm{ps}).
  8150. \begin{lstlisting}
  8151. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  8152. |$\Rightarrow$|
  8153. (Closure |\itm{arity}| (cons (FunRef |\itm{name}|) |\itm{fvs}|))
  8154. \end{lstlisting}
  8155. In addition to transforming each \key{Lambda} into a \key{Closure}, we
  8156. create a top-level function definition for each \key{Lambda}, as
  8157. shown below.\\
  8158. \begin{minipage}{0.8\textwidth}
  8159. \begin{lstlisting}
  8160. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  8161. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  8162. ...
  8163. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  8164. |\itm{body'}|)...))
  8165. \end{lstlisting}
  8166. \end{minipage}\\
  8167. The \code{clos} parameter refers to the closure. Translate the type
  8168. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  8169. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The types
  8170. $\itm{fvts}$ are the types of the free variables in the lambda and the
  8171. underscore \code{\_} is a dummy type that we use because it is rather
  8172. difficult to give a type to the function in the closure's
  8173. type.\footnote{To give an accurate type to a closure, we would need to
  8174. add existential types to the type checker~\citep{Minamide:1996ys}.}
  8175. The dummy type is considered to be equal to any other type during type
  8176. checking. The sequence of \key{Let} forms bind the free variables to
  8177. their values obtained from the closure.
  8178. Closure conversion turns functions into vectors, so the type
  8179. annotations in the program must also be translated. We recommend
  8180. defining a auxiliary recursive function for this purpose. Function
  8181. types should be translated as follows.
  8182. \begin{lstlisting}
  8183. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  8184. |$\Rightarrow$|
  8185. (Vector ((Vector _) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  8186. \end{lstlisting}
  8187. The above type says that the first thing in the vector is a function
  8188. pointer. The first parameter of the function pointer is a vector (a
  8189. closure) and the rest of the parameters are the ones from the original
  8190. function, with types $T'_1, \ldots, T'_n$. The \code{Vector} type for
  8191. the closure omits the types of the free variables because 1) those
  8192. types are not available in this context and 2) we do not need them in
  8193. the code that is generated for function application.
  8194. We transform function application into code that retrieves the
  8195. function pointer from the closure and then calls the function, passing
  8196. in the closure as the first argument. We bind $e'$ to a temporary
  8197. variable to avoid code duplication.
  8198. \begin{lstlisting}
  8199. (Apply |$e$| |\itm{es}|)
  8200. |$\Rightarrow$|
  8201. (Let |\itm{tmp}| |$e'$|
  8202. (Apply (Prim 'vector-ref (list (Var |\itm{tmp}|) (Int 0))) (cons |\itm{tmp}| |\itm{es'}|)))
  8203. \end{lstlisting}
  8204. There is also the question of what to do with references top-level
  8205. function definitions. To maintain a uniform translation of function
  8206. application, we turn function references into closures.
  8207. \begin{tabular}{lll}
  8208. \begin{minipage}{0.3\textwidth}
  8209. \begin{lstlisting}
  8210. (FunRefArity |$f$| |$n$|)
  8211. \end{lstlisting}
  8212. \end{minipage}
  8213. &
  8214. $\Rightarrow$
  8215. &
  8216. \begin{minipage}{0.5\textwidth}
  8217. \begin{lstlisting}
  8218. (Closure |$n$| (FunRef |$f$|) '())
  8219. \end{lstlisting}
  8220. \end{minipage}
  8221. \end{tabular} \\
  8222. %
  8223. The top-level function definitions need to be updated as well to take
  8224. an extra closure parameter.
  8225. \section{An Example Translation}
  8226. \label{sec:example-lambda}
  8227. Figure~\ref{fig:lexical-functions-example} shows the result of
  8228. \code{reveal-functions} and \code{convert-to-closures} for the example
  8229. program demonstrating lexical scoping that we discussed at the
  8230. beginning of this chapter.
  8231. \begin{figure}[tbp]
  8232. \begin{minipage}{0.8\textwidth}
  8233. % tests/lambda_test_6.rkt
  8234. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8235. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  8236. (let ([y8 4])
  8237. (lambda: ([z9 : Integer]) : Integer
  8238. (+ x7 (+ y8 z9)))))
  8239. (define (main) : Integer
  8240. (let ([g0 ((fun-ref-arity f6 1) 5)])
  8241. (let ([h1 ((fun-ref-arity f6 1) 3)])
  8242. (+ (g0 11) (h1 15)))))
  8243. \end{lstlisting}
  8244. $\Rightarrow$
  8245. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8246. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  8247. (let ([y8 4])
  8248. (closure 1 (list (fun-ref lambda2) x7 y8))))
  8249. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  8250. (let ([x7 (vector-ref fvs3 1)])
  8251. (let ([y8 (vector-ref fvs3 2)])
  8252. (+ x7 (+ y8 z9)))))
  8253. (define (main) : Integer
  8254. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6)))])
  8255. ((vector-ref clos5 0) clos5 5))])
  8256. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6)))])
  8257. ((vector-ref clos6 0) clos6 3))])
  8258. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  8259. \end{lstlisting}
  8260. \end{minipage}
  8261. \caption{Example of closure conversion.}
  8262. \label{fig:lexical-functions-example}
  8263. \end{figure}
  8264. \begin{exercise}\normalfont
  8265. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  8266. Create 5 new programs that use \key{lambda} functions and make use of
  8267. lexical scoping. Test your compiler on these new programs and all of
  8268. your previously created test programs.
  8269. \end{exercise}
  8270. \section{Expose Allocation}
  8271. \label{sec:expose-allocation-r5}
  8272. Compile the $\CLOSURE{\itm{arity}}{\LP\Exp\ldots\RP}$ form into code
  8273. that allocates and initializes a vector, similar to the translation of
  8274. the \code{vector} operator in Section~\ref{sec:expose-allocation}.
  8275. The only difference is replacing the use of
  8276. \ALLOC{\itm{len}}{\itm{type}} with
  8277. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  8278. \section{Explicate Control and \LangCLam{}}
  8279. \label{sec:explicate-r5}
  8280. The output language of \code{explicate-control} is \LangCLam{} whose
  8281. abstract syntax is defined in Figure~\ref{fig:c4-syntax}. The only
  8282. difference with respect to \LangCFun{} is the addition of the
  8283. \code{AllocateClosure} form to the grammar for $\Exp$. The handling
  8284. of \code{AllocateClosure} in the \code{explicate-control} pass is
  8285. similar to the handling of other expressions such as primitive
  8286. operators.
  8287. \begin{figure}[tp]
  8288. \fbox{
  8289. \begin{minipage}{0.96\textwidth}
  8290. \small
  8291. \[
  8292. \begin{array}{lcl}
  8293. \Exp &::= & \ldots
  8294. \mid \ALLOCCLOS{\Int}{\Type}{\Int} \\
  8295. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  8296. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  8297. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  8298. \mid \GOTO{\itm{label}} } \\
  8299. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  8300. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  8301. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  8302. \LangCLam{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  8303. \end{array}
  8304. \]
  8305. \end{minipage}
  8306. }
  8307. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  8308. \label{fig:c4-syntax}
  8309. \end{figure}
  8310. \section{Select Instructions}
  8311. \label{sec:select-instructions-Rlambda}
  8312. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  8313. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  8314. (Section~\ref{sec:select-instructions-gc}). The only difference is
  8315. that you should place the \itm{arity} in the tag that is stored at
  8316. position $0$ of the vector. Recall that in
  8317. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  8318. was not used. We store the arity in the $5$ bits starting at position
  8319. $58$.
  8320. Compile the \code{procedure-arity} operator into a sequence of
  8321. instructions that access the tag from position $0$ of the vector and
  8322. extract the $5$-bits starting at position $58$ from the tag.
  8323. \begin{figure}[p]
  8324. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8325. \node (Rfun) at (0,2) {\large \LangFun{}};
  8326. \node (Rfun-2) at (3,2) {\large \LangFun{}};
  8327. \node (Rfun-3) at (6,2) {\large \LangFun{}};
  8328. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  8329. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  8330. \node (F1-3) at (6,0) {\large $F_1$};
  8331. \node (F1-4) at (3,0) {\large $F_1$};
  8332. \node (F1-5) at (0,0) {\large $F_1$};
  8333. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  8334. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  8335. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  8336. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  8337. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  8338. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  8339. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  8340. \path[->,bend left=15] (Rfun) edge [above] node
  8341. {\ttfamily\footnotesize shrink} (Rfun-2);
  8342. \path[->,bend left=15] (Rfun-2) edge [above] node
  8343. {\ttfamily\footnotesize uniquify} (Rfun-3);
  8344. \path[->,bend left=15] (Rfun-3) edge [right] node
  8345. {\ttfamily\footnotesize reveal-functions} (F1-1);
  8346. \path[->,bend left=15] (F1-1) edge [below] node
  8347. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  8348. \path[->,bend right=15] (F1-2) edge [above] node
  8349. {\ttfamily\footnotesize limit-fun.} (F1-3);
  8350. \path[->,bend right=15] (F1-3) edge [above] node
  8351. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  8352. \path[->,bend right=15] (F1-4) edge [above] node
  8353. {\ttfamily\footnotesize remove-complex.} (F1-5);
  8354. \path[->,bend right=15] (F1-5) edge [right] node
  8355. {\ttfamily\footnotesize explicate-control} (C3-2);
  8356. \path[->,bend left=15] (C3-2) edge [left] node
  8357. {\ttfamily\footnotesize select-instr.} (x86-2);
  8358. \path[->,bend right=15] (x86-2) edge [left] node
  8359. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  8360. \path[->,bend right=15] (x86-2-1) edge [below] node
  8361. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  8362. \path[->,bend right=15] (x86-2-2) edge [left] node
  8363. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  8364. \path[->,bend left=15] (x86-3) edge [above] node
  8365. {\ttfamily\footnotesize patch-instr.} (x86-4);
  8366. \path[->,bend left=15] (x86-4) edge [right] node
  8367. {\ttfamily\footnotesize print-x86} (x86-5);
  8368. \end{tikzpicture}
  8369. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  8370. functions.}
  8371. \label{fig:Rlambda-passes}
  8372. \end{figure}
  8373. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  8374. for the compilation of \LangLam{}.
  8375. \clearpage
  8376. \section{Challenge: Optimize Closures}
  8377. \label{sec:optimize-closures}
  8378. In this chapter we compiled lexically-scoped functions into a
  8379. relatively efficient representation: flat closures. However, even this
  8380. representation comes with some overhead. For example, consider the
  8381. following program with a function \code{tail-sum} that does not have
  8382. any free variables and where all the uses of \code{tail-sum} are in
  8383. applications where we know that only \code{tail-sum} is being applied
  8384. (and not any other functions).
  8385. \begin{center}
  8386. \begin{minipage}{0.95\textwidth}
  8387. \begin{lstlisting}
  8388. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  8389. (if (eq? n 0)
  8390. r
  8391. (tail-sum (- n 1) (+ n r))))
  8392. (+ (tail-sum 5 0) 27)
  8393. \end{lstlisting}
  8394. \end{minipage}
  8395. \end{center}
  8396. As described in this chapter, we uniformly apply closure conversion to
  8397. all functions, obtaining the following output for this program.
  8398. \begin{center}
  8399. \begin{minipage}{0.95\textwidth}
  8400. \begin{lstlisting}
  8401. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [r3 : Integer]) : Integer
  8402. (if (eq? n2 0)
  8403. r3
  8404. (let ([clos4 (closure (list (fun-ref tail_sum1)))])
  8405. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 r3)))))
  8406. (define (main) : Integer
  8407. (+ (let ([clos6 (closure (list (fun-ref tail_sum1)))])
  8408. ((vector-ref clos6 0) clos6 5 0)) 27))
  8409. \end{lstlisting}
  8410. \end{minipage}
  8411. \end{center}
  8412. In the previous Chapter, there would be no allocation in the program
  8413. and the calls to \code{tail-sum} would be direct calls. In contrast,
  8414. the above program allocates memory for each \code{closure} and the
  8415. calls to \code{tail-sum} are indirect. These two differences incur
  8416. considerable overhead in a program such as this one, where the
  8417. allocations and indirect calls occur inside a tight loop.
  8418. One might think that this problem is trivial to solve: can't we just
  8419. recognize calls of the form \code{((fun-ref $f$) $e_1 \ldots e_n$)}
  8420. and compile them to direct calls \code{((fun-ref $f$) $e'_1 \ldots
  8421. e'_n$)} instead of treating it like a call to a closure? We would
  8422. also drop the \code{fvs5} parameter of \code{tail\_sum1}.
  8423. %
  8424. However, this problem is not so trivial because a global function may
  8425. ``escape'' and become involved in applications that also involve
  8426. closures. Consider the following example in which the application
  8427. \code{(f 41)} needs to be compiled into a closure application, because
  8428. the \code{lambda} may get bound to \code{f}, but the \code{add1}
  8429. function might also get bound to \code{f}.
  8430. \begin{lstlisting}
  8431. (define (add1 [x : Integer]) : Integer
  8432. (+ x 1))
  8433. (let ([y (read)])
  8434. (let ([f (if (eq? (read) 0)
  8435. add1
  8436. (lambda: ([x : Integer]) : Integer (- x y)))])
  8437. (f 41)))
  8438. \end{lstlisting}
  8439. If a global function name is used in any way other than as the
  8440. operator in a direct call, then we say that the function
  8441. \emph{escapes}. If a global function does not escape, then we do not
  8442. need to perform closure conversion on the function.
  8443. \begin{exercise}\normalfont
  8444. Implement an auxiliary function for detecting which global
  8445. functions escape. Using that function, implement an improved version
  8446. of closure conversion that does not apply closure conversion to
  8447. global functions that do not escape but instead compiles them as
  8448. regular functions. Create several new test cases that check whether
  8449. you properly detect whether global functions escape or not.
  8450. \end{exercise}
  8451. So far we have reduced the overhead of calling global functions, but
  8452. it would also be nice to reduce the overhead of calling a
  8453. \code{lambda} when we can determine at compile time which
  8454. \code{lambda} will be called. We refer to such calls as \emph{known
  8455. calls}. Consider the following example in which a \code{lambda} is
  8456. bound to \code{f} and then applied.
  8457. \begin{lstlisting}
  8458. (let ([y (read)])
  8459. (let ([f (lambda: ([x : Integer]) : Integer
  8460. (+ x y))])
  8461. (f 21)))
  8462. \end{lstlisting}
  8463. Closure conversion compiles \code{(f 21)} into an indirect call:
  8464. \begin{lstlisting}
  8465. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  8466. (let ([y2 (vector-ref fvs6 1)])
  8467. (+ x3 y2)))
  8468. (define (main) : Integer
  8469. (let ([y2 (read)])
  8470. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  8471. ((vector-ref f4 0) f4 21))))
  8472. \end{lstlisting}
  8473. but we can instead compile the application \code{(f 21)} into a direct call
  8474. to \code{lambda5}:
  8475. \begin{lstlisting}
  8476. (define (main) : Integer
  8477. (let ([y2 (read)])
  8478. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  8479. ((fun-ref lambda5) f4 21))))
  8480. \end{lstlisting}
  8481. The problem of determining which lambda will be called from a
  8482. particular application is quite challenging in general and the topic
  8483. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  8484. following exercise we recommend that you compile an application to a
  8485. direct call when the operator is a variable and the variable is
  8486. \code{let}-bound to a closure. This can be accomplished by maintaining
  8487. an environment mapping \code{let}-bound variables to function names.
  8488. Extend the environment whenever you encounter a closure on the
  8489. right-hand side of a \code{let}, mapping the \code{let}-bound variable
  8490. to the name of the global function for the closure. This pass should
  8491. come after closure conversion.
  8492. \begin{exercise}\normalfont
  8493. Implement a compiler pass, named \code{optimize-known-calls}, that
  8494. compiles known calls into direct calls. Verify that your compiler is
  8495. successful in this regard on several example programs.
  8496. \end{exercise}
  8497. These exercises only scratches the surface of optimizing of
  8498. closures. A good next step for the interested reader is to look at the
  8499. work of \citet{Keep:2012ab}.
  8500. \section{Further Reading}
  8501. The notion of lexically scoped anonymous functions predates modern
  8502. computers by about a decade. They were invented by
  8503. \citet{Church:1932aa}, who proposed the $\lambda$ calculus as a
  8504. foundation for logic. Anonymous functions were included in the
  8505. LISP~\citep{McCarthy:1960dz} programming language but were initially
  8506. dynamically scoped. The Scheme dialect of LISP adopted lexical scoping
  8507. and \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently
  8508. compile Scheme programs. However, environments were represented as
  8509. linked lists, so variable lookup was linear in the size of the
  8510. environment. In this chapter we represent environments using flat
  8511. closures, which were invented by
  8512. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  8513. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  8514. closures, variable lookup is constant time but the time to create a
  8515. closure is proportional to the number of its free variables. Flat
  8516. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  8517. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  8518. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8519. \chapter{Dynamic Typing}
  8520. \label{ch:Rdyn}
  8521. \index{dynamic typing}
  8522. In this chapter we discuss the compilation of \LangDyn{}, a dynamically
  8523. typed language that is a subset of Racket. This is in contrast to the
  8524. previous chapters, which have studied the compilation of Typed
  8525. Racket. In dynamically typed languages such as \LangDyn{}, a given
  8526. expression may produce a value of a different type each time it is
  8527. executed. Consider the following example with a conditional \code{if}
  8528. expression that may return a Boolean or an integer depending on the
  8529. input to the program.
  8530. % part of dynamic_test_25.rkt
  8531. \begin{lstlisting}
  8532. (not (if (eq? (read) 1) #f 0))
  8533. \end{lstlisting}
  8534. Languages that allow expressions to produce different kinds of values
  8535. are called \emph{polymorphic}, a word composed of the Greek roots
  8536. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  8537. are several kinds of polymorphism in programming languages, such as
  8538. subtype polymorphism and parametric
  8539. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  8540. study in this chapter does not have a special name but it is the kind
  8541. that arises in dynamically typed languages.
  8542. Another characteristic of dynamically typed languages is that
  8543. primitive operations, such as \code{not}, are often defined to operate
  8544. on many different types of values. In fact, in Racket, the \code{not}
  8545. operator produces a result for any kind of value: given \code{\#f} it
  8546. returns \code{\#t} and given anything else it returns \code{\#f}.
  8547. Furthermore, even when primitive operations restrict their inputs to
  8548. values of a certain type, this restriction is enforced at runtime
  8549. instead of during compilation. For example, the following vector
  8550. reference results in a run-time contract violation because the index
  8551. must be in integer, not a Boolean such as \code{\#t}.
  8552. \begin{lstlisting}
  8553. (vector-ref (vector 42) #t)
  8554. \end{lstlisting}
  8555. \begin{figure}[tp]
  8556. \centering
  8557. \fbox{
  8558. \begin{minipage}{0.97\textwidth}
  8559. \[
  8560. \begin{array}{rcl}
  8561. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  8562. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp}
  8563. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} \\
  8564. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  8565. &\mid& \key{\#t} \mid \key{\#f}
  8566. \mid \CBINOP{\key{and}}{\Exp}{\Exp}
  8567. \mid \CBINOP{\key{or}}{\Exp}{\Exp}
  8568. \mid \CUNIOP{\key{not}}{\Exp} \\
  8569. &\mid& \LP\itm{cmp}\;\Exp\;\Exp\RP \mid \CIF{\Exp}{\Exp}{\Exp} \\
  8570. &\mid& \LP\key{vector}\;\Exp\ldots\RP \mid
  8571. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  8572. &\mid& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \mid \LP\key{void}\RP \\
  8573. &\mid& \LP\Exp \; \Exp\ldots\RP
  8574. \mid \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  8575. & \mid & \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP\\
  8576. & \mid & \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \mid \LP\key{void?}\;\Exp\RP \\
  8577. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  8578. \LangDyn{} &::=& \Def\ldots\; \Exp
  8579. \end{array}
  8580. \]
  8581. \end{minipage}
  8582. }
  8583. \caption{Syntax of \LangDyn{}, an untyped language (a subset of Racket).}
  8584. \label{fig:r7-concrete-syntax}
  8585. \end{figure}
  8586. \begin{figure}[tp]
  8587. \centering
  8588. \fbox{
  8589. \begin{minipage}{0.96\textwidth}
  8590. \small
  8591. \[
  8592. \begin{array}{lcl}
  8593. \Exp &::=& \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  8594. &\mid& \PRIM{\itm{op}}{\Exp\ldots} \\
  8595. &\mid& \BOOL{\itm{bool}}
  8596. \mid \IF{\Exp}{\Exp}{\Exp} \\
  8597. &\mid& \VOID{} \mid \APPLY{\Exp}{\Exp\ldots} \\
  8598. &\mid& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  8599. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  8600. \LangDyn{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  8601. \end{array}
  8602. \]
  8603. \end{minipage}
  8604. }
  8605. \caption{The abstract syntax of \LangDyn{}.}
  8606. \label{fig:r7-syntax}
  8607. \end{figure}
  8608. The concrete and abstract syntax of \LangDyn{}, our subset of Racket, is
  8609. defined in Figures~\ref{fig:r7-concrete-syntax} and
  8610. \ref{fig:r7-syntax}.
  8611. %
  8612. There is no type checker for \LangDyn{} because it is not a statically
  8613. typed language (it's dynamically typed!).
  8614. The definitional interpreter for \LangDyn{} is presented in
  8615. Figure~\ref{fig:interp-Rdyn} and its auxiliary functions are defined i
  8616. Figure~\ref{fig:interp-Rdyn-aux}. Consider the match case for
  8617. \code{(Int n)}. Instead of simply returning the integer \code{n} (as
  8618. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Rvar}), the
  8619. interpreter for \LangDyn{} creates a \emph{tagged value}\index{tagged
  8620. value} that combines an underlying value with a tag that identifies
  8621. what kind of value it is. We define the following struct
  8622. to represented tagged values.
  8623. \begin{lstlisting}
  8624. (struct Tagged (value tag) #:transparent)
  8625. \end{lstlisting}
  8626. The tags are \code{Integer}, \code{Boolean}, \code{Void},
  8627. \code{Vector}, and \code{Procedure}. Tags are closely related to types
  8628. but don't always capture all the information that a type does. For
  8629. example, a vector of type \code{(Vector Any Any)} is tagged with
  8630. \code{Vector} and a procedure of type \code{(Any Any -> Any)}
  8631. is tagged with \code{Procedure}.
  8632. Next consider the match case for \code{vector-ref}. The
  8633. \code{check-tag} auxiliary function (Figure~\ref{fig:interp-Rdyn-aux})
  8634. is used to ensure that the first argument is a vector and the second
  8635. is an integer. If they are not, a \code{trapped-error} is raised.
  8636. Recall from Section~\ref{sec:interp-Rint} that when a definition
  8637. interpreter raises a \code{trapped-error} error, the compiled code
  8638. must also signal an error by exiting with return code \code{255}. A
  8639. \code{trapped-error} is also raised if the index is not less than
  8640. length of the vector.
  8641. \begin{figure}[tbp]
  8642. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8643. (define ((interp-Rdyn-exp env) ast)
  8644. (define recur (interp-Rdyn-exp env))
  8645. (match ast
  8646. [(Var x) (lookup x env)]
  8647. [(Int n) (Tagged n 'Integer)]
  8648. [(Bool b) (Tagged b 'Boolean)]
  8649. [(Lambda xs rt body)
  8650. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  8651. [(Prim 'vector es)
  8652. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  8653. [(Prim 'vector-ref (list e1 e2))
  8654. (define vec (recur e1)) (define i (recur e2))
  8655. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  8656. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  8657. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  8658. (vector-ref (Tagged-value vec) (Tagged-value i))]
  8659. [(Prim 'vector-set! (list e1 e2 e3))
  8660. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  8661. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  8662. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  8663. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  8664. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  8665. (Tagged (void) 'Void)]
  8666. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  8667. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  8668. [(Prim 'or (list e1 e2))
  8669. (define v1 (recur e1))
  8670. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  8671. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  8672. [(Prim op (list e1))
  8673. #:when (set-member? type-predicates op)
  8674. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  8675. [(Prim op es)
  8676. (define args (map recur es))
  8677. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  8678. (unless (for/or ([expected-tags (op-tags op)])
  8679. (equal? expected-tags tags))
  8680. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  8681. (tag-value
  8682. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  8683. [(If q t f)
  8684. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  8685. [(Apply f es)
  8686. (define new-f (recur f)) (define args (map recur es))
  8687. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  8688. (match f-val
  8689. [`(function ,xs ,body ,lam-env)
  8690. (unless (eq? (length xs) (length args))
  8691. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  8692. (define new-env (append (map cons xs args) lam-env))
  8693. ((interp-Rdyn-exp new-env) body)]
  8694. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  8695. \end{lstlisting}
  8696. \caption{Interpreter for the \LangDyn{} language.}
  8697. \label{fig:interp-Rdyn}
  8698. \end{figure}
  8699. \begin{figure}[tbp]
  8700. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8701. (define (interp-op op)
  8702. (match op
  8703. ['+ fx+]
  8704. ['- fx-]
  8705. ['read read-fixnum]
  8706. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  8707. ['< (lambda (v1 v2)
  8708. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  8709. ['<= (lambda (v1 v2)
  8710. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  8711. ['> (lambda (v1 v2)
  8712. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  8713. ['>= (lambda (v1 v2)
  8714. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  8715. ['boolean? boolean?]
  8716. ['integer? fixnum?]
  8717. ['void? void?]
  8718. ['vector? vector?]
  8719. ['vector-length vector-length]
  8720. ['procedure? (match-lambda
  8721. [`(functions ,xs ,body ,env) #t] [else #f])]
  8722. [else (error 'interp-op "unknown operator" op)]))
  8723. (define (op-tags op)
  8724. (match op
  8725. ['+ '((Integer Integer))]
  8726. ['- '((Integer Integer) (Integer))]
  8727. ['read '(())]
  8728. ['not '((Boolean))]
  8729. ['< '((Integer Integer))]
  8730. ['<= '((Integer Integer))]
  8731. ['> '((Integer Integer))]
  8732. ['>= '((Integer Integer))]
  8733. ['vector-length '((Vector))]))
  8734. (define type-predicates
  8735. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  8736. (define (tag-value v)
  8737. (cond [(boolean? v) (Tagged v 'Boolean)]
  8738. [(fixnum? v) (Tagged v 'Integer)]
  8739. [(procedure? v) (Tagged v 'Procedure)]
  8740. [(vector? v) (Tagged v 'Vector)]
  8741. [(void? v) (Tagged v 'Void)]
  8742. [else (error 'tag-value "unidentified value ~a" v)]))
  8743. (define (check-tag val expected ast)
  8744. (define tag (Tagged-tag val))
  8745. (unless (eq? tag expected)
  8746. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  8747. \end{lstlisting}
  8748. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  8749. \label{fig:interp-Rdyn-aux}
  8750. \end{figure}
  8751. \clearpage
  8752. \section{Representation of Tagged Values}
  8753. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  8754. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  8755. values at the bit level. Because almost every operation in \LangDyn{}
  8756. involves manipulating tagged values, the representation must be
  8757. efficient. Recall that all of our values are 64 bits. We shall steal
  8758. the 3 right-most bits to encode the tag. We use $001$ to identify
  8759. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  8760. and $101$ for the void value. We define the following auxiliary
  8761. function for mapping types to tag codes.
  8762. \begin{align*}
  8763. \itm{tagof}(\key{Integer}) &= 001 \\
  8764. \itm{tagof}(\key{Boolean}) &= 100 \\
  8765. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  8766. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  8767. \itm{tagof}(\key{Void}) &= 101
  8768. \end{align*}
  8769. This stealing of 3 bits comes at some price: our integers are reduced
  8770. to ranging from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  8771. affect vectors and procedures because those values are addresses, and
  8772. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  8773. they are always $000$. Thus, we do not lose information by overwriting
  8774. the rightmost 3 bits with the tag and we can simply zero-out the tag
  8775. to recover the original address.
  8776. To make tagged values into first-class entities, we can give them a
  8777. type, called \code{Any}, and define operations such as \code{Inject}
  8778. and \code{Project} for creating and using them, yielding the \LangAny{}
  8779. intermediate language. We describe how to compile \LangDyn{} to \LangAny{} in
  8780. Section~\ref{sec:compile-r7} but first we describe the \LangAny{} language
  8781. in greater detail.
  8782. \section{The \LangAny{} Language}
  8783. \label{sec:Rany-lang}
  8784. \begin{figure}[tp]
  8785. \centering
  8786. \fbox{
  8787. \begin{minipage}{0.96\textwidth}
  8788. \small
  8789. \[
  8790. \begin{array}{lcl}
  8791. \Type &::= & \ldots \mid \key{Any} \\
  8792. \itm{op} &::= & \ldots \mid \code{any-vector-length}
  8793. \mid \code{any-vector-ref} \mid \code{any-vector-set!}\\
  8794. &\mid& \code{boolean?} \mid \code{integer?} \mid \code{vector?}
  8795. \mid \code{procedure?} \mid \code{void?} \\
  8796. \Exp &::=& \ldots
  8797. \mid \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  8798. &\mid& \INJECT{\Exp}{\FType} \mid \PROJECT{\Exp}{\FType} \\
  8799. \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  8800. \LangAny{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  8801. \end{array}
  8802. \]
  8803. \end{minipage}
  8804. }
  8805. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Rlam-syntax}).}
  8806. \label{fig:Rany-syntax}
  8807. \end{figure}
  8808. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Rany-syntax}.
  8809. (The concrete syntax of \LangAny{} is in the Appendix,
  8810. Figure~\ref{fig:Rany-concrete-syntax}.) The $\INJECT{e}{T}$ form
  8811. converts the value produced by expression $e$ of type $T$ into a
  8812. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  8813. produced by expression $e$ into a value of type $T$ or else halts the
  8814. program if the type tag is not equivalent to $T$.
  8815. %
  8816. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  8817. restricted to a flat type $\FType$, which simplifies the
  8818. implementation and corresponds with what is needed for compiling \LangDyn{}.
  8819. The \code{any-vector} operators adapt the vector operations so that
  8820. they can be applied to a value of type \code{Any}. They also
  8821. generalize the vector operations in that the index is not restricted
  8822. to be a literal integer in the grammar but is allowed to be any
  8823. expression.
  8824. The type predicates such as \key{boolean?} expect their argument to
  8825. produce a tagged value; they return \key{\#t} if the tag corresponds
  8826. to the predicate and they return \key{\#f} otherwise.
  8827. The type checker for \LangAny{} is shown in
  8828. Figures~\ref{fig:type-check-Rany-part-1} and
  8829. \ref{fig:type-check-Rany-part-2} and uses the auxiliary functions in
  8830. Figure~\ref{fig:type-check-Rany-aux}.
  8831. %
  8832. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Rany} and the
  8833. auxiliary functions \code{apply-inject} and \code{apply-project} are
  8834. in Figure~\ref{fig:apply-project}.
  8835. \begin{figure}[btp]
  8836. \begin{lstlisting}[basicstyle=\ttfamily\small]
  8837. (define type-check-Rany-class
  8838. (class type-check-Rlambda-class
  8839. (super-new)
  8840. (inherit check-type-equal?)
  8841. (define/override (type-check-exp env)
  8842. (lambda (e)
  8843. (define recur (type-check-exp env))
  8844. (match e
  8845. [(Inject e1 ty)
  8846. (unless (flat-ty? ty)
  8847. (error 'type-check "may only inject from flat type, not ~a" ty))
  8848. (define-values (new-e1 e-ty) (recur e1))
  8849. (check-type-equal? e-ty ty e)
  8850. (values (Inject new-e1 ty) 'Any)]
  8851. [(Project e1 ty)
  8852. (unless (flat-ty? ty)
  8853. (error 'type-check "may only project to flat type, not ~a" ty))
  8854. (define-values (new-e1 e-ty) (recur e1))
  8855. (check-type-equal? e-ty 'Any e)
  8856. (values (Project new-e1 ty) ty)]
  8857. [(Prim 'any-vector-length (list e1))
  8858. (define-values (e1^ t1) (recur e1))
  8859. (check-type-equal? t1 'Any e)
  8860. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  8861. [(Prim 'any-vector-ref (list e1 e2))
  8862. (define-values (e1^ t1) (recur e1))
  8863. (define-values (e2^ t2) (recur e2))
  8864. (check-type-equal? t1 'Any e)
  8865. (check-type-equal? t2 'Integer e)
  8866. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  8867. [(Prim 'any-vector-set! (list e1 e2 e3))
  8868. (define-values (e1^ t1) (recur e1))
  8869. (define-values (e2^ t2) (recur e2))
  8870. (define-values (e3^ t3) (recur e3))
  8871. (check-type-equal? t1 'Any e)
  8872. (check-type-equal? t2 'Integer e)
  8873. (check-type-equal? t3 'Any e)
  8874. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  8875. \end{lstlisting}
  8876. \caption{Type checker for the \LangAny{} language, part 1.}
  8877. \label{fig:type-check-Rany-part-1}
  8878. \end{figure}
  8879. \begin{figure}[btp]
  8880. \begin{lstlisting}[basicstyle=\ttfamily\small]
  8881. [(ValueOf e ty)
  8882. (define-values (new-e e-ty) (recur e))
  8883. (values (ValueOf new-e ty) ty)]
  8884. [(Prim pred (list e1))
  8885. #:when (set-member? (type-predicates) pred)
  8886. (define-values (new-e1 e-ty) (recur e1))
  8887. (check-type-equal? e-ty 'Any e)
  8888. (values (Prim pred (list new-e1)) 'Boolean)]
  8889. [(If cnd thn els)
  8890. (define-values (cnd^ Tc) (recur cnd))
  8891. (define-values (thn^ Tt) (recur thn))
  8892. (define-values (els^ Te) (recur els))
  8893. (check-type-equal? Tc 'Boolean cnd)
  8894. (check-type-equal? Tt Te e)
  8895. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  8896. [(Exit) (values (Exit) '_)]
  8897. [(Prim 'eq? (list arg1 arg2))
  8898. (define-values (e1 t1) (recur arg1))
  8899. (define-values (e2 t2) (recur arg2))
  8900. (match* (t1 t2)
  8901. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  8902. [(other wise) (check-type-equal? t1 t2 e)])
  8903. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  8904. [else ((super type-check-exp env) e)])))
  8905. ))
  8906. \end{lstlisting}
  8907. \caption{Type checker for the \LangAny{} language, part 2.}
  8908. \label{fig:type-check-Rany-part-2}
  8909. \end{figure}
  8910. \begin{figure}[tbp]
  8911. \begin{lstlisting}
  8912. (define/override (operator-types)
  8913. (append
  8914. '((integer? . ((Any) . Boolean))
  8915. (vector? . ((Any) . Boolean))
  8916. (procedure? . ((Any) . Boolean))
  8917. (void? . ((Any) . Boolean))
  8918. (tag-of-any . ((Any) . Integer))
  8919. (make-any . ((_ Integer) . Any))
  8920. )
  8921. (super operator-types)))
  8922. (define/public (type-predicates)
  8923. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  8924. (define/public (combine-types t1 t2)
  8925. (match (list t1 t2)
  8926. [(list '_ t2) t2]
  8927. [(list t1 '_) t1]
  8928. [(list `(Vector ,ts1 ...)
  8929. `(Vector ,ts2 ...))
  8930. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  8931. (combine-types t1 t2)))]
  8932. [(list `(,ts1 ... -> ,rt1)
  8933. `(,ts2 ... -> ,rt2))
  8934. `(,@(for/list ([t1 ts1] [t2 ts2])
  8935. (combine-types t1 t2))
  8936. -> ,(combine-types rt1 rt2))]
  8937. [else t1]))
  8938. (define/public (flat-ty? ty)
  8939. (match ty
  8940. [(or `Integer `Boolean '_ `Void) #t]
  8941. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  8942. [`(,ts ... -> ,rt)
  8943. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  8944. [else #f]))
  8945. \end{lstlisting}
  8946. \caption{Auxiliary methods for type checking \LangAny{}.}
  8947. \label{fig:type-check-Rany-aux}
  8948. \end{figure}
  8949. \begin{figure}[btp]
  8950. \begin{lstlisting}
  8951. (define interp-Rany-class
  8952. (class interp-Rlambda-class
  8953. (super-new)
  8954. (define/override (interp-op op)
  8955. (match op
  8956. ['boolean? (match-lambda
  8957. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  8958. [else #f])]
  8959. ['integer? (match-lambda
  8960. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  8961. [else #f])]
  8962. ['vector? (match-lambda
  8963. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  8964. [else #f])]
  8965. ['procedure? (match-lambda
  8966. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  8967. [else #f])]
  8968. ['eq? (match-lambda*
  8969. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  8970. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  8971. [ls (apply (super interp-op op) ls)])]
  8972. ['any-vector-ref (lambda (v i)
  8973. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  8974. ['any-vector-set! (lambda (v i a)
  8975. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  8976. ['any-vector-length (lambda (v)
  8977. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  8978. [else (super interp-op op)]))
  8979. (define/override ((interp-exp env) e)
  8980. (define recur (interp-exp env))
  8981. (match e
  8982. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  8983. [(Project e ty2) (apply-project (recur e) ty2)]
  8984. [else ((super interp-exp env) e)]))
  8985. ))
  8986. (define (interp-Rany p)
  8987. (send (new interp-Rany-class) interp-program p))
  8988. \end{lstlisting}
  8989. \caption{Interpreter for \LangAny{}.}
  8990. \label{fig:interp-Rany}
  8991. \end{figure}
  8992. \begin{figure}[tbp]
  8993. \begin{lstlisting}
  8994. (define/public (apply-inject v tg) (Tagged v tg))
  8995. (define/public (apply-project v ty2)
  8996. (define tag2 (any-tag ty2))
  8997. (match v
  8998. [(Tagged v1 tag1)
  8999. (cond
  9000. [(eq? tag1 tag2)
  9001. (match ty2
  9002. [`(Vector ,ts ...)
  9003. (define l1 ((interp-op 'vector-length) v1))
  9004. (cond
  9005. [(eq? l1 (length ts)) v1]
  9006. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  9007. l1 (length ts))])]
  9008. [`(,ts ... -> ,rt)
  9009. (match v1
  9010. [`(function ,xs ,body ,env)
  9011. (cond [(eq? (length xs) (length ts)) v1]
  9012. [else
  9013. (error 'apply-project "arity mismatch ~a != ~a"
  9014. (length xs) (length ts))])]
  9015. [else (error 'apply-project "expected function not ~a" v1)])]
  9016. [else v1])]
  9017. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  9018. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  9019. \end{lstlisting}
  9020. \caption{Auxiliary functions for injection and projection.}
  9021. \label{fig:apply-project}
  9022. \end{figure}
  9023. \clearpage
  9024. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  9025. \label{sec:compile-r7}
  9026. The \code{cast-insert} pass compiles from \LangDyn{} to \LangAny{}.
  9027. Figure~\ref{fig:compile-r7-Rany} shows the compilation of many of the
  9028. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  9029. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  9030. an expression $e'$ in \LangAny{} that has type \key{Any}. For example, the
  9031. first row in Figure~\ref{fig:compile-r7-Rany} shows the compilation of
  9032. the Boolean \code{\#t}, which must be injected to produce an
  9033. expression of type \key{Any}.
  9034. %
  9035. The second row of Figure~\ref{fig:compile-r7-Rany}, the compilation of
  9036. addition, is representative of compilation for many primitive
  9037. operations: the arguments have type \key{Any} and must be projected to
  9038. \key{Integer} before the addition can be performed.
  9039. The compilation of \key{lambda} (third row of
  9040. Figure~\ref{fig:compile-r7-Rany}) shows what happens when we need to
  9041. produce type annotations: we simply use \key{Any}.
  9042. %
  9043. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  9044. has to account for some differences in behavior between \LangDyn{} and
  9045. \LangAny{}. The \LangDyn{} language is more permissive than \LangAny{} regarding what
  9046. kind of values can be used in various places. For example, the
  9047. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  9048. the arguments need not be of the same type (in that case the
  9049. result is \code{\#f}).
  9050. \begin{figure}[btp]
  9051. \centering
  9052. \begin{tabular}{|lll|} \hline
  9053. \begin{minipage}{0.27\textwidth}
  9054. \begin{lstlisting}
  9055. #t
  9056. \end{lstlisting}
  9057. \end{minipage}
  9058. &
  9059. $\Rightarrow$
  9060. &
  9061. \begin{minipage}{0.65\textwidth}
  9062. \begin{lstlisting}
  9063. (inject #t Boolean)
  9064. \end{lstlisting}
  9065. \end{minipage}
  9066. \\[2ex]\hline
  9067. \begin{minipage}{0.27\textwidth}
  9068. \begin{lstlisting}
  9069. (+ |$e_1$| |$e_2$|)
  9070. \end{lstlisting}
  9071. \end{minipage}
  9072. &
  9073. $\Rightarrow$
  9074. &
  9075. \begin{minipage}{0.65\textwidth}
  9076. \begin{lstlisting}
  9077. (inject
  9078. (+ (project |$e'_1$| Integer)
  9079. (project |$e'_2$| Integer))
  9080. Integer)
  9081. \end{lstlisting}
  9082. \end{minipage}
  9083. \\[2ex]\hline
  9084. \begin{minipage}{0.27\textwidth}
  9085. \begin{lstlisting}
  9086. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  9087. \end{lstlisting}
  9088. \end{minipage}
  9089. &
  9090. $\Rightarrow$
  9091. &
  9092. \begin{minipage}{0.65\textwidth}
  9093. \begin{lstlisting}
  9094. (inject
  9095. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  9096. (Any|$\ldots$|Any -> Any))
  9097. \end{lstlisting}
  9098. \end{minipage}
  9099. \\[2ex]\hline
  9100. \begin{minipage}{0.27\textwidth}
  9101. \begin{lstlisting}
  9102. (|$e_0$| |$e_1 \ldots e_n$|)
  9103. \end{lstlisting}
  9104. \end{minipage}
  9105. &
  9106. $\Rightarrow$
  9107. &
  9108. \begin{minipage}{0.65\textwidth}
  9109. \begin{lstlisting}
  9110. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  9111. \end{lstlisting}
  9112. \end{minipage}
  9113. \\[2ex]\hline
  9114. \begin{minipage}{0.27\textwidth}
  9115. \begin{lstlisting}
  9116. (vector-ref |$e_1$| |$e_2$|)
  9117. \end{lstlisting}
  9118. \end{minipage}
  9119. &
  9120. $\Rightarrow$
  9121. &
  9122. \begin{minipage}{0.65\textwidth}
  9123. \begin{lstlisting}
  9124. (any-vector-ref |$e_1'$| |$e_2'$|)
  9125. \end{lstlisting}
  9126. \end{minipage}
  9127. \\[2ex]\hline
  9128. \begin{minipage}{0.27\textwidth}
  9129. \begin{lstlisting}
  9130. (if |$e_1$| |$e_2$| |$e_3$|)
  9131. \end{lstlisting}
  9132. \end{minipage}
  9133. &
  9134. $\Rightarrow$
  9135. &
  9136. \begin{minipage}{0.65\textwidth}
  9137. \begin{lstlisting}
  9138. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  9139. \end{lstlisting}
  9140. \end{minipage}
  9141. \\[2ex]\hline
  9142. \begin{minipage}{0.27\textwidth}
  9143. \begin{lstlisting}
  9144. (eq? |$e_1$| |$e_2$|)
  9145. \end{lstlisting}
  9146. \end{minipage}
  9147. &
  9148. $\Rightarrow$
  9149. &
  9150. \begin{minipage}{0.65\textwidth}
  9151. \begin{lstlisting}
  9152. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  9153. \end{lstlisting}
  9154. \end{minipage}
  9155. \\[2ex]\hline
  9156. \begin{minipage}{0.27\textwidth}
  9157. \begin{lstlisting}
  9158. (not |$e_1$|)
  9159. \end{lstlisting}
  9160. \end{minipage}
  9161. &
  9162. $\Rightarrow$
  9163. &
  9164. \begin{minipage}{0.65\textwidth}
  9165. \begin{lstlisting}
  9166. (if (eq? |$e'_1$| (inject #f Boolean))
  9167. (inject #t Boolean) (inject #f Boolean))
  9168. \end{lstlisting}
  9169. \end{minipage}
  9170. \\[2ex]\hline
  9171. \end{tabular}
  9172. \caption{Cast Insertion}
  9173. \label{fig:compile-r7-Rany}
  9174. \end{figure}
  9175. \section{Reveal Casts}
  9176. \label{sec:reveal-casts-Rany}
  9177. % TODO: define R'_6
  9178. In the \code{reveal-casts} pass we recommend compiling \code{project}
  9179. into an \code{if} expression that checks whether the value's tag
  9180. matches the target type; if it does, the value is converted to a value
  9181. of the target type by removing the tag; if it does not, the program
  9182. exits. To perform these actions we need a new primitive operation,
  9183. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  9184. The \code{tag-of-any} operation retrieves the type tag from a tagged
  9185. value of type \code{Any}. The \code{ValueOf} form retrieves the
  9186. underlying value from a tagged value. The \code{ValueOf} form
  9187. includes the type for the underlying value which is used by the type
  9188. checker. Finally, the \code{Exit} form ends the execution of the
  9189. program.
  9190. If the target type of the projection is \code{Boolean} or
  9191. \code{Integer}, then \code{Project} can be translated as follows.
  9192. \begin{center}
  9193. \begin{minipage}{1.0\textwidth}
  9194. \begin{lstlisting}
  9195. (Project |$e$| |$\FType$|)
  9196. |$\Rightarrow$|
  9197. (Let |$\itm{tmp}$| |$e'$|
  9198. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  9199. (Int |$\itm{tagof}(\FType)$|)))
  9200. (ValueOf |$\itm{tmp}$| |$\FType$|)
  9201. (Exit)))
  9202. \end{lstlisting}
  9203. \end{minipage}
  9204. \end{center}
  9205. If the target type of the projection is a vector or function type,
  9206. then there is a bit more work to do. For vectors, check that the
  9207. length of the vector type matches the length of the vector (using the
  9208. \code{vector-length} primitive). For functions, check that the number
  9209. of parameters in the function type matches the function's arity (using
  9210. \code{procedure-arity}).
  9211. Regarding \code{inject}, we recommend compiling it to a slightly
  9212. lower-level primitive operation named \code{make-any}. This operation
  9213. takes a tag instead of a type.
  9214. \begin{center}
  9215. \begin{minipage}{1.0\textwidth}
  9216. \begin{lstlisting}
  9217. (Inject |$e$| |$\FType$|)
  9218. |$\Rightarrow$|
  9219. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  9220. \end{lstlisting}
  9221. \end{minipage}
  9222. \end{center}
  9223. The type predicates (\code{boolean?}, etc.) can be translated into
  9224. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  9225. translation of \code{Project}.
  9226. The \code{any-vector-ref} and \code{any-vector-set!} operations
  9227. combine the projection action with the vector operation. Also, the
  9228. read and write operations allow arbitrary expressions for the index so
  9229. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany-part-1})
  9230. cannot guarantee that the index is within bounds. Thus, we insert code
  9231. to perform bounds checking at runtime. The translation for
  9232. \code{any-vector-ref} is as follows and the other two operations are
  9233. translated in a similar way.
  9234. \begin{lstlisting}
  9235. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  9236. |$\Rightarrow$|
  9237. (Let |$v$| |$e'_1$|
  9238. (Let |$i$| |$e'_2$|
  9239. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  9240. (If (Prim '< (list (Var |$i$|)
  9241. (Prim 'any-vector-length (list (Var |$v$|)))))
  9242. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  9243. (Exit))))
  9244. \end{lstlisting}
  9245. \section{Remove Complex Operands}
  9246. \label{sec:rco-Rany}
  9247. The \code{ValueOf} and \code{Exit} forms are both complex expressions.
  9248. The subexpression of \code{ValueOf} must be atomic.
  9249. \section{Explicate Control and \LangCAny{}}
  9250. \label{sec:explicate-Rany}
  9251. The output of \code{explicate-control} is the \LangCAny{} language whose
  9252. syntax is defined in Figure~\ref{fig:c5-syntax}. The \code{ValueOf}
  9253. form that we added to \LangAny{} remains an expression and the \code{Exit}
  9254. expression becomes a $\Tail$. Also, note that the index argument of
  9255. \code{vector-ref} and \code{vector-set!} is an $\Atm$ instead
  9256. of an integer, as in \LangCVec{} (Figure~\ref{fig:c2-syntax}).
  9257. \begin{figure}[tp]
  9258. \fbox{
  9259. \begin{minipage}{0.96\textwidth}
  9260. \small
  9261. \[
  9262. \begin{array}{lcl}
  9263. \Exp &::= & \ldots
  9264. \mid \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  9265. &\mid& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  9266. &\mid& \VALUEOF{\Exp}{\FType} \\
  9267. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  9268. \mid \LP\key{Collect} \,\itm{int}\RP }\\
  9269. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  9270. \mid \GOTO{\itm{label}} } \\
  9271. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  9272. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  9273. \mid \LP\key{Exit}\RP \\
  9274. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  9275. \LangCLam{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  9276. \end{array}
  9277. \]
  9278. \end{minipage}
  9279. }
  9280. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  9281. \label{fig:c5-syntax}
  9282. \end{figure}
  9283. \section{Select Instructions}
  9284. \label{sec:select-Rany}
  9285. In the \code{select-instructions} pass we translate the primitive
  9286. operations on the \code{Any} type to x86 instructions that involve
  9287. manipulating the 3 tag bits of the tagged value.
  9288. \paragraph{Make-any}
  9289. We recommend compiling the \key{make-any} primitive as follows if the
  9290. tag is for \key{Integer} or \key{Boolean}. The \key{salq} instruction
  9291. shifts the destination to the left by the number of bits specified its
  9292. source argument (in this case $3$, the length of the tag) and it
  9293. preserves the sign of the integer. We use the \key{orq} instruction to
  9294. combine the tag and the value to form the tagged value. \\
  9295. \begin{lstlisting}
  9296. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  9297. |$\Rightarrow$|
  9298. movq |$e'$|, |\itm{lhs'}|
  9299. salq $3, |\itm{lhs'}|
  9300. orq $|$\itm{tag}$|, |\itm{lhs'}|
  9301. \end{lstlisting}
  9302. The instruction selection for vectors and procedures is different
  9303. because their is no need to shift them to the left. The rightmost 3
  9304. bits are already zeros as described at the beginning of this
  9305. chapter. So we just combine the value and the tag using \key{orq}. \\
  9306. \begin{lstlisting}
  9307. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  9308. |$\Rightarrow$|
  9309. movq |$e'$|, |\itm{lhs'}|
  9310. orq $|$\itm{tag}$|, |\itm{lhs'}|
  9311. \end{lstlisting}
  9312. \paragraph{Tag-of-any}
  9313. Recall that the \code{tag-of-any} operation extracts the type tag from
  9314. a value of type \code{Any}. The type tag is the bottom three bits, so
  9315. we obtain the tag by taking the bitwise-and of the value with $111$
  9316. ($7$ in decimal).
  9317. \begin{lstlisting}
  9318. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  9319. |$\Rightarrow$|
  9320. movq |$e'$|, |\itm{lhs'}|
  9321. andq $7, |\itm{lhs'}|
  9322. \end{lstlisting}
  9323. \paragraph{ValueOf}
  9324. Like \key{make-any}, the instructions for \key{ValueOf} are different
  9325. depending on whether the type $T$ is a pointer (vector or procedure)
  9326. or not (Integer or Boolean). The following shows the instruction
  9327. selection for Integer and Boolean. We produce an untagged value by
  9328. shifting it to the right by 3 bits.
  9329. \begin{lstlisting}
  9330. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  9331. |$\Rightarrow$|
  9332. movq |$e'$|, |\itm{lhs'}|
  9333. sarq $3, |\itm{lhs'}|
  9334. \end{lstlisting}
  9335. %
  9336. In the case for vectors and procedures, there is no need to
  9337. shift. Instead we just need to zero-out the rightmost 3 bits. We
  9338. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  9339. decimal) and apply \code{bitwise-not} to obtain $\ldots 11111000$ (-8
  9340. in decimal) which we \code{movq} into the destination $\itm{lhs}$. We
  9341. then apply \code{andq} with the tagged value to get the desired
  9342. result. \\
  9343. \begin{lstlisting}
  9344. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  9345. |$\Rightarrow$|
  9346. movq $|$-8$|, |\itm{lhs'}|
  9347. andq |$e'$|, |\itm{lhs'}|
  9348. \end{lstlisting}
  9349. %% \paragraph{Type Predicates} We leave it to the reader to
  9350. %% devise a sequence of instructions to implement the type predicates
  9351. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  9352. \paragraph{Any-vector-length}
  9353. \begin{lstlisting}
  9354. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$a_1$|)))
  9355. |$\Longrightarrow$|
  9356. movq |$\neg 111$|, %r11
  9357. andq |$a_1'$|, %r11
  9358. movq 0(%r11), %r11
  9359. andq $126, %r11
  9360. sarq $1, %r11
  9361. movq %r11, |$\itm{lhs'}$|
  9362. \end{lstlisting}
  9363. \paragraph{Any-vector-ref}
  9364. The index may be an arbitrary atom so instead of computing the offset
  9365. at compile time, instructions need to be generated to compute the
  9366. offset at runtime as follows. Note the use of the new instruction
  9367. \code{imulq}.
  9368. \begin{center}
  9369. \begin{minipage}{0.96\textwidth}
  9370. \begin{lstlisting}
  9371. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$a_1$| |$a_2$|)))
  9372. |$\Longrightarrow$|
  9373. movq |$\neg 111$|, %r11
  9374. andq |$a_1'$|, %r11
  9375. movq |$a_2'$|, %rax
  9376. addq $1, %rax
  9377. imulq $8, %rax
  9378. addq %rax, %r11
  9379. movq 0(%r11) |$\itm{lhs'}$|
  9380. \end{lstlisting}
  9381. \end{minipage}
  9382. \end{center}
  9383. \paragraph{Any-vector-set!}
  9384. The code generation for \code{any-vector-set!} is similar to the other
  9385. \code{any-vector} operations.
  9386. \section{Register Allocation for \LangAny{}}
  9387. \label{sec:register-allocation-Rany}
  9388. \index{register allocation}
  9389. There is an interesting interaction between tagged values and garbage
  9390. collection that has an impact on register allocation. A variable of
  9391. type \code{Any} might refer to a vector and therefore it might be a
  9392. root that needs to be inspected and copied during garbage
  9393. collection. Thus, we need to treat variables of type \code{Any} in a
  9394. similar way to variables of type \code{Vector} for purposes of
  9395. register allocation. In particular,
  9396. \begin{itemize}
  9397. \item If a variable of type \code{Any} is live during a function call,
  9398. then it must be spilled. This can be accomplished by changing
  9399. \code{build-interference} to mark all variables of type \code{Any}
  9400. that are live after a \code{callq} as interfering with all the
  9401. registers.
  9402. \item If a variable of type \code{Any} is spilled, it must be spilled
  9403. to the root stack instead of the normal procedure call stack.
  9404. \end{itemize}
  9405. Another concern regarding the root stack is that the garbage collector
  9406. needs to differentiate between (1) plain old pointers to tuples, (2) a
  9407. tagged value that points to a tuple, and (3) a tagged value that is
  9408. not a tuple. We enable this differentiation by choosing not to use the
  9409. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  9410. reserved for identifying plain old pointers to tuples. That way, if
  9411. one of the first three bits is set, then we have a tagged value and
  9412. inspecting the tag can differentiation between vectors ($010$) and the
  9413. other kinds of values.
  9414. \begin{exercise}\normalfont
  9415. Expand your compiler to handle \LangAny{} as discussed in the last few
  9416. sections. Create 5 new programs that use the \code{Any} type and the
  9417. new operations (\code{inject}, \code{project}, \code{boolean?},
  9418. etc.). Test your compiler on these new programs and all of your
  9419. previously created test programs.
  9420. \end{exercise}
  9421. \begin{exercise}\normalfont
  9422. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  9423. Create tests for \LangDyn{} by adapting ten of your previous test programs
  9424. by removing type annotations. Add 5 more tests programs that
  9425. specifically rely on the language being dynamically typed. That is,
  9426. they should not be legal programs in a statically typed language, but
  9427. nevertheless, they should be valid \LangDyn{} programs that run to
  9428. completion without error.
  9429. \end{exercise}
  9430. \begin{figure}[p]
  9431. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9432. \node (Rfun) at (0,4) {\large \LangDyn{}};
  9433. \node (Rfun-2) at (3,4) {\large \LangDyn{}};
  9434. \node (Rfun-3) at (6,4) {\large \LangDyn{}};
  9435. \node (Rfun-4) at (9,4) {\large \LangDynFunRef{}};
  9436. \node (Rfun-5) at (9,2) {\large \LangAnyFunRef{}};
  9437. \node (Rfun-6) at (12,2) {\large \LangAnyFunRef{}};
  9438. \node (Rfun-7) at (12,0) {\large \LangAnyFunRef{}};
  9439. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  9440. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  9441. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  9442. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  9443. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  9444. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  9445. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  9446. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  9447. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  9448. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  9449. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  9450. \path[->,bend left=15] (Rfun) edge [above] node
  9451. {\ttfamily\footnotesize shrink} (Rfun-2);
  9452. \path[->,bend left=15] (Rfun-2) edge [above] node
  9453. {\ttfamily\footnotesize uniquify} (Rfun-3);
  9454. \path[->,bend left=15] (Rfun-3) edge [above] node
  9455. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  9456. \path[->,bend right=15] (Rfun-4) edge [left] node
  9457. {\ttfamily\footnotesize cast-insert} (Rfun-5);
  9458. \path[->,bend left=15] (Rfun-5) edge [above] node
  9459. {\ttfamily\footnotesize check-bounds} (Rfun-6);
  9460. \path[->,bend left=15] (Rfun-6) edge [left] node
  9461. {\ttfamily\footnotesize reveal-casts} (Rfun-7);
  9462. \path[->,bend left=15] (Rfun-7) edge [below] node
  9463. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  9464. \path[->,bend right=15] (F1-2) edge [above] node
  9465. {\ttfamily\footnotesize limit-fun.} (F1-3);
  9466. \path[->,bend right=15] (F1-3) edge [above] node
  9467. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9468. \path[->,bend right=15] (F1-4) edge [above] node
  9469. {\ttfamily\footnotesize remove-complex.} (F1-5);
  9470. \path[->,bend right=15] (F1-5) edge [right] node
  9471. {\ttfamily\footnotesize explicate-control} (C3-2);
  9472. \path[->,bend left=15] (C3-2) edge [left] node
  9473. {\ttfamily\footnotesize select-instr.} (x86-2);
  9474. \path[->,bend right=15] (x86-2) edge [left] node
  9475. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  9476. \path[->,bend right=15] (x86-2-1) edge [below] node
  9477. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  9478. \path[->,bend right=15] (x86-2-2) edge [left] node
  9479. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  9480. \path[->,bend left=15] (x86-3) edge [above] node
  9481. {\ttfamily\footnotesize patch-instr.} (x86-4);
  9482. \path[->,bend left=15] (x86-4) edge [right] node
  9483. {\ttfamily\footnotesize print-x86} (x86-5);
  9484. \end{tikzpicture}
  9485. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  9486. \label{fig:Rdyn-passes}
  9487. \end{figure}
  9488. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  9489. for the compilation of \LangDyn{}.
  9490. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9491. \chapter{Loops and Assignment}
  9492. \label{ch:Rwhile}
  9493. % TODO: define R'_8
  9494. % TODO: multi-graph
  9495. In this chapter we study two features that are the hallmarks of
  9496. imperative programming languages: loops and assignments to local
  9497. variables. The following example demonstrates these new features by
  9498. computing the sum of the first five positive integers.
  9499. % similar to loop_test_1.rkt
  9500. \begin{lstlisting}
  9501. (let ([sum 0])
  9502. (let ([i 5])
  9503. (begin
  9504. (while (> i 0)
  9505. (begin
  9506. (set! sum (+ sum i))
  9507. (set! i (- i 1))))
  9508. sum)))
  9509. \end{lstlisting}
  9510. The \code{while} loop consists of a condition and a body.
  9511. %
  9512. The \code{set!} consists of a variable and a right-hand-side expression.
  9513. %
  9514. The primary purpose of both the \code{while} loop and \code{set!} is
  9515. to cause side effects, so it is convenient to also include in a
  9516. language feature for sequencing side effects: the \code{begin}
  9517. expression. It consists of one or more subexpressions that are
  9518. evaluated left-to-right.
  9519. \section{The \LangLoop{} Language}
  9520. \begin{figure}[tp]
  9521. \centering
  9522. \fbox{
  9523. \begin{minipage}{0.96\textwidth}
  9524. \small
  9525. \[
  9526. \begin{array}{lcl}
  9527. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  9528. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  9529. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  9530. &\mid& \gray{\key{\#t} \mid \key{\#f}
  9531. \mid (\key{and}\;\Exp\;\Exp)
  9532. \mid (\key{or}\;\Exp\;\Exp)
  9533. \mid (\key{not}\;\Exp) } \\
  9534. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  9535. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  9536. (\key{vector-ref}\;\Exp\;\Int)} \\
  9537. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  9538. \mid (\Exp \; \Exp\ldots) } \\
  9539. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP
  9540. \mid \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  9541. &\mid& \CSETBANG{\Var}{\Exp}
  9542. \mid \CBEGIN{\Exp\ldots}{\Exp}
  9543. \mid \CWHILE{\Exp}{\Exp} \\
  9544. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  9545. \LangLoop{} &::=& \gray{\Def\ldots \; \Exp}
  9546. \end{array}
  9547. \]
  9548. \end{minipage}
  9549. }
  9550. \caption{The concrete syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-concrete-syntax}).}
  9551. \label{fig:Rwhile-concrete-syntax}
  9552. \end{figure}
  9553. \begin{figure}[tp]
  9554. \centering
  9555. \fbox{
  9556. \begin{minipage}{0.96\textwidth}
  9557. \small
  9558. \[
  9559. \begin{array}{lcl}
  9560. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  9561. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  9562. &\mid& \gray{ \BOOL{\itm{bool}}
  9563. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  9564. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  9565. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  9566. &\mid& \gray{ \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp} }\\
  9567. &\mid& \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  9568. \mid \WHILE{\Exp}{\Exp} \\
  9569. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  9570. \LangLoop{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  9571. \end{array}
  9572. \]
  9573. \end{minipage}
  9574. }
  9575. \caption{The abstract syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-syntax}).}
  9576. \label{fig:Rwhile-syntax}
  9577. \end{figure}
  9578. The concrete syntax of \LangLoop{} is defined in
  9579. Figure~\ref{fig:Rwhile-concrete-syntax} and its abstract syntax is defined
  9580. in Figure~\ref{fig:Rwhile-syntax}.
  9581. %
  9582. The definitional interpreter for \LangLoop{} is shown in
  9583. Figure~\ref{fig:interp-Rwhile}. We add three new cases for \code{SetBang},
  9584. \code{WhileLoop}, and \code{Begin} and we make changes to the cases
  9585. for \code{Var}, \code{Let}, and \code{Apply} regarding variables. To
  9586. support assignment to variables and to make their lifetimes indefinite
  9587. (see the second example in Section~\ref{sec:assignment-scoping}), we
  9588. box the value that is bound to each variable (in \code{Let}) and
  9589. function parameter (in \code{Apply}). The case for \code{Var} unboxes
  9590. the value.
  9591. %
  9592. Now to discuss the new cases. For \code{SetBang}, we lookup the
  9593. variable in the environment to obtain a boxed value and then we change
  9594. it using \code{set-box!} to the result of evaluating the right-hand
  9595. side. The result value of a \code{SetBang} is \code{void}.
  9596. %
  9597. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  9598. if the result is true, 2) evaluate the body.
  9599. The result value of a \code{while} loop is also \code{void}.
  9600. %
  9601. Finally, the $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  9602. subexpressions \itm{es} for their effects and then evaluates
  9603. and returns the result from \itm{body}.
  9604. \begin{figure}[tbp]
  9605. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9606. (define interp-Rwhile-class
  9607. (class interp-Rany-class
  9608. (super-new)
  9609. (define/override ((interp-exp env) e)
  9610. (define recur (interp-exp env))
  9611. (match e
  9612. [(SetBang x rhs)
  9613. (set-box! (lookup x env) (recur rhs))]
  9614. [(WhileLoop cnd body)
  9615. (define (loop)
  9616. (cond [(recur cnd) (recur body) (loop)]
  9617. [else (void)]))
  9618. (loop)]
  9619. [(Begin es body)
  9620. (for ([e es]) (recur e))
  9621. (recur body)]
  9622. [else ((super interp-exp env) e)]))
  9623. ))
  9624. (define (interp-Rwhile p)
  9625. (send (new interp-Rwhile-class) interp-program p))
  9626. \end{lstlisting}
  9627. \caption{Interpreter for \LangLoop{}.}
  9628. \label{fig:interp-Rwhile}
  9629. \end{figure}
  9630. The type checker for \LangLoop{} is define in
  9631. Figure~\ref{fig:type-check-Rwhile}. For \code{SetBang}, the type of the
  9632. variable and the right-hand-side must agree. The result type is
  9633. \code{Void}. For the \code{WhileLoop}, the condition must be a
  9634. \code{Boolean}. The result type is also \code{Void}. For
  9635. \code{Begin}, the result type is the type of its last subexpression.
  9636. \begin{figure}[tbp]
  9637. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9638. (define type-check-Rwhile-class
  9639. (class type-check-Rany-class
  9640. (super-new)
  9641. (inherit check-type-equal?)
  9642. (define/override (type-check-exp env)
  9643. (lambda (e)
  9644. (define recur (type-check-exp env))
  9645. (match e
  9646. [(SetBang x rhs)
  9647. (define-values (rhs^ rhsT) (recur rhs))
  9648. (define varT (dict-ref env x))
  9649. (check-type-equal? rhsT varT e)
  9650. (values (SetBang x rhs^) 'Void)]
  9651. [(WhileLoop cnd body)
  9652. (define-values (cnd^ Tc) (recur cnd))
  9653. (check-type-equal? Tc 'Boolean e)
  9654. (define-values (body^ Tbody) ((type-check-exp env) body))
  9655. (values (WhileLoop cnd^ body^) 'Void)]
  9656. [(Begin es body)
  9657. (define-values (es^ ts)
  9658. (for/lists (l1 l2) ([e es]) (recur e)))
  9659. (define-values (body^ Tbody) (recur body))
  9660. (values (Begin es^ body^) Tbody)]
  9661. [else ((super type-check-exp env) e)])))
  9662. ))
  9663. (define (type-check-Rwhile p)
  9664. (send (new type-check-Rwhile-class) type-check-program p))
  9665. \end{lstlisting}
  9666. \caption{Type checking \key{SetBang}, \key{WhileLoop},
  9667. and \code{Begin} in \LangLoop{}.}
  9668. \label{fig:type-check-Rwhile}
  9669. \end{figure}
  9670. At first glance, the translation of these language features to x86
  9671. seems straightforward because the \LangCFun{} intermediate language already
  9672. supports all of the ingredients that we need: assignment, \code{goto},
  9673. conditional branching, and sequencing. However, there are two
  9674. complications that arise which we discuss in the next two
  9675. sections. After that we introduce one new compiler pass and the
  9676. changes necessary to the existing passes.
  9677. \section{Assignment and Lexically Scoped Functions}
  9678. \label{sec:assignment-scoping}
  9679. The addition of assignment raises a problem with our approach to
  9680. implementing lexically-scoped functions. Consider the following
  9681. example in which function \code{f} has a free variable \code{x} that
  9682. is changed after \code{f} is created but before the call to \code{f}.
  9683. % loop_test_11.rkt
  9684. \begin{lstlisting}
  9685. (let ([x 0])
  9686. (let ([y 0])
  9687. (let ([z 20])
  9688. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  9689. (begin
  9690. (set! x 10)
  9691. (set! y 12)
  9692. (f y))))))
  9693. \end{lstlisting}
  9694. The correct output for this example is \code{42} because the call to
  9695. \code{f} is required to use the current value of \code{x} (which is
  9696. \code{10}). Unfortunately, the closure conversion pass
  9697. (Section~\ref{sec:closure-conversion}) generates code for the
  9698. \code{lambda} that copies the old value of \code{x} into a
  9699. closure. Thus, if we naively add support for assignment to our current
  9700. compiler, the output of this program would be \code{32}.
  9701. A first attempt at solving this problem would be to save a pointer to
  9702. \code{x} in the closure and change the occurrences of \code{x} inside
  9703. the lambda to dereference the pointer. Of course, this would require
  9704. assigning \code{x} to the stack and not to a register. However, the
  9705. problem goes a bit deeper. Consider the following example in which we
  9706. create a counter abstraction by creating a pair of functions that
  9707. share the free variable \code{x}.
  9708. % similar to loop_test_10.rkt
  9709. \begin{lstlisting}
  9710. (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  9711. (vector
  9712. (lambda: () : Integer x)
  9713. (lambda: () : Void (set! x (+ 1 x)))))
  9714. (let ([counter (f 0)])
  9715. (let ([get (vector-ref counter 0)])
  9716. (let ([inc (vector-ref counter 1)])
  9717. (begin
  9718. (inc)
  9719. (get)))))
  9720. \end{lstlisting}
  9721. In this example, the lifetime of \code{x} extends beyond the lifetime
  9722. of the call to \code{f}. Thus, if we were to store \code{x} on the
  9723. stack frame for the call to \code{f}, it would be gone by the time we
  9724. call \code{inc} and \code{get}, leaving us with dangling pointers for
  9725. \code{x}. This example demonstrates that when a variable occurs free
  9726. inside a \code{lambda}, its lifetime becomes indefinite. Thus, the
  9727. value of the variable needs to live on the heap. The verb ``box'' is
  9728. often used for allocating a single value on the heap, producing a
  9729. pointer, and ``unbox'' for dereferencing the pointer.
  9730. We recommend solving these problems by ``boxing'' the local variables
  9731. that are in the intersection of 1) variables that appear on the
  9732. left-hand-side of a \code{set!} and 2) variables that occur free
  9733. inside a \code{lambda}. We shall introduce a new pass named
  9734. \code{convert-assignments} in Section~\ref{sec:convert-assignments} to
  9735. perform this translation. But before diving into the compiler passes,
  9736. we one more problem to discuss.
  9737. \section{Cyclic Control Flow and Dataflow Analysis}
  9738. \label{sec:dataflow-analysis}
  9739. Up until this point the control-flow graphs generated in
  9740. \code{explicate-control} were guaranteed to be acyclic. However, each
  9741. \code{while} loop introduces a cycle in the control-flow graph.
  9742. But does that matter?
  9743. %
  9744. Indeed it does. Recall that for register allocation, the compiler
  9745. performs liveness analysis to determine which variables can share the
  9746. same register. In Section~\ref{sec:liveness-analysis-Rif} we analyze
  9747. the control-flow graph in reverse topological order, but topological
  9748. order is only well-defined for acyclic graphs.
  9749. Let us return to the example of computing the sum of the first five
  9750. positive integers. Here is the program after instruction selection but
  9751. before register allocation.
  9752. \begin{center}
  9753. \begin{minipage}{0.45\textwidth}
  9754. \begin{lstlisting}
  9755. (define (main) : Integer
  9756. mainstart:
  9757. movq $0, sum1
  9758. movq $5, i2
  9759. jmp block5
  9760. block5:
  9761. movq i2, tmp3
  9762. cmpq tmp3, $0
  9763. jl block7
  9764. jmp block8
  9765. \end{lstlisting}
  9766. \end{minipage}
  9767. \begin{minipage}{0.45\textwidth}
  9768. \begin{lstlisting}
  9769. block7:
  9770. addq i2, sum1
  9771. movq $1, tmp4
  9772. negq tmp4
  9773. addq tmp4, i2
  9774. jmp block5
  9775. block8:
  9776. movq $27, %rax
  9777. addq sum1, %rax
  9778. jmp mainconclusion
  9779. )
  9780. \end{lstlisting}
  9781. \end{minipage}
  9782. \end{center}
  9783. Recall that liveness analysis works backwards, starting at the end
  9784. of each function. For this example we could start with \code{block8}
  9785. because we know what is live at the beginning of the conclusion,
  9786. just \code{rax} and \code{rsp}. So the live-before set
  9787. for \code{block8} is $\{\ttm{rsp},\ttm{sum1}\}$.
  9788. %
  9789. Next we might try to analyze \code{block5} or \code{block7}, but
  9790. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9791. we are stuck.
  9792. The way out of this impasse comes from the realization that one can
  9793. perform liveness analysis starting with an empty live-after set to
  9794. compute an under-approximation of the live-before set. By
  9795. \emph{under-approximation}, we mean that the set only contains
  9796. variables that are really live, but it may be missing some. Next, the
  9797. under-approximations for each block can be improved by 1) updating the
  9798. live-after set for each block using the approximate live-before sets
  9799. from the other blocks and 2) perform liveness analysis again on each
  9800. block. In fact, by iterating this process, the under-approximations
  9801. eventually become the correct solutions!
  9802. %
  9803. This approach of iteratively analyzing a control-flow graph is
  9804. applicable to many static analysis problems and goes by the name
  9805. \emph{dataflow analysis}\index{dataflow analysis}. It was invented by
  9806. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  9807. Washington.
  9808. Let us apply this approach to the above example. We use the empty set
  9809. for the initial live-before set for each block. Let $m_0$ be the
  9810. following mapping from label names to sets of locations (variables and
  9811. registers).
  9812. \begin{center}
  9813. \begin{lstlisting}
  9814. mainstart: {}
  9815. block5: {}
  9816. block7: {}
  9817. block8: {}
  9818. \end{lstlisting}
  9819. \end{center}
  9820. Using the above live-before approximations, we determine the
  9821. live-after for each block and then apply liveness analysis to each
  9822. block. This produces our next approximation $m_1$ of the live-before
  9823. sets.
  9824. \begin{center}
  9825. \begin{lstlisting}
  9826. mainstart: {}
  9827. block5: {i2}
  9828. block7: {i2, sum1}
  9829. block8: {rsp, sum1}
  9830. \end{lstlisting}
  9831. \end{center}
  9832. For the second round, the live-after for \code{mainstart} is the
  9833. current live-before for \code{block5}, which is \code{\{i2\}}. So the
  9834. liveness analysis for \code{mainstart} computes the empty set. The
  9835. live-after for \code{block5} is the union of the live-before sets for
  9836. \code{block7} and \code{block8}, which is \code{\{i2 , rsp, sum1\}}.
  9837. So the liveness analysis for \code{block5} computes \code{\{i2 , rsp,
  9838. sum1\}}. The live-after for \code{block7} is the live-before for
  9839. \code{block5} (from the previous iteration), which is \code{\{i2\}}.
  9840. So the liveness analysis for \code{block7} remains \code{\{i2,
  9841. sum1\}}. Together these yield the following approximation $m_2$ of
  9842. the live-before sets.
  9843. \begin{center}
  9844. \begin{lstlisting}
  9845. mainstart: {}
  9846. block5: {i2, rsp, sum1}
  9847. block7: {i2, sum1}
  9848. block8: {rsp, sum1}
  9849. \end{lstlisting}
  9850. \end{center}
  9851. In the preceding iteration, only \code{block5} changed, so we can
  9852. limit our attention to \code{mainstart} and \code{block7}, the two
  9853. blocks that jump to \code{block5}. As a result, the live-before sets
  9854. for \code{mainstart} and \code{block7} are updated to include
  9855. \code{rsp}, yielding the following approximation $m_3$.
  9856. \begin{center}
  9857. \begin{lstlisting}
  9858. mainstart: {rsp}
  9859. block5: {i2, rsp, sum1}
  9860. block7: {i2, rsp, sum1}
  9861. block8: {rsp, sum1}
  9862. \end{lstlisting}
  9863. \end{center}
  9864. Because \code{block7} changed, we analyze \code{block5} once more, but
  9865. its live-before set remains \code{\{ i2, rsp, sum1 \}}. At this point
  9866. our approximations have converged, so $m_3$ is the solution.
  9867. This iteration process is guaranteed to converge to a solution by the
  9868. Kleene Fixed-Point Theorem, a general theorem about functions on
  9869. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9870. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9871. elements, a least element $\bot$ (pronounced bottom), and a join
  9872. operator $\sqcup$.\index{lattice}\index{bottom}\index{partial
  9873. ordering}\index{join}\footnote{Technically speaking, we will be
  9874. working with join semi-lattices.} When two elements are ordered $m_i
  9875. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  9876. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  9877. approximation than $m_i$. The bottom element $\bot$ represents the
  9878. complete lack of information, i.e., the worst approximation. The join
  9879. operator takes two lattice elements and combines their information,
  9880. i.e., it produces the least upper bound of the two.\index{least upper
  9881. bound}
  9882. A dataflow analysis typically involves two lattices: one lattice to
  9883. represent abstract states and another lattice that aggregates the
  9884. abstract states of all the blocks in the control-flow graph. For
  9885. liveness analysis, an abstract state is a set of locations. We form
  9886. the lattice $L$ by taking its elements to be sets of locations, the
  9887. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9888. set, and the join operator to be set union.
  9889. %
  9890. We form a second lattice $M$ by taking its elements to be mappings
  9891. from the block labels to sets of locations (elements of $L$). We
  9892. order the mappings point-wise, using the ordering of $L$. So given any
  9893. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9894. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9895. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9896. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  9897. We can think of one iteration of liveness analysis as being a function
  9898. $f$ on the lattice $M$. It takes a mapping as input and computes a new
  9899. mapping.
  9900. \[
  9901. f(m_i) = m_{i+1}
  9902. \]
  9903. Next let us think for a moment about what a final solution $m_s$
  9904. should look like. If we perform liveness analysis using the solution
  9905. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9906. solution should be a \emph{fixed point} of the function $f$.\index{fixed point}
  9907. \[
  9908. f(m_s) = m_s
  9909. \]
  9910. Furthermore, the solution should only include locations that are
  9911. forced to be there by performing liveness analysis on the program, so
  9912. the solution should be the \emph{least} fixed point.\index{least fixed point}
  9913. The Kleene Fixed-Point Theorem states that if a function $f$ is
  9914. monotone (better inputs produce better outputs), then the least fixed
  9915. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9916. chain} obtained by starting at $\bot$ and iterating $f$ as
  9917. follows.\index{Kleene Fixed-Point Theorem}
  9918. \[
  9919. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9920. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9921. \]
  9922. When a lattice contains only finitely-long ascending chains, then
  9923. every Kleene chain tops out at some fixed point after a number of
  9924. iterations of $f$. So that fixed point is also a least upper
  9925. bound of the chain.
  9926. \[
  9927. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9928. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9929. \]
  9930. The liveness analysis is indeed a monotone function and the lattice
  9931. $M$ only has finitely-long ascending chains because there are only a
  9932. finite number of variables and blocks in the program. Thus we are
  9933. guaranteed that iteratively applying liveness analysis to all blocks
  9934. in the program will eventually produce the least fixed point solution.
  9935. Next let us consider dataflow analysis in general and discuss the
  9936. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  9937. %
  9938. The algorithm has four parameters: the control-flow graph \code{G}, a
  9939. function \code{transfer} that applies the analysis to one block, the
  9940. \code{bottom} and \code{join} operator for the lattice of abstract
  9941. states. The algorithm begins by creating the bottom mapping,
  9942. represented by a hash table. It then pushes all of the nodes in the
  9943. control-flow graph onto the work list (a queue). The algorithm repeats
  9944. the \code{while} loop as long as there are items in the work list. In
  9945. each iteration, a node is popped from the work list and processed. The
  9946. \code{input} for the node is computed by taking the join of the
  9947. abstract states of all the predecessor nodes. The \code{transfer}
  9948. function is then applied to obtain the \code{output} abstract
  9949. state. If the output differs from the previous state for this block,
  9950. the mapping for this block is updated and its successor nodes are
  9951. pushed onto the work list.
  9952. \begin{figure}[tb]
  9953. \begin{lstlisting}
  9954. (define (analyze-dataflow G transfer bottom join)
  9955. (define mapping (make-hash))
  9956. (for ([v (in-vertices G)])
  9957. (dict-set! mapping v bottom))
  9958. (define worklist (make-queue))
  9959. (for ([v (in-vertices G)])
  9960. (enqueue! worklist v))
  9961. (define trans-G (transpose G))
  9962. (while (not (queue-empty? worklist))
  9963. (define node (dequeue! worklist))
  9964. (define input (for/fold ([state bottom])
  9965. ([pred (in-neighbors trans-G node)])
  9966. (join state (dict-ref mapping pred))))
  9967. (define output (transfer node input))
  9968. (cond [(not (equal? output (dict-ref mapping node)))
  9969. (dict-set! mapping node output)
  9970. (for ([v (in-neighbors G node)])
  9971. (enqueue! worklist v))]))
  9972. mapping)
  9973. \end{lstlisting}
  9974. \caption{Generic work list algorithm for dataflow analysis}
  9975. \label{fig:generic-dataflow}
  9976. \end{figure}
  9977. Having discussed the two complications that arise from adding support
  9978. for assignment and loops, we turn to discussing the one new compiler
  9979. pass and the significant changes to existing passes.
  9980. \section{Convert Assignments}
  9981. \label{sec:convert-assignments}
  9982. Recall that in Section~\ref{sec:assignment-scoping} we learned that
  9983. the combination of assignments and lexically-scoped functions requires
  9984. that we box those variables that are both assigned-to and that appear
  9985. free inside a \code{lambda}. The purpose of the
  9986. \code{convert-assignments} pass is to carry out that transformation.
  9987. We recommend placing this pass after \code{uniquify} but before
  9988. \code{reveal-functions}.
  9989. Consider again the first example from
  9990. Section~\ref{sec:assignment-scoping}:
  9991. \begin{lstlisting}
  9992. (let ([x 0])
  9993. (let ([y 0])
  9994. (let ([z 20])
  9995. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  9996. (begin
  9997. (set! x 10)
  9998. (set! y 12)
  9999. (f y))))))
  10000. \end{lstlisting}
  10001. The variables \code{x} and \code{y} are assigned-to. The variables
  10002. \code{x} and \code{z} occur free inside the \code{lambda}. Thus,
  10003. variable \code{x} needs to be boxed but not \code{y} and \code{z}.
  10004. The boxing of \code{x} consists of three transformations: initialize
  10005. \code{x} with a vector, replace reads from \code{x} with
  10006. \code{vector-ref}'s, and replace each \code{set!} on \code{x} with a
  10007. \code{vector-set!}. The output of \code{convert-assignments} for this
  10008. example is as follows.
  10009. \begin{lstlisting}
  10010. (define (main) : Integer
  10011. (let ([x0 (vector 0)])
  10012. (let ([y1 0])
  10013. (let ([z2 20])
  10014. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  10015. (+ a3 (+ (vector-ref x0 0) z2)))])
  10016. (begin
  10017. (vector-set! x0 0 10)
  10018. (set! y1 12)
  10019. (f4 y1)))))))
  10020. \end{lstlisting}
  10021. \paragraph{Assigned \& Free}
  10022. We recommend defining an auxiliary function named
  10023. \code{assigned\&free} that takes an expression and simultaneously
  10024. computes 1) a set of assigned variables $A$, 2) a set $F$ of variables
  10025. that occur free within lambda's, and 3) a new version of the
  10026. expression that records which bound variables occurred in the
  10027. intersection of $A$ and $F$. You can use the struct
  10028. \code{AssignedFree} to do this. Consider the case for
  10029. $\LET{x}{\itm{rhs}}{\itm{body}}$. Suppose the the recursive call on
  10030. $\itm{rhs}$ produces $\itm{rhs}'$, $A_r$, and $F_r$ and the recursive
  10031. call on the $\itm{body}$ produces $\itm{body}'$, $A_b$, and $F_b$. If
  10032. $x$ is in $A_b\cap F_b$, then transforms the \code{Let} as follows.
  10033. \begin{lstlisting}
  10034. (Let |$x$| |$rhs$| |$body$|)
  10035. |$\Rightarrow$|
  10036. (Let (AssignedFree |$x$|) |$rhs'$| |$body'$|)
  10037. \end{lstlisting}
  10038. If $x$ is not in $A_b\cap F_b$ then omit the use of \code{AssignedFree}.
  10039. The set of assigned variables for this \code{Let} is
  10040. $A_r \cup (A_b - \{x\})$
  10041. and the set of variables free in lambda's is
  10042. $F_r \cup (F_b - \{x\})$.
  10043. The case for $\SETBANG{x}{\itm{rhs}}$ is straightforward but
  10044. important. Recursively process \itm{rhs} to obtain \itm{rhs'}, $A_r$,
  10045. and $F_r$. The result is $\SETBANG{x}{\itm{rhs'}}$, $\{x\} \cup A_r$,
  10046. and $F_r$.
  10047. The case for $\LAMBDA{\itm{params}}{T}{\itm{body}}$ is a bit more
  10048. involved. Let \itm{body'}, $A_b$, and $F_b$ be the result of
  10049. recursively processing \itm{body}. Wrap each of parameter that occurs
  10050. in $A_b \cap F_b$ with \code{AssignedFree} to produce \itm{params'}.
  10051. Let $P$ be the set of parameter names in \itm{params}. The result is
  10052. $\LAMBDA{\itm{params'}}{T}{\itm{body'}}$, $A_b - P$, and $(F_b \cup
  10053. \mathrm{FV}(\itm{body})) - P$, where $\mathrm{FV}$ computes the free
  10054. variables of an expression (see Chapter~\ref{ch:Rlam}).
  10055. \paragraph{Convert Assignments}
  10056. Next we discuss the \code{convert-assignment} pass with its auxiliary
  10057. functions for expressions and definitions. The function for
  10058. expressions, \code{cnvt-assign-exp}, should take an expression and a
  10059. set of assigned-and-free variables (obtained from the result of
  10060. \code{assigned\&free}. In the case for $\VAR{x}$, if $x$ is
  10061. assigned-and-free, then unbox it by translating $\VAR{x}$ to a
  10062. \code{vector-ref}.
  10063. \begin{lstlisting}
  10064. (Var |$x$|)
  10065. |$\Rightarrow$|
  10066. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  10067. \end{lstlisting}
  10068. %
  10069. In the case for $\LET{\LP\code{AssignedFree}\,
  10070. x\RP}{\itm{rhs}}{\itm{body}}$, recursively process \itm{rhs} to
  10071. obtain \itm{rhs'}. Next, recursively process \itm{body} to obtain
  10072. \itm{body'} but with $x$ added to the set of assigned-and-free
  10073. variables. Translate the let-expression as follows to bind $x$ to a
  10074. boxed value.
  10075. \begin{lstlisting}
  10076. (Let (AssignedFree |$x$|) |$rhs$| |$body$|)
  10077. |$\Rightarrow$|
  10078. (Let |$x$| (Prim 'vector (list |$rhs'$|)) |$body'$|)
  10079. \end{lstlisting}
  10080. %
  10081. In the case for $\SETBANG{x}{\itm{rhs}}$, recursively process
  10082. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in the assigned-and-free
  10083. variables, translate the \code{set!} into a \code{vector-set!}
  10084. as follows.
  10085. \begin{lstlisting}
  10086. (SetBang |$x$| |$\itm{rhs}$|)
  10087. |$\Rightarrow$|
  10088. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  10089. \end{lstlisting}
  10090. %
  10091. The case for \code{Lambda} is non-trivial, but it is similar to the
  10092. case for function definitions, which we discuss next.
  10093. The auxiliary function for definitions, \code{cnvt-assign-def},
  10094. applies assignment conversion to function definitions.
  10095. We translate a function definition as follows.
  10096. \begin{lstlisting}
  10097. (Def |$f$| |$\itm{params}$| |$T$| |$\itm{info}$| |$\itm{body_1}$|)
  10098. |$\Rightarrow$|
  10099. (Def |$f$| |$\itm{params'}$| |$T$| |$\itm{info}$| |$\itm{body_4}$|)
  10100. \end{lstlisting}
  10101. So it remains to explain \itm{params'} and $\itm{body}_4$.
  10102. Let \itm{body_2}, $A_b$, and $F_b$ be the result of
  10103. \code{assigned\&free} on $\itm{body_1}$.
  10104. Let $P$ be the parameter names in \itm{params}.
  10105. We then apply \code{cnvt-assign-exp} to $\itm{body_2}$ to
  10106. obtain \itm{body_3}, passing $A_b \cap F_b \cap P$
  10107. as the set of assigned-and-free variables.
  10108. Finally, we obtain \itm{body_4} by wrapping \itm{body_3}
  10109. in a sequence of let-expressions that box the parameters
  10110. that are in $A_b \cap F_b$.
  10111. %
  10112. Regarding \itm{params'}, change the names of the parameters that are
  10113. in $A_b \cap F_b$ to maintain uniqueness (and so the let-bound
  10114. variables can retain the original names). Recall the second example in
  10115. Section~\ref{sec:assignment-scoping} involving a counter
  10116. abstraction. The following is the output of assignment version for
  10117. function \code{f}.
  10118. \begin{lstlisting}
  10119. (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  10120. (vector
  10121. (lambda: () : Integer x1)
  10122. (lambda: () : Void (set! x1 (+ 1 x1)))))
  10123. |$\Rightarrow$|
  10124. (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  10125. (let ([x1 (vector param_x1)])
  10126. (vector (lambda: () : Integer (vector-ref x1 0))
  10127. (lambda: () : Void
  10128. (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  10129. \end{lstlisting}
  10130. \section{Remove Complex Operands}
  10131. \label{sec:rco-loop}
  10132. The three new language forms, \code{while}, \code{set!}, and
  10133. \code{begin} are all complex expressions and their subexpressions are
  10134. allowed to be complex. Figure~\ref{fig:Rfun-anf-syntax} defines the
  10135. output language \LangFunANF{} of this pass.
  10136. \begin{figure}[tp]
  10137. \centering
  10138. \fbox{
  10139. \begin{minipage}{0.96\textwidth}
  10140. \small
  10141. \[
  10142. \begin{array}{rcl}
  10143. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  10144. \mid \VOID{} } \\
  10145. \Exp &::=& \ldots \mid \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  10146. &\mid& \WHILE{\Exp}{\Exp} \mid \SETBANG{\Var}{\Exp}
  10147. \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  10148. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  10149. R^{\dagger}_8 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  10150. \end{array}
  10151. \]
  10152. \end{minipage}
  10153. }
  10154. \caption{\LangLoopANF{} is \LangLoop{} in administrative normal form (ANF).}
  10155. \label{fig:Rwhile-anf-syntax}
  10156. \end{figure}
  10157. As usual, when a complex expression appears in a grammar position that
  10158. needs to be atomic, such as the argument of a primitive operator, we
  10159. must introduce a temporary variable and bind it to the complex
  10160. expression. This approach applies, unchanged, to handle the new
  10161. language forms. For example, in the following code there are two
  10162. \code{begin} expressions appearing as arguments to \code{+}. The
  10163. output of \code{rco-exp} is shown below, in which the \code{begin}
  10164. expressions have been bound to temporary variables. Recall that
  10165. \code{let} expressions in \LangLoopANF{} are allowed to have
  10166. arbitrary expressions in their right-hand-side expression, so it is
  10167. fine to place \code{begin} there.
  10168. \begin{lstlisting}
  10169. (let ([x0 10])
  10170. (let ([y1 0])
  10171. (+ (+ (begin (set! y1 (read)) x0)
  10172. (begin (set! x0 (read)) y1))
  10173. x0)))
  10174. |$\Rightarrow$|
  10175. (let ([x0 10])
  10176. (let ([y1 0])
  10177. (let ([tmp2 (begin (set! y1 (read)) x0)])
  10178. (let ([tmp3 (begin (set! x0 (read)) y1)])
  10179. (let ([tmp4 (+ tmp2 tmp3)])
  10180. (+ tmp4 x0))))))
  10181. \end{lstlisting}
  10182. \section{Explicate Control and \LangCLoop{}}
  10183. \label{sec:explicate-loop}
  10184. Recall that in the \code{explicate-control} pass we define one helper
  10185. function for each kind of position in the program. For the \LangVar{}
  10186. language of integers and variables we needed kinds of positions:
  10187. assignment and tail. The \code{if} expressions of \LangIf{} introduced
  10188. predicate positions. For \LangLoop{}, the \code{begin} expression introduces
  10189. yet another kind of position: effect position. Except for the last
  10190. subexpression, the subexpressions inside a \code{begin} are evaluated
  10191. only for their effect. Their result values are discarded. We can
  10192. generate better code by taking this fact into account.
  10193. The output language of \code{explicate-control} is \LangCLoop{}
  10194. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  10195. \LangCLam{}. The only syntactic difference is that \code{Call},
  10196. \code{vector-set!}, and \code{read} may also appear as statements.
  10197. The most significant difference between \LangCLam{} and \LangCLoop{}
  10198. is that the control-flow graphs of the later may contain cycles.
  10199. \begin{figure}[tp]
  10200. \fbox{
  10201. \begin{minipage}{0.96\textwidth}
  10202. \small
  10203. \[
  10204. \begin{array}{lcl}
  10205. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  10206. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  10207. &\mid& \CALL{\Atm}{\LP\Atm\ldots\RP} \mid \READ{}\\
  10208. &\mid& \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP \\
  10209. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  10210. \LangCLoop{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  10211. \end{array}
  10212. \]
  10213. \end{minipage}
  10214. }
  10215. \caption{The abstract syntax of \LangCLoop{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  10216. \label{fig:c7-syntax}
  10217. \end{figure}
  10218. The new auxiliary function \code{explicate-effect} takes an expression
  10219. (in an effect position) and a promise of a continuation block. The
  10220. function returns a promise for a $\Tail$ that includes the generated
  10221. code for the input expression followed by the continuation block. If
  10222. the expression is obviously pure, that is, never causes side effects,
  10223. then the expression can be removed, so the result is just the
  10224. continuation block.
  10225. %
  10226. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  10227. case. First, you will need a fresh label $\itm{loop}$ for the top of
  10228. the loop. Recursively process the \itm{body} (in effect position)
  10229. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  10230. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  10231. \itm{body'} as the then-branch and the continuation block as the
  10232. else-branch. The result should be added to the control-flow graph with
  10233. the label \itm{loop}. The result for the whole \code{while} loop is a
  10234. \code{goto} to the \itm{loop} label. Note that the loop should only be
  10235. added to the control-flow graph if the loop is indeed used, which can
  10236. be accomplished using \code{delay}.
  10237. The auxiliary functions for tail, assignment, and predicate positions
  10238. need to be updated. The three new language forms, \code{while},
  10239. \code{set!}, and \code{begin}, can appear in assignment and tail
  10240. positions. Only \code{begin} may appear in predicate positions; the
  10241. other two have result type \code{Void}.
  10242. \section{Select Instructions}
  10243. \label{sec:select-instructions-loop}
  10244. Only three small additions are needed in the
  10245. \code{select-instructions} pass to handle the changes to \LangCLoop{}. That
  10246. is, \code{Call}, \code{read}, and \code{vector-set!} may now appear as
  10247. stand-alone statements instead of only appearing on the right-hand
  10248. side of an assignment statement. The code generation is nearly
  10249. identical; just leave off the instruction for moving the result into
  10250. the left-hand side.
  10251. \section{Register Allocation}
  10252. \label{sec:register-allocation-loop}
  10253. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  10254. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  10255. which complicates the liveness analysis needed for register
  10256. allocation.
  10257. \subsection{Liveness Analysis}
  10258. \label{sec:liveness-analysis-r8}
  10259. We recommend using the generic \code{analyze-dataflow} function that
  10260. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  10261. perform liveness analysis, replacing the code in
  10262. \code{uncover-live-CFG} that processed the basic blocks in topological
  10263. order (Section~\ref{sec:liveness-analysis-Rif}).
  10264. The \code{analyze-dataflow} function has four parameters.
  10265. \begin{enumerate}
  10266. \item The first parameter \code{G} should be a directed graph from the
  10267. \code{racket/graph} package (see the sidebar in
  10268. Section~\ref{sec:build-interference}) that represents the
  10269. control-flow graph.
  10270. \item The second parameter \code{transfer} is a function that applies
  10271. liveness analysis to a basic block. It takes two parameters: the
  10272. label for the block to analyze and the live-after set for that
  10273. block. The transfer function should return the live-before set for
  10274. the block. Also, as a side-effect, it should update the block's
  10275. $\itm{info}$ with the liveness information for each instruction. To
  10276. implement the \code{transfer} function, you should be able to reuse
  10277. the code you already have for analyzing basic blocks.
  10278. \item The third and fourth parameters of \code{analyze-dataflow} are
  10279. \code{bottom} and \code{join} for the lattice of abstract states,
  10280. i.e. sets of locations. The bottom of the lattice is the empty set
  10281. \code{(set)} and the join operator is \code{set-union}.
  10282. \end{enumerate}
  10283. \begin{figure}[p]
  10284. \begin{tikzpicture}[baseline=(current bounding box.center)]
  10285. \node (Rfun) at (0,2) {\large \LangLoop{}};
  10286. \node (Rfun-2) at (3,2) {\large \LangLoop{}};
  10287. \node (Rfun-3) at (6,2) {\large \LangLoop{}};
  10288. \node (Rfun-4) at (9,2) {\large \LangLoopFunRef{}};
  10289. \node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  10290. \node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  10291. \node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  10292. \node (F1-4) at (3,0) {\large \LangLoopAlloc{}};
  10293. \node (F1-5) at (0,0) {\large \LangLoopAlloc{}};
  10294. \node (C3-2) at (3,-2) {\large \LangCLoop{}};
  10295. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  10296. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  10297. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  10298. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  10299. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  10300. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  10301. %% \path[->,bend left=15] (Rfun) edge [above] node
  10302. %% {\ttfamily\footnotesize type-check} (Rfun-2);
  10303. \path[->,bend left=15] (Rfun) edge [above] node
  10304. {\ttfamily\footnotesize shrink} (Rfun-2);
  10305. \path[->,bend left=15] (Rfun-2) edge [above] node
  10306. {\ttfamily\footnotesize uniquify} (Rfun-3);
  10307. \path[->,bend left=15] (Rfun-3) edge [above] node
  10308. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  10309. \path[->,bend left=15] (Rfun-4) edge [right] node
  10310. {\ttfamily\footnotesize convert-assignments} (F1-1);
  10311. \path[->,bend left=15] (F1-1) edge [below] node
  10312. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  10313. \path[->,bend right=15] (F1-2) edge [above] node
  10314. {\ttfamily\footnotesize limit-fun.} (F1-3);
  10315. \path[->,bend right=15] (F1-3) edge [above] node
  10316. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  10317. \path[->,bend right=15] (F1-4) edge [above] node
  10318. {\ttfamily\footnotesize remove-complex.} (F1-5);
  10319. \path[->,bend right=15] (F1-5) edge [right] node
  10320. {\ttfamily\footnotesize explicate-control} (C3-2);
  10321. \path[->,bend left=15] (C3-2) edge [left] node
  10322. {\ttfamily\footnotesize select-instr.} (x86-2);
  10323. \path[->,bend right=15] (x86-2) edge [left] node
  10324. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  10325. \path[->,bend right=15] (x86-2-1) edge [below] node
  10326. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  10327. \path[->,bend right=15] (x86-2-2) edge [left] node
  10328. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  10329. \path[->,bend left=15] (x86-3) edge [above] node
  10330. {\ttfamily\footnotesize patch-instr.} (x86-4);
  10331. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  10332. \end{tikzpicture}
  10333. \caption{Diagram of the passes for \LangLoop{} (loops and assignment).}
  10334. \label{fig:Rwhile-passes}
  10335. \end{figure}
  10336. Figure~\ref{fig:Rwhile-passes} provides an overview of all the passes needed
  10337. for the compilation of \LangLoop{}.
  10338. \section{Challenge: Arrays}
  10339. \label{sec:arrays}
  10340. In Chapter~\ref{ch:Rvec} we studied tuples, that is, sequences of
  10341. elements whose length is determined at compile-time and where each
  10342. element of a tuple may have a different type (they are
  10343. heterogeous). This challenge is also about sequences, but this time
  10344. the length is determined at run-time and all the elements have the same
  10345. type (they are homogeneous). We use the term ``array'' for this later
  10346. kind of sequence.
  10347. The Racket language does not distinguish between tuples and arrays,
  10348. they are both represented by vectors. However, Typed Racket
  10349. distinguishes between tuples and arrays: the \code{Vector} type is for
  10350. tuples and the \code{Vectorof} type is for arrays.
  10351. %
  10352. Figure~\ref{fig:Rvecof-concrete-syntax} defines the concrete syntax
  10353. for \LangArray{}, extending \LangLoop{} with the \code{Vectorof} type
  10354. and the \code{make-vector} primitive operator for creating an array,
  10355. whose arguments are the length of the array and an initial value for
  10356. all the elements in the array. The \code{vector-length},
  10357. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  10358. for tuples become overloaded for use with arrays.
  10359. %
  10360. We also include integer multiplication in \LangArray{}, as it is
  10361. useful in many examples involving arrays such as computing the
  10362. inner-product of two arrays (Figure~\ref{fig:inner-product}).
  10363. \begin{figure}[tp]
  10364. \centering
  10365. \fbox{
  10366. \begin{minipage}{0.96\textwidth}
  10367. \small
  10368. \[
  10369. \begin{array}{lcl}
  10370. \Type &::=& \ldots \mid \LP \key{Vectorof}~\Type \RP \\
  10371. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  10372. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \mid \CMUL{\Exp}{\Exp}\\
  10373. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  10374. &\mid& \gray{\key{\#t} \mid \key{\#f}
  10375. \mid \LP\key{and}\;\Exp\;\Exp\RP
  10376. \mid \LP\key{or}\;\Exp\;\Exp\RP
  10377. \mid \LP\key{not}\;\Exp\RP } \\
  10378. &\mid& \gray{ \LP\key{eq?}\;\Exp\;\Exp\RP \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  10379. &\mid& \gray{ \LP\key{vector}\;\Exp\ldots\RP \mid
  10380. \LP\key{vector-ref}\;\Exp\;\Int\RP} \\
  10381. &\mid& \gray{\LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP\mid \LP\key{void}\RP
  10382. \mid \LP\Exp \; \Exp\ldots\RP } \\
  10383. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP
  10384. \mid \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  10385. &\mid& \gray{ \CSETBANG{\Var}{\Exp}
  10386. \mid \CBEGIN{\Exp\ldots}{\Exp}
  10387. \mid \CWHILE{\Exp}{\Exp} } \\
  10388. &\mid& \CMAKEVEC{\Exp}{\Exp} \\
  10389. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  10390. \LangArray{} &::=& \gray{\Def\ldots \; \Exp}
  10391. \end{array}
  10392. \]
  10393. \end{minipage}
  10394. }
  10395. \caption{The concrete syntax of \LangArray{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  10396. \label{fig:Rvecof-concrete-syntax}
  10397. \end{figure}
  10398. \begin{figure}[tp]
  10399. \begin{lstlisting}
  10400. (define (inner-product [A : (Vectorof Integer)] [B : (Vectorof Integer)]
  10401. [n : Integer]) : Integer
  10402. (let ([i 0])
  10403. (let ([prod 0])
  10404. (begin
  10405. (while (< i n)
  10406. (begin
  10407. (set! prod (+ prod (* (vector-ref A i)
  10408. (vector-ref B i))))
  10409. (set! i (+ i 1))
  10410. ))
  10411. prod))))
  10412. (let ([A (make-vector 2 2)])
  10413. (let ([B (make-vector 2 3)])
  10414. (+ (inner-product A B 2)
  10415. 30)))
  10416. \end{lstlisting}
  10417. \caption{Example program that computes the inner-product.}
  10418. \label{fig:inner-product}
  10419. \end{figure}
  10420. The type checker for \LangArray{} is define in
  10421. Figure~\ref{fig:type-check-Rvecof}. The result type of
  10422. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  10423. of the intializing expression. The length expression is required to
  10424. have type \code{Integer}. The type checking of the operators
  10425. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  10426. updated to handle the situation where the vector has type
  10427. \code{Vectorof}. In these cases we translate the operators to their
  10428. \code{vectorof} form so that later passes can easily distinguish
  10429. between operations on tuples versus arrays. We override the
  10430. \code{operator-types} method to provide the type signature for
  10431. multiplication: it takes two integers and returns an integer. To
  10432. support injection and projection of arrays to the \code{Any} type
  10433. (Section~\ref{sec:Rany-lang}), we also override the \code{flat-ty?}
  10434. predicate.
  10435. \begin{figure}[tbp]
  10436. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10437. (define type-check-Rvecof-class
  10438. (class type-check-Rwhile-class
  10439. (super-new)
  10440. (inherit check-type-equal?)
  10441. (define/override (flat-ty? ty)
  10442. (match ty
  10443. ['(Vectorof Any) #t]
  10444. [else (super flat-ty? ty)]))
  10445. (define/override (operator-types)
  10446. (append '((* . ((Integer Integer) . Integer)))
  10447. (super operator-types)))
  10448. (define/override (type-check-exp env)
  10449. (lambda (e)
  10450. (define recur (type-check-exp env))
  10451. (match e
  10452. [(Prim 'make-vector (list e1 e2))
  10453. (define-values (e1^ t1) (recur e1))
  10454. (define-values (e2^ elt-type) (recur e2))
  10455. (define vec-type `(Vectorof ,elt-type))
  10456. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  10457. vec-type)]
  10458. [(Prim 'vector-ref (list e1 e2))
  10459. (define-values (e1^ t1) (recur e1))
  10460. (define-values (e2^ t2) (recur e2))
  10461. (match* (t1 t2)
  10462. [(`(Vectorof ,elt-type) 'Integer)
  10463. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  10464. [(other wise) ((super type-check-exp env) e)])]
  10465. [(Prim 'vector-set! (list e1 e2 e3) )
  10466. (define-values (e-vec t-vec) (recur e1))
  10467. (define-values (e2^ t2) (recur e2))
  10468. (define-values (e-arg^ t-arg) (recur e3))
  10469. (match t-vec
  10470. [`(Vectorof ,elt-type)
  10471. (check-type-equal? elt-type t-arg e)
  10472. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  10473. [else ((super type-check-exp env) e)])]
  10474. [(Prim 'vector-length (list e1))
  10475. (define-values (e1^ t1) (recur e1))
  10476. (match t1
  10477. [`(Vectorof ,t)
  10478. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  10479. [else ((super type-check-exp env) e)])]
  10480. [else ((super type-check-exp env) e)])))
  10481. ))
  10482. (define (type-check-Rvecof p)
  10483. (send (new type-check-Rvecof-class) type-check-program p))
  10484. \end{lstlisting}
  10485. \caption{Type checker for the \LangArray{} language.}
  10486. \label{fig:type-check-Rvecof}
  10487. \end{figure}
  10488. The interpreter for \LangArray{} is defined in
  10489. Figure~\ref{fig:interp-Rvecof}. The \code{make-vector} operator is
  10490. implemented with Racket's \code{make-vector} function and
  10491. multiplication is \code{fx*}, multiplication for \code{fixnum}
  10492. integers.
  10493. \begin{figure}[tbp]
  10494. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10495. (define interp-Rvecof-class
  10496. (class interp-Rwhile-class
  10497. (super-new)
  10498. (define/override (interp-op op)
  10499. (verbose "Rvecof/interp-op" op)
  10500. (match op
  10501. ['make-vector make-vector]
  10502. ['* fx*]
  10503. [else (super interp-op op)]))
  10504. ))
  10505. (define (interp-Rvecof p)
  10506. (send (new interp-Rvecof-class) interp-program p))
  10507. \end{lstlisting}
  10508. \caption{Interpreter for \LangArray{}.}
  10509. \label{fig:interp-Rvecof}
  10510. \end{figure}
  10511. \subsection{Data Representation}
  10512. \label{sec:array-rep}
  10513. Just like tuples, we store arrays on the heap which means that the
  10514. garbage collector will need to inspect arrays. An immediate thought is
  10515. to use the same representation for arrays that we use for tuples.
  10516. However, we limit tuples to a length of $50$ so that their length and
  10517. pointer mask can fit into the 64-bit tag at the beginning of each
  10518. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  10519. millions of elements, so we need more bits to store the length.
  10520. However, because arrays are homogeneous, we only need $1$ bit for the
  10521. pointer mask instead of one bit per array elements. Finally, the
  10522. garbage collector will need to be able to distinguish between tuples
  10523. and arrays, so we need to reserve $1$ bit for that purpose. So we
  10524. arrive at the following layout for the 64-bit tag at the beginning of
  10525. an array:
  10526. \begin{itemize}
  10527. \item The right-most bit is the forwarding bit, just like in a tuple.
  10528. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  10529. it is not.
  10530. \item The next bit to the left is the pointer mask. A $0$ indicates
  10531. that none of the elements are pointers to the heap and a $1$
  10532. indicates that all of the elements are pointers.
  10533. \item The next $61$ bits store the length of the array.
  10534. \item The left-most bit distinguishes between a tuple ($0$) versus an
  10535. array ($1$).
  10536. \end{itemize}
  10537. Recall that in Chapter~\ref{ch:Rdyn}, we use a $3$-bit tag to
  10538. differentiate the kinds of values that have been injected into the
  10539. \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  10540. to indicate that the value is an array.
  10541. In the following subsections we provide hints regarding how to update
  10542. the passes to handle arrays.
  10543. \subsection{Reveal Casts}
  10544. The array-access operators \code{vectorof-ref} and
  10545. \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  10546. \code{any-vector-set!} operators of Chapter~\ref{ch:Rdyn} in
  10547. that the type checker cannot tell whether the index will be in bounds,
  10548. so the bounds check must be performed at run time. Recall that the
  10549. \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  10550. an \code{If} arround a vector reference for update to check whether
  10551. the index is less than the length. You should do the same for
  10552. \code{vectorof-ref} and \code{vectorof-set!} .
  10553. In addition, the handling of the \code{any-vector} operators in
  10554. \code{reveal-casts} needs to be updated to account for arrays that are
  10555. injected to \code{Any}. For the \code{any-vector-length} operator, the
  10556. generated code should test whether the tag is for tuples (\code{010})
  10557. or arrays (\code{110}) and then dispatch to either
  10558. \code{any-vector-length} or \code{any-vectorof-length}. For the later
  10559. we add a case in \code{select-instructions} to generate the
  10560. appropriate instructions for accessing the array length from the
  10561. header of an array.
  10562. For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  10563. the generated code needs to check that the index is less than the
  10564. vector length, so like the code for \code{any-vector-length}, check
  10565. the tag to determine whether to use \code{any-vector-length} or
  10566. \code{any-vectorof-length} for this purpose. Once the bounds checking
  10567. is complete, the generated code can use \code{any-vector-ref} and
  10568. \code{any-vector-set!} for both tuples and arrays because the
  10569. instructions used for those operators do not look at the tag at the
  10570. front of the tuple or array.
  10571. \subsection{Expose Allocation}
  10572. This pass should translate the \code{make-vector} operator into
  10573. lower-level operations. In particular, the new AST node
  10574. $\LP\key{AllocateArray}~\Exp~\Type\RP$ allocates an array of the
  10575. length specified by the $\Exp$, but does not initialize the elements
  10576. of the array. (Analogous to the \code{Allocate} AST node for tuples.)
  10577. The $\Type$ argument must be $\LP\key{Vectorof}~T\RP$ where $T$ is the
  10578. element type for the array. Regarding the initialization of the array,
  10579. we recommend generated a \code{while} loop that uses
  10580. \code{vector-set!} to put the initializing value into every element of
  10581. the array.
  10582. \subsection{Remove Complex Operands}
  10583. Add cases in the \code{rco-atom} and \code{rco-exp} for
  10584. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  10585. complex and its subexpression must be atomic.
  10586. \subsection{Explicate Control}
  10587. Add cases for \code{AllocateArray} to \code{explicate-tail} and
  10588. \code{explicate-assign}.
  10589. \subsection{Select Instructions}
  10590. Generate instructions for \code{AllocateArray} similar to those for
  10591. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  10592. that the tag at the front of the array should instead use the
  10593. representation discussed in Section~\ref{sec:array-rep}.
  10594. Regarding \code{vectorof-length}, extract the length from the tag
  10595. according to the representation discussed in
  10596. Section~\ref{sec:array-rep}.
  10597. The instructions generated for \code{vectorof-ref} differ from those
  10598. for \code{vector-ref} (Section~\ref{sec:select-instructions-gc}) in
  10599. that the index is not a constant so the offset must be computed at
  10600. runtime, similar to the instructions generated for
  10601. \code{any-vector-of-ref} (Section~\ref{sec:select-Rany}). The same is
  10602. true for \code{vectorof-set!}. Also, the \code{vectorof-set!} may
  10603. appear in an assignment and as a stand-alone statement, so make sure
  10604. to handle both situations in this pass.
  10605. Finally, the instructions for \code{any-vectorof-length} should be
  10606. similar to those for \code{vectorof-length}, except that one must
  10607. first project the array by writing zeroes into the $3$-bit tag
  10608. \begin{exercise}\normalfont
  10609. Implement a compiler for the \LangArray{} language by extending your
  10610. compiler for \LangLoop{}. Test your compiler on a half dozen new
  10611. programs, including the one in Figure~\ref{fig:inner-product} and also
  10612. a program that multiplies two matrices. Note that matrices are
  10613. 2-dimensional arrays, but those can be encoded into 1-dimensional
  10614. arrays by laying out each row in the array, one after the next.
  10615. \end{exercise}
  10616. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10617. \chapter{Gradual Typing}
  10618. \label{ch:Rgrad}
  10619. \index{gradual typing}
  10620. This chapter studies a language, \LangGrad{}, in which the programmer
  10621. can choose between static and dynamic type checking in different parts
  10622. of a program, thereby mixing the statically typed \LangLoop{} language
  10623. with the dynamically typed \LangDyn{}. There are several approaches to
  10624. mixing static and dynamic typing, including multi-language
  10625. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  10626. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  10627. we focus on \emph{gradual typing}\index{gradual typing}, in which the
  10628. programmer controls the amount of static versus dynamic checking by
  10629. adding or removing type annotations on parameters and
  10630. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  10631. %
  10632. The concrete syntax of \LangGrad{} is defined in
  10633. Figure~\ref{fig:Rgrad-concrete-syntax} and its abstract syntax is defined
  10634. in Figure~\ref{fig:Rgrad-syntax}. The main syntactic difference between
  10635. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  10636. non-terminals that make type annotations optional. The return types
  10637. are not optional in the abstract syntax; the parser fills in
  10638. \code{Any} when the return type is not specified in the concrete
  10639. syntax.
  10640. \begin{figure}[tp]
  10641. \centering
  10642. \fbox{
  10643. \begin{minipage}{0.96\textwidth}
  10644. \small
  10645. \[
  10646. \begin{array}{lcl}
  10647. \itm{param} &::=& \Var \mid \LS\Var \key{:} \Type\RS \\
  10648. \itm{ret} &::=& \epsilon \mid \key{:} \Type \\
  10649. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  10650. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  10651. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  10652. &\mid& \gray{\key{\#t} \mid \key{\#f}
  10653. \mid (\key{and}\;\Exp\;\Exp)
  10654. \mid (\key{or}\;\Exp\;\Exp)
  10655. \mid (\key{not}\;\Exp) } \\
  10656. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  10657. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  10658. (\key{vector-ref}\;\Exp\;\Int)} \\
  10659. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  10660. \mid (\Exp \; \Exp\ldots) } \\
  10661. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  10662. \mid \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  10663. &\mid& \gray{ \CSETBANG{\Var}{\Exp}
  10664. \mid \CBEGIN{\Exp\ldots}{\Exp}
  10665. \mid \CWHILE{\Exp}{\Exp} } \\
  10666. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  10667. \LangGrad{} &::=& \gray{\Def\ldots \; \Exp}
  10668. \end{array}
  10669. \]
  10670. \end{minipage}
  10671. }
  10672. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  10673. \label{fig:Rgrad-concrete-syntax}
  10674. \end{figure}
  10675. \begin{figure}[tp]
  10676. \centering
  10677. \fbox{
  10678. \begin{minipage}{0.96\textwidth}
  10679. \small
  10680. \[
  10681. \begin{array}{lcl}
  10682. \itm{param} &::=& \Var \mid \LS\Var \key{:} \Type\RS \\
  10683. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  10684. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  10685. &\mid& \gray{ \BOOL{\itm{bool}}
  10686. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  10687. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  10688. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  10689. &\mid& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  10690. &\mid& \gray{ \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  10691. &\mid& \gray{ \WHILE{\Exp}{\Exp} } \\
  10692. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  10693. \LangGrad{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  10694. \end{array}
  10695. \]
  10696. \end{minipage}
  10697. }
  10698. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  10699. \label{fig:Rgrad-syntax}
  10700. \end{figure}
  10701. Both the type checker and the interpreter for \LangGrad{} require some
  10702. interesting changes to enable gradual typing, which we discuss in the
  10703. next two sections in the context of the \code{map-vec} example from
  10704. Chapter~\ref{ch:Rfun}. In Figure~\ref{fig:gradual-map-vec} we
  10705. revised the \code{map-vec} example, omitting the type annotations from
  10706. the \code{add1} function.
  10707. \begin{figure}[btp]
  10708. % gradual_test_9.rkt
  10709. \begin{lstlisting}
  10710. (define (map-vec [f : (Integer -> Integer)]
  10711. [v : (Vector Integer Integer)])
  10712. : (Vector Integer Integer)
  10713. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10714. (define (add1 x) (+ x 1))
  10715. (vector-ref (map-vec add1 (vector 0 41)) 1)
  10716. \end{lstlisting}
  10717. \caption{A partially-typed version of the \code{map-vec} example.}
  10718. \label{fig:gradual-map-vec}
  10719. \end{figure}
  10720. \section{Type Checking \LangGrad{}, Casts, and \LangCast{}}
  10721. \label{sec:gradual-type-check}
  10722. The type checker for \LangGrad{} uses the \code{Any} type for missing
  10723. parameter and return types. For example, the \code{x} parameter of
  10724. \code{add1} in Figure~\ref{fig:gradual-map-vec} is given the type
  10725. \code{Any} and the return type of \code{add1} is \code{Any}. Next
  10726. consider the \code{+} operator inside \code{add1}. It expects both
  10727. arguments to have type \code{Integer}, but its first argument \code{x}
  10728. has type \code{Any}. In a gradually typed language, such differences
  10729. are allowed so long as the types are \emph{consistent}, that is, they
  10730. are equal except in places where there is an \code{Any} type. The type
  10731. \code{Any} is consistent with every other type.
  10732. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  10733. \begin{figure}[tbp]
  10734. \begin{lstlisting}
  10735. (define/public (consistent? t1 t2)
  10736. (match* (t1 t2)
  10737. [('Integer 'Integer) #t]
  10738. [('Boolean 'Boolean) #t]
  10739. [('Void 'Void) #t]
  10740. [('Any t2) #t]
  10741. [(t1 'Any) #t]
  10742. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10743. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  10744. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10745. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  10746. (consistent? rt1 rt2))]
  10747. [(other wise) #f]))
  10748. \end{lstlisting}
  10749. \caption{The consistency predicate on types.}
  10750. \label{fig:consistent}
  10751. \end{figure}
  10752. Returning to the \code{map-vec} example of
  10753. Figure~\ref{fig:gradual-map-vec}, the \code{add1} function has type
  10754. \code{(Any -> Any)} but parameter \code{f} of \code{map-vec} has type
  10755. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  10756. because the two types are consistent. In particular, \code{->} is
  10757. equal to \code{->} and because \code{Any} is consistent with
  10758. \code{Integer}.
  10759. Next consider a program with an error, such as applying the
  10760. \code{map-vec} to a function that sometimes returns a Boolean, as
  10761. shown in Figure~\ref{fig:map-vec-maybe-add1}. The type checker for
  10762. \LangGrad{} accepts this program because the type of \code{maybe-add1} is
  10763. consistent with the type of parameter \code{f} of \code{map-vec}, that
  10764. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  10765. Integer)}. One might say that a gradual type checker is optimistic
  10766. in that it accepts programs that might execute without a runtime type
  10767. error.
  10768. %
  10769. Unfortunately, running this program with input \code{1} triggers an
  10770. error when the \code{maybe-add1} function returns \code{\#t}. \LangGrad{}
  10771. performs checking at runtime to ensure the integrity of the static
  10772. types, such as the \code{(Integer -> Integer)} annotation on parameter
  10773. \code{f} of \code{map-vec}. This runtime checking is carried out by a
  10774. new \code{Cast} form that is inserted by the type checker. Thus, the
  10775. output of the type checker is a program in the \LangCast{} language, which
  10776. adds \code{Cast} to \LangLoop{}, as shown in
  10777. Figure~\ref{fig:Rgrad-prime-syntax}.
  10778. \begin{figure}[tp]
  10779. \centering
  10780. \fbox{
  10781. \begin{minipage}{0.96\textwidth}
  10782. \small
  10783. \[
  10784. \begin{array}{lcl}
  10785. \Exp &::=& \ldots \mid \CAST{\Exp}{\Type}{\Type} \\
  10786. \LangCast{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  10787. \end{array}
  10788. \]
  10789. \end{minipage}
  10790. }
  10791. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  10792. \label{fig:Rgrad-prime-syntax}
  10793. \end{figure}
  10794. \begin{figure}[tbp]
  10795. \begin{lstlisting}
  10796. (define (map-vec [f : (Integer -> Integer)]
  10797. [v : (Vector Integer Integer)])
  10798. : (Vector Integer Integer)
  10799. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10800. (define (add1 x) (+ x 1))
  10801. (define (true) #t)
  10802. (define (maybe-add1 x) (if (eq? 0 (read)) (add1 x) (true)))
  10803. (vector-ref (map-vec maybe-add1 (vector 0 41)) 0)
  10804. \end{lstlisting}
  10805. \caption{A variant of the \code{map-vec} example with an error.}
  10806. \label{fig:map-vec-maybe-add1}
  10807. \end{figure}
  10808. Figure~\ref{fig:map-vec-cast} shows the output of the type checker for
  10809. \code{map-vec} and \code{maybe-add1}. The idea is that \code{Cast} is
  10810. inserted every time the type checker sees two types that are
  10811. consistent but not equal. In the \code{add1} function, \code{x} is
  10812. cast to \code{Integer} and the result of the \code{+} is cast to
  10813. \code{Any}. In the call to \code{map-vec}, the \code{add1} argument
  10814. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  10815. \begin{figure}[btp]
  10816. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10817. (define (map-vec [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  10818. : (Vector Integer Integer)
  10819. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10820. (define (add1 [x : Any]) : Any
  10821. (cast (+ (cast x Any Integer) 1) Integer Any))
  10822. (define (true) : Any (cast #t Boolean Any))
  10823. (define (maybe-add1 [x : Any]) : Any
  10824. (if (eq? 0 (read)) (add1 x) (true)))
  10825. (vector-ref (map-vec (cast maybe-add1 (Any -> Any) (Integer -> Integer))
  10826. (vector 0 41)) 0)
  10827. \end{lstlisting}
  10828. \caption{Output of type checking \code{map-vec}
  10829. and \code{maybe-add1}.}
  10830. \label{fig:map-vec-cast}
  10831. \end{figure}
  10832. The type checker for \LangGrad{} is defined in
  10833. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  10834. and \ref{fig:type-check-Rgradual-3}.
  10835. \begin{figure}[tbp]
  10836. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10837. (define type-check-gradual-class
  10838. (class type-check-Rwhile-class
  10839. (super-new)
  10840. (inherit operator-types type-predicates)
  10841. (define/override (type-check-exp env)
  10842. (lambda (e)
  10843. (define recur (type-check-exp env))
  10844. (match e
  10845. [(Prim 'vector-length (list e1))
  10846. (define-values (e1^ t) (recur e1))
  10847. (match t
  10848. [`(Vector ,ts ...)
  10849. (values (Prim 'vector-length (list e1^)) 'Integer)]
  10850. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  10851. [(Prim 'vector-ref (list e1 e2))
  10852. (define-values (e1^ t1) (recur e1))
  10853. (define-values (e2^ t2) (recur e2))
  10854. (check-consistent? t2 'Integer e)
  10855. (match t1
  10856. [`(Vector ,ts ...)
  10857. (match e2^
  10858. [(Int i)
  10859. (unless (and (0 . <= . i) (i . < . (length ts)))
  10860. (error 'type-check "invalid index ~a in ~a" i e))
  10861. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10862. [else (define e1^^ (make-cast e1^ t1 'Any))
  10863. (define e2^^ (make-cast e2^ t2 'Integer))
  10864. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  10865. ['Any
  10866. (define e2^^ (make-cast e2^ t2 'Integer))
  10867. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  10868. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  10869. [(Prim 'vector-set! (list e1 e2 e3) )
  10870. (define-values (e1^ t1) (recur e1))
  10871. (define-values (e2^ t2) (recur e2))
  10872. (define-values (e3^ t3) (recur e3))
  10873. (check-consistent? t2 'Integer e)
  10874. (match t1
  10875. [`(Vector ,ts ...)
  10876. (match e2^
  10877. [(Int i)
  10878. (unless (and (0 . <= . i) (i . < . (length ts)))
  10879. (error 'type-check "invalid index ~a in ~a" i e))
  10880. (check-consistent? (list-ref ts i) t3 e)
  10881. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  10882. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  10883. [else
  10884. (define e1^^ (make-cast e1^ t1 'Any))
  10885. (define e2^^ (make-cast e2^ t2 'Integer))
  10886. (define e3^^ (make-cast e3^ t3 'Any))
  10887. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  10888. ['Any
  10889. (define e2^^ (make-cast e2^ t2 'Integer))
  10890. (define e3^^ (make-cast e3^ t3 'Any))
  10891. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  10892. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  10893. \end{lstlisting}
  10894. \caption{Type checker for the \LangGrad{} language, part 1.}
  10895. \label{fig:type-check-Rgradual-1}
  10896. \end{figure}
  10897. \begin{figure}[tbp]
  10898. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10899. [(Prim 'eq? (list e1 e2))
  10900. (define-values (e1^ t1) (recur e1))
  10901. (define-values (e2^ t2) (recur e2))
  10902. (check-consistent? t1 t2 e)
  10903. (define T (meet t1 t2))
  10904. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  10905. 'Boolean)]
  10906. [(Prim 'not (list e1))
  10907. (define-values (e1^ t1) (recur e1))
  10908. (match t1
  10909. ['Any
  10910. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  10911. (Bool #t) (Bool #f)))]
  10912. [else
  10913. (define-values (t-ret new-es^)
  10914. (type-check-op 'not (list t1) (list e1^) e))
  10915. (values (Prim 'not new-es^) t-ret)])]
  10916. [(Prim 'and (list e1 e2))
  10917. (recur (If e1 e2 (Bool #f)))]
  10918. [(Prim 'or (list e1 e2))
  10919. (define tmp (gensym 'tmp))
  10920. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  10921. [(Prim op es)
  10922. #:when (not (set-member? explicit-prim-ops op))
  10923. (define-values (new-es ts)
  10924. (for/lists (exprs types) ([e es])
  10925. (recur e)))
  10926. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  10927. (values (Prim op new-es^) t-ret)]
  10928. [(If e1 e2 e3)
  10929. (define-values (e1^ T1) (recur e1))
  10930. (define-values (e2^ T2) (recur e2))
  10931. (define-values (e3^ T3) (recur e3))
  10932. (check-consistent? T2 T3 e)
  10933. (match T1
  10934. ['Boolean
  10935. (define Tif (join T2 T3))
  10936. (values (If e1^ (make-cast e2^ T2 Tif)
  10937. (make-cast e3^ T3 Tif)) Tif)]
  10938. ['Any
  10939. (define Tif (meet T2 T3))
  10940. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  10941. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  10942. Tif)]
  10943. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  10944. [(HasType e1 T)
  10945. (define-values (e1^ T1) (recur e1))
  10946. (check-consistent? T1 T)
  10947. (values (make-cast e1^ T1 T) T)]
  10948. [(SetBang x e1)
  10949. (define-values (e1^ T1) (recur e1))
  10950. (define varT (dict-ref env x))
  10951. (check-consistent? T1 varT e)
  10952. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  10953. [(WhileLoop e1 e2)
  10954. (define-values (e1^ T1) (recur e1))
  10955. (check-consistent? T1 'Boolean e)
  10956. (define-values (e2^ T2) ((type-check-exp env) e2))
  10957. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  10958. \end{lstlisting}
  10959. \caption{Type checker for the \LangGrad{} language, part 2.}
  10960. \label{fig:type-check-Rgradual-2}
  10961. \end{figure}
  10962. \begin{figure}[tbp]
  10963. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10964. [(Apply e1 e2s)
  10965. (define-values (e1^ T1) (recur e1))
  10966. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  10967. (match T1
  10968. [`(,T1ps ... -> ,T1rt)
  10969. (for ([T2 T2s] [Tp T1ps])
  10970. (check-consistent? T2 Tp e))
  10971. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  10972. (make-cast e2 src tgt)))
  10973. (values (Apply e1^ e2s^^) T1rt)]
  10974. [`Any
  10975. (define e1^^ (make-cast e1^ 'Any
  10976. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  10977. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  10978. (make-cast e2 src 'Any)))
  10979. (values (Apply e1^^ e2s^^) 'Any)]
  10980. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  10981. [(Lambda params Tr e1)
  10982. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  10983. (match p
  10984. [`[,x : ,T] (values x T)]
  10985. [(? symbol? x) (values x 'Any)])))
  10986. (define-values (e1^ T1)
  10987. ((type-check-exp (append (map cons xs Ts) env)) e1))
  10988. (check-consistent? Tr T1 e)
  10989. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  10990. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  10991. [else ((super type-check-exp env) e)]
  10992. )))
  10993. \end{lstlisting}
  10994. \caption{Type checker for the \LangGrad{} language, part 3.}
  10995. \label{fig:type-check-Rgradual-3}
  10996. \end{figure}
  10997. \begin{figure}[tbp]
  10998. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10999. (define/public (join t1 t2)
  11000. (match* (t1 t2)
  11001. [('Integer 'Integer) 'Integer]
  11002. [('Boolean 'Boolean) 'Boolean]
  11003. [('Void 'Void) 'Void]
  11004. [('Any t2) t2]
  11005. [(t1 'Any) t1]
  11006. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11007. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  11008. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11009. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  11010. -> ,(join rt1 rt2))]))
  11011. (define/public (meet t1 t2)
  11012. (match* (t1 t2)
  11013. [('Integer 'Integer) 'Integer]
  11014. [('Boolean 'Boolean) 'Boolean]
  11015. [('Void 'Void) 'Void]
  11016. [('Any t2) 'Any]
  11017. [(t1 'Any) 'Any]
  11018. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11019. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  11020. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11021. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  11022. -> ,(meet rt1 rt2))]))
  11023. (define/public (make-cast e src tgt)
  11024. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  11025. (define/public (check-consistent? t1 t2 e)
  11026. (unless (consistent? t1 t2)
  11027. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  11028. (define/override (type-check-op op arg-types args e)
  11029. (match (dict-ref (operator-types) op)
  11030. [`(,param-types . ,return-type)
  11031. (for ([at arg-types] [pt param-types])
  11032. (check-consistent? at pt e))
  11033. (values return-type
  11034. (for/list ([e args] [s arg-types] [t param-types])
  11035. (make-cast e s t)))]
  11036. [else (error 'type-check-op "unrecognized ~a" op)]))
  11037. (define explicit-prim-ops
  11038. (set-union
  11039. (type-predicates)
  11040. (set 'procedure-arity 'eq?
  11041. 'vector 'vector-length 'vector-ref 'vector-set!
  11042. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  11043. (define/override (fun-def-type d)
  11044. (match d
  11045. [(Def f params rt info body)
  11046. (define ps
  11047. (for/list ([p params])
  11048. (match p
  11049. [`[,x : ,T] T]
  11050. [(? symbol?) 'Any]
  11051. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  11052. `(,@ps -> ,rt)]
  11053. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  11054. \end{lstlisting}
  11055. \caption{Auxiliary functions for type checking \LangGrad{}.}
  11056. \label{fig:type-check-Rgradual-aux}
  11057. \end{figure}
  11058. \clearpage
  11059. \section{Interpreting \LangCast{}}
  11060. \label{sec:interp-casts}
  11061. The runtime behavior of first-order casts is straightforward, that is,
  11062. casts involving simple types such as \code{Integer} and
  11063. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  11064. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  11065. puts the integer into a tagged value
  11066. (Figure~\ref{fig:interp-Rany}). Similarly, a cast from \code{Any} to
  11067. \code{Integer} is accomplished with the \code{Project} operator, that
  11068. is, by checking the value's tag and either retrieving the underlying
  11069. integer or signaling an error if it the tag is not the one for
  11070. integers (Figure~\ref{fig:apply-project}).
  11071. %
  11072. Things get more interesting for higher-order casts, that is, casts
  11073. involving function or vector types.
  11074. Consider the cast of the function \code{maybe-add1} from \code{(Any ->
  11075. Any)} to \code{(Integer -> Integer)}. When a function flows through
  11076. this cast at runtime, we can't know in general whether the function
  11077. will always return an integer.\footnote{Predicting the return value of
  11078. a function is equivalent to the halting problem, which is
  11079. undecidable.} The \LangCast{} interpreter therefore delays the checking
  11080. of the cast until the function is applied. This is accomplished by
  11081. wrapping \code{maybe-add1} in a new function that casts its parameter
  11082. from \code{Integer} to \code{Any}, applies \code{maybe-add1}, and then
  11083. casts the return value from \code{Any} to \code{Integer}.
  11084. Turning our attention to casts involving vector types, we consider the
  11085. example in Figure~\ref{fig:map-vec-bang} that defines a
  11086. partially-typed version of \code{map-vec} whose parameter \code{v} has
  11087. type \code{(Vector Any Any)} and that updates \code{v} in place
  11088. instead of returning a new vector. So we name this function
  11089. \code{map-vec!}. We apply \code{map-vec!} to a vector of integers, so
  11090. the type checker inserts a cast from \code{(Vector Integer Integer)}
  11091. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  11092. cast between vector types would be a build a new vector whose elements
  11093. are the result of casting each of the original elements to the
  11094. appropriate target type. However, this approach is only valid for
  11095. immutable vectors; and our vectors are mutable. In the example of
  11096. Figure~\ref{fig:map-vec-bang}, if the cast created a new vector, then
  11097. the updates inside of \code{map-vec!} would happen to the new vector
  11098. and not the original one.
  11099. \begin{figure}[tbp]
  11100. % gradual_test_11.rkt
  11101. \begin{lstlisting}
  11102. (define (map-vec! [f : (Any -> Any)]
  11103. [v : (Vector Any Any)]) : Void
  11104. (begin
  11105. (vector-set! v 0 (f (vector-ref v 0)))
  11106. (vector-set! v 1 (f (vector-ref v 1)))))
  11107. (define (add1 x) (+ x 1))
  11108. (let ([v (vector 0 41)])
  11109. (begin (map-vec! add1 v) (vector-ref v 1)))
  11110. \end{lstlisting}
  11111. \caption{An example involving casts on vectors.}
  11112. \label{fig:map-vec-bang}
  11113. \end{figure}
  11114. Instead the interpreter needs to create a new kind of value, a
  11115. \emph{vector proxy}, that intercepts every vector operation. On a
  11116. read, the proxy reads from the underlying vector and then applies a
  11117. cast to the resulting value. On a write, the proxy casts the argument
  11118. value and then performs the write to the underlying vector. For the
  11119. first \code{(vector-ref v 0)} in \code{map-vec!}, the proxy casts
  11120. \code{0} from \code{Integer} to \code{Any}. For the first
  11121. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  11122. to \code{Integer}.
  11123. The final category of cast that we need to consider are casts between
  11124. the \code{Any} type and either a function or a vector
  11125. type. Figure~\ref{fig:map-vec-any} shows a variant of \code{map-vec!}
  11126. in which parameter \code{v} does not have a type annotation, so it is
  11127. given type \code{Any}. In the call to \code{map-vec!}, the vector has
  11128. type \code{(Vector Integer Integer)} so the type checker inserts a
  11129. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  11130. thought is to use \code{Inject}, but that doesn't work because
  11131. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  11132. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  11133. to \code{Any}.
  11134. \begin{figure}[tbp]
  11135. \begin{lstlisting}
  11136. (define (map-vec! [f : (Any -> Any)] v) : Void
  11137. (begin
  11138. (vector-set! v 0 (f (vector-ref v 0)))
  11139. (vector-set! v 1 (f (vector-ref v 1)))))
  11140. (define (add1 x) (+ x 1))
  11141. (let ([v (vector 0 41)])
  11142. (begin (map-vec! add1 v) (vector-ref v 1)))
  11143. \end{lstlisting}
  11144. \caption{Casting a vector to \code{Any}.}
  11145. \label{fig:map-vec-any}
  11146. \end{figure}
  11147. The \LangCast{} interpreter uses an auxiliary function named
  11148. \code{apply-cast} to cast a value from a source type to a target type,
  11149. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  11150. of the kinds of casts that we've discussed in this section.
  11151. \begin{figure}[tbp]
  11152. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11153. (define/public (apply-cast v s t)
  11154. (match* (s t)
  11155. [(t1 t2) #:when (equal? t1 t2) v]
  11156. [('Any t2)
  11157. (match t2
  11158. [`(,ts ... -> ,rt)
  11159. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  11160. (define v^ (apply-project v any->any))
  11161. (apply-cast v^ any->any `(,@ts -> ,rt))]
  11162. [`(Vector ,ts ...)
  11163. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  11164. (define v^ (apply-project v vec-any))
  11165. (apply-cast v^ vec-any `(Vector ,@ts))]
  11166. [else (apply-project v t2)])]
  11167. [(t1 'Any)
  11168. (match t1
  11169. [`(,ts ... -> ,rt)
  11170. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  11171. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  11172. (apply-inject v^ (any-tag any->any))]
  11173. [`(Vector ,ts ...)
  11174. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  11175. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  11176. (apply-inject v^ (any-tag vec-any))]
  11177. [else (apply-inject v (any-tag t1))])]
  11178. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11179. (define x (gensym 'x))
  11180. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  11181. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  11182. (define cast-writes
  11183. (for/list ([t1 ts1] [t2 ts2])
  11184. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  11185. `(vector-proxy ,(vector v (apply vector cast-reads)
  11186. (apply vector cast-writes)))]
  11187. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11188. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  11189. `(function ,xs ,(Cast
  11190. (Apply (Value v)
  11191. (for/list ([x xs][t1 ts1][t2 ts2])
  11192. (Cast (Var x) t2 t1)))
  11193. rt1 rt2) ())]
  11194. ))
  11195. \end{lstlisting}
  11196. \caption{The \code{apply-cast} auxiliary method.}
  11197. \label{fig:apply-cast}
  11198. \end{figure}
  11199. The interpreter for \LangCast{} is defined in
  11200. Figure~\ref{fig:interp-Rcast}, with the case for \code{Cast}
  11201. dispatching to \code{apply-cast}. To handle the addition of vector
  11202. proxies, we update the vector primitives in \code{interp-op} using the
  11203. functions in Figure~\ref{fig:guarded-vector}.
  11204. \begin{figure}[tbp]
  11205. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11206. (define interp-Rcast-class
  11207. (class interp-Rwhile-class
  11208. (super-new)
  11209. (inherit apply-fun apply-inject apply-project)
  11210. (define/override (interp-op op)
  11211. (match op
  11212. ['vector-length guarded-vector-length]
  11213. ['vector-ref guarded-vector-ref]
  11214. ['vector-set! guarded-vector-set!]
  11215. ['any-vector-ref (lambda (v i)
  11216. (match v [`(tagged ,v^ ,tg)
  11217. (guarded-vector-ref v^ i)]))]
  11218. ['any-vector-set! (lambda (v i a)
  11219. (match v [`(tagged ,v^ ,tg)
  11220. (guarded-vector-set! v^ i a)]))]
  11221. ['any-vector-length (lambda (v)
  11222. (match v [`(tagged ,v^ ,tg)
  11223. (guarded-vector-length v^)]))]
  11224. [else (super interp-op op)]
  11225. ))
  11226. (define/override ((interp-exp env) e)
  11227. (define (recur e) ((interp-exp env) e))
  11228. (match e
  11229. [(Value v) v]
  11230. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  11231. [else ((super interp-exp env) e)]))
  11232. ))
  11233. (define (interp-Rcast p)
  11234. (send (new interp-Rcast-class) interp-program p))
  11235. \end{lstlisting}
  11236. \caption{The interpreter for \LangCast{}.}
  11237. \label{fig:interp-Rcast}
  11238. \end{figure}
  11239. \begin{figure}[tbp]
  11240. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11241. (define (guarded-vector-ref vec i)
  11242. (match vec
  11243. [`(vector-proxy ,proxy)
  11244. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  11245. (define rd (vector-ref (vector-ref proxy 1) i))
  11246. (apply-fun rd (list val) 'guarded-vector-ref)]
  11247. [else (vector-ref vec i)]))
  11248. (define (guarded-vector-set! vec i arg)
  11249. (match vec
  11250. [`(vector-proxy ,proxy)
  11251. (define wr (vector-ref (vector-ref proxy 2) i))
  11252. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  11253. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  11254. [else (vector-set! vec i arg)]))
  11255. (define (guarded-vector-length vec)
  11256. (match vec
  11257. [`(vector-proxy ,proxy)
  11258. (guarded-vector-length (vector-ref proxy 0))]
  11259. [else (vector-length vec)]))
  11260. \end{lstlisting}
  11261. \caption{The guarded-vector auxiliary functions.}
  11262. \label{fig:guarded-vector}
  11263. \end{figure}
  11264. \section{Lower Casts}
  11265. \label{sec:lower-casts}
  11266. The next step in the journey towards x86 is the \code{lower-casts}
  11267. pass that translates the casts in \LangCast{} to the lower-level
  11268. \code{Inject} and \code{Project} operators and a new operator for
  11269. creating vector proxies, extending the \LangLoop{} language to create
  11270. \LangProxy{}. We recommend creating an auxiliary function named
  11271. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  11272. and a target type, and translates it to expression in \LangProxy{} that has
  11273. the same behavior as casting the expression from the source to the
  11274. target type in the interpreter.
  11275. The \code{lower-cast} function can follow a code structure similar to
  11276. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  11277. the interpreter for \LangCast{} because it must handle the same cases as
  11278. \code{apply-cast} and it needs to mimic the behavior of
  11279. \code{apply-cast}. The most interesting cases are those concerning the
  11280. casts between two vector types and between two function types.
  11281. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  11282. type to another vector type is accomplished by creating a proxy that
  11283. intercepts the operations on the underlying vector. Here we make the
  11284. creation of the proxy explicit with the \code{vector-proxy} primitive
  11285. operation. It takes three arguments, the first is an expression for
  11286. the vector, the second is a vector of functions for casting an element
  11287. that is being read from the vector, and the third is a vector of
  11288. functions for casting an element that is being written to the vector.
  11289. You can create the functions using \code{Lambda}. Also, as we shall
  11290. see in the next section, we need to differentiate these vectors from
  11291. the user-created ones, so we recommend using a new primitive operator
  11292. named \code{raw-vector} instead of \code{vector} to create these
  11293. vectors of functions. Figure~\ref{fig:map-vec-bang-lower-cast} shows
  11294. the output of \code{lower-casts} on the example in
  11295. Figure~\ref{fig:map-vec-bang} that involved casting a vector of
  11296. integers to a vector of \code{Any}.
  11297. \begin{figure}[tbp]
  11298. \begin{lstlisting}
  11299. (define (map-vec! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  11300. (begin
  11301. (vector-set! v 0 (f (vector-ref v 0)))
  11302. (vector-set! v 1 (f (vector-ref v 1)))))
  11303. (define (add1 [x : Any]) : Any
  11304. (inject (+ (project x Integer) 1) Integer))
  11305. (let ([v (vector 0 41)])
  11306. (begin
  11307. (map-vec! add1 (vector-proxy v
  11308. (raw-vector (lambda: ([x9 : Integer]) : Any
  11309. (inject x9 Integer))
  11310. (lambda: ([x9 : Integer]) : Any
  11311. (inject x9 Integer)))
  11312. (raw-vector (lambda: ([x9 : Any]) : Integer
  11313. (project x9 Integer))
  11314. (lambda: ([x9 : Any]) : Integer
  11315. (project x9 Integer)))))
  11316. (vector-ref v 1)))
  11317. \end{lstlisting}
  11318. \caption{Output of \code{lower-casts} on the example in
  11319. Figure~\ref{fig:map-vec-bang}.}
  11320. \label{fig:map-vec-bang-lower-cast}
  11321. \end{figure}
  11322. A cast from one function type to another function type is accomplished
  11323. by generating a \code{Lambda} whose parameter and return types match
  11324. the target function type. The body of the \code{Lambda} should cast
  11325. the parameters from the target type to the source type (yes,
  11326. backwards! functions are contravariant\index{contravariant} in the
  11327. parameters), then call the underlying function, and finally cast the
  11328. result from the source return type to the target return type.
  11329. Figure~\ref{fig:map-vec-lower-cast} shows the output of the
  11330. \code{lower-casts} pass on the \code{map-vec} example in
  11331. Figure~\ref{fig:gradual-map-vec}. Note that the \code{add1} argument
  11332. in the call to \code{map-vec} is wrapped in a \code{lambda}.
  11333. \begin{figure}[tbp]
  11334. \begin{lstlisting}
  11335. (define (map-vec [f : (Integer -> Integer)]
  11336. [v : (Vector Integer Integer)])
  11337. : (Vector Integer Integer)
  11338. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11339. (define (add1 [x : Any]) : Any
  11340. (inject (+ (project x Integer) 1) Integer))
  11341. (vector-ref (map-vec (lambda: ([x9 : Integer]) : Integer
  11342. (project (add1 (inject x9 Integer)) Integer))
  11343. (vector 0 41)) 1)
  11344. \end{lstlisting}
  11345. \caption{Output of \code{lower-casts} on the example in
  11346. Figure~\ref{fig:gradual-map-vec}.}
  11347. \label{fig:map-vec-lower-cast}
  11348. \end{figure}
  11349. \section{Differentiate Proxies}
  11350. \label{sec:differentiate-proxies}
  11351. So far the job of differentiating vectors and vector proxies has been
  11352. the job of the interpreter. For example, the interpreter for \LangCast{}
  11353. implements \code{vector-ref} using the \code{guarded-vector-ref}
  11354. function in Figure~\ref{fig:guarded-vector}. In the
  11355. \code{differentiate-proxies} pass we shift this responsibility to the
  11356. generated code.
  11357. We begin by designing the output language $R^p_8$. In
  11358. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  11359. proxies. In $R^p_8$ we return the \code{Vector} type to
  11360. its original meaning, as the type of real vectors, and we introduce a
  11361. new type, \code{PVector}, whose values can be either real vectors or
  11362. vector proxies. This new type comes with a suite of new primitive
  11363. operations for creating and using values of type \code{PVector}. We
  11364. don't need to introduce a new type to represent vector proxies. A
  11365. proxy is represented by a vector containing three things: 1) the
  11366. underlying vector, 2) a vector of functions for casting elements that
  11367. are read from the vector, and 3) a vector of functions for casting
  11368. values to be written to the vector. So we define the following
  11369. abbreviation for the type of a vector proxy:
  11370. \[
  11371. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  11372. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  11373. \to (\key{PVector}~ T' \ldots)
  11374. \]
  11375. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  11376. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  11377. %
  11378. Next we describe each of the new primitive operations.
  11379. \begin{description}
  11380. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  11381. (\key{PVector} $T \ldots$)]\ \\
  11382. %
  11383. This operation brands a vector as a value of the \code{PVector} type.
  11384. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  11385. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  11386. %
  11387. This operation brands a vector proxy as value of the \code{PVector} type.
  11388. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  11389. \code{Boolean}] \ \\
  11390. %
  11391. returns true if the value is a vector proxy and false if it is a
  11392. real vector.
  11393. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  11394. (\key{Vector} $T \ldots$)]\ \\
  11395. %
  11396. Assuming that the input is a vector (and not a proxy), this
  11397. operation returns the vector.
  11398. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  11399. $\to$ \code{Boolean}]\ \\
  11400. %
  11401. Given a vector proxy, this operation returns the length of the
  11402. underlying vector.
  11403. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  11404. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  11405. %
  11406. Given a vector proxy, this operation returns the $i$th element of
  11407. the underlying vector.
  11408. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  11409. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  11410. proxy, this operation writes a value to the $i$th element of the
  11411. underlying vector.
  11412. \end{description}
  11413. Now to discuss the translation that differentiates vectors from
  11414. proxies. First, every type annotation in the program must be
  11415. translated (recursively) to replace \code{Vector} with \code{PVector}.
  11416. Next, we must insert uses of \code{PVector} operations in the
  11417. appropriate places. For example, we wrap every vector creation with an
  11418. \code{inject-vector}.
  11419. \begin{lstlisting}
  11420. (vector |$e_1 \ldots e_n$|)
  11421. |$\Rightarrow$|
  11422. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  11423. \end{lstlisting}
  11424. The \code{raw-vector} operator that we introduced in the previous
  11425. section does not get injected.
  11426. \begin{lstlisting}
  11427. (raw-vector |$e_1 \ldots e_n$|)
  11428. |$\Rightarrow$|
  11429. (vector |$e'_1 \ldots e'_n$|)
  11430. \end{lstlisting}
  11431. The \code{vector-proxy} primitive translates as follows.
  11432. \begin{lstlisting}
  11433. (vector-proxy |$e_1~e_2~e_3$|)
  11434. |$\Rightarrow$|
  11435. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  11436. \end{lstlisting}
  11437. We translate the vector operations into conditional expressions that
  11438. check whether the value is a proxy and then dispatch to either the
  11439. appropriate proxy vector operation or the regular vector operation.
  11440. For example, the following is the translation for \code{vector-ref}.
  11441. \begin{lstlisting}
  11442. (vector-ref |$e_1$| |$i$|)
  11443. |$\Rightarrow$|
  11444. (let ([|$v~e_1$|])
  11445. (if (proxy? |$v$|)
  11446. (proxy-vector-ref |$v$| |$i$|)
  11447. (vector-ref (project-vector |$v$|) |$i$|)
  11448. \end{lstlisting}
  11449. Note in the case of a real vector, we must apply \code{project-vector}
  11450. before the \code{vector-ref}.
  11451. \section{Reveal Casts}
  11452. \label{sec:reveal-casts-gradual}
  11453. Recall that the \code{reveal-casts} pass
  11454. (Section~\ref{sec:reveal-casts-Rany}) is responsible for lowering
  11455. \code{Inject} and \code{Project} into lower-level operations. In
  11456. particular, \code{Project} turns into a conditional expression that
  11457. inspects the tag and retrieves the underlying value. Here we need to
  11458. augment the translation of \code{Project} to handle the situation when
  11459. the target type is \code{PVector}. Instead of using
  11460. \code{vector-length} we need to use \code{proxy-vector-length}.
  11461. \begin{lstlisting}
  11462. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  11463. |$\Rightarrow$|
  11464. (let |$\itm{tmp}$| |$e'$|
  11465. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  11466. (let |$\itm{vec}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  11467. (if (eq? (proxy-vector-length |$\itm{vec}$|) |$n$|) |$\itm{vec}$| (exit)))
  11468. (exit)))
  11469. \end{lstlisting}
  11470. \section{Closure Conversion}
  11471. \label{sec:closure-conversion-gradual}
  11472. The closure conversion pass only requires one minor adjustment. The
  11473. auxiliary function that translates type annotations needs to be
  11474. updated to handle the \code{PVector} type.
  11475. \section{Explicate Control}
  11476. \label{sec:explicate-control-gradual}
  11477. Update the \code{explicate-control} pass to handle the new primitive
  11478. operations on the \code{PVector} type.
  11479. \section{Select Instructions}
  11480. \label{sec:select-instructions-gradual}
  11481. Recall that the \code{select-instructions} pass is responsible for
  11482. lowering the primitive operations into x86 instructions. So we need
  11483. to translate the new \code{PVector} operations to x86. To do so, the
  11484. first question we need to answer is how will we differentiate the two
  11485. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  11486. We need just one bit to accomplish this, and use the bit in position
  11487. $57$ of the 64-bit tag at the front of every vector (see
  11488. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  11489. for \code{inject-vector} we leave it that way.
  11490. \begin{lstlisting}
  11491. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  11492. |$\Rightarrow$|
  11493. movq |$e'_1$|, |$\itm{lhs'}$|
  11494. \end{lstlisting}
  11495. On the other hand, \code{inject-proxy} sets bit $57$ to $1$.
  11496. \begin{lstlisting}
  11497. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  11498. |$\Rightarrow$|
  11499. movq |$e'_1$|, %r11
  11500. movq |$(1 << 57)$|, %rax
  11501. orq 0(%r11), %rax
  11502. movq %rax, 0(%r11)
  11503. movq %r11, |$\itm{lhs'}$|
  11504. \end{lstlisting}
  11505. The \code{proxy?} operation consumes the information so carefully
  11506. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  11507. isolates the $57$th bit to tell whether the value is a real vector or
  11508. a proxy.
  11509. \begin{lstlisting}
  11510. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  11511. |$\Rightarrow$|
  11512. movq |$e_1'$|, %r11
  11513. movq 0(%r11), %rax
  11514. sarq $57, %rax
  11515. andq $1, %rax
  11516. movq %rax, |$\itm{lhs'}$|
  11517. \end{lstlisting}
  11518. The \code{project-vector} operation is straightforward to translate,
  11519. so we leave it up to the reader.
  11520. Regarding the \code{proxy-vector} operations, the runtime provides
  11521. procedures that implement them (they are recursive functions!) so
  11522. here we simply need to translate these vector operations into the
  11523. appropriate function call. For example, here is the translation for
  11524. \code{proxy-vector-ref}.
  11525. \begin{lstlisting}
  11526. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  11527. |$\Rightarrow$|
  11528. movq |$e_1'$|, %rdi
  11529. movq |$e_2'$|, %rsi
  11530. callq proxy_vector_ref
  11531. movq %rax, |$\itm{lhs'}$|
  11532. \end{lstlisting}
  11533. We have another batch of vector operations to deal with, those for the
  11534. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  11535. \code{any-vector-ref} when there is a \code{vector-ref} on something
  11536. of type \code{Any}, and similarly for \code{any-vector-set!} and
  11537. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  11538. Section~\ref{sec:select-Rany} we selected instructions for these
  11539. operations based on the idea that the underlying value was a real
  11540. vector. But in the current setting, the underlying value is of type
  11541. \code{PVector}. So \code{any-vector-ref} can be translates to
  11542. pseudo-x86 as follows. We begin by projecting the underlying value out
  11543. of the tagged value and then call the \code{proxy\_vector\_ref}
  11544. procedure in the runtime.
  11545. \begin{lstlisting}
  11546. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  11547. movq |$\neg 111$|, %rdi
  11548. andq |$e_1'$|, %rdi
  11549. movq |$e_2'$|, %rsi
  11550. callq proxy_vector_ref
  11551. movq %rax, |$\itm{lhs'}$|
  11552. \end{lstlisting}
  11553. The \code{any-vector-set!} and \code{any-vector-length} operators can
  11554. be translated in a similar way.
  11555. \begin{exercise}\normalfont
  11556. Implement a compiler for the gradually-typed \LangGrad{} language by
  11557. extending and adapting your compiler for \LangLoop{}. Create 10 new
  11558. partially-typed test programs. In addition to testing with these
  11559. new programs, also test your compiler on all the tests for \LangLoop{}
  11560. and tests for \LangDyn{}. Sometimes you may get a type checking error
  11561. on the \LangDyn{} programs but you can adapt them by inserting
  11562. a cast to the \code{Any} type around each subexpression
  11563. causing a type error. While \LangDyn{} doesn't have explicit casts,
  11564. you can induce one by wrapping the subexpression \code{e}
  11565. with a call to an un-annotated identity function, like this:
  11566. \code{((lambda (x) x) e)}.
  11567. \end{exercise}
  11568. \begin{figure}[p]
  11569. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11570. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  11571. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  11572. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  11573. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  11574. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  11575. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  11576. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  11577. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  11578. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  11579. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  11580. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  11581. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  11582. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  11583. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  11584. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  11585. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  11586. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  11587. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  11588. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  11589. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  11590. \path[->,bend right=15] (Rgradual) edge [above] node
  11591. {\ttfamily\footnotesize type-check} (Rgradualp);
  11592. \path[->,bend right=15] (Rgradualp) edge [above] node
  11593. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  11594. \path[->,bend right=15] (Rwhilepp) edge [right] node
  11595. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  11596. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  11597. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  11598. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  11599. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  11600. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  11601. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  11602. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  11603. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  11604. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  11605. {\ttfamily\footnotesize convert-assignments} (F1-1);
  11606. \path[->,bend left=15] (F1-1) edge [below] node
  11607. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  11608. \path[->,bend right=15] (F1-2) edge [above] node
  11609. {\ttfamily\footnotesize limit-fun.} (F1-3);
  11610. \path[->,bend right=15] (F1-3) edge [above] node
  11611. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  11612. \path[->,bend right=15] (F1-4) edge [above] node
  11613. {\ttfamily\footnotesize remove-complex.} (F1-5);
  11614. \path[->,bend right=15] (F1-5) edge [right] node
  11615. {\ttfamily\footnotesize explicate-control} (C3-2);
  11616. \path[->,bend left=15] (C3-2) edge [left] node
  11617. {\ttfamily\footnotesize select-instr.} (x86-2);
  11618. \path[->,bend right=15] (x86-2) edge [left] node
  11619. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  11620. \path[->,bend right=15] (x86-2-1) edge [below] node
  11621. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  11622. \path[->,bend right=15] (x86-2-2) edge [left] node
  11623. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  11624. \path[->,bend left=15] (x86-3) edge [above] node
  11625. {\ttfamily\footnotesize patch-instr.} (x86-4);
  11626. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  11627. \end{tikzpicture}
  11628. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  11629. \label{fig:Rgradual-passes}
  11630. \end{figure}
  11631. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  11632. for the compilation of \LangGrad{}.
  11633. \section{Further Reading}
  11634. This chapter just scratches the surface of gradual typing. The basic
  11635. approach described here is missing two key ingredients that one would
  11636. want in a implementation of gradual typing: blame
  11637. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  11638. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  11639. problem addressed by blame tracking is that when a cast on a
  11640. higher-order value fails, it often does so at a point in the program
  11641. that is far removed from the original cast. Blame tracking is a
  11642. technique for propagating extra information through casts and proxies
  11643. so that when a cast fails, the error message can point back to the
  11644. original location of the cast in the source program.
  11645. The problem addressed by space-efficient casts also relates to
  11646. higher-order casts. It turns out that in partially typed programs, a
  11647. function or vector can flow through very-many casts at runtime. With
  11648. the approach described in this chapter, each cast adds another
  11649. \code{lambda} wrapper or a vector proxy. Not only does this take up
  11650. considerable space, but it also makes the function calls and vector
  11651. operations slow. For example, a partially-typed version of quicksort
  11652. could, in the worst case, build a chain of proxies of length $O(n)$
  11653. around the vector, changing the overall time complexity of the
  11654. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  11655. solution to this problem by representing casts using the coercion
  11656. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  11657. long chains of proxies by compressing them into a concise normal
  11658. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  11659. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  11660. the Grift compiler.
  11661. \begin{center}
  11662. \url{https://github.com/Gradual-Typing/Grift}
  11663. \end{center}
  11664. There are also interesting interactions between gradual typing and
  11665. other language features, such as parametetric polymorphism,
  11666. information-flow types, and type inference, to name a few. We
  11667. recommend the reader to the online gradual typing bibliography:
  11668. \begin{center}
  11669. \url{http://samth.github.io/gradual-typing-bib/}
  11670. \end{center}
  11671. % TODO: challenge problem:
  11672. % type analysis and type specialization?
  11673. % coercions?
  11674. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11675. \chapter{Parametric Polymorphism}
  11676. \label{ch:Rpoly}
  11677. \index{parametric polymorphism}
  11678. \index{generics}
  11679. This chapter studies the compilation of parametric
  11680. polymorphism\index{parametric polymorphism}
  11681. (aka. generics\index{generics}) in the subset \LangPoly{} of Typed
  11682. Racket. Parametric polymorphism enables improved code reuse by
  11683. parameterizing functions and data structures with respect to the types
  11684. that they operate on. For example, Figure~\ref{fig:map-vec-poly}
  11685. revisits the \code{map-vec} example but this time gives it a more
  11686. fitting type. This \code{map-vec} function is parameterized with
  11687. respect to the element type of the vector. The type of \code{map-vec}
  11688. is the following polymorphic type as specified by the \code{All} and
  11689. the type parameter \code{a}.
  11690. \begin{lstlisting}
  11691. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  11692. \end{lstlisting}
  11693. The idea is that \code{map-vec} can be used at \emph{all} choices of a
  11694. type for parameter \code{a}. In Figure~\ref{fig:map-vec-poly} we apply
  11695. \code{map-vec} to a vector of integers, a choice of \code{Integer} for
  11696. \code{a}, but we could have just as well applied \code{map-vec} to a
  11697. vector of Booleans (and a function on Booleans).
  11698. \begin{figure}[tbp]
  11699. % poly_test_2.rkt
  11700. \begin{lstlisting}
  11701. (: map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  11702. (define (map-vec f v)
  11703. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11704. (define (add1 [x : Integer]) : Integer (+ x 1))
  11705. (vector-ref (map-vec add1 (vector 0 41)) 1)
  11706. \end{lstlisting}
  11707. \caption{The \code{map-vec} example using parametric polymorphism.}
  11708. \label{fig:map-vec-poly}
  11709. \end{figure}
  11710. Figure~\ref{fig:Rpoly-concrete-syntax} defines the concrete syntax of
  11711. \LangPoly{} and Figure~\ref{fig:Rpoly-syntax} defines the abstract
  11712. syntax. We add a second form for function definitions in which a type
  11713. declaration comes before the \code{define}. In the abstract syntax,
  11714. the return type in the \code{Def} is \code{Any}, but that should be
  11715. ignored in favor of the return type in the type declaration. (The
  11716. \code{Any} comes from using the same parser as in
  11717. Chapter~\ref{ch:Rdyn}.) The presence of a type declaration
  11718. enables the use of an \code{All} type for a function, thereby making
  11719. it polymorphic. The grammar for types is extended to include
  11720. polymorphic types and type variables.
  11721. \begin{figure}[tp]
  11722. \centering
  11723. \fbox{
  11724. \begin{minipage}{0.96\textwidth}
  11725. \small
  11726. \[
  11727. \begin{array}{lcl}
  11728. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11729. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  11730. &\mid& \LP\key{:}~\Var~\Type\RP \\
  11731. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  11732. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  11733. \end{array}
  11734. \]
  11735. \end{minipage}
  11736. }
  11737. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  11738. (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  11739. \label{fig:Rpoly-concrete-syntax}
  11740. \end{figure}
  11741. \begin{figure}[tp]
  11742. \centering
  11743. \fbox{
  11744. \begin{minipage}{0.96\textwidth}
  11745. \small
  11746. \[
  11747. \begin{array}{lcl}
  11748. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11749. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  11750. &\mid& \DECL{\Var}{\Type} \\
  11751. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  11752. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11753. \end{array}
  11754. \]
  11755. \end{minipage}
  11756. }
  11757. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  11758. (Figure~\ref{fig:Rwhile-syntax}).}
  11759. \label{fig:Rpoly-syntax}
  11760. \end{figure}
  11761. By including polymorphic types in the $\Type$ non-terminal we choose
  11762. to make them first-class which has interesting repercussions on the
  11763. compiler. Many languages with polymorphism, such as
  11764. C++~\citep{stroustrup88:_param_types} and Standard
  11765. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  11766. it is useful to see an example of first-class polymorphism. In
  11767. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  11768. whose parameter is a polymorphic function. The occurrence of a
  11769. polymorphic type underneath a function type is enabled by the normal
  11770. recursive structure of the grammar for $\Type$ and the categorization
  11771. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  11772. applies the polymorphic function to a Boolean and to an integer.
  11773. \begin{figure}[tbp]
  11774. \begin{lstlisting}
  11775. (: apply-twice ((All (b) (b -> b)) -> Integer))
  11776. (define (apply-twice f)
  11777. (if (f #t) (f 42) (f 777)))
  11778. (: id (All (a) (a -> a)))
  11779. (define (id x) x)
  11780. (apply-twice id)
  11781. \end{lstlisting}
  11782. \caption{An example illustrating first-class polymorphism.}
  11783. \label{fig:apply-twice}
  11784. \end{figure}
  11785. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Rvar0} has
  11786. three new responsibilities (compared to \LangLoop{}). The type checking of
  11787. function application is extended to handle the case where the operator
  11788. expression is a polymorphic function. In that case the type arguments
  11789. are deduced by matching the type of the parameters with the types of
  11790. the arguments.
  11791. %
  11792. The \code{match-types} auxiliary function carries out this deduction
  11793. by recursively descending through a parameter type \code{pt} and the
  11794. corresponding argument type \code{at}, making sure that they are equal
  11795. except when there is a type parameter on the left (in the parameter
  11796. type). If it's the first time that the type parameter has been
  11797. encountered, then the algorithm deduces an association of the type
  11798. parameter to the corresponding type on the right (in the argument
  11799. type). If it's not the first time that the type parameter has been
  11800. encountered, the algorithm looks up its deduced type and makes sure
  11801. that it is equal to the type on the right.
  11802. %
  11803. Once the type arguments are deduced, the operator expression is
  11804. wrapped in an \code{Inst} AST node (for instantiate) that records the
  11805. type of the operator, but more importantly, records the deduced type
  11806. arguments. The return type of the application is the return type of
  11807. the polymorphic function, but with the type parameters replaced by the
  11808. deduced type arguments, using the \code{subst-type} function.
  11809. The second responsibility of the type checker is extending the
  11810. function \code{type-equal?} to handle the \code{All} type. This is
  11811. not quite a simple as equal on other types, such as function and
  11812. vector types, because two polymorphic types can be syntactically
  11813. different even though they are equivalent types. For example,
  11814. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  11815. Two polymorphic types should be considered equal if they differ only
  11816. in the choice of the names of the type parameters. The
  11817. \code{type-equal?} function in Figure~\ref{fig:type-check-Rvar0-aux}
  11818. renames the type parameters of the first type to match the type
  11819. parameters of the second type.
  11820. The third responsibility of the type checker is making sure that only
  11821. defined type variables appear in type annotations. The
  11822. \code{check-well-formed} function defined in
  11823. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  11824. sure that each type variable has been defined.
  11825. The output language of the type checker is \LangInst{}, defined in
  11826. Figure~\ref{fig:Rpoly-prime-syntax}. The type checker combines the type
  11827. declaration and polymorphic function into a single definition, using
  11828. the \code{Poly} form, to make polymorphic functions more convenient to
  11829. process in next pass of the compiler.
  11830. \begin{figure}[tp]
  11831. \centering
  11832. \fbox{
  11833. \begin{minipage}{0.96\textwidth}
  11834. \small
  11835. \[
  11836. \begin{array}{lcl}
  11837. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11838. \Exp &::=& \ldots \mid \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  11839. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  11840. &\mid& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  11841. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11842. \end{array}
  11843. \]
  11844. \end{minipage}
  11845. }
  11846. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  11847. (Figure~\ref{fig:Rwhile-syntax}).}
  11848. \label{fig:Rpoly-prime-syntax}
  11849. \end{figure}
  11850. The output of the type checker on the polymorphic \code{map-vec}
  11851. example is listed in Figure~\ref{fig:map-vec-type-check}.
  11852. \begin{figure}[tbp]
  11853. % poly_test_2.rkt
  11854. \begin{lstlisting}
  11855. (poly (a) (define (map-vec [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  11856. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  11857. (define (add1 [x : Integer]) : Integer (+ x 1))
  11858. (vector-ref ((inst map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  11859. (Integer))
  11860. add1 (vector 0 41)) 1)
  11861. \end{lstlisting}
  11862. \caption{Output of the type checker on the \code{map-vec} example.}
  11863. \label{fig:map-vec-type-check}
  11864. \end{figure}
  11865. \begin{figure}[tbp]
  11866. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11867. (define type-check-poly-class
  11868. (class type-check-Rwhile-class
  11869. (super-new)
  11870. (inherit check-type-equal?)
  11871. (define/override (type-check-apply env e1 es)
  11872. (define-values (e^ ty) ((type-check-exp env) e1))
  11873. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  11874. ((type-check-exp env) e)))
  11875. (match ty
  11876. [`(,ty^* ... -> ,rt)
  11877. (for ([arg-ty ty*] [param-ty ty^*])
  11878. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  11879. (values e^ es^ rt)]
  11880. [`(All ,xs (,tys ... -> ,rt))
  11881. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  11882. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  11883. (match-types env^^ param-ty arg-ty)))
  11884. (define targs
  11885. (for/list ([x xs])
  11886. (match (dict-ref env^^ x (lambda () #f))
  11887. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  11888. x (Apply e1 es))]
  11889. [ty ty])))
  11890. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  11891. [else (error 'type-check "expected a function, not ~a" ty)]))
  11892. (define/override ((type-check-exp env) e)
  11893. (match e
  11894. [(Lambda `([,xs : ,Ts] ...) rT body)
  11895. (for ([T Ts]) ((check-well-formed env) T))
  11896. ((check-well-formed env) rT)
  11897. ((super type-check-exp env) e)]
  11898. [(HasType e1 ty)
  11899. ((check-well-formed env) ty)
  11900. ((super type-check-exp env) e)]
  11901. [else ((super type-check-exp env) e)]))
  11902. (define/override ((type-check-def env) d)
  11903. (verbose 'type-check "poly/def" d)
  11904. (match d
  11905. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  11906. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  11907. (for ([p ps]) ((check-well-formed ts-env) p))
  11908. ((check-well-formed ts-env) rt)
  11909. (define new-env (append ts-env (map cons xs ps) env))
  11910. (define-values (body^ ty^) ((type-check-exp new-env) body))
  11911. (check-type-equal? ty^ rt body)
  11912. (Generic ts (Def f p:t* rt info body^))]
  11913. [else ((super type-check-def env) d)]))
  11914. (define/override (type-check-program p)
  11915. (match p
  11916. [(Program info body)
  11917. (type-check-program (ProgramDefsExp info '() body))]
  11918. [(ProgramDefsExp info ds body)
  11919. (define ds^ (combine-decls-defs ds))
  11920. (define new-env (for/list ([d ds^])
  11921. (cons (def-name d) (fun-def-type d))))
  11922. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  11923. (define-values (body^ ty) ((type-check-exp new-env) body))
  11924. (check-type-equal? ty 'Integer body)
  11925. (ProgramDefsExp info ds^^ body^)]))
  11926. ))
  11927. \end{lstlisting}
  11928. \caption{Type checker for the \LangPoly{} language.}
  11929. \label{fig:type-check-Rvar0}
  11930. \end{figure}
  11931. \begin{figure}[tbp]
  11932. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11933. (define/override (type-equal? t1 t2)
  11934. (match* (t1 t2)
  11935. [(`(All ,xs ,T1) `(All ,ys ,T2))
  11936. (define env (map cons xs ys))
  11937. (type-equal? (subst-type env T1) T2)]
  11938. [(other wise)
  11939. (super type-equal? t1 t2)]))
  11940. (define/public (match-types env pt at)
  11941. (match* (pt at)
  11942. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  11943. [('Void 'Void) env] [('Any 'Any) env]
  11944. [(`(Vector ,pts ...) `(Vector ,ats ...))
  11945. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  11946. (match-types env^ pt1 at1))]
  11947. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  11948. (define env^ (match-types env prt art))
  11949. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  11950. (match-types env^^ pt1 at1))]
  11951. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  11952. (define env^ (append (map cons pxs axs) env))
  11953. (match-types env^ pt1 at1)]
  11954. [((? symbol? x) at)
  11955. (match (dict-ref env x (lambda () #f))
  11956. [#f (error 'type-check "undefined type variable ~a" x)]
  11957. ['Type (cons (cons x at) env)]
  11958. [t^ (check-type-equal? at t^ 'matching) env])]
  11959. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  11960. (define/public (subst-type env pt)
  11961. (match pt
  11962. ['Integer 'Integer] ['Boolean 'Boolean]
  11963. ['Void 'Void] ['Any 'Any]
  11964. [`(Vector ,ts ...)
  11965. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  11966. [`(,ts ... -> ,rt)
  11967. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  11968. [`(All ,xs ,t)
  11969. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  11970. [(? symbol? x) (dict-ref env x)]
  11971. [else (error 'type-check "expected a type not ~a" pt)]))
  11972. (define/public (combine-decls-defs ds)
  11973. (match ds
  11974. ['() '()]
  11975. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  11976. (unless (equal? name f)
  11977. (error 'type-check "name mismatch, ~a != ~a" name f))
  11978. (match type
  11979. [`(All ,xs (,ps ... -> ,rt))
  11980. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  11981. (cons (Generic xs (Def name params^ rt info body))
  11982. (combine-decls-defs ds^))]
  11983. [`(,ps ... -> ,rt)
  11984. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  11985. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  11986. [else (error 'type-check "expected a function type, not ~a" type) ])]
  11987. [`(,(Def f params rt info body) . ,ds^)
  11988. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  11989. \end{lstlisting}
  11990. \caption{Auxiliary functions for type checking \LangPoly{}.}
  11991. \label{fig:type-check-Rvar0-aux}
  11992. \end{figure}
  11993. \begin{figure}[tbp]
  11994. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  11995. (define/public ((check-well-formed env) ty)
  11996. (match ty
  11997. ['Integer (void)]
  11998. ['Boolean (void)]
  11999. ['Void (void)]
  12000. [(? symbol? a)
  12001. (match (dict-ref env a (lambda () #f))
  12002. ['Type (void)]
  12003. [else (error 'type-check "undefined type variable ~a" a)])]
  12004. [`(Vector ,ts ...)
  12005. (for ([t ts]) ((check-well-formed env) t))]
  12006. [`(,ts ... -> ,t)
  12007. (for ([t ts]) ((check-well-formed env) t))
  12008. ((check-well-formed env) t)]
  12009. [`(All ,xs ,t)
  12010. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  12011. ((check-well-formed env^) t)]
  12012. [else (error 'type-check "unrecognized type ~a" ty)]))
  12013. \end{lstlisting}
  12014. \caption{Well-formed types.}
  12015. \label{fig:well-formed-types}
  12016. \end{figure}
  12017. % TODO: interpreter for R'_10
  12018. \section{Compiling Polymorphism}
  12019. \label{sec:compiling-poly}
  12020. Broadly speaking, there are four approaches to compiling parametric
  12021. polymorphism, which we describe below.
  12022. \begin{description}
  12023. \item[Monomorphization] generates a different version of a polymorphic
  12024. function for each set of type arguments that it is used with,
  12025. producing type-specialized code. This approach results in the most
  12026. efficient code but requires whole-program compilation (no separate
  12027. compilation) and increases code size. For our current purposes
  12028. monomorphization is a non-starter because, with first-class
  12029. polymorphism, it is sometimes not possible to determine which
  12030. generic functions are used with which type arguments during
  12031. compilation. (It can be done at runtime, with just-in-time
  12032. compilation.) This approach is used to compile C++
  12033. templates~\citep{stroustrup88:_param_types} and polymorphic
  12034. functions in NESL~\citep{Blelloch:1993aa} and
  12035. ML~\citep{Weeks:2006aa}.
  12036. \item[Uniform representation] generates one version of each
  12037. polymorphic function but requires all values have a common ``boxed''
  12038. format, such as the tagged values of type \code{Any} in
  12039. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  12040. similarly to code in a dynamically typed language (like \LangDyn{}), in
  12041. which primitive operators require their arguments to be projected
  12042. from \code{Any} and their results are injected into \code{Any}. (In
  12043. object-oriented languages, the projection is accomplished via
  12044. virtual method dispatch.) The uniform representation approach is
  12045. compatible with separate compilation and with first-class
  12046. polymorphism. However, it produces the least-efficient code because
  12047. it introduces overhead in the entire program, including
  12048. non-polymorphic code. This approach is used in the implementation of
  12049. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  12050. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  12051. Java~\citep{Bracha:1998fk}.
  12052. \item[Mixed representation] generates one version of each polymorphic
  12053. function, using a boxed representation for type
  12054. variables. Monomorphic code is compiled as usual (as in \LangLoop{}) and
  12055. conversions are performed at the boundaries between monomorphic and
  12056. polymorphic (e.g. when a polymorphic function is instantiated and
  12057. called). This approach is compatible with separate compilation and
  12058. first-class polymorphism and maintains the efficiency for
  12059. monomorphic code. The tradeoff is increased overhead at the boundary
  12060. between monomorphic and polymorphic code. This approach is used in
  12061. compilers for variants of ML~\citep{Leroy:1992qb} and starting in
  12062. Java 5 with the addition of autoboxing.
  12063. \item[Type passing] uses the unboxed representation in both
  12064. monomorphic and polymorphic code. Each polymorphic function is
  12065. compiled to a single function with extra parameters that describe
  12066. the type arguments. The type information is used by the generated
  12067. code to direct access of the unboxed values at runtime. This
  12068. approach is used in compilers for the Napier88
  12069. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. This
  12070. approach is compatible with separate compilation and first-class
  12071. polymorphism and maintains the efficiency for monomorphic
  12072. code. There is runtime overhead in polymorphic code from dispatching
  12073. on type information.
  12074. \end{description}
  12075. In this chapter we use the mixed representation approach, partly
  12076. because of its favorable attributes, and partly because it is
  12077. straightforward to implement using the tools that we have already
  12078. built to support gradual typing. To compile polymorphic functions, we
  12079. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  12080. \LangCast{}.
  12081. \section{Erase Types}
  12082. \label{sec:erase-types}
  12083. We use the \code{Any} type from Chapter~\ref{ch:Rdyn} to
  12084. represent type variables. For example, Figure~\ref{fig:map-vec-erase}
  12085. shows the output of the \code{erase-types} pass on the polymorphic
  12086. \code{map-vec} (Figure~\ref{fig:map-vec-poly}). The occurrences of
  12087. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  12088. \code{All} types are removed from the type of \code{map-vec}.
  12089. \begin{figure}[tbp]
  12090. \begin{lstlisting}
  12091. (define (map-vec [f : (Any -> Any)] [v : (Vector Any Any)])
  12092. : (Vector Any Any)
  12093. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12094. (define (add1 [x : Integer]) : Integer (+ x 1))
  12095. (vector-ref ((cast map-vec
  12096. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  12097. ((Integer -> Integer) (Vector Integer Integer)
  12098. -> (Vector Integer Integer)))
  12099. add1 (vector 0 41)) 1)
  12100. \end{lstlisting}
  12101. \caption{The polymorphic \code{map-vec} example after type erasure.}
  12102. \label{fig:map-vec-erase}
  12103. \end{figure}
  12104. This process of type erasure creates a challenge at points of
  12105. instantiation. For example, consider the instantiation of
  12106. \code{map-vec} in Figure~\ref{fig:map-vec-type-check}.
  12107. The type of \code{map-vec} is
  12108. \begin{lstlisting}
  12109. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  12110. \end{lstlisting}
  12111. and it is instantiated to
  12112. \begin{lstlisting}
  12113. ((Integer -> Integer) (Vector Integer Integer)
  12114. -> (Vector Integer Integer))
  12115. \end{lstlisting}
  12116. After erasure, the type of \code{map-vec} is
  12117. \begin{lstlisting}
  12118. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  12119. \end{lstlisting}
  12120. but we need to convert it to the instantiated type. This is easy to
  12121. do in the target language \LangCast{} with a single \code{cast}. In
  12122. Figure~\ref{fig:map-vec-erase}, the instantiation of \code{map-vec}
  12123. has been compiled to a \code{cast} from the type of \code{map-vec} to
  12124. the instantiated type. The source and target type of a cast must be
  12125. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  12126. because both the source and target are obtained from the same
  12127. polymorphic type of \code{map-vec}, replacing the type parameters with
  12128. \code{Any} in the former and with the deduced type arguments in the
  12129. later. (Recall that the \code{Any} type is consistent with any type.)
  12130. To implement the \code{erase-types} pass, we recommend defining a
  12131. recursive auxiliary function named \code{erase-type} that applies the
  12132. following two transformations. It replaces type variables with
  12133. \code{Any}
  12134. \begin{lstlisting}
  12135. |$x$|
  12136. |$\Rightarrow$|
  12137. Any
  12138. \end{lstlisting}
  12139. and it removes the polymorphic \code{All} types.
  12140. \begin{lstlisting}
  12141. (All |$xs$| |$T_1$|)
  12142. |$\Rightarrow$|
  12143. |$T'_1$|
  12144. \end{lstlisting}
  12145. Apply the \code{erase-type} function to all of the type annotations in
  12146. the program.
  12147. Regarding the translation of expressions, the case for \code{Inst} is
  12148. the interesting one. We translate it into a \code{Cast}, as shown
  12149. below. The type of the subexpression $e$ is the polymorphic type
  12150. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  12151. $T$, the type $T'$. The target type $T''$ is the result of
  12152. substituting the arguments types $ts$ for the type parameters $xs$ in
  12153. $T$ followed by doing type erasure.
  12154. \begin{lstlisting}
  12155. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  12156. |$\Rightarrow$|
  12157. (Cast |$e'$| |$T'$| |$T''$|)
  12158. \end{lstlisting}
  12159. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  12160. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  12161. Finally, each polymorphic function is translated to a regular
  12162. functions in which type erasure has been applied to all the type
  12163. annotations and the body.
  12164. \begin{lstlisting}
  12165. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  12166. |$\Rightarrow$|
  12167. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  12168. \end{lstlisting}
  12169. \begin{exercise}\normalfont
  12170. Implement a compiler for the polymorphic language \LangPoly{} by
  12171. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  12172. programs that use polymorphic functions. Some of them should make
  12173. use of first-class polymorphism.
  12174. \end{exercise}
  12175. \begin{figure}[p]
  12176. \begin{tikzpicture}[baseline=(current bounding box.center)]
  12177. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  12178. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  12179. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  12180. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  12181. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  12182. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  12183. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  12184. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  12185. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  12186. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  12187. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  12188. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  12189. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  12190. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  12191. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  12192. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  12193. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  12194. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  12195. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  12196. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  12197. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  12198. \path[->,bend right=15] (Rpoly) edge [above] node
  12199. {\ttfamily\footnotesize type-check} (Rpolyp);
  12200. \path[->,bend right=15] (Rpolyp) edge [above] node
  12201. {\ttfamily\footnotesize erase-types} (Rgradualp);
  12202. \path[->,bend right=15] (Rgradualp) edge [above] node
  12203. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  12204. \path[->,bend right=15] (Rwhilepp) edge [right] node
  12205. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  12206. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  12207. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  12208. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  12209. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  12210. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  12211. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  12212. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  12213. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  12214. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  12215. {\ttfamily\footnotesize convert-assignments} (F1-1);
  12216. \path[->,bend left=15] (F1-1) edge [below] node
  12217. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  12218. \path[->,bend right=15] (F1-2) edge [above] node
  12219. {\ttfamily\footnotesize limit-fun.} (F1-3);
  12220. \path[->,bend right=15] (F1-3) edge [above] node
  12221. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  12222. \path[->,bend right=15] (F1-4) edge [above] node
  12223. {\ttfamily\footnotesize remove-complex.} (F1-5);
  12224. \path[->,bend right=15] (F1-5) edge [right] node
  12225. {\ttfamily\footnotesize explicate-control} (C3-2);
  12226. \path[->,bend left=15] (C3-2) edge [left] node
  12227. {\ttfamily\footnotesize select-instr.} (x86-2);
  12228. \path[->,bend right=15] (x86-2) edge [left] node
  12229. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  12230. \path[->,bend right=15] (x86-2-1) edge [below] node
  12231. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  12232. \path[->,bend right=15] (x86-2-2) edge [left] node
  12233. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  12234. \path[->,bend left=15] (x86-3) edge [above] node
  12235. {\ttfamily\footnotesize patch-instr.} (x86-4);
  12236. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  12237. \end{tikzpicture}
  12238. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  12239. \label{fig:Rpoly-passes}
  12240. \end{figure}
  12241. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  12242. for the compilation of \LangPoly{}.
  12243. % TODO: challenge problem: specialization of instantiations
  12244. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12245. \chapter{Appendix}
  12246. \section{Interpreters}
  12247. \label{appendix:interp}
  12248. \index{interpreter}
  12249. We provide interpreters for each of the source languages \LangInt{},
  12250. \LangVar{}, $\ldots$ in the files \code{interp-Rint.rkt},
  12251. \code{interp-Rvar.rkt}, etc. The interpreters for the intermediate
  12252. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  12253. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  12254. and x86 are in the \key{interp.rkt} file.
  12255. \section{Utility Functions}
  12256. \label{appendix:utilities}
  12257. The utility functions described in this section are in the
  12258. \key{utilities.rkt} file of the support code.
  12259. \paragraph{\code{interp-tests}}
  12260. The \key{interp-tests} function runs the compiler passes and the
  12261. interpreters on each of the specified tests to check whether each pass
  12262. is correct. The \key{interp-tests} function has the following
  12263. parameters:
  12264. \begin{description}
  12265. \item[name (a string)] a name to identify the compiler,
  12266. \item[typechecker] a function of exactly one argument that either
  12267. raises an error using the \code{error} function when it encounters a
  12268. type error, or returns \code{\#f} when it encounters a type
  12269. error. If there is no type error, the type checker returns the
  12270. program.
  12271. \item[passes] a list with one entry per pass. An entry is a list with
  12272. four things:
  12273. \begin{enumerate}
  12274. \item a string giving the name of the pass,
  12275. \item the function that implements the pass (a translator from AST
  12276. to AST),
  12277. \item a function that implements the interpreter (a function from
  12278. AST to result value) for the output language,
  12279. \item and a type checker for the output language. Type checkers for
  12280. the $R$ and $C$ languages are provided in the support code. For
  12281. example, the type checkers for \LangVar{} and \LangCVar{} are in
  12282. \code{type-check-Rvar.rkt} and \code{type-check-Cvar.rkt}. The
  12283. type checker entry is optional. The support code does not provide
  12284. type checkers for the x86 languages.
  12285. \end{enumerate}
  12286. \item[source-interp] an interpreter for the source language. The
  12287. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  12288. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  12289. \item[tests] a list of test numbers that specifies which tests to
  12290. run. (see below)
  12291. \end{description}
  12292. %
  12293. The \key{interp-tests} function assumes that the subdirectory
  12294. \key{tests} has a collection of Racket programs whose names all start
  12295. with the family name, followed by an underscore and then the test
  12296. number, ending with the file extension \key{.rkt}. Also, for each test
  12297. program that calls \code{read} one or more times, there is a file with
  12298. the same name except that the file extension is \key{.in} that
  12299. provides the input for the Racket program. If the test program is
  12300. expected to fail type checking, then there should be an empty file of
  12301. the same name but with extension \key{.tyerr}.
  12302. \paragraph{\code{compiler-tests}}
  12303. runs the compiler passes to generate x86 (a \key{.s} file) and then
  12304. runs the GNU C compiler (gcc) to generate machine code. It runs the
  12305. machine code and checks that the output is $42$. The parameters to the
  12306. \code{compiler-tests} function are similar to those of the
  12307. \code{interp-tests} function, and consist of
  12308. \begin{itemize}
  12309. \item a compiler name (a string),
  12310. \item a type checker,
  12311. \item description of the passes,
  12312. \item name of a test-family, and
  12313. \item a list of test numbers.
  12314. \end{itemize}
  12315. \paragraph{\code{compile-file}}
  12316. takes a description of the compiler passes (see the comment for
  12317. \key{interp-tests}) and returns a function that, given a program file
  12318. name (a string ending in \key{.rkt}), applies all of the passes and
  12319. writes the output to a file whose name is the same as the program file
  12320. name but with \key{.rkt} replaced with \key{.s}.
  12321. \paragraph{\code{read-program}}
  12322. takes a file path and parses that file (it must be a Racket program)
  12323. into an abstract syntax tree.
  12324. \paragraph{\code{parse-program}}
  12325. takes an S-expression representation of an abstract syntax tree and converts it into
  12326. the struct-based representation.
  12327. \paragraph{\code{assert}}
  12328. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  12329. and displays the message \key{msg} if the Boolean \key{bool} is false.
  12330. \paragraph{\code{lookup}}
  12331. % remove discussion of lookup? -Jeremy
  12332. takes a key and an alist, and returns the first value that is
  12333. associated with the given key, if there is one. If not, an error is
  12334. triggered. The alist may contain both immutable pairs (built with
  12335. \key{cons}) and mutable pairs (built with \key{mcons}).
  12336. %The \key{map2} function ...
  12337. \section{x86 Instruction Set Quick-Reference}
  12338. \label{sec:x86-quick-reference}
  12339. \index{x86}
  12340. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  12341. do. We write $A \to B$ to mean that the value of $A$ is written into
  12342. location $B$. Address offsets are given in bytes. The instruction
  12343. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  12344. registers (such as \code{\%rax}), or memory references (such as
  12345. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  12346. reference per instruction. Other operands must be immediates or
  12347. registers.
  12348. \begin{table}[tbp]
  12349. \centering
  12350. \begin{tabular}{l|l}
  12351. \textbf{Instruction} & \textbf{Operation} \\ \hline
  12352. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  12353. \texttt{negq} $A$ & $- A \to A$ \\
  12354. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  12355. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  12356. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  12357. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  12358. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  12359. \texttt{retq} & Pops the return address and jumps to it \\
  12360. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  12361. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  12362. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  12363. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  12364. be an immediate) \\
  12365. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  12366. matches the condition code of the instruction, otherwise go to the
  12367. next instructions. The condition codes are \key{e} for ``equal'',
  12368. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  12369. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  12370. \texttt{jl} $L$ & \\
  12371. \texttt{jle} $L$ & \\
  12372. \texttt{jg} $L$ & \\
  12373. \texttt{jge} $L$ & \\
  12374. \texttt{jmp} $L$ & Jump to label $L$ \\
  12375. \texttt{movq} $A$, $B$ & $A \to B$ \\
  12376. \texttt{movzbq} $A$, $B$ &
  12377. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  12378. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  12379. and the extra bytes of $B$ are set to zero.} \\
  12380. & \\
  12381. & \\
  12382. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  12383. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  12384. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  12385. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  12386. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  12387. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  12388. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  12389. description of the condition codes. $A$ must be a single byte register
  12390. (e.g., \texttt{al} or \texttt{cl}).} \\
  12391. \texttt{setl} $A$ & \\
  12392. \texttt{setle} $A$ & \\
  12393. \texttt{setg} $A$ & \\
  12394. \texttt{setge} $A$ &
  12395. \end{tabular}
  12396. \vspace{5pt}
  12397. \caption{Quick-reference for the x86 instructions used in this book.}
  12398. \label{tab:x86-instr}
  12399. \end{table}
  12400. \cleardoublepage
  12401. \section{Concrete Syntax for Intermediate Languages}
  12402. The concrete syntax of \LangAny{} is defined in
  12403. Figure~\ref{fig:Rany-concrete-syntax}.
  12404. \begin{figure}[tp]
  12405. \centering
  12406. \fbox{
  12407. \begin{minipage}{0.97\textwidth}\small
  12408. \[
  12409. \begin{array}{lcl}
  12410. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  12411. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \key{Void}} \\
  12412. &\mid& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \mid \key{Any} \\
  12413. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void}
  12414. \mid \LP\key{Vector}\; \key{Any}\ldots\RP \\
  12415. &\mid& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  12416. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \mid \CPROJECT{\Exp}{\FType}\\
  12417. &\mid& \LP\key{any-vector-length}\;\Exp\RP
  12418. \mid \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  12419. &\mid& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  12420. &\mid& \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP
  12421. \mid \LP\key{void?}\;\Exp\RP \\
  12422. &\mid& \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \\
  12423. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  12424. \LangAny{} &::=& \gray{\Def\ldots \; \Exp}
  12425. \end{array}
  12426. \]
  12427. \end{minipage}
  12428. }
  12429. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  12430. (Figure~\ref{fig:Rlam-syntax}).}
  12431. \label{fig:Rany-concrete-syntax}
  12432. \end{figure}
  12433. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and \LangCFun{} is
  12434. defined in Figures~\ref{fig:c0-concrete-syntax},
  12435. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax},
  12436. and \ref{fig:c3-concrete-syntax}, respectively.
  12437. \begin{figure}[tbp]
  12438. \fbox{
  12439. \begin{minipage}{0.96\textwidth}
  12440. \[
  12441. \begin{array}{lcl}
  12442. \Atm &::=& \Int \mid \Var \\
  12443. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  12444. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  12445. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  12446. \LangCVar{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  12447. \end{array}
  12448. \]
  12449. \end{minipage}
  12450. }
  12451. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  12452. \label{fig:c0-concrete-syntax}
  12453. \end{figure}
  12454. \begin{figure}[tbp]
  12455. \fbox{
  12456. \begin{minipage}{0.96\textwidth}
  12457. \small
  12458. \[
  12459. \begin{array}{lcl}
  12460. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  12461. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  12462. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  12463. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  12464. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  12465. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  12466. \mid \key{goto}~\itm{label}\key{;}\\
  12467. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  12468. \LangCIf{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  12469. \end{array}
  12470. \]
  12471. \end{minipage}
  12472. }
  12473. \caption{The concrete syntax of the \LangCIf{} intermediate language.}
  12474. \label{fig:c1-concrete-syntax}
  12475. \end{figure}
  12476. \begin{figure}[tbp]
  12477. \fbox{
  12478. \begin{minipage}{0.96\textwidth}
  12479. \small
  12480. \[
  12481. \begin{array}{lcl}
  12482. \Atm &::=& \gray{ \Int \mid \Var \mid \itm{bool} } \\
  12483. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  12484. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  12485. &\mid& \gray{ \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP } \\
  12486. &\mid& \LP \key{allocate}~\Int~\Type \RP \\
  12487. &\mid& (\key{vector-ref}\;\Atm\;\Int) \mid (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  12488. &\mid& \LP \key{global-value}~\Var \RP \mid \LP \key{void} \RP \\
  12489. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \mid \LP\key{collect}~\Int \RP\\
  12490. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  12491. \mid \gray{ \key{goto}~\itm{label}\key{;} }\\
  12492. &\mid& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  12493. \LangCVec{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  12494. \end{array}
  12495. \]
  12496. \end{minipage}
  12497. }
  12498. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  12499. \label{fig:c2-concrete-syntax}
  12500. \end{figure}
  12501. \begin{figure}[tp]
  12502. \fbox{
  12503. \begin{minipage}{0.96\textwidth}
  12504. \small
  12505. \[
  12506. \begin{array}{lcl}
  12507. \Atm &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  12508. \\
  12509. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  12510. \Exp &::= & \gray{ \Atm \mid \LP\key{read}\RP \mid \LP\key{-}\;\Atm\RP \mid \LP\key{+} \; \Atm\;\Atm\RP
  12511. \mid \LP\key{not}\;\Atm\RP \mid \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  12512. &\mid& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  12513. \mid \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  12514. &\mid& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \mid \LP\key{global-value} \,\itm{name}\RP \mid \LP\key{void}\RP } \\
  12515. &\mid& \LP\key{fun-ref}~\itm{label}\RP \mid \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  12516. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  12517. \mid \LP\key{collect} \,\itm{int}\RP }\\
  12518. \Tail &::= & \gray{\RETURN{\Exp} \mid \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  12519. &\mid& \gray{\LP\key{goto}\,\itm{label}\RP
  12520. \mid \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  12521. &\mid& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  12522. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  12523. \LangCFun{} & ::= & \Def\ldots
  12524. \end{array}
  12525. \]
  12526. \end{minipage}
  12527. }
  12528. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  12529. \label{fig:c3-concrete-syntax}
  12530. \end{figure}
  12531. \cleardoublepage
  12532. \addcontentsline{toc}{chapter}{Index}
  12533. \printindex
  12534. \cleardoublepage
  12535. \bibliographystyle{plainnat}
  12536. \bibliography{all}
  12537. \addcontentsline{toc}{chapter}{Bibliography}
  12538. \end{document}
  12539. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  12540. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  12541. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  12542. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  12543. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator jane
  12544. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  12545. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  12546. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  12547. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs Tt
  12548. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  12549. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  12550. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  12551. %% LocalWords: boolean type-check notq cmpq sete movzbq jmp al xorq
  12552. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  12553. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  12554. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  12555. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  12556. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  12557. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  12558. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  12559. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  12560. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  12561. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  12562. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  12563. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  12564. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  12565. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  12566. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  12567. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  12568. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  12569. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  12570. % LocalWords: struct Friedman's MacOS Nystrom alist sam kate
  12571. % LocalWords: alists arity github unordered pqueue exprs ret param
  12572. % LocalWords: tyerr bytereg dh dl JmpIf HasType Osterlund Jacek TODO
  12573. % LocalWords: Gamari GlobalValue ProgramDefsExp prm ProgramDefs vn
  12574. % LocalWords: FunRef TailCall tailjmp IndirectCallq TailJmp Gilray
  12575. % LocalWords: dereference unbox Dataflow versa dataflow Kildall rhs
  12576. % LocalWords: Kleene enqueue dequeue AssignedFree FV cnvt SetBang tg
  12577. % LocalWords: ValueOf typechecker