book.tex 572 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754
  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. \newcommand{\ocaml}[1]{{\color{blue}{#1}}}
  70. \newenvironment{ocamlx}{
  71. \begin{color}{blue}
  72. }
  73. {
  74. \end{color}
  75. }
  76. \definecolor{BLUE}{rgb}{0,0,1} % no idea why we need this
  77. \lstdefinestyle{racket}{
  78. language=Lisp,
  79. basicstyle=\ttfamily\small,
  80. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  81. deletekeywords={read,mapping,vector},
  82. escapechar=|,
  83. columns=flexible,
  84. moredelim=[is][\color{red}]{~}{~},
  85. showstringspaces=false
  86. }
  87. \lstset{style=racket}
  88. \lstdefinestyle{ocaml}{
  89. language=[Objective]Caml,
  90. basicstyle=\ttfamily\small\color{blue},
  91. columns=flexible,
  92. escapechar=~,
  93. showstringspaces=false
  94. }
  95. \newtheorem{theorem}{Theorem}
  96. \newtheorem{lemma}[theorem]{Lemma}
  97. \newtheorem{corollary}[theorem]{Corollary}
  98. \newtheorem{proposition}[theorem]{Proposition}
  99. \newtheorem{constraint}[theorem]{Constraint}
  100. \newtheorem{definition}[theorem]{Definition}
  101. \newtheorem{exercise}[theorem]{Exercise}
  102. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  103. % 'dedication' environment: To add a dedication paragraph at the start of book %
  104. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  105. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  106. \newenvironment{dedication}
  107. {
  108. \cleardoublepage
  109. \thispagestyle{empty}
  110. \vspace*{\stretch{1}}
  111. \hfill\begin{minipage}[t]{0.66\textwidth}
  112. \raggedright
  113. }
  114. {
  115. \end{minipage}
  116. \vspace*{\stretch{3}}
  117. \clearpage
  118. }
  119. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  120. % Chapter quote at the start of chapter %
  121. % Source: http://tex.stackexchange.com/a/53380 %
  122. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  123. \makeatletter
  124. \renewcommand{\@chapapp}{}% Not necessary...
  125. \newenvironment{chapquote}[2][2em]
  126. {\setlength{\@tempdima}{#1}%
  127. \def\chapquote@author{#2}%
  128. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  129. \itshape}
  130. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  131. \makeatother
  132. \input{defs}
  133. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  134. \title{\Huge \textbf{Essentials of Compilation} \\
  135. \huge The Incremental, Nano-Pass Approach}
  136. \author{\textsc{Jeremy G. Siek} \\
  137. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  138. Indiana University \\
  139. \\
  140. with contributions from: \\
  141. Carl Factora \\
  142. Andre Kuhlenschmidt \\
  143. Ryan R. Newton \\
  144. Ryan Scott \\
  145. Cameron Swords \\
  146. Michael M. Vitousek \\
  147. Michael Vollmer \\
  148. \\
  149. \ocaml{OCaml version:} \\
  150. \ocaml{Andrew Tolmach} \\
  151. \ocaml{(with inspiration from a Haskell version by Ian Winter)}
  152. }
  153. \begin{document}
  154. \frontmatter
  155. \maketitle
  156. \begin{dedication}
  157. This book is dedicated to the programming language wonks at Indiana
  158. University.
  159. \end{dedication}
  160. \tableofcontents
  161. \listoffigures
  162. %\listoftables
  163. \mainmatter
  164. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  165. \chapter*{Preface}
  166. There is a magical moment when a programmer presses the ``run'' button
  167. and the software begins to execute. Somehow a program written in a
  168. high-level language is running on a computer that is only capable of
  169. shuffling bits. Here we reveal the wizardry that makes that moment
  170. possible. Beginning with the groundbreaking work of Backus and
  171. colleagues in the 1950s, computer scientists discovered techniques for
  172. constructing programs, called \emph{compilers}, that automatically
  173. translate high-level programs into machine code.
  174. We take you on a journey by constructing your own compiler for a small
  175. but powerful language. Along the way we explain the essential
  176. concepts, algorithms, and data structures that underlie compilers. We
  177. develop your understanding of how programs are mapped onto computer
  178. hardware, which is helpful when reasoning about properties at the
  179. junction between hardware and software such as execution time,
  180. software errors, and security vulnerabilities. For those interested
  181. in pursuing compiler construction, our goal is to provide a
  182. stepping-stone to advanced topics such as just-in-time compilation,
  183. program analysis, and program optimization. For those interested in
  184. designing and implementing their own programming languages, we connect
  185. language design choices to their impact on the compiler its generated
  186. code.
  187. A compiler is typically organized as a sequence of stages that
  188. progressively translates a program to code that runs on hardware. We
  189. take this approach to the extreme by partitioning our compiler into a
  190. large number of \emph{nanopasses}, each of which performs a single
  191. task. This allows us to test the output of each pass in isolation, and
  192. furthermore, allows us to focus our attention making the compiler far
  193. easier to understand.
  194. %% [TODO: easier to understand/debug for those maintaining the compiler,
  195. %% proving correctness]
  196. The most familiar approach to describing compilers is with one pass
  197. per chapter. The problem with that is it obfuscates how language
  198. features motivate design choices in a compiler. We take an
  199. \emph{incremental} approach in which we build a complete compiler in
  200. each chapter, starting with arithmetic and variables and add new
  201. features in subsequent chapters.
  202. Our choice of language features is designed to elicit the fundamental
  203. concepts and algorithms used in compilers.
  204. \begin{itemize}
  205. \item We begin with integer arithmetic and local variables in
  206. Chapters~\ref{ch:trees-recur} and \ref{ch:Rvar}, where we introduce
  207. the fundamental tools of compiler construction: \emph{abstract
  208. syntax trees} and \emph{recursive functions}.
  209. \item In Chapter~\ref{ch:register-allocation-Rvar} we apply
  210. \emph{graph coloring} to assign variables to machine registers.
  211. \item Chapter~\ref{ch:Rif} adds \code{if} expressions, which motivates
  212. an elegant recursive algorithm for mapping expressions to
  213. \emph{control-flow graphs}.
  214. \item Chapter~\ref{ch:Rvec} adds heap-allocated tuples, motivating
  215. \emph{garbage collection}.
  216. \item Chapter~\ref{ch:Rfun} adds functions that are first-class values
  217. but lack lexical scoping, similar to the C programming
  218. language~\citep{Kernighan:1988nx} except that we generate efficient
  219. tail calls. The reader learns about the procedure call stack,
  220. \emph{calling conventions}, and their interaction with register
  221. allocation and garbage collection.
  222. \item Chapter~\ref{ch:Rlam} adds anonymous functions with lexical
  223. scoping, i.e., \emph{lambda abstraction}. The reader learns about
  224. \emph{closure conversion}, in which lambdas are translated into a
  225. combination of functions and tuples.
  226. \item Chapter~\ref{ch:Rdyn} adds \emph{dynamic typing}. Prior to this
  227. point the input languages are statically typed. The reader extends
  228. the statically typed language with an \code{Any} type which serves
  229. as a target for compiling the dynamically typed language.
  230. \item Chapter~\ref{ch:Rwhile} fleshes out support for imperative
  231. programming languages with the addition of loops and mutable
  232. variables. These additions elicit the need for \emph{dataflow
  233. analysis} in the register allocator.
  234. \item Chapter~\ref{ch:Rgrad} uses the \code{Any} type of
  235. Chapter~\ref{ch:Rdyn} to implement a \emph{gradually typed language}
  236. in which different regions of a program may be static or dynamically
  237. typed. The reader implements runtime support for \emph{proxies} that
  238. allow values to safely move between regions.
  239. \item Chapter~\ref{ch:Rpoly} adds \emph{generics} with autoboxing,
  240. leveraging the \code{Any} type and type casts developed in Chapters
  241. \ref{ch:Rdyn} and \ref{ch:Rgrad}.
  242. \end{itemize}
  243. There are many language features that we do not include. Our choices
  244. weigh the incidental complexity of a feature against the fundamental
  245. concepts that it exposes. For example, we include tuples and not
  246. records because they both elicit the study of heap allocation and
  247. garbage collection but records come with more incidental complexity.
  248. Since 2016 this book has served as the textbook for the compiler
  249. course at Indiana University, a 16-week course for upper-level
  250. undergraduates and first-year graduate students.
  251. %
  252. Prior to this course, students learn to program in both imperative and
  253. functional languages, study data structures and algorithms, and take
  254. discrete mathematics.
  255. %
  256. At the beginning of the course, students form groups of 2-4 people.
  257. The groups complete one chapter every two weeks, starting with
  258. Chapter~\ref{ch:Rvar} and finishing with Chapter~\ref{ch:Rdyn}. Many
  259. chapters include a challenge problem that we assign to the graduate
  260. students. The last two weeks of the course involve a final project in
  261. which students design and implement a compiler extension of their
  262. choosing. Chapters~\ref{ch:Rwhile}, \ref{ch:Rgrad}, and
  263. \ref{ch:Rpoly} can be used in support of these projects or they can
  264. replace some of the earlier chapters. For example, a course with an
  265. emphasis on statically-typed imperative languages would skip
  266. Chapter~\ref{ch:Rdyn} in favor of
  267. Chapter~\ref{ch:Rwhile}. Figure~\ref{fig:chapter-dependences} depicts
  268. the dependencies between chapters.
  269. This book has also been used in compiler courses at California
  270. Polytechnic State University, Rose–Hulman Institute of Technology, and
  271. University of Massachusetts Lowell.
  272. \begin{figure}[tp]
  273. \begin{tikzpicture}[baseline=(current bounding box.center)]
  274. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  275. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Rvar} Variables};
  276. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Rvar} Registers};
  277. \node (C4) at (0,0) {\small Ch.~\ref{ch:Rif} Control Flow};
  278. \node (C5) at (4,0) {\small Ch.~\ref{ch:Rvec} Tuples};
  279. \node (C6) at (8,0) {\small Ch.~\ref{ch:Rfun} Functions};
  280. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Rwhile} Loops};
  281. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Rdyn} Dynamic};
  282. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Rlam} Lambda};
  283. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Rgrad} Gradual};
  284. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Rpoly} Generics};
  285. \path[->] (C1) edge [above] node {} (C2);
  286. \path[->] (C2) edge [above] node {} (C3);
  287. \path[->] (C3) edge [above] node {} (C4);
  288. \path[->] (C4) edge [above] node {} (C5);
  289. \path[->] (C5) edge [above] node {} (C6);
  290. \path[->] (C6) edge [above] node {} (C7);
  291. \path[->] (C4) edge [above] node {} (C8);
  292. \path[->] (C4) edge [above] node {} (C9);
  293. \path[->] (C8) edge [above] node {} (C10);
  294. \path[->] (C10) edge [above] node {} (C11);
  295. \end{tikzpicture}
  296. \caption{Diagram of chapter dependencies.}
  297. \label{fig:chapter-dependences}
  298. \end{figure}
  299. We use the \href{https://racket-lang.org/}{Racket} language both for
  300. the implementation of the compiler and for the input language, so the
  301. reader should be proficient with Racket or Scheme. There are many
  302. excellent resources for learning Scheme and
  303. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. The
  304. support code for this book is in the \code{github} repository at the
  305. following URL:
  306. \begin{center}\small
  307. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  308. \end{center}
  309. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  310. is helpful but not necessary for the reader to have taken a computer
  311. systems course~\citep{Bryant:2010aa}. This book introduces the parts
  312. of x86-64 assembly language that are needed.
  313. %
  314. We follow the System V calling
  315. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  316. that we generate works with the runtime system (written in C) when it
  317. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  318. operating systems.
  319. %
  320. On the Windows operating system, \code{gcc} uses the Microsoft x64
  321. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  322. assembly code that we generate does \emph{not} work with the runtime
  323. system on Windows. One workaround is to use a virtual machine with
  324. Linux as the guest operating system.
  325. \section*{Acknowledgments}
  326. The tradition of compiler construction at Indiana University goes back
  327. to research and courses on programming languages by Daniel Friedman in
  328. the 1970's and 1980's. One of his students, Kent Dybvig, implemented
  329. Chez Scheme~\citep{Dybvig:2006aa}, a production-quality, efficient
  330. compiler for Scheme. Throughout the 1990's and 2000's, Dybvig taught
  331. the compiler course and continued the development of Chez Scheme.
  332. %
  333. The compiler course evolved to incorporate novel pedagogical ideas
  334. while also including elements of efficient real-world compilers. One
  335. of Friedman's ideas was to split the compiler into many small
  336. passes. Another idea, called ``the game'', was to test the code
  337. generated by each pass on interpreters.
  338. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  339. developed infrastructure to support this approach and evolved the
  340. course to use even smaller
  341. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  342. design decisions in this book are inspired by the assignment
  343. descriptions of \citet{Dybvig:2010aa}. In the mid 2000's a student of
  344. Dybvig's named Abdulaziz Ghuloum observed that the front-to-back
  345. organization of the course made it difficult for students to
  346. understand the rationale for the compiler design. Ghuloum proposed the
  347. incremental approach~\citep{Ghuloum:2006bh}.
  348. We thank Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph Near, Nate
  349. Nystrom, and Michael Wollowski for teaching courses based on early
  350. drafts.
  351. We thank Ronald Garcia for being Jeremy's partner when they took the
  352. compiler course in the early 2000's and especially for finding the bug
  353. that sent the garbage collector on a wild goose chase!
  354. \mbox{}\\
  355. \noindent Jeremy G. Siek \\
  356. Bloomington, Indiana
  357. %Oscar Waddell ??
  358. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  359. \chapter{Preliminaries}
  360. \label{ch:trees-recur}
  361. \begin{ocamlx}
  362. Text in blue, like this, represents additions to the original book
  363. text to support the use of OCaml rather than Racket as our compiler
  364. implementation language. The original text is never changed, so you
  365. can see both the Racket and OCaml versions in parallel. The main
  366. motivation for this is to save a lot of rote editing: the bulk of
  367. the story being told in this book is substantially the same
  368. regardless of implementation language, so most of what has been
  369. written about the Racket version applies directly to OCaml
  370. with just small mental adjustments between the syntaxes of the two
  371. languages. A secondary motivation is that it is sometimes easier to
  372. see key underlying ideas when they are expressed in more than one
  373. way.
  374. In many respects, Racket and OCaml are very similar languages: they
  375. both encourage a purely functional style of programming while also supporting
  376. imperative programming, provide higher-order functions, use
  377. garbage collection to guarantee memory safety, etc. Indeed, the
  378. ``back ends'' of Racket and OCaml implementations are nearly
  379. interchangeable. By far the most fundamental difference between them is
  380. that OCaml uses static typing, whereas Racket uses runtime typing.
  381. The latter can provide useful flexibility, but the former has the
  382. big advantage of providing compile-time feedback on type errors.
  383. This is our main motivation for using OCaml.
  384. \end{ocamlx}
  385. In this chapter we review the basic tools that are needed to implement
  386. a compiler. Programs are typically input by a programmer as text,
  387. i.e., a sequence of characters. The program-as-text representation is
  388. called \emph{concrete syntax}. We use concrete syntax to concisely
  389. write down and talk about programs. Inside the compiler, we use
  390. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  391. that efficiently supports the operations that the compiler needs to
  392. perform.\index{concrete syntax}\index{abstract syntax}\index{abstract
  393. syntax tree}\index{AST}\index{program}\index{parse} The translation
  394. from concrete syntax to abstract syntax is a process called
  395. \emph{parsing}~\citep{Aho:1986qf}. We do not cover the theory and
  396. implementation of parsing in this book. A parser is provided in the
  397. support code for translating from concrete to abstract syntax.
  398. ASTs can be represented in many different ways inside the compiler,
  399. depending on the programming language used to write the compiler.
  400. %
  401. We use Racket's
  402. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  403. feature to represent ASTs (Section~\ref{sec:ast}).
  404. \ocaml{OCaml: we use \emph{variants} (also called algebraic data types) to
  405. represent ASTs.}
  406. We use grammars to
  407. define the abstract syntax of programming languages
  408. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  409. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  410. recursive functions to construct and deconstruct ASTs
  411. (Section~\ref{sec:recursion}). This chapter provides an brief
  412. introduction to these ideas. \index{struct}
  413. \section{Abstract Syntax Trees and Racket Structures \ocaml{/ OCaml Variants}}
  414. \label{sec:ast}
  415. Compilers use abstract syntax trees to represent programs because they
  416. often need to ask questions like: for a given part of a program, what
  417. kind of language feature is it? What are its sub-parts? Consider the
  418. program on the left and its AST on the right.
  419. \begin{ocamlx}
  420. This program is
  421. itself in Racket; in addition to using Racket as the compiler implementation
  422. language, the original version of this book uses subsets of Racket as the
  423. \emph{source} languages that we compile. In the OCaml version we will be using
  424. ad-hoc source languages that look a lot like subsets of Racket, but sometimes
  425. made simpler (because there is no particular advantage to matching the messier details
  426. of Racket syntax). The code on the left will be valid in all of our source languages too.
  427. \end{ocamlx}
  428. This program is an
  429. addition operation and it has two sub-parts, a read operation and a
  430. negation. The negation has another sub-part, the integer constant
  431. \code{8}. By using a tree to represent the program, we can easily
  432. follow the links to go from one part of a program to its sub-parts.
  433. \begin{center}
  434. \begin{minipage}{0.4\textwidth}
  435. \begin{lstlisting}
  436. (+ (read) (- 8))
  437. \end{lstlisting}
  438. \end{minipage}
  439. \begin{minipage}{0.4\textwidth}
  440. \begin{equation}
  441. \begin{tikzpicture}
  442. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  443. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  444. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  445. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  446. \draw[->] (plus) to (read);
  447. \draw[->] (plus) to (minus);
  448. \draw[->] (minus) to (8);
  449. \end{tikzpicture}
  450. \label{eq:arith-prog}
  451. \end{equation}
  452. \end{minipage}
  453. \end{center}
  454. We use the standard terminology for trees to describe ASTs: each
  455. circle above is called a \emph{node}. The arrows connect a node to its
  456. \emph{children} (which are also nodes). The top-most node is the
  457. \emph{root}. Every node except for the root has a \emph{parent} (the
  458. node it is the child of). If a node has no children, it is a
  459. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  460. \index{node}
  461. \index{children}
  462. \index{root}
  463. \index{parent}
  464. \index{leaf}
  465. \index{internal node}
  466. %% Recall that an \emph{symbolic expression} (S-expression) is either
  467. %% \begin{enumerate}
  468. %% \item an atom, or
  469. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  470. %% where $e_1$ and $e_2$ are each an S-expression.
  471. %% \end{enumerate}
  472. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  473. %% null value \code{'()}, etc. We can create an S-expression in Racket
  474. %% simply by writing a backquote (called a quasi-quote in Racket)
  475. %% followed by the textual representation of the S-expression. It is
  476. %% quite common to use S-expressions to represent a list, such as $a, b
  477. %% ,c$ in the following way:
  478. %% \begin{lstlisting}
  479. %% `(a . (b . (c . ())))
  480. %% \end{lstlisting}
  481. %% Each element of the list is in the first slot of a pair, and the
  482. %% second slot is either the rest of the list or the null value, to mark
  483. %% the end of the list. Such lists are so common that Racket provides
  484. %% special notation for them that removes the need for the periods
  485. %% and so many parenthesis:
  486. %% \begin{lstlisting}
  487. %% `(a b c)
  488. %% \end{lstlisting}
  489. %% The following expression creates an S-expression that represents AST
  490. %% \eqref{eq:arith-prog}.
  491. %% \begin{lstlisting}
  492. %% `(+ (read) (- 8))
  493. %% \end{lstlisting}
  494. %% When using S-expressions to represent ASTs, the convention is to
  495. %% represent each AST node as a list and to put the operation symbol at
  496. %% the front of the list. The rest of the list contains the children. So
  497. %% in the above case, the root AST node has operation \code{`+} and its
  498. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  499. %% diagram \eqref{eq:arith-prog}.
  500. %% To build larger S-expressions one often needs to splice together
  501. %% several smaller S-expressions. Racket provides the comma operator to
  502. %% splice an S-expression into a larger one. For example, instead of
  503. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  504. %% we could have first created an S-expression for AST
  505. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  506. %% S-expression.
  507. %% \begin{lstlisting}
  508. %% (define ast1.4 `(- 8))
  509. %% (define ast1.1 `(+ (read) ,ast1.4))
  510. %% \end{lstlisting}
  511. %% In general, the Racket expression that follows the comma (splice)
  512. %% can be any expression that produces an S-expression.
  513. We define a Racket \code{struct} for each kind of node. For this
  514. chapter we require just two kinds of nodes: one for integer constants
  515. and one for primitive operations. The following is the \code{struct}
  516. definition for integer constants.
  517. \begin{lstlisting}
  518. (struct Int (value))
  519. \end{lstlisting}
  520. An integer node includes just one thing: the integer value.
  521. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  522. \begin{lstlisting}
  523. (define eight (Int 8))
  524. \end{lstlisting}
  525. We say that the value created by \code{(Int 8)} is an
  526. \emph{instance} of the \code{Int} structure.
  527. The following is the \code{struct} definition for primitives operations.
  528. \begin{lstlisting}
  529. (struct Prim (op args))
  530. \end{lstlisting}
  531. A primitive operation node includes an operator symbol \code{op}
  532. and a list of children \code{args}. For example, to create
  533. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  534. \begin{lstlisting}
  535. (define neg-eight (Prim '- (list eight)))
  536. \end{lstlisting}
  537. Primitive operations may have zero or more children. The \code{read}
  538. operator has zero children:
  539. \begin{lstlisting}
  540. (define rd (Prim 'read '()))
  541. \end{lstlisting}
  542. whereas the addition operator has two children:
  543. \begin{lstlisting}
  544. (define ast1.1 (Prim '+ (list rd neg-eight)))
  545. \end{lstlisting}
  546. \begin{ocamlx}
  547. We define an OCaml variant type for ASTs, with a different constructor for each
  548. kind of node:
  549. \begin{lstlisting}[style=ocaml]
  550. type exp =
  551. Int of int
  552. | Prim of primop * exp list
  553. \end{lstlisting}
  554. This definition depends on the definition of another variant type that enumerates the possible primops
  555. (in place of the single-quoted symbols used in Racket):
  556. \begin{lstlisting}[style=ocaml]
  557. type primop =
  558. Read
  559. | Neg
  560. | Add
  561. \end{lstlisting}
  562. To create an AST node for the integer 8, we write \code{Int 8}.
  563. To create an AST that negates
  564. the number 8, we write \code{Prim(Neg,[Int 8])}, and so on:
  565. \begin{lstlisting}[style=ocaml]
  566. let eight = Int 8
  567. let neg_eight = Prim(Neg,[eight])
  568. let rd = Prim(Read,[])
  569. let ast1_1 = Prim(Add,[rd,neg_eight])
  570. \end{lstlisting}
  571. Note that OCaml identifiers are more restricted in form than those of Racket; we will typically replace uses of dash (\code{-}), dot (\code{.}), etc. by underscores (\code{\_}).
  572. \end{ocamlx}
  573. We have made a design choice regarding the \code{Prim} structure.
  574. Instead of using one structure for many different operations
  575. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  576. structure for each operation, as follows.
  577. \begin{lstlisting}
  578. (struct Read ())
  579. (struct Add (left right))
  580. (struct Neg (value))
  581. \end{lstlisting}
  582. The reason we choose to use just one structure is that in many parts
  583. of the compiler the code for the different primitive operators is the
  584. same, so we might as well just write that code once, which is enabled
  585. by using a single structure.
  586. \begin{ocamlx}
  587. We have made a similar design choice in OCaml. The corresponding
  588. alternative would have been to define our AST type as
  589. \begin{lstlisting}[style=ocaml]
  590. type exp =
  591. Int of int
  592. | Read
  593. | Add of exp * exp
  594. | Neg of exp
  595. \end{lstlisting}
  596. Note that one advantage of using this alternative is that it would explicitly enforce
  597. that each primitive operator is given the correct number of arguments (its \emph{arity});
  598. this restriction is not captured in the list-based version.
  599. \end{ocamlx}
  600. When compiling a program such as \eqref{eq:arith-prog}, we need to
  601. know that the operation associated with the root node is addition and
  602. we need to be able to access its two children. Racket provides pattern
  603. matching to support these kinds of queries, as we see in
  604. Section~\ref{sec:pattern-matching}. \ocaml{So does OCaml.}
  605. In this book, we often write down the concrete syntax of a program
  606. even when we really have in mind the AST because the concrete syntax
  607. is more concise. We recommend that, in your mind, you always think of
  608. programs as abstract syntax trees.
  609. \section{Grammars}
  610. \label{sec:grammar}
  611. \index{integer}
  612. \index{literal}
  613. \index{constant}
  614. A programming language can be thought of as a \emph{set} of programs.
  615. The set is typically infinite (one can always create larger and larger
  616. programs), so one cannot simply describe a language by listing all of
  617. the programs in the language. Instead we write down a set of rules, a
  618. \emph{grammar}, for building programs. Grammars are often used to
  619. define the concrete syntax of a language, but they can also be used to
  620. describe the abstract syntax. We write our rules in a variant of
  621. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  622. \index{Backus-Naur Form}\index{BNF}
  623. As an example, we describe a small language, named \LangInt{}, that consists of
  624. integers and arithmetic operations.
  625. \index{grammar}
  626. \begin{ocamlx}
  627. Using a grammar to describe abstract syntax is less useful in OCaml than in
  628. Racket, because our variant type definition for ASTs already serves to specify
  629. the legal forms of tree (except that it is overly flexible about the arity of
  630. primops, as mentioned above). So don't worry too much about the details of
  631. the AST grammar here---but do make sure you understand how the same ideas
  632. are applied to \emph{concrete} grammars, below.
  633. \end{ocamlx}
  634. The first grammar rule for the abstract syntax of \LangInt{} says that an
  635. instance of the \code{Int} structure is an expression:
  636. \begin{equation}
  637. \Exp ::= \INT{\Int} \label{eq:arith-int}
  638. \end{equation}
  639. %
  640. Each rule has a left-hand-side and a right-hand-side. The way to read
  641. a rule is that if you have an AST node that matches the
  642. right-hand-side, then you can categorize it according to the
  643. left-hand-side.
  644. %
  645. A name such as $\Exp$ that is defined by the grammar rules is a
  646. \emph{non-terminal}. \index{non-terminal}
  647. %
  648. The name $\Int$ is a also a non-terminal, but instead of defining it
  649. with a grammar rule, we define it with the following explanation. We
  650. make the simplifying design decision that all of the languages in this
  651. book only handle machine-representable integers. On most modern
  652. machines this corresponds to integers represented with 64-bits, i.e.,
  653. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  654. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  655. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  656. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  657. that the sequence of decimals represent an integer in range $-2^{62}$
  658. to $2^{62}-1$.
  659. \ocaml{As it happens, OCaml's standard integer type
  660. (\code{int}) is also 63 bits on a 64-bit machine. Initially, we
  661. will adopt the corresponding convention that $\Int$ is a 63-bit integer,
  662. but soon we will move to full 64-bit integers.}
  663. The second grammar rule is the \texttt{read} operation that receives
  664. an input integer from the user of the program.
  665. \begin{equation}
  666. \Exp ::= \READ{} \label{eq:arith-read}
  667. \end{equation}
  668. The third rule says that, given an $\Exp$ node, the negation of that
  669. node is also an $\Exp$.
  670. \begin{equation}
  671. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  672. \end{equation}
  673. Symbols in typewriter font such as \key{-} and \key{read} are
  674. \emph{terminal} symbols and must literally appear in the program for
  675. the rule to be applicable.
  676. \index{terminal}
  677. We can apply these rules to categorize the ASTs that are in the
  678. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  679. \texttt{(Int 8)} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  680. following AST is an $\Exp$.
  681. \begin{center}
  682. \begin{minipage}{0.4\textwidth}
  683. \begin{lstlisting}
  684. (Prim '- (list (Int 8)))
  685. \end{lstlisting}
  686. \end{minipage}
  687. \begin{minipage}{0.25\textwidth}
  688. \begin{equation}
  689. \begin{tikzpicture}
  690. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  691. \node[draw, circle] (8) at (0, -1.2) {$8$};
  692. \draw[->] (minus) to (8);
  693. \end{tikzpicture}
  694. \label{eq:arith-neg8}
  695. \end{equation}
  696. \end{minipage}
  697. \end{center}
  698. \begin{ocamlx}
  699. The corresponding OCaml AST expression is \code{Prim(Neg,[Int 8])}.
  700. \end{ocamlx}
  701. The next grammar rule is for addition expressions:
  702. \begin{equation}
  703. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  704. \end{equation}
  705. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  706. \LangInt{}. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  707. \eqref{eq:arith-read} and we have already categorized \code{(Prim '-
  708. (list (Int 8)))} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  709. to show that
  710. \begin{lstlisting}
  711. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  712. \end{lstlisting}
  713. is an $\Exp$ in the \LangInt{} language.
  714. \ocaml{\\ OCaml: \code{Prim(Add,[Prim(Read,[]);Prim(Neg,[Int 8])])}.}
  715. If you have an AST for which the above rules do not apply, then the
  716. AST is not in \LangInt{}. For example, the program \code{(- (read) (+ 8))}
  717. is not in \LangInt{} because there are no rules for \code{+} with only one
  718. argument, nor for \key{-} with two arguments. Whenever we define a
  719. language with a grammar, the language only includes those programs
  720. that are justified by the rules.
  721. The last grammar rule for \LangInt{} states that there is a \code{Program}
  722. node to mark the top of the whole program:
  723. \[
  724. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  725. \]
  726. The \code{Program} structure is defined as follows
  727. \begin{lstlisting}
  728. (struct Program (info body))
  729. \end{lstlisting}
  730. where \code{body} is an expression. In later chapters, the \code{info}
  731. part will be used to store auxiliary information but for now it is
  732. just the empty list.
  733. \begin{ocamlx}
  734. In OCaml:
  735. \begin{lstlisting}[style=ocaml]
  736. type 'info program = Program of 'info * exp
  737. \end{lstlisting}
  738. Again, we represent the structure as a variant type
  739. (\code{rint\_program}), this time just with one constructor
  740. (\code{Program)}. We \emph{parameterize} \code{program} by a
  741. \emph{type variable} \code{'info} (type variables are distinguished by having
  742. a leading tick mark). This says that \code{rint\_program} is a family of types which can
  743. be instantiated to represent programs holding a particular kind of auxiliary information.
  744. For now, we'll just instantiate \code{'info}
  745. with the \emph{unit} type, written \code{unit}, whose sole (boring)
  746. value is written \code{()}.
  747. \begin{lstlisting}[style=ocaml]
  748. let p : unit program = Program () body
  749. \end{lstlisting}
  750. Here the colon (\code{:}) introduces an explicit type annotation on \code{p}; it can be read ``has type.''
  751. \end{ocamlx}
  752. It is common to have many grammar rules with the same left-hand side
  753. but different right-hand sides, such as the rules for $\Exp$ in the
  754. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  755. combine several right-hand-sides into a single rule.
  756. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  757. in Figure~\ref{fig:r0-syntax} \ocaml{along with the corresponding OCaml type definitions}.
  758. The concrete syntax for \LangInt{} is
  759. defined in Figure~\ref{fig:r0-concrete-syntax}.
  760. The \code{read-program} function provided in \code{utilities.rkt} of
  761. the support code reads a program in from a file (the sequence of
  762. characters in the concrete syntax of Racket) and parses it into an
  763. abstract syntax tree. See the description of \code{read-program} in
  764. Appendix~\ref{appendix:utilities} for more details.
  765. \begin{ocamlx}
  766. As noted above, the concrete syntaxes we will use are similar to Racket's own syntax.
  767. In particular, programs are described as \emph{S-expressions}. An S-expression can be
  768. either an atom (an integer, symbol, or quoted string) or a list of S-expressions enclosed in
  769. parentheses. You can see that the concrete syntax for \LangInt{} is written as
  770. S-expressions where the symbols used are \code{read},\code{-}, and \code{+}, and
  771. a primitive operation invocation is described by a list whose first element is
  772. the operation symbol and whose remaining elements (0 or more of them) are
  773. S-expressions representing the arguments (which can themselves be lists).
  774. All the source languages we consider in this book will be written as S-expressions in
  775. a similar style; the details of which symbols and shapes of list are allowed
  776. will vary from language to language.
  777. To handle all this neatly in OCaml, we split the parsing of concrete
  778. programs into two phases. First, the \code{parse} function provided
  779. in \code{sexpr.ml} of the support code reads text from a file and
  780. parses it into a generic S-expression data type. (This code is a
  781. bit complicated and messy, but you don't have to understand its
  782. internals in order to use it.) Then, a source-language-specific
  783. program is used to convert the S-expression into the abstract syntax
  784. of that particular language. We will see later on that OCaml's pattern
  785. matching facilities make it very easy to write such conversion
  786. routines. This is particularly true because the S-expression format
  787. we use for our concrete source languages is already very close to an
  788. abstract syntax, which means the conversion has very little work to
  789. do. For example, as you have seen, primitive operations are all
  790. written in prefix, rather than infix, notation, so there is no need
  791. to worry about issues like precedence and associativity of operators
  792. in an expression like \code{(2 * 3 + 4)}: the S-expression syntax
  793. will be either \code{(+ (* 2 3) 4)} or \code{(* 2 (+ 3 4))}, so
  794. there is no possible ambiguity. The downside is that source programs
  795. are a bit more tedious to write, and may sometimes seem to be drowning in
  796. parentheses.
  797. The OCaml representation of generic S-expressions is just another
  798. variant type:
  799. \begin{lstlisting}[style=ocaml]
  800. type sexp =
  801. | SList of sexp list
  802. (* list of expressions delimited by parentheses *)
  803. | SNum of Int64.t
  804. (* 64-bit integers *)
  805. | SSym of string
  806. (* character sequence starting with non-digit,
  807. delimited by white space *)
  808. | SString of string
  809. (* arbitrary character sequence delimited by double quotes *)
  810. \end{lstlisting}
  811. The generic S-expression parser handles (nestable) comments delimited by
  812. curly braces (\code{\{} and \code{\}}). Symbols must start with a non-digit
  813. character and can contain any
  814. non-whitespace characters except parentheses, curly braces, and
  815. the back tick (\code{\`}); this last exclusion is handy when we want to
  816. generate internal names during compilation and be sure they don't clash
  817. with a user-defined symbol.
  818. \end{ocamlx}
  819. \begin{figure}[tp]
  820. \fbox{
  821. \begin{minipage}{0.96\textwidth}
  822. \[
  823. \begin{array}{rcl}
  824. \begin{array}{rcl}
  825. \Exp &::=& \Int \mid \LP\key{read}\RP \mid \LP\key{-}\;\Exp\RP \mid \LP\key{+} \; \Exp\;\Exp\RP\\
  826. \LangInt{} &::=& \Exp
  827. \end{array}
  828. \end{array}
  829. \]
  830. \end{minipage}
  831. }
  832. \caption{The concrete syntax of \LangInt{}.}
  833. \label{fig:r0-concrete-syntax}
  834. \end{figure}
  835. \begin{figure}[tp]
  836. \fbox{
  837. \begin{minipage}{0.96\textwidth}
  838. \[
  839. \begin{array}{rcl}
  840. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  841. &\mid& \ADD{\Exp}{\Exp} \\
  842. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  843. \end{array}
  844. \]
  845. \end{minipage}
  846. }
  847. \begin{minipage}{0.96\textwidth}
  848. \begin{lstlisting}[style=ocaml,frame=single]
  849. type primop =
  850. Read
  851. | Neg
  852. | Add
  853. type exp =
  854. Int of int
  855. | Prim of primop * exp list
  856. type 'info program = Program of 'info * exp
  857. \end{lstlisting}
  858. \end{minipage}
  859. \caption{The abstract syntax of \LangInt{}.}
  860. \label{fig:r0-syntax}
  861. \end{figure}
  862. \section{Pattern Matching}
  863. \label{sec:pattern-matching}
  864. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  865. the parts of an AST node. Racket provides the \texttt{match} form to
  866. access the parts of a structure. Consider the following example and
  867. the output on the right. \index{match} \index{pattern matching}
  868. \begin{center}
  869. \begin{minipage}{0.5\textwidth}
  870. \begin{lstlisting}
  871. (match ast1.1
  872. [(Prim op (list child1 child2))
  873. (print op)])
  874. \end{lstlisting}
  875. \end{minipage}
  876. \vrule
  877. \begin{minipage}{0.25\textwidth}
  878. \begin{lstlisting}
  879. '+
  880. \end{lstlisting}
  881. \end{minipage}
  882. \end{center}
  883. In the above example, the \texttt{match} form takes an AST
  884. \eqref{eq:arith-prog} and binds its parts to the three pattern
  885. variables \texttt{op}, \texttt{child1}, and \texttt{child2}, and then
  886. prints out the operator. In general, a match clause consists of a
  887. \emph{pattern} and a \emph{body}.\index{pattern} Patterns are
  888. recursively defined to be either a pattern variable, a structure name
  889. followed by a pattern for each of the structure's arguments, or an
  890. S-expression (symbols, lists, etc.). (See Chapter 12 of The Racket
  891. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  892. and Chapter 9 of The Racket
  893. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  894. for a complete description of \code{match}.)
  895. %
  896. The body of a match clause may contain arbitrary Racket code. The
  897. pattern variables can be used in the scope of the body, such as
  898. \code{op} in \code{(print op)}.
  899. \begin{ocamlx}
  900. Here is the OCaml version, which is quite similar:
  901. \begin{center}
  902. \begin{minipage}{0.5\textwidth}
  903. \begin{lstlisting}[style=ocaml]
  904. match ast1_1 with
  905. | Prim(op,[child1;child2]) -> op
  906. \end{lstlisting}
  907. \end{minipage}
  908. \vrule
  909. \begin{minipage}{0.25\textwidth}
  910. \begin{lstlisting}[style=ocaml]
  911. Add
  912. \end{lstlisting}
  913. \end{minipage}
  914. \end{center}
  915. \end{ocamlx}
  916. A \code{match} form may contain several clauses, as in the following
  917. function \code{leaf?} that recognizes when an \LangInt{} node is a leaf in
  918. the AST. The \code{match} proceeds through the clauses in order,
  919. checking whether the pattern can match the input AST. The body of the
  920. first clause that matches is executed.
  921. \begin{ocamlx}
  922. In fact, in OCaml, we will get a warning message about the code above, because the \code{match} only contains
  923. a clause for a {\tt Prim} with two children, not for other other possible forms of \code{exp}.
  924. Although in this particular instance, that's OK (because of the value of \code{ast1\_1}), in general
  925. it suggests a possible error. Getting warnings like this is one of the advantages of static typing.
  926. \end{ocamlx}
  927. The output of \code{leaf?} for
  928. several ASTs is shown on the right.
  929. \begin{center}
  930. \begin{minipage}{0.6\textwidth}
  931. \begin{lstlisting}
  932. (define (leaf? arith)
  933. (match arith
  934. [(Int n) #t]
  935. [(Prim 'read '()) #t]
  936. [(Prim '- (list e1)) #f]
  937. [(Prim '+ (list e1 e2)) #f]))
  938. (leaf? (Prim 'read '()))
  939. (leaf? (Prim '- (list (Int 8))))
  940. (leaf? (Int 8))
  941. \end{lstlisting}
  942. \end{minipage}
  943. \vrule
  944. \begin{minipage}{0.25\textwidth}
  945. \begin{lstlisting}
  946. #t
  947. #f
  948. #t
  949. \end{lstlisting}
  950. \end{minipage}
  951. \end{center}
  952. When writing a \code{match}, we refer to the grammar definition to
  953. identify which non-terminal we are expecting to match against, then we
  954. make sure that 1) we have one clause for each alternative of that
  955. non-terminal and 2) that the pattern in each clause corresponds to the
  956. corresponding right-hand side of a grammar rule. For the \code{match}
  957. in the \code{leaf?} function, we refer to the grammar for \LangInt{} in
  958. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  959. alternatives, so the \code{match} has 4 clauses. The pattern in each
  960. clause corresponds to the right-hand side of a grammar rule. For
  961. example, the pattern \code{(Prim '+ (list e1 e2))} corresponds to the
  962. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  963. patterns, replace non-terminals such as $\Exp$ with pattern variables
  964. of your choice (e.g. \code{e1} and \code{e2}).
  965. \begin{ocamlx}
  966. Here is the directly corresponding OCaml version.
  967. \begin{center}
  968. \begin{minipage}{0.6\textwidth}
  969. \begin{lstlisting}[style=ocaml]
  970. let is_leaf arith =
  971. match arith with
  972. | Int n -> true
  973. | Prim(Read,[]) -> true
  974. | Prim(Neg,[e1]) -> false
  975. | Prim(Add,[e1;e2]) -> false
  976. | _ -> assert false
  977. is_leaf (Prim(Read,[]))
  978. is_leaf (Prim(Neg,[Int 8]))
  979. is_leaf (Int 8)
  980. \end{lstlisting}
  981. \end{minipage}
  982. \vrule
  983. \begin{minipage}{0.25\textwidth}
  984. \begin{lstlisting}[style=ocaml]
  985. true
  986. false
  987. true
  988. \end{lstlisting}
  989. \end{minipage}
  990. \end{center}
  991. The final clause uses a wildcard pattern {\tt \_}, which matches anything of type \code{exp},
  992. to cover the (ill-formed) cases where a primop is given the wrong number of arguments;
  993. otherwise, the compiler will again issue a warning that not all cases have been considered.
  994. The \code{assert false} causes OCaml execution to halt with an uncaught exception message.
  995. In this particular case, we can use wildcards to write a more idiomatic version of
  996. \code{is\_leaf} that doesn't require a catch-all case (and is also ``future-proof''
  997. against later additions to the \code{primop} type). We also make use of the following
  998. short-cut: a function that takes an argument $arg$ and then immediately performs
  999. a \code{match} over $arg$ can be written more concisely using the \code{function} keyword.
  1000. \begin{center}
  1001. \begin{minipage}{0.5\textwidth}
  1002. \begin{lstlisting}[style=ocaml]
  1003. let is_leaf = function
  1004. | Int _ -> true
  1005. | Prim(_,[]) -> true
  1006. | _ -> false
  1007. \end{lstlisting}
  1008. \end{minipage}
  1009. \end{center}
  1010. \end{ocamlx}
  1011. \section{Recursive Functions}
  1012. \label{sec:recursion}
  1013. \index{recursive function}
  1014. Programs are inherently recursive. For example, an \LangInt{} expression is
  1015. often made of smaller expressions. Thus, the natural way to process an
  1016. entire program is with a recursive function. As a first example of
  1017. such a recursive function, we define \texttt{exp?} below, which takes
  1018. an arbitrary value and determines whether or not it is an \LangInt{}
  1019. expression.
  1020. %
  1021. We say that a function is defined by \emph{structural recursion} when
  1022. it is defined using a sequence of match clauses that correspond to a
  1023. grammar, and the body of each clause makes a recursive call on each
  1024. child node.\footnote{This principle of structuring code according to
  1025. the data definition is advocated in the book \emph{How to Design
  1026. Programs} \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}.
  1027. Below we also define a second function, named \code{Rint?}, that
  1028. determines whether an AST is an \LangInt{} program. In general we can
  1029. expect to write one recursive function to handle each non-terminal in
  1030. a grammar.\index{structural recursion}
  1031. %
  1032. \begin{center}
  1033. \begin{minipage}{0.7\textwidth}
  1034. \begin{lstlisting}
  1035. (define (exp? ast)
  1036. (match ast
  1037. [(Int n) #t]
  1038. [(Prim 'read '()) #t]
  1039. [(Prim '- (list e)) (exp? e)]
  1040. [(Prim '+ (list e1 e2))
  1041. (and (exp? e1) (exp? e2))]
  1042. [else #f]))
  1043. (define (Rint? ast)
  1044. (match ast
  1045. [(Program '() e) (exp? e)]
  1046. [else #f]))
  1047. (Rint? (Program '() ast1.1)
  1048. (Rint? (Program '()
  1049. (Prim '- (list (Prim 'read '())
  1050. (Prim '+ (list (Num 8)))))))
  1051. \end{lstlisting}
  1052. \end{minipage}
  1053. \vrule
  1054. \begin{minipage}{0.25\textwidth}
  1055. \begin{lstlisting}
  1056. #t
  1057. #f
  1058. \end{lstlisting}
  1059. \end{minipage}
  1060. \end{center}
  1061. You may be tempted to merge the two functions into one, like this:
  1062. \begin{center}
  1063. \begin{minipage}{0.5\textwidth}
  1064. \begin{lstlisting}
  1065. (define (Rint? ast)
  1066. (match ast
  1067. [(Int n) #t]
  1068. [(Prim 'read '()) #t]
  1069. [(Prim '- (list e)) (Rint? e)]
  1070. [(Prim '+ (list e1 e2)) (and (Rint? e1) (Rint? e2))]
  1071. [(Program '() e) (Rint? e)]
  1072. [else #f]))
  1073. \end{lstlisting}
  1074. \end{minipage}
  1075. \end{center}
  1076. %
  1077. Sometimes such a trick will save a few lines of code, especially when
  1078. it comes to the \code{Program} wrapper. Yet this style is generally
  1079. \emph{not} recommended because it can get you into trouble.
  1080. %
  1081. For example, the above function is subtly wrong:
  1082. \lstinline{(Rint? (Program '() (Program '() (Int 3))))}
  1083. returns true when it should return false.
  1084. \begin{ocamlx}
  1085. There is almost no point in writing OCaml analogs to \code{exp?} or \code{Rint?}, because static
  1086. typing guarantees that values claimed to be in type \code{exp} or \code{rint\_program} really are
  1087. (or the OCaml program will not pass the OCaml typechecker). However, it is still worth
  1088. writing a function to check that primops are applied to the right number of arguments.
  1089. Here is an idiomatic way to do that:
  1090. \begin{center}
  1091. \begin{minipage}{0.85\textwidth}
  1092. \begin{lstlisting}[style=ocaml]
  1093. let arity = function
  1094. | Read -> 0
  1095. | Neg -> 1
  1096. | Add -> 2
  1097. let rec check_exp = function
  1098. | Int _ -> true
  1099. | Prim(op,args) ->
  1100. List.length args = arity op && check_exps args
  1101. and check_exps = function
  1102. | [] -> true
  1103. | (exp::exps') -> check_exp exp && check_exps exps'
  1104. let check_program (Program(_,e)) = check_exp e
  1105. check_program (Program((),ast1_1))
  1106. check_program (Program((),Prim(Neg,[Prim(Read,[]);
  1107. Prim(Plus,[Int 8])])))
  1108. \end{lstlisting}
  1109. \end{minipage}
  1110. \vrule
  1111. \begin{minipage}{0.1\textwidth}
  1112. \begin{lstlisting}[style=ocaml]
  1113. true
  1114. false
  1115. \end{lstlisting}
  1116. \end{minipage}
  1117. \end{center}
  1118. In the definition of \code{check\_program}, since the argument type \code{rint\_program}
  1119. has only one constructor, we can write a pattern \code{Program(\_,e)} which matches that constructor directly in
  1120. place of an argument name; this binds the variable(s) (here \code{e}) of the pattern in the body of the function.
  1121. Note that \code{check\_exp} is declared to be recursive by using the \code{rec} keyword;
  1122. in fact, \code{check\_exp} and \code{check\_exps} are \emph{mutually} recursive because
  1123. their definitions are connected by the \code{and} keyword. \code{List.length} is a library
  1124. function that returns the length of a list. Actually, the library also has a handy higher-order
  1125. function \code{List.for\_all} that applies a specified boolean-value function to a list and returns
  1126. whether it is true on all elements. Using that, we could rewrite the \code{Prim}
  1127. clause of \code{check\_exp} as
  1128. \begin{lstlisting}[style=ocaml]
  1129. | Prim(op,args) ->
  1130. List.length args = arity op && List.for_all check_exp args
  1131. \end{lstlisting}
  1132. and dispense with \code{check\_exps} altogether. Being able to operate on entire lists
  1133. uniformly like this is one of the payoffs for using a single generic \code{Prim} constructor.
  1134. \end{ocamlx}
  1135. \section{Interpreters}
  1136. \label{sec:interp-Rint}
  1137. \index{interpreter}
  1138. In general, the intended behavior of a program is defined by the
  1139. specification of the language. For example, the Scheme language is
  1140. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  1141. defined in its reference manual~\citep{plt-tr}. In this book we use
  1142. interpreters to specify each language that we consider. An interpreter
  1143. that is designated as the definition of a language is called a
  1144. \emph{definitional interpreter}~\citep{reynolds72:_def_interp}.
  1145. \index{definitional interpreter} We warm up by creating a definitional
  1146. interpreter for the \LangInt{} language, which serves as a second example
  1147. of structural recursion. The \texttt{interp-Rint} function is defined in
  1148. Figure~\ref{fig:interp-Rint}. The body of the function is a match on the
  1149. input program followed by a call to the \lstinline{interp-exp} helper
  1150. function, which in turn has one match clause per grammar rule for
  1151. \LangInt{} expressions. \ocaml{The OCaml version is in Figure~\ref{fig:ocaml-interp-Rint}.}
  1152. \begin{figure}[tp]
  1153. \begin{lstlisting}
  1154. (define (interp-exp e)
  1155. (match e
  1156. [(Int n) n]
  1157. [(Prim 'read '())
  1158. (define r (read))
  1159. (cond [(fixnum? r) r]
  1160. [else (error 'interp-exp "read expected an integer" r)])]
  1161. [(Prim '- (list e))
  1162. (define v (interp-exp e))
  1163. (fx- 0 v)]
  1164. [(Prim '+ (list e1 e2))
  1165. (define v1 (interp-exp e1))
  1166. (define v2 (interp-exp e2))
  1167. (fx+ v1 v2)]))
  1168. (define (interp-Rint p)
  1169. (match p
  1170. [(Program '() e) (interp-exp e)]))
  1171. \end{lstlisting}
  1172. \caption{Interpreter for the \LangInt{} language.}
  1173. \label{fig:interp-Rint}
  1174. \end{figure}
  1175. \begin{figure}[tp]
  1176. \begin{lstlisting}[style=ocaml]
  1177. let interp_exp exp =
  1178. match exp with
  1179. | Int n -> n
  1180. | Prim(Read,[]) -> read_int()
  1181. | Prim(Neg,[e]) -> - (interp_exp e)
  1182. | Prim(Add,[e1;e2]) ->
  1183. (* must explicitly sequence evaluation order! *)
  1184. let v1 = interp_exp e1 in
  1185. let v2 = interp_exp e2 in
  1186. v1 + v2
  1187. | _ -> assert false (* arity mismatch *)
  1188. let interp_program (Program(_,e)) = interp_exp e
  1189. \end{lstlisting}
  1190. \caption{\ocaml{OCaml interpreter for the \LangInt{} language.}}
  1191. \label{fig:ocaml-interp-Rint}
  1192. \end{figure}
  1193. Let us consider the result of interpreting a few \LangInt{} programs. The
  1194. following program adds two integers.
  1195. \begin{lstlisting}
  1196. (+ 10 32)
  1197. \end{lstlisting}
  1198. The result is \key{42}, the answer to life, the universe, and
  1199. everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to the
  1200. Galaxy} by Douglas Adams.}.
  1201. %
  1202. We wrote the above program in concrete syntax whereas the parsed
  1203. abstract syntax is:
  1204. \begin{lstlisting}
  1205. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1206. \end{lstlisting}
  1207. \begin{ocamlx}
  1208. Ocaml:
  1209. \begin{lstlisting}[style=ocaml]
  1210. Program((),Prim(Add,[Int 10; Int 32]))
  1211. \end{lstlisting}
  1212. \end{ocamlx}
  1213. The next example demonstrates that expressions may be nested within
  1214. each other, in this case nesting several additions and negations.
  1215. \begin{lstlisting}
  1216. (+ 10 (- (+ 12 20)))
  1217. \end{lstlisting}
  1218. What is the result of the above program?
  1219. As mentioned previously, the \LangInt{} language does not support
  1220. arbitrarily-large integers, but only $63$-bit integers, so we
  1221. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1222. in Racket.
  1223. Suppose
  1224. \[
  1225. n = 999999999999999999
  1226. \]
  1227. which indeed fits in $63$-bits. What happens when we run the
  1228. following program in our interpreter?
  1229. \begin{lstlisting}
  1230. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1231. \end{lstlisting}
  1232. It produces an error:
  1233. \begin{lstlisting}
  1234. fx+: result is not a fixnum
  1235. \end{lstlisting}
  1236. We establish the convention that if running the definitional
  1237. interpreter on a program produces an error then the meaning of that
  1238. program is \emph{unspecified}\index{unspecified behavior}, unless the
  1239. error is a \code{trapped-error}. A compiler for the language is under
  1240. no obligations regarding programs with unspecified behavior; it does
  1241. not have to produce an executable, and if it does, that executable can
  1242. do anything. On the other hand, if the error is a
  1243. \code{trapped-error}, then the compiler must produce an executable and
  1244. it is required to report that an error occurred. To signal an error,
  1245. exit with a return code of \code{255}. The interpreters in chapters
  1246. \ref{ch:Rdyn} and \ref{ch:Rgrad} use
  1247. \code{trapped-error}.
  1248. \begin{ocamlx}
  1249. In OCaml, overflow does not cause a trap; instead values ``wrap around''
  1250. to produce results modulo $2^{63}$. The result of this program is
  1251. \key{-1223372036854775816}.
  1252. \end{ocamlx}
  1253. %% This convention applies to the languages defined in this
  1254. %% book, as a way to simplify the student's task of implementing them,
  1255. %% but this convention is not applicable to all programming languages.
  1256. %%
  1257. Moving on to the last feature of the \LangInt{} language, the \key{read}
  1258. operation prompts the user of the program for an integer. \ocaml{The \code{read\_int}
  1259. function is in the standard library.} Recall that
  1260. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  1261. \code{8}. So if we run
  1262. \begin{lstlisting}
  1263. (interp-Rint (Program '() ast1.1))
  1264. \end{lstlisting}
  1265. and if the input is \code{50}, the result is \code{42}.
  1266. We include the \key{read} operation in \LangInt{} so a clever student
  1267. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  1268. during compilation to obtain the output and then generates the trivial
  1269. code to produce the output. (Yes, a clever student did this in the
  1270. first instance of this course.)
  1271. The job of a compiler is to translate a program in one language into a
  1272. program in another language so that the output program behaves the
  1273. same way as the input program does. This idea is depicted in the
  1274. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1275. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1276. Given a compiler that translates from language $\mathcal{L}_1$ to
  1277. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1278. compiler must translate it into some program $P_2$ such that
  1279. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1280. same input $i$ yields the same output $o$.
  1281. \begin{equation} \label{eq:compile-correct}
  1282. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1283. \node (p1) at (0, 0) {$P_1$};
  1284. \node (p2) at (3, 0) {$P_2$};
  1285. \node (o) at (3, -2.5) {$o$};
  1286. \path[->] (p1) edge [above] node {compile} (p2);
  1287. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  1288. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  1289. \end{tikzpicture}
  1290. \end{equation}
  1291. In the next section we see our first example of a compiler.
  1292. \section{Example Compiler: a Partial Evaluator}
  1293. \label{sec:partial-evaluation}
  1294. In this section we consider a compiler that translates \LangInt{} programs
  1295. into \LangInt{} programs that may be more efficient, that is, this compiler
  1296. is an optimizer. This optimizer eagerly computes the parts of the
  1297. program that do not depend on any inputs, a process known as
  1298. \emph{partial evaluation}~\citep{Jones:1993uq}.
  1299. \index{partial evaluation}
  1300. For example, given the following program
  1301. \begin{lstlisting}
  1302. (+ (read) (- (+ 5 3)))
  1303. \end{lstlisting}
  1304. our compiler will translate it into the program
  1305. \begin{lstlisting}
  1306. (+ (read) -8)
  1307. \end{lstlisting}
  1308. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1309. evaluator for the \LangInt{} language. The output of the partial evaluator
  1310. is an \LangInt{} program. In Figure~\ref{fig:pe-arith}, the structural
  1311. recursion over $\Exp$ is captured in the \code{pe-exp} function
  1312. whereas the code for partially evaluating the negation and addition
  1313. operations is factored into two separate helper functions:
  1314. \code{pe-neg} and \code{pe-add}. The input to these helper
  1315. functions is the output of partially evaluating the children.
  1316. \begin{figure}[tp]
  1317. \begin{lstlisting}
  1318. (define (pe-neg r)
  1319. (match r
  1320. [(Int n) (Int (fx- 0 n))]
  1321. [else (Prim '- (list r))]))
  1322. (define (pe-add r1 r2)
  1323. (match* (r1 r2)
  1324. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1325. [(_ _) (Prim '+ (list r1 r2))]))
  1326. (define (pe-exp e)
  1327. (match e
  1328. [(Int n) (Int n)]
  1329. [(Prim 'read '()) (Prim 'read '())]
  1330. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  1331. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]))
  1332. (define (pe-Rint p)
  1333. (match p
  1334. [(Program '() e) (Program '() (pe-exp e))]))
  1335. \end{lstlisting}
  1336. \caption{A partial evaluator for \LangInt{}.}
  1337. \label{fig:pe-arith}
  1338. \end{figure}
  1339. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  1340. arguments are integers and if they are, perform the appropriate
  1341. arithmetic. Otherwise, they create an AST node for the arithmetic
  1342. operation.
  1343. \begin{ocamlx}
  1344. The corresponding OCaml code is in Figure~\ref{fig:ocaml-pe-arith}. In \code{pe\_add}, note
  1345. the syntax for matching over a pair of values simultaneously.
  1346. \begin{figure}[tp]
  1347. \begin{lstlisting}[style=ocaml]
  1348. let pe_neg = function
  1349. Int n -> Int (-n)
  1350. | e -> Prim(Neg,[e])
  1351. let pe_add e1 e2 =
  1352. match e1,e2 with
  1353. Int n1,Int n2 -> Int (n1+n2)
  1354. | e1,e2 -> Prim(Add,[e1;e2])
  1355. let rec pe_exp = function
  1356. Prim(Neg,[e]) -> pe_neg (pe_exp e)
  1357. | Prim(Add,[e1;e2]) -> pe_add (pe_exp e1) (pe_exp e2)
  1358. | e -> e
  1359. let pe_program (Program(info,e)) = Program(info,pe_exp e)
  1360. \end{lstlisting}
  1361. \caption{\ocaml{An OCaml partial evaluator for \LangInt{}}.}
  1362. \label{fig:ocaml-pe-arith}
  1363. \end{figure}
  1364. \end{ocamlx}
  1365. To gain some confidence that the partial evaluator is correct, we can
  1366. test whether it produces programs that get the same result as the
  1367. input programs. That is, we can test whether it satisfies Diagram
  1368. \ref{eq:compile-correct}. The following code runs the partial
  1369. evaluator on several examples and tests the output program. The
  1370. \texttt{parse-program} and \texttt{assert} functions are defined in
  1371. Appendix~\ref{appendix:utilities}.\\
  1372. \begin{minipage}{1.0\textwidth}
  1373. \begin{lstlisting}
  1374. (define (test-pe p)
  1375. (assert "testing pe-Rint"
  1376. (equal? (interp-Rint p) (interp-Rint (pe-Rint p)))))
  1377. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1378. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1379. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  1380. \end{lstlisting}
  1381. \end{minipage}
  1382. \begin{ocamlx}
  1383. We can perform a similar kind of test in OCaml using a utility
  1384. function called \code{interp\_from\_string} which is in the support
  1385. code for this chapter (not yet in the Appendix).
  1386. Note, however, that comparing
  1387. results like this isn't a very satisfactory way of testing programs
  1388. that use \code{Read} anyhow, because it requires us to input the
  1389. same values twice, once for each execution, or the test will fail!
  1390. A more straightforward approach is to know what result value we
  1391. expect from each test program on a given set of input, and simply check
  1392. that the partially evaluated program still produces that result.
  1393. The support code also contains a simple driver that implements this approach.
  1394. \end{ocamlx}
  1395. \begin{ocamlx}
  1396. {\bf Warmup Exercises}
  1397. 1. Extend the concrete language and implementation for \LangInt{} with an additional arity-2 primop that
  1398. performs subtraction. The concrete form for this is \code{(- $e_1$ $e_2$)} where
  1399. $e_1$ and $e_2$ are expressions. Note that there are several ways to do this: you can add
  1400. an additional primop \code{Sub} to the AST, and add new code to check and interpret it,
  1401. or you can choose to ``de-sugar'' the new form into a combination of existing primops when
  1402. converting S-expressions to ASTs. Either way, make sure that you understand why the concrete
  1403. language remains unambiguous even though (a) we already have a unary negation operaror that is also written
  1404. with \code{-}, and (b) unlike addition, subtraction is not an associative operator, i.e.
  1405. $((a-b)-c$ is not generally the same thing as $(a-(b-c))$.
  1406. 2. Make some non-trivial improvement to the partial evaluator. This task is intentionally open-ended, but here
  1407. are some suggestions, in increasing order of difficulty.
  1408. \begin{itemize}
  1409. \item
  1410. If you added a new primop for subtraction in part 1, add support for
  1411. partially evaluating subtractions involving constants, analogous to what is already there
  1412. for addition.
  1413. \item
  1414. Add support for simplifying expressions
  1415. based on simple algebraic identities, e.g. $x + 0 = x$ for all $x$.
  1416. \item Try to simplify expressions to
  1417. the point where they contain no more than one \code{Int} leaf expression (the remaining leaves should all be
  1418. \code{Read}s).
  1419. \end{itemize}
  1420. 3. Change the AST, interpreter and (improved) partial evaluator for \LangInt{} so that they
  1421. use true 64-bit integers throughout.
  1422. (Currently, these are used in S-expressions in the front end, but everything else uses 63-bit integers instead.)
  1423. This will bring our interpreter and partial evaluator in line with X86-64 machine code, our ultimate
  1424. compilation target.
  1425. The point of this exercise is to get you familiar with exploring an OCaml library, in this case \code{Int64},
  1426. which is documented at \url{https://ocaml.org/releases/4.12/api/Int64.html}.
  1427. \end{ocamlx}
  1428. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1429. \chapter{Integers and Variables}
  1430. \label{ch:Rvar}
  1431. This chapter is about compiling a subset of Racket to x86-64 assembly
  1432. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1433. integer arithmetic and local variable binding. We often refer to
  1434. x86-64 simply as x86. The chapter begins with a description of the
  1435. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  1436. to of x86 assembly (Section~\ref{sec:x86}). The x86 assembly language
  1437. is large so we discuss only the instructions needed for compiling
  1438. \LangVar{}. We introduce more x86 instructions in later chapters.
  1439. After introducing \LangVar{} and x86, we reflect on their differences
  1440. and come up with a plan to break down the translation from \LangVar{}
  1441. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  1442. rest of the sections in this chapter give detailed hints regarding
  1443. each step (Sections~\ref{sec:uniquify-Rvar} through \ref{sec:patch-s0}).
  1444. We hope to give enough hints that the well-prepared reader, together
  1445. with a few friends, can implement a compiler from \LangVar{} to x86 in
  1446. a couple weeks. To give the reader a feeling for the scale of this
  1447. first compiler, the instructor solution for the \LangVar{} compiler is
  1448. approximately 500 lines of code. \ocaml{For the OCaml-based course,
  1449. several pieces of the compiler will be provided for you, leaving enough
  1450. work for a week-long assignment. The instructor solution for
  1451. the tasks left to you is under 200 lines of code.
  1452. However, in return for not writing so much code,
  1453. you will need to \emph{read} more existing code.}
  1454. \section{The \LangVar{} Language}
  1455. \label{sec:s0}
  1456. \index{variable}
  1457. The \LangVar{} language extends the \LangInt{} language with variable
  1458. definitions. The concrete syntax of the \LangVar{} language is defined by
  1459. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  1460. syntax is defined in Figure~\ref{fig:r1-syntax}. \ocaml{For the OCaml
  1461. version, we don't feel the need to match the syntax of Racket exactly,
  1462. so we can simplify the concrete syntax of \key{let} bindings.} The non-terminal
  1463. \Var{} may be any Racket identifier. \ocaml{For OCaml, it can be any S-expression symbol.}
  1464. As in \LangInt{}, \key{read} is a
  1465. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  1466. operator. \ocaml{We also add \key{-} as a binary subtraction operator in
  1467. the concrete syntax, but not in the abstract syntax:
  1468. we will ``de-sugar'' substraction into a combination
  1469. of addition and negation.}Similar to \LangInt{}, the abstract syntax of \LangVar{} includes the
  1470. \key{Program} struct to mark the top of the program.
  1471. %% The $\itm{info}$
  1472. %% field of the \key{Program} structure contains an \emph{association
  1473. %% list} (a list of key-value pairs) that is used to communicate
  1474. %% auxiliary data from one compiler pass the next.
  1475. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1476. exhibit several compilation techniques.
  1477. \begin{figure}[tp]
  1478. \centering
  1479. \fbox{
  1480. \begin{minipage}{0.96\textwidth}
  1481. \[
  1482. \begin{array}{rcl}
  1483. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp}\\
  1484. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  1485. \LangVar{} &::=& \Exp
  1486. \end{array}
  1487. \]
  1488. \end{minipage}
  1489. }
  1490. \begin{ocamlx}
  1491. \fbox{
  1492. \begin{minipage}{0.96\textwidth}
  1493. \[
  1494. \begin{array}{rcl}
  1495. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp}\\
  1496. &\mid& \Var \mid \code{(let $\Var$ $\Exp$ $\Exp$)}\\
  1497. \LangVar{} &::=& \Exp
  1498. \end{array}
  1499. \]
  1500. \end{minipage}
  1501. }
  1502. \end{ocamlx}
  1503. \caption{The concrete syntax of \LangVar{} \ocaml{in OCaml}.}
  1504. \label{fig:r1-concrete-syntax}
  1505. \end{figure}
  1506. \begin{figure}[tp]
  1507. \centering
  1508. \fbox{
  1509. \begin{minipage}{0.96\textwidth}
  1510. \[
  1511. \begin{array}{rcl}
  1512. \Exp &::=& \INT{\Int} \mid \READ{} \\
  1513. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  1514. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  1515. \LangVar{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1516. \end{array}
  1517. \]
  1518. \end{minipage}
  1519. }
  1520. \begin{lstlisting}[style=ocaml,frame=single]
  1521. type primop =
  1522. Read
  1523. | Neg
  1524. | Add
  1525. type var = string
  1526. type exp =
  1527. Int of int64
  1528. | Prim of primop * exp list
  1529. | Var of var
  1530. | Let of var * exp * exp
  1531. type 'info program = Program of 'info * exp
  1532. \end{lstlisting}
  1533. \caption{The abstract syntax of \LangVar{}.}
  1534. \label{fig:r1-syntax}
  1535. \end{figure}
  1536. Let us dive further into the syntax and semantics of the \LangVar{}
  1537. language. The \key{let} feature defines a variable for use within its
  1538. body and initializes the variable with the value of an expression.
  1539. The abstract syntax for \key{let} is defined in
  1540. Figure~\ref{fig:r1-syntax}. The concrete syntax for \key{let} is
  1541. \begin{lstlisting}
  1542. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1543. \end{lstlisting}
  1544. \begin{lstlisting}[style=ocaml]
  1545. (let ~$\itm{var}$~ ~$\itm{exp}$~ ~$\itm{exp}$~)
  1546. \end{lstlisting}
  1547. For example, the following program initializes \code{x} to $32$ and then
  1548. evaluates the body \code{(+ 10 x)}, producing $42$.
  1549. \begin{lstlisting}
  1550. (let ([x (+ 12 20)]) (+ 10 x))
  1551. \end{lstlisting}
  1552. \begin{lstlisting}[style=ocaml]
  1553. (let x (+ 12 20) (+ 10 x))
  1554. \end{lstlisting}
  1555. When there are multiple \key{let}'s for the same variable, the closest
  1556. enclosing \key{let} is used. That is, variable definitions overshadow
  1557. prior definitions. Consider the following program with two \key{let}'s
  1558. that define variables named \code{x}. Can you figure out the result?
  1559. \begin{lstlisting}
  1560. (let ([x 32]) (+ (let ([x 10]) x) x))
  1561. \end{lstlisting}
  1562. \begin{lstlisting}[style=ocaml]
  1563. (let x 32 (+ (let x 10 x) x))
  1564. \end{lstlisting}
  1565. For the purposes of depicting which variable uses correspond to which
  1566. definitions, the following shows the \code{x}'s annotated with
  1567. subscripts to distinguish them. Double check that your answer for the
  1568. above is the same as your answer for this annotated version of the
  1569. program.
  1570. \begin{lstlisting}
  1571. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1572. \end{lstlisting}
  1573. \begin{lstlisting}[style=ocaml]
  1574. (let x~$_1$~ 32 (+ (let x~$_2$~ 10 x~$_2$~) x~$_1$~))
  1575. \end{lstlisting}
  1576. The initializing expression is always evaluated before the body of the
  1577. \key{let}, so in the following, the \key{read} for \code{x} is
  1578. performed before the \key{read} for \code{y}. Given the input
  1579. $52$ then $10$, the following produces $42$ (not $-42$).
  1580. \begin{lstlisting}
  1581. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1582. \end{lstlisting}
  1583. \begin{lstlisting}[style=ocaml]
  1584. (let x (read) (let y (read) (+ x (- y)))))
  1585. \end{lstlisting}
  1586. \subsection{Extensible Interpreters via Method Overriding}
  1587. \label{sec:extensible-interp}
  1588. \begin{ocamlx}
  1589. We are not going to bother with making our OCaml interpreters
  1590. extensible, although there are several mechanisms in OCaml that
  1591. we could use to acheive this. The languages involved here just
  1592. don't seem big enough to warrant the added complexity.
  1593. We will, however, break out the definition and interpretation of
  1594. primops into a separate module, so that this can be easily shared among
  1595. different languages.
  1596. \end{ocamlx}
  1597. To prepare for discussing the interpreter for \LangVar{}, we need to
  1598. explain why we choose to implement the interpreter using
  1599. object-oriented programming, that is, as a collection of methods
  1600. inside of a class. Throughout this book we define many interpreters,
  1601. one for each of the languages that we study. Because each language
  1602. builds on the prior one, there is a lot of commonality between their
  1603. interpreters. We want to write down those common parts just once
  1604. instead of many times. A naive approach would be to have, for example,
  1605. the interpreter for \LangIf{} handle all of the new features in that
  1606. language and then have a default case that dispatches to the
  1607. interpreter for \LangVar{}. The following code sketches this idea.
  1608. \begin{center}
  1609. \begin{minipage}{0.45\textwidth}
  1610. \begin{lstlisting}
  1611. (define (interp-Rvar e)
  1612. (match e
  1613. [(Prim '- (list e))
  1614. (fx- 0 (interp-Rvar e))]
  1615. ...))
  1616. \end{lstlisting}
  1617. \end{minipage}
  1618. \begin{minipage}{0.45\textwidth}
  1619. \begin{lstlisting}
  1620. (define (interp-Rif e)
  1621. (match e
  1622. [(If cnd thn els)
  1623. (match (interp-Rif cnd)
  1624. [#t (interp-Rif thn)]
  1625. [#f (interp-Rif els)])]
  1626. ...
  1627. [else (interp-Rvar e)]))
  1628. \end{lstlisting}
  1629. \end{minipage}
  1630. \end{center}
  1631. The problem with this approach is that it does not handle situations
  1632. in which an \LangIf{} feature, like \code{If}, is nested inside an \LangVar{}
  1633. feature, like the \code{-} operator, as in the following program.
  1634. \begin{lstlisting}
  1635. (Prim '- (list (If (Bool #t) (Int 42) (Int 0))))
  1636. \end{lstlisting}
  1637. If we invoke \code{interp-Rif} on this program, it dispatches to
  1638. \code{interp-Rvar} to handle the \code{-} operator, but then it
  1639. recurisvely calls \code{interp-Rvar} again on the argument of \code{-},
  1640. which is an \code{If}. But there is no case for \code{If} in
  1641. \code{interp-Rvar}, so we get an error!
  1642. To make our interpreters extensible we need something called
  1643. \emph{open recursion}\index{open recursion}, where the tying of the
  1644. recursive knot is delayed to when the functions are
  1645. composed. Object-oriented languages provide open recursion with the
  1646. late-binding of overridden methods\index{method overriding}. The
  1647. following code sketches this idea for interpreting \LangVar{} and
  1648. \LangIf{} using the
  1649. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1650. \index{class} feature of Racket. We define one class for each
  1651. language and define a method for interpreting expressions inside each
  1652. class. The class for \LangIf{} inherits from the class for \LangVar{}
  1653. and the method \code{interp-exp} in \LangIf{} overrides the
  1654. \code{interp-exp} in \LangVar{}. Note that the default case of
  1655. \code{interp-exp} in \LangIf{} uses \code{super} to invoke
  1656. \code{interp-exp}, and because \LangIf{} inherits from \LangVar{},
  1657. that dispatches to the \code{interp-exp} in \LangVar{}.
  1658. \begin{center}
  1659. \begin{minipage}{0.45\textwidth}
  1660. \begin{lstlisting}
  1661. (define interp-Rvar-class
  1662. (class object%
  1663. (define/public (interp-exp e)
  1664. (match e
  1665. [(Prim '- (list e))
  1666. (fx- 0 (interp-exp e))]
  1667. ...))
  1668. ...))
  1669. \end{lstlisting}
  1670. \end{minipage}
  1671. \begin{minipage}{0.45\textwidth}
  1672. \begin{lstlisting}
  1673. (define interp-Rif-class
  1674. (class interp-Rvar-class
  1675. (define/override (interp-exp e)
  1676. (match e
  1677. [(If cnd thn els)
  1678. (match (interp-exp cnd)
  1679. [#t (interp-exp thn)]
  1680. [#f (interp-exp els)])]
  1681. ...
  1682. [else (super interp-exp e)]))
  1683. ...
  1684. ))
  1685. \end{lstlisting}
  1686. \end{minipage}
  1687. \end{center}
  1688. Getting back to the troublesome example, repeated here:
  1689. \begin{lstlisting}
  1690. (define e0 (Prim '- (list (If (Bool #t) (Int 42) (Int 0)))))
  1691. \end{lstlisting}
  1692. We can invoke the \code{interp-exp} method for \LangIf{} on this
  1693. expression by creating an object of the \LangIf{} class and sending it the
  1694. \code{interp-exp} method with the argument \code{e0}.
  1695. \begin{lstlisting}
  1696. (send (new interp-Rif-class) interp-exp e0)
  1697. \end{lstlisting}
  1698. The default case of \code{interp-exp} in \LangIf{} handles it by
  1699. dispatching to the \code{interp-exp} method in \LangVar{}, which
  1700. handles the \code{-} operator. But then for the recursive method call,
  1701. it dispatches back to \code{interp-exp} in \LangIf{}, where the
  1702. \code{If} is handled correctly. Thus, method overriding gives us the
  1703. open recursion that we need to implement our interpreters in an
  1704. extensible way.
  1705. \newpage
  1706. \subsection{Definitional Interpreter for \LangVar{}}
  1707. \begin{wrapfigure}[25]{r}[1.0in]{0.6\textwidth}
  1708. \small
  1709. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1710. An \emph{association list} (alist) is a list of key-value pairs.
  1711. For example, we can map people to their ages with an alist.
  1712. \index{alist}\index{association list}
  1713. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1714. (define ages
  1715. '((jane . 25) (sam . 24) (kate . 45)))
  1716. \end{lstlisting}
  1717. The \emph{dictionary} interface is for mapping keys to values.
  1718. Every alist implements this interface. \index{dictionary} The package
  1719. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1720. provides many functions for working with dictionaries. Here
  1721. are a few of them:
  1722. \begin{description}
  1723. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1724. returns the value associated with the given $\itm{key}$.
  1725. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1726. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1727. but otherwise is the same as $\itm{dict}$.
  1728. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1729. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1730. of keys and values in $\itm{dict}$. For example, the following
  1731. creates a new alist in which the ages are incremented.
  1732. \end{description}
  1733. \vspace{-10pt}
  1734. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1735. (for/list ([(k v) (in-dict ages)])
  1736. (cons k (add1 v)))
  1737. \end{lstlisting}
  1738. \end{tcolorbox}
  1739. \end{wrapfigure}
  1740. Having justified the use of classes and methods to implement
  1741. interpreters \ocaml{(or not)}, we turn to the definitional interpreter for \LangVar{}
  1742. in Figure~\ref{fig:interp-Rvar} \ocaml{(Figure~\ref{fig:interp-Rvar-ocaml})}.
  1743. It is similar to the interpreter for
  1744. \LangInt{} but adds two new \key{match} cases for variables and
  1745. \key{let}. \ocaml{Also, the code for performing primops has been split out
  1746. into a separate function. We rely on the fact that
  1747. \code{List.map} processes list elements from left to right to
  1748. enforce the intended order of evaluation of primop subexpressions.}
  1749. For \key{let} we need a way to communicate the value bound
  1750. to a variable to all the uses of the variable. To accomplish this, we
  1751. maintain a mapping from variables to values. Throughout the compiler
  1752. we often need to map variables to information about them. We refer to
  1753. these mappings as
  1754. \emph{environments}\index{environment}.\footnote{Another common term
  1755. for environment in the compiler literature is \emph{symbol
  1756. table}\index{symbol table}.}
  1757. %
  1758. For simplicity, we use an association list (alist) to represent the
  1759. environment. The sidebar to the right gives a brief introduction to
  1760. alists and the \code{racket/dict} package. The \code{interp-exp}
  1761. function takes the current environment, \code{env}, as an extra
  1762. parameter. When the interpreter encounters a variable, it finds the
  1763. corresponding value using the \code{dict-ref} function. When the
  1764. interpreter encounters a \key{Let}, it evaluates the initializing
  1765. expression, extends the environment with the result value bound to the
  1766. variable, using \code{dict-set}, then evaluates the body of the
  1767. \key{Let}.
  1768. \begin{ocamlx}
  1769. In OCaml, we thread environments in the same way, but
  1770. it is convenient to represent environments using
  1771. the \code{Map} library module, which provides efficient
  1772. mappings from keys to values (using balanced binary trees,
  1773. although that is an implementation detail we don't need to
  1774. know about). \code{Map} is an example of a module that
  1775. is \emph{parameterized} by another module signature; this
  1776. is sometimes called a \emph{functor}. Here we use \code{Map.Make}
  1777. to \emph{apply} the functor, thereby defining a module \code{Env} that provides operations
  1778. specialized to \code{string} keys (suitable for variables).
  1779. The type of environments is written \code{'a Env.t}; it is
  1780. parametric in the type \code{'a} of values stored in the map.
  1781. Here we will be using \LangVar{}
  1782. values, i.e. \code{int64}s, so the type is \code{int64 Env.t}.
  1783. \code{Env.empty} represents an empty environment.
  1784. \code{Env.find $x$ $env$} returns the value associated with
  1785. variable $x$ in $env$ (throwing an exception if $x$ is not found).
  1786. \code{Env.add $x$ $v$ $env$} produces a new environment
  1787. that is the same as $env$ except that variable $x$ is associated to
  1788. value $v$. Note that these operations are \emph{pure}; that is, they
  1789. do not mutate any environment.
  1790. \end{ocamlx}
  1791. \begin{ocamlx}
  1792. The OCaml code for \LangVar{} ASTs, concrete parsing and printing (for debug purposes),
  1793. and interpretation are in file \texttt{RVar.ml}, which also imports
  1794. from file \texttt{Primops.ml}. These files also contain code for
  1795. static checking of \LangVar{} programs. The checker makes sure that
  1796. (i) every use of a variable is in the scope of a corresponding \code{let} binding;
  1797. and (ii) each primop is applied to the correct number of arguments.
  1798. Note that if a source program fails the checker for reason (i), this is a static user error
  1799. that should be reported as such. (Violations of (ii) in user programs
  1800. should be caught by the parser; parse errors are always reported as user errors.)
  1801. Your compiler should stop trying to process a file as soon as it reports a static user
  1802. error! (That's what the provided test driver will do.)
  1803. However, if a program initially passes
  1804. the checker but is subsequently transformed by the compiler and then
  1805. fails a re-check, this indicates that the problem is the compiler's fault.
  1806. In this case, the compiler itself should halt with a suitable error message.
  1807. The checker has a boolean flag to distinguish these cases.
  1808. \end{ocamlx}
  1809. \begin{figure}[tp]
  1810. \begin{lstlisting}
  1811. (define interp-Rvar-class
  1812. (class object%
  1813. (super-new)
  1814. (define/public ((interp-exp env) e)
  1815. (match e
  1816. [(Int n) n]
  1817. [(Prim 'read '())
  1818. (define r (read))
  1819. (cond [(fixnum? r) r]
  1820. [else (error 'interp-exp "expected an integer" r)])]
  1821. [(Prim '- (list e)) (fx- 0 ((interp-exp env) e))]
  1822. [(Prim '+ (list e1 e2))
  1823. (fx+ ((interp-exp env) e1) ((interp-exp env) e2))]
  1824. [(Var x) (dict-ref env x)]
  1825. [(Let x e body)
  1826. (define new-env (dict-set env x ((interp-exp env) e)))
  1827. ((interp-exp new-env) body)]))
  1828. (define/public (interp-program p)
  1829. (match p
  1830. [(Program '() e) ((interp-exp '()) e)]))
  1831. ))
  1832. (define (interp-Rvar p)
  1833. (send (new interp-Rvar-class) interp-program p))
  1834. \end{lstlisting}
  1835. \caption{Interpreter for the \LangVar{} language.}
  1836. \label{fig:interp-Rvar}
  1837. \end{figure}
  1838. \begin{figure}[tp]
  1839. \begin{lstlisting}[style=ocaml]
  1840. type value = int64
  1841. let interp_primop (op:primop) (args: value list) : value =
  1842. match op,args with
  1843. Read,[] -> read_int()
  1844. | Neg,[v] -> Int64.neg v
  1845. | Add,[v1;v2] -> Int64.add v1 v2
  1846. | _,_ -> assert false (* arity mismatch *)
  1847. module StringKey = struct type t = string let compare = String.compare end
  1848. module Env = Map.Make(StringKey)
  1849. let rec interp_exp (env:value Env.t) = function
  1850. Int n -> n
  1851. | Prim(op,args) -> interp_primop op (List.map (interp_exp env) args)
  1852. | Var x -> Env.find x env
  1853. | Let (x,e1,e2) -> interp_exp (Env.add x (interp_exp env e1) env) e2
  1854. let interp_program (Program(_,e)) = interp_exp Env.empty e
  1855. \end{lstlisting}
  1856. \caption{\ocaml{Ocaml interpreter for the \LangVar{} language.}}
  1857. \label{fig:interp-Rvar-ocaml}
  1858. \end{figure}
  1859. The goal for this chapter is to implement a compiler that translates
  1860. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  1861. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1862. computer as the $P_1$ program interpreted by \code{interp-Rvar}. That
  1863. is, they output the same integer $n$. We depict this correctness
  1864. criteria in the following diagram.
  1865. \[
  1866. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1867. \node (p1) at (0, 0) {$P_1$};
  1868. \node (p2) at (4, 0) {$P_2$};
  1869. \node (o) at (4, -2) {$n$};
  1870. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1871. \path[->] (p1) edge [left] node {\footnotesize\code{interp-Rvar}} (o);
  1872. \path[->] (p2) edge [right] node {\footnotesize\code{interp-x86int}} (o);
  1873. \end{tikzpicture}
  1874. \]
  1875. In the next section we introduce the \LangXInt{} subset of x86 that
  1876. suffices for compiling \LangVar{}.
  1877. \section{The \LangXInt{} Assembly Language}
  1878. \label{sec:x86}
  1879. \index{x86}
  1880. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  1881. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  1882. assembler.
  1883. %
  1884. A program begins with a \code{main} label followed by a sequence of
  1885. instructions. The \key{globl} directive says that the \key{main}
  1886. procedure is externally visible, which is necessary so that the
  1887. operating system can call it. In the grammar, ellipses such as
  1888. $\ldots$ are used to indicate a sequence of items, e.g., $\Instr
  1889. \ldots$ is a sequence of instructions.\index{instruction}
  1890. %
  1891. An x86 program is stored in the computer's memory. For our purposes,
  1892. the computer's memory is as a mapping of 64-bit addresses to 64-bit
  1893. values. The computer has a \emph{program counter} (PC)\index{program
  1894. counter}\index{PC} stored in the \code{rip} register that points to
  1895. the address of the next instruction to be executed. For most
  1896. instructions, the program counter is incremented after the instruction
  1897. is executed, so it points to the next instruction in memory. Most x86
  1898. instructions take two operands, where each operand is either an
  1899. integer constant (called \emph{immediate value}\index{immediate
  1900. value}), a \emph{register}\index{register}, or a memory location.
  1901. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1902. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1903. && \key{r8} \mid \key{r9} \mid \key{r10}
  1904. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1905. \mid \key{r14} \mid \key{r15}}
  1906. \begin{figure}[tp]
  1907. \fbox{
  1908. \begin{minipage}{0.96\textwidth}
  1909. \[
  1910. \begin{array}{lcl}
  1911. \Reg &::=& \allregisters{} \\
  1912. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1913. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1914. \key{subq} \; \Arg\key{,} \Arg \mid
  1915. \key{negq} \; \Arg \mid \\
  1916. && \key{movq} \; \Arg\key{,} \Arg \mid \ocaml{\key{movabsq} \; \Arg\key{,} \Arg \mid} \\
  1917. && \key{callq} \; \mathit{label} \mid
  1918. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} \\
  1919. && \itm{label}\key{:}\; \Instr \\
  1920. \LangXInt{} &::= & \key{.globl main}\\
  1921. & & \key{main:} \; \Instr\ldots
  1922. \end{array}
  1923. \]
  1924. \end{minipage}
  1925. }
  1926. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  1927. \label{fig:x86-int-concrete}
  1928. \end{figure}
  1929. A register is a special kind of variable. Each one holds a 64-bit
  1930. value; there are 16 general-purpose registers in the computer and
  1931. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  1932. is written with a \key{\%} followed by the register name, such as
  1933. \key{\%rax}.
  1934. An immediate value is written using the notation \key{\$}$n$ where $n$
  1935. is an integer.
  1936. %
  1937. %
  1938. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1939. which obtains the address stored in register $r$ and then adds $n$
  1940. bytes to the address. The resulting address is used to load or store
  1941. to memory depending on whether it occurs as a source or destination
  1942. argument of an instruction.
  1943. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1944. source $s$ and destination $d$, applies the arithmetic operation, then
  1945. writes the result back to the destination $d$.
  1946. %
  1947. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1948. stores the result in $d$.
  1949. %
  1950. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  1951. specified by the label and $\key{retq}$ returns from a procedure to
  1952. its caller.
  1953. %
  1954. We discuss procedure calls in more detail later in this chapter and in
  1955. Chapter~\ref{ch:Rfun}. The instruction $\key{jmp}\,\itm{label}$
  1956. updates the program counter to the address of the instruction after
  1957. the specified label.
  1958. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  1959. all of the x86 instructions used in this book.
  1960. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent to
  1961. \code{(+ 10 32)}. The instruction \lstinline{movq $10, %rax}
  1962. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  1963. adds $32$ to the $10$ in \key{rax} and
  1964. puts the result, $42$, back into \key{rax}.
  1965. %
  1966. The last instruction, \key{retq}, finishes the \key{main} function by
  1967. returning the integer in \key{rax} to the operating system. The
  1968. operating system interprets this integer as the program's exit
  1969. code. By convention, an exit code of 0 indicates that a program
  1970. completed successfully, and all other exit codes indicate various
  1971. errors. \ocaml{Also, exit codes are unsigned bytes, so they cannot accurately represent
  1972. arbitrary \code{int64}s.} Nevertheless, in this book we return the result of the program
  1973. as the exit code. \ocaml{(Incidentally, if you run a program at the unix shell
  1974. prompt, you can retrieve its exit code by typing \texttt{echo \$?} as the very next command.)}
  1975. \begin{figure}[tbp]
  1976. \begin{lstlisting}
  1977. .globl main
  1978. main:
  1979. movq $10, %rax
  1980. addq $32, %rax
  1981. retq
  1982. \end{lstlisting}
  1983. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1984. \label{fig:p0-x86}
  1985. \end{figure}
  1986. The x86 assembly language varies in a couple ways depending on what
  1987. operating system it is assembled in. The code examples shown here are
  1988. correct on Linux and most Unix-like platforms, but when assembled on
  1989. Mac OS X, labels like \key{main} must be prefixed with an underscore,
  1990. as in \key{\_main}. \ocaml{There is a utility function \code{get\_ostype}
  1991. provided in the \texttt{utils.ml} module provided with the support materials.}
  1992. We exhibit the use of memory for storing intermediate results in the
  1993. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1994. equivalent to \code{(+ 52 (- 10))}. This program uses a region of
  1995. memory called the \emph{procedure call stack} (or \emph{stack} for
  1996. short). \index{stack}\index{procedure call stack} The stack consists
  1997. of a separate \emph{frame}\index{frame} for each procedure call. The
  1998. memory layout for an individual frame is shown in
  1999. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  2000. \emph{stack pointer}\index{stack pointer} and points to the item at
  2001. the top of the stack. The stack grows downward in memory, so we
  2002. increase the size of the stack by subtracting from the stack pointer.
  2003. In the context of a procedure call, the \emph{return
  2004. address}\index{return address} is the instruction after the call
  2005. instruction on the caller side. The function call instruction,
  2006. \code{callq}, pushes the return address onto the stack prior to
  2007. jumping to the procedure. The register \key{rbp} is the \emph{base
  2008. pointer}\index{base pointer} and is used to access variables that
  2009. are stored in the frame of the current procedure call. The base
  2010. pointer of the caller is pushed onto the stack after the return
  2011. address and then the base pointer is set to the location of the old
  2012. base pointer. In Figure~\ref{fig:frame} we number the variables from
  2013. $1$ to $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$,
  2014. variable $2$ at $-16\key{(\%rbp)}$, etc.
  2015. \begin{figure}[tbp]
  2016. \begin{lstlisting}
  2017. start:
  2018. movq $10, -8(%rbp)
  2019. negq -8(%rbp)
  2020. movq -8(%rbp), %rax
  2021. addq $52, %rax
  2022. jmp conclusion
  2023. .globl main
  2024. main:
  2025. pushq %rbp
  2026. movq %rsp, %rbp
  2027. subq $16, %rsp
  2028. jmp start
  2029. conclusion:
  2030. addq $16, %rsp
  2031. popq %rbp
  2032. retq
  2033. \end{lstlisting}
  2034. \caption{An x86 program equivalent to \code{(+ 52 (- 10))}.}
  2035. \label{fig:p1-x86}
  2036. \end{figure}
  2037. \begin{figure}[tbp]
  2038. \centering
  2039. \begin{tabular}{|r|l|} \hline
  2040. Position & Contents \\ \hline
  2041. 8(\key{\%rbp}) & return address \\
  2042. 0(\key{\%rbp}) & old \key{rbp} \\
  2043. -8(\key{\%rbp}) & variable $1$ \\
  2044. -16(\key{\%rbp}) & variable $2$ \\
  2045. \ldots & \ldots \\
  2046. 0(\key{\%rsp}) & variable $n$\\ \hline
  2047. \end{tabular}
  2048. \caption{Memory layout of a frame.}
  2049. \label{fig:frame}
  2050. \end{figure}
  2051. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  2052. control is transferred from the operating system to the \code{main}
  2053. function. The operating system issues a \code{callq main} instruction
  2054. which pushes its return address on the stack and then jumps to
  2055. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2056. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2057. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  2058. alignment (because the \code{callq} pushed the return address). The
  2059. first three instructions are the typical \emph{prelude}\index{prelude}
  2060. for a procedure. The instruction \code{pushq \%rbp} saves the base
  2061. pointer for the caller onto the stack and subtracts $8$ from the stack
  2062. pointer. The second instruction \code{movq \%rsp, \%rbp} changes the
  2063. base pointer so that it points the location of the old base
  2064. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  2065. pointer down to make enough room for storing variables. This program
  2066. needs one variable ($8$ bytes) but we round up to 16 bytes so that
  2067. \code{rsp} is 16-byte aligned and we're ready to make calls to other
  2068. functions. The last instruction of the prelude is \code{jmp start},
  2069. which transfers control to the instructions that were generated from
  2070. the Racket expression \code{(+ 52 (- 10))}.
  2071. The first instruction under the \code{start} label is
  2072. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2073. %
  2074. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  2075. %
  2076. The next instruction moves the $-10$ from variable $1$ into the
  2077. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2078. the value in \code{rax}, updating its contents to $42$.
  2079. The three instructions under the label \code{conclusion} are the
  2080. typical \emph{conclusion}\index{conclusion} of a procedure. The first
  2081. two instructions restore the \code{rsp} and \code{rbp} registers to
  2082. the state they were in at the beginning of the procedure. The
  2083. instruction \key{addq \$16, \%rsp} moves the stack pointer back to
  2084. point at the old base pointer. Then \key{popq \%rbp} returns the old
  2085. base pointer to \key{rbp} and adds $8$ to the stack pointer. The last
  2086. instruction, \key{retq}, jumps back to the procedure that called this
  2087. one and adds $8$ to the stack pointer.
  2088. The compiler needs a convenient representation for manipulating x86
  2089. programs, so we define an abstract syntax for x86 in
  2090. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  2091. \LangXInt{}. The main difference compared to the concrete syntax of
  2092. \LangXInt{} (Figure~\ref{fig:x86-int-concrete}) is that labels are not
  2093. allowed in front of every instructions. Instead instructions are
  2094. grouped into \emph{blocks}\index{block}\index{basic block} with a
  2095. label associated with every block, which is why the \key{X86Program}
  2096. struct includes an alist mapping labels to blocks. The reason for this
  2097. organization becomes apparent in Chapter~\ref{ch:Rif} when we
  2098. introduce conditional branching. The \code{Block} structure includes
  2099. an $\itm{info}$ field that is not needed for this chapter, but becomes
  2100. useful in Chapter~\ref{ch:register-allocation-Rvar}. For now, the
  2101. $\itm{info}$ field should contain an empty list. \ocaml{The \code{'binfo}
  2102. type parameter should be instantiated with \code{unit}.}
  2103. Also, regarding the
  2104. abstract syntax for \code{callq}, the \code{Callq} struct includes an
  2105. integer for representing the arity of the function, i.e., the number
  2106. of arguments, which is helpful to know during register allocation
  2107. (Chapter~\ref{ch:register-allocation-Rvar}).
  2108. \begin{ocamlx}
  2109. The OCaml code for \LangXInt{} AST, printing, and checking is
  2110. in file \texttt{X86Int.ml}. Printing is used to produce \texttt{.s} files that
  2111. can be input to the system assembler; it can also be useful for debugging.
  2112. File \texttt{utils.ml} contains functions for invoking the assembler and linker and
  2113. running the resulting executables from inside OCaml; these are invoked
  2114. from the test drivers also defined in that file.
  2115. \end{ocamlx}
  2116. \begin{figure}[tp]
  2117. \fbox{
  2118. \begin{minipage}{0.98\textwidth}
  2119. \small
  2120. \[
  2121. \begin{array}{lcl}
  2122. \Reg &::=& \allregisters{} \\
  2123. \Arg &::=& \IMM{\Int} \mid \REG{\Reg}
  2124. \mid \DEREF{\Reg}{\Int} \\
  2125. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2126. \mid \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  2127. &\mid& \UNIINSTR{\code{negq}}{\Arg}\\
  2128. &\mid& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2129. \ocaml{\mid \BININSTR{\code{movabsq}}{\Arg}{\Arg}} \\
  2130. &\mid& \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  2131. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  2132. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP} \\
  2133. \LangXInt{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2134. \end{array}
  2135. \]
  2136. \end{minipage}
  2137. }
  2138. \begin{lstlisting}[style=ocaml,frame=single]
  2139. type reg =
  2140. RSP | RBP | RAX | RBX | RCX | RDX | RSI | RDI
  2141. | R8 | R9 | R10 | R11 | R12 | R13 | R14 | R15
  2142. type label = string
  2143. type arg =
  2144. Imm of int64 (* in most cases must actually be an int32 *)
  2145. | Reg of reg
  2146. | Deref of reg*int32
  2147. | Var of string (* a pseudo-argument for ~$\LangXVar{}$~ *)
  2148. type instr =
  2149. Addq of arg*arg | Subq of arg*arg | Negq of arg
  2150. | Movq of arg*arg | Movabsq of arg*arg | Callq of label*int
  2151. | Retq | Pushq of arg | Popq of arg | Jmp of label
  2152. type 'binfo block = Block of 'binfo * instr list
  2153. type ('pinfo,'binfo) program =
  2154. Program of 'pinfo * (label * 'binfo block) list
  2155. \end{lstlisting}
  2156. \caption{The abstract syntax of \LangXInt{} \ocaml{and \LangXVar{}} assembly.}
  2157. \label{fig:x86-int-ast}
  2158. \end{figure}
  2159. \section{Planning the trip to x86 via the \LangCVar{} language}
  2160. \label{sec:plan-s0-x86}
  2161. To compile one language to another it helps to focus on the
  2162. differences between the two languages because the compiler will need
  2163. to bridge those differences. What are the differences between \LangVar{}
  2164. and x86 assembly? Here are some of the most important ones:
  2165. \begin{enumerate}
  2166. \item[(a)] x86 arithmetic instructions typically have two arguments
  2167. and update the second argument in place. In contrast, \LangVar{}
  2168. arithmetic operations take two arguments and produce a new value.
  2169. An x86 instruction may have at most one memory-accessing argument.
  2170. Furthermore, some instructions place special restrictions on their
  2171. arguments. \ocaml{For example, immediate operands are usually restricted
  2172. to fit in 32 bits (except for the \code{movabsq} instruction).}
  2173. \item[(b)] An argument of an \LangVar{} operator can be a deeply-nested
  2174. expression, whereas x86 instructions restrict their arguments to be
  2175. integers constants, registers, and memory locations.
  2176. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  2177. sequence of instructions and jumps to labeled positions, whereas in
  2178. \LangVar{} the order of evaluation is a left-to-right depth-first
  2179. traversal of the abstract syntax tree.
  2180. \item[(d)] A program in \LangVar{} can have any number of variables
  2181. whereas x86 has 16 registers and the procedure calls stack.
  2182. \item[(e)] Variables in \LangVar{} can overshadow other variables with the
  2183. same name. In x86, registers have unique names and memory locations
  2184. have unique addresses.
  2185. \end{enumerate}
  2186. We ease the challenge of compiling from \LangVar{} to x86 by breaking down
  2187. the problem into several steps, dealing with the above differences one
  2188. at a time. Each of these steps is called a \emph{pass} of the
  2189. compiler.\index{pass}\index{compiler pass}
  2190. %
  2191. This terminology comes from the way each step passes over the AST of
  2192. the program.
  2193. %
  2194. We begin by sketching how we might implement each pass, and give them
  2195. names. We then figure out an ordering of the passes and the
  2196. input/output language for each pass. The very first pass has
  2197. \LangVar{} as its input language and the last pass has \LangXInt{} as
  2198. its output language. In between we can choose whichever language is
  2199. most convenient for expressing the output of each pass, whether that
  2200. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  2201. our own design. Finally, to implement each pass we write one
  2202. recursive function per non-terminal in the grammar of the input
  2203. language of the pass. \index{intermediate language}
  2204. \begin{description}
  2205. \item[\key{select-instructions}] handles the difference between
  2206. \LangVar{} operations and x86 instructions. This pass converts each
  2207. \LangVar{} operation to a short sequence of instructions that
  2208. accomplishes the same task.
  2209. \item[\key{remove-complex-opera*}] ensures that each subexpression of
  2210. a primitive operation is a variable or integer, that is, an
  2211. \emph{atomic} expression. We refer to non-atomic expressions as
  2212. \emph{complex}. This pass introduces temporary variables to hold
  2213. the results of complex subexpressions.\index{atomic
  2214. expression}\index{complex expression}%
  2215. \footnote{The subexpressions of an operation are often called
  2216. operators and operands which explains the presence of
  2217. \code{opera*} in the name of this pass.}
  2218. \item[\key{explicate-control}] makes the execution order of the
  2219. program explicit. It convert the abstract syntax tree representation
  2220. into a control-flow graph in which each node contains a sequence of
  2221. statements and the edges between nodes say which nodes contain jumps
  2222. to other nodes.
  2223. \item[\key{assign-homes}] replaces the variables in \LangVar{} with
  2224. registers or stack locations in x86.
  2225. \item[\key{uniquify}] deals with the shadowing of variables by
  2226. renaming every variable to a unique name.
  2227. \end{description}
  2228. The next question is: in what order should we apply these passes? This
  2229. question can be challenging because it is difficult to know ahead of
  2230. time which orderings will be better (easier to implement, produce more
  2231. efficient code, etc.) so oftentimes trial-and-error is
  2232. involved. Nevertheless, we can try to plan ahead and make educated
  2233. choices regarding the ordering.
  2234. What should be the ordering of \key{explicate-control} with respect to
  2235. \key{uniquify}? The \key{uniquify} pass should come first because
  2236. \key{explicate-control} changes all the \key{let}-bound variables to
  2237. become local variables whose scope is the entire program, which would
  2238. confuse variables with the same name.
  2239. %
  2240. We place \key{remove-complex-opera*} before \key{explicate-control}
  2241. because the latter removes the \key{let} form, but it is convenient to
  2242. use \key{let} in the output of \key{remove-complex-opera*}.
  2243. %
  2244. The ordering of \key{uniquify} with respect to
  2245. \key{remove-complex-opera*} does not matter so we arbitrarily choose
  2246. \key{uniquify} to come first.
  2247. Last, we consider \key{select-instructions} and \key{assign-homes}.
  2248. These two passes are intertwined. In Chapter~\ref{ch:Rfun} we
  2249. learn that, in x86, registers are used for passing arguments to
  2250. functions and it is preferable to assign parameters to their
  2251. corresponding registers. On the other hand, by selecting instructions
  2252. first we may run into a dead end in \key{assign-homes}. Recall that
  2253. only one argument of an x86 instruction may be a memory access but
  2254. \key{assign-homes} might fail to assign even one of them to a
  2255. register.
  2256. %
  2257. A sophisticated approach is to iteratively repeat the two passes until
  2258. a solution is found. However, to reduce implementation complexity we
  2259. recommend a simpler approach in which \key{select-instructions} comes
  2260. first, followed by the \key{assign-homes}, then a third pass named
  2261. \key{patch-instructions} that uses a reserved register to fix
  2262. outstanding problems.
  2263. \begin{figure}[tbp]
  2264. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2265. \node (Rvar) at (0,2) {\large \LangVar{}};
  2266. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  2267. \node (Rvar-3) at (6,2) {\large \LangVarANF{}};
  2268. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2269. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  2270. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  2271. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  2272. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  2273. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  2274. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  2275. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvar-3);
  2276. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate-control} (Cvar-2);
  2277. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  2278. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  2279. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  2280. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  2281. \end{tikzpicture}
  2282. \caption{Diagram of the passes for compiling \LangVar{}. }
  2283. \label{fig:Rvar-passes}
  2284. \end{figure}
  2285. Figure~\ref{fig:Rvar-passes} presents the ordering of the compiler
  2286. passes and identifies the input and output language of each pass. The
  2287. last pass, \key{print-x86}, converts from the abstract syntax of
  2288. \LangXInt{} to the concrete syntax. In the following two sections
  2289. we discuss the \LangCVar{} intermediate language and the \LangXVar{}
  2290. dialect of x86. The remainder of this chapter gives hints regarding
  2291. the implementation of each of the compiler passes in
  2292. Figure~\ref{fig:Rvar-passes}.
  2293. %% The output of \key{uniquify} and \key{remove-complex-opera*}
  2294. %% are programs that are still in the \LangVar{} language, though the
  2295. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2296. %% (Section~\ref{sec:remove-complex-opera-Rvar}).
  2297. %% %
  2298. %% The output of \key{explicate-control} is in an intermediate language
  2299. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2300. %% syntax, which we introduce in the next section. The
  2301. %% \key{select-instruction} pass translates from \LangCVar{} to
  2302. %% \LangXVar{}. The \key{assign-homes} and
  2303. %% \key{patch-instructions}
  2304. %% passes input and output variants of x86 assembly.
  2305. \subsection{The \LangCVar{} Intermediate Language}
  2306. The output of \key{explicate-control} is similar to the $C$
  2307. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2308. categories for expressions and statements, so we name it \LangCVar{}. The
  2309. abstract syntax for \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  2310. (The concrete syntax for \LangCVar{} is in the Appendix,
  2311. Figure~\ref{fig:c0-concrete-syntax}. \ocaml{(This appendix is not quite accurate
  2312. for the OCaml version, but the details of the concrete syntax of
  2313. an IR like this don't matter much, since it will normally be used
  2314. only to dump out information when debugging; it won't be parsed.})
  2315. %
  2316. The \LangCVar{} language supports the same operators as \LangVar{} but
  2317. the arguments of operators are restricted to atomic
  2318. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2319. assignment statements which can be executed in sequence using the
  2320. \key{Seq} form. A sequence of statements always ends with
  2321. \key{Return}, a guarantee that is baked into the grammar rules for
  2322. \itm{tail}. The naming of this non-terminal comes from the term
  2323. \emph{tail position}\index{tail position}, which refers to an
  2324. expression that is the last one to execute within a function.
  2325. A \LangCVar{} program consists of a control-flow graph represented as
  2326. an alist mapping labels to tails \ocaml{(that is, a list of \code{(label*tail)} pairs)}.
  2327. This is more general than necessary
  2328. for the present chapter, as we do not yet introduce \key{goto} for
  2329. jumping to labels, but it saves us from having to change the syntax in
  2330. Chapter~\ref{ch:Rif}. For now there will be just one label,
  2331. \key{start}, and the whole program \ocaml{body} is its tail.
  2332. %
  2333. The $\itm{info}$ field of the \key{CProgram} form, after the
  2334. \key{explicate-control} pass, contains a mapping from the symbol
  2335. \key{locals} to a list of variables, that is, a list of all the
  2336. variables used in the program. \ocaml{It is represented as a \code{unit Env.t},
  2337. a kind of degenerate map that effectively acts like a set.}
  2338. At the start of the program, these
  2339. variables are uninitialized; they become initialized on their first
  2340. assignment.
  2341. \begin{figure}[tbp]
  2342. \fbox{
  2343. \begin{minipage}{0.96\textwidth}
  2344. \[
  2345. \begin{array}{lcl}
  2346. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  2347. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  2348. &\mid& \ADD{\Atm}{\Atm}\\
  2349. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2350. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  2351. \LangCVar{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2352. \end{array}
  2353. \]
  2354. \end{minipage}
  2355. }
  2356. \begin{lstlisting}[style=ocaml,frame=single]
  2357. type var = string
  2358. type label = string
  2359. type atm =
  2360. Int of int64
  2361. | Var of var
  2362. type exp =
  2363. Atom of atm
  2364. | Prim of primop * atm list
  2365. type stmt =
  2366. Assign of var * exp
  2367. type tail =
  2368. Return of exp
  2369. | Seq of stmt*tail
  2370. type 'pinfo program = Program of 'pinfo * (label*tail) list
  2371. \end{lstlisting}
  2372. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2373. \label{fig:c0-syntax}
  2374. \end{figure}
  2375. The definitional interpreter for \LangCVar{} is in the support code,
  2376. in the file \code{interp-Cvar.rkt}.
  2377. \begin{ocamlx}
  2378. The OCaml code for \LangCVar{} AST, checking, printing (for debug purposes),
  2379. and interpretation is in file \texttt{CVar.ml}.
  2380. \end{ocamlx}
  2381. \subsection{The \LangXVar{} dialect}
  2382. The \LangXVar{} language is the output of the pass
  2383. \key{select-instructions}. It extends \LangXInt{} with an unbounded
  2384. number of program-scope variables and removes the restrictions
  2385. regarding instruction arguments.
  2386. \begin{ocamlx}
  2387. For simplicity, we treat \LangXInt{} and \LangXVar{} as the same
  2388. language, defined in \texttt{X86Int.ml}. In particular, we allow \code{Var}
  2389. as one of the possible forms for an instruction argument (\code{arg}).
  2390. We provide two different check routines.
  2391. \begin{itemize}
  2392. \item \code{CheckLabels.check\_program}
  2393. just checks that all label
  2394. declarations are unique and that all jump targets are defined; this
  2395. is suitable for checking the code produced from the \key{select-instructions}
  2396. pass, which will use \code{Var} arguments freely.
  2397. \item
  2398. \code{CheckArgs.check\_program} checks that all arguments are legal for the
  2399. actual X86-64 machine (in particular, that they are not \code{Var} arguments);
  2400. this is suitable for checking the output of the \key{patch-instr} pass.
  2401. \end{itemize}
  2402. \end{ocamlx}
  2403. \section{Uniquify Variables}
  2404. \label{sec:uniquify-Rvar}
  2405. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2406. programs in which every \key{let} binds a unique variable name. For
  2407. example, the \code{uniquify} pass should translate the program on the
  2408. left into the program on the right. \\
  2409. \begin{tabular}{lll}
  2410. \begin{minipage}{0.4\textwidth}
  2411. \begin{lstlisting}
  2412. (let ([x 32])
  2413. (+ (let ([x 10]) x) x))
  2414. \end{lstlisting}
  2415. \end{minipage}
  2416. &
  2417. $\Rightarrow$
  2418. &
  2419. \begin{minipage}{0.4\textwidth}
  2420. \begin{lstlisting}
  2421. (let ([x.1 32])
  2422. (+ (let ([x.2 10]) x.2) x.1))
  2423. \end{lstlisting}
  2424. \end{minipage}
  2425. \end{tabular} \\
  2426. %
  2427. \begin{tabular}{lll}
  2428. \begin{minipage}{0.4\textwidth}
  2429. \begin{lstlisting}[style=ocaml]
  2430. (let x 32
  2431. (+ (let x 10 x) x))
  2432. \end{lstlisting}
  2433. \end{minipage}
  2434. &
  2435. \ocaml{$\Rightarrow$}
  2436. &
  2437. \begin{minipage}{0.4\textwidth}
  2438. \begin{lstlisting}[style=ocaml]
  2439. (let x.1 32
  2440. (+ (let x.2 10 x.2) x.1))
  2441. \end{lstlisting}
  2442. \end{minipage}
  2443. \end{tabular} \\
  2444. %
  2445. The following is another example translation, this time of a program
  2446. with a \key{let} nested inside the initializing expression of another
  2447. \key{let}.\\
  2448. \begin{tabular}{lll}
  2449. \begin{minipage}{0.4\textwidth}
  2450. \begin{lstlisting}
  2451. (let ([x (let ([x 4])
  2452. (+ x 1))])
  2453. (+ x 2))
  2454. \end{lstlisting}
  2455. \end{minipage}
  2456. &
  2457. $\Rightarrow$
  2458. &
  2459. \begin{minipage}{0.4\textwidth}
  2460. \begin{lstlisting}
  2461. (let ([x.2 (let ([x.1 4])
  2462. (+ x.1 1))])
  2463. (+ x.2 2))
  2464. \end{lstlisting}
  2465. \end{minipage}
  2466. \end{tabular}
  2467. \ocaml{You can transliterate examples like this for yourself by now...}
  2468. We recommend implementing \code{uniquify} by creating a structurally
  2469. recursive function named \code{uniquify-exp} that mostly just copies
  2470. an expression. However, when encountering a \key{let}, it should
  2471. generate a unique name for the variable and associate the old name
  2472. with the new name in an alist \ocaml{(Ocaml: \key{Env})}.\footnote{The Racket function
  2473. \code{gensym} is handy for generating unique variable names. \ocaml{There is a similar
  2474. function defined in \texttt{utils.ml}.}} The
  2475. \code{uniquify-exp} function needs to access this alist \ocaml{(\key{Env})} when it gets
  2476. to a variable reference, so we add a parameter to \code{uniquify-exp}
  2477. for the alist \ocaml{(\key{Env})} .
  2478. The skeleton of the \code{uniquify-exp} function is shown in
  2479. Figure~\ref{fig:uniquify-Rvar}. The function is curried so that it is
  2480. convenient to partially apply it to an alist \ocaml{(\key{Env})} and then apply it to
  2481. different expressions, as in the last case for primitive operations in
  2482. Figure~\ref{fig:uniquify-Rvar}. The
  2483. %
  2484. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2485. %
  2486. form of Racket is useful for transforming each element of a list to
  2487. produce a new list.\index{for/list}
  2488. \ocaml{The \code{List.map} function is similar.}
  2489. \ocaml{In addition to writing the \code{uniquify} transformation, it is worthwhile
  2490. to write a \emph{checker} to make sure that the result obeys any invariants we
  2491. expect to hold. (Sometimes these invariants are baked into the abstract syntax
  2492. of the target, but that's not the case here.) Our checker should re-traverse the
  2493. result AST and make sure that no identifier is bound more than once. It should also
  2494. re-run the \LangVar{} checker defined in module \code{RVar} to make sure that
  2495. all variables uses are in the scope of a binding (something we might easily have
  2496. messed up) and that we have not accidentally introduced a primop arity error (much
  2497. less likely, but still possible).
  2498. }
  2499. \begin{exercise}
  2500. \normalfont % I don't like the italics for exercises. -Jeremy
  2501. Complete the \code{uniquify} pass by filling in the blanks in
  2502. Figure~\ref{fig:uniquify-Rvar}, that is, implement the cases for
  2503. variables and for the \key{let} form in the file \code{compiler.rkt}
  2504. in the support code. \ocaml{This exercise is done for you, in the
  2505. \code{Uniquify} module of file \code{Chapter2.ml}.}
  2506. \end{exercise}
  2507. \begin{figure}[tbp]
  2508. \begin{lstlisting}
  2509. (define (uniquify-exp env)
  2510. (lambda (e)
  2511. (match e
  2512. [(Var x) ___]
  2513. [(Int n) (Int n)]
  2514. [(Let x e body) ___]
  2515. [(Prim op es)
  2516. (Prim op (for/list ([e es]) ((uniquify-exp env) e)))])))
  2517. (define (uniquify p)
  2518. (match p
  2519. [(Program '() e) (Program '() ((uniquify-exp '()) e))]))
  2520. \end{lstlisting}
  2521. \caption{Skeleton for the \key{uniquify} pass.}
  2522. \label{fig:uniquify-Rvar}
  2523. \end{figure}
  2524. \begin{exercise}
  2525. \normalfont % I don't like the italics for exercises. -Jeremy
  2526. Create five \LangVar{} programs that exercise the most interesting
  2527. parts of the \key{uniquify} pass, that is, the programs should include
  2528. \key{let} forms, variables, and variables that overshadow each other.
  2529. The five programs should be placed in the subdirectory named
  2530. \key{tests} and the file names should start with \code{var\_test\_}
  2531. followed by a unique integer and end with the file extension
  2532. \key{.rkt}. \ocaml{OCaml: use extension \key{.r}.}
  2533. %
  2534. The \key{run-tests.rkt} script in the support code \ocaml{(\key{test\_files}
  2535. function in \code{Chapter2.ml}, which is invoked by the \code{driver}
  2536. executable)} checks whether the
  2537. output programs produce the same result as the input programs. The
  2538. script uses the \key{interp-tests} function
  2539. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} \ocaml{(\key{test\_files}
  2540. function from \code{utils.ml})} to test
  2541. your \key{uniquify} pass on the example programs. The \code{passes}
  2542. parameter of \key{interp-tests} is a list that should have one entry
  2543. for each pass in your compiler. For now, define \code{passes} to
  2544. contain just one entry for \code{uniquify} \ocaml{(plus the fixed initial pass)} as follows.
  2545. \begin{lstlisting}
  2546. (define passes
  2547. (list (list "uniquify" uniquify interp-Rvar type-check-Rvar)))
  2548. \end{lstlisting}
  2549. \begin{ocamlx}
  2550. \begin{lstlisting}{style=ocaml}
  2551. let passes = PCons(initial_pass,
  2552. PCons(Uniquify.pass,PNil))
  2553. \end{lstlisting}
  2554. \end{ocamlx}
  2555. Run the \key{run-tests.rkt} script in the support code
  2556. \ocaml{(the \key{driver} executable)} to check
  2557. whether the output programs produce the same result as the input
  2558. programs.
  2559. \end{exercise}
  2560. \section{Remove Complex Operands}
  2561. \label{sec:remove-complex-opera-Rvar}
  2562. The \code{remove-complex-opera*} pass compiles \LangVar{} programs
  2563. into a restricted form in which the arguments of operations are atomic
  2564. expressions. Put another way, this pass removes complex
  2565. operands\index{complex operand}, such as the expression \code{(- 10)}
  2566. in the program below. This is accomplished by introducing a new
  2567. \key{let}-bound variable, binding the complex operand to the new
  2568. variable, and then using the new variable in place of the complex
  2569. operand, as shown in the output of \code{remove-complex-opera*} on the
  2570. right.\\
  2571. \begin{tabular}{lll}
  2572. \begin{minipage}{0.4\textwidth}
  2573. % var_test_19.rkt
  2574. \begin{lstlisting}
  2575. (+ 52 (- 10))
  2576. \end{lstlisting}
  2577. \end{minipage}
  2578. &
  2579. $\Rightarrow$
  2580. &
  2581. \begin{minipage}{0.4\textwidth}
  2582. \begin{lstlisting}
  2583. (let ([tmp.1 (- 10)])
  2584. (+ 52 tmp.1))
  2585. \end{lstlisting}
  2586. \end{minipage}
  2587. \end{tabular}
  2588. \begin{ocamlx}
  2589. We suggest generating temporary names that begin with a back-tick (\verb'`')
  2590. since these are illegal as S-expression symbols, and so cannot conflict with existing
  2591. user-defined names.
  2592. \end{ocamlx}
  2593. \begin{figure}[tp]
  2594. \centering
  2595. \fbox{
  2596. \begin{minipage}{0.96\textwidth}
  2597. \[
  2598. \begin{array}{rcl}
  2599. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  2600. \Exp &::=& \Atm \mid \READ{} \\
  2601. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  2602. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  2603. R^{\dagger}_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  2604. \end{array}
  2605. \]
  2606. \end{minipage}
  2607. }
  2608. \caption{\LangVarANF{} is \LangVar{} in administrative normal form (ANF).}
  2609. \label{fig:r1-anf-syntax}
  2610. \end{figure}
  2611. Figure~\ref{fig:r1-anf-syntax} presents the grammar for the output of
  2612. this pass, the language \LangVarANF{}. The only difference is that
  2613. operator arguments are restricted to be atomic expressions that are
  2614. defined by the \Atm{} non-terminal. In particular, integer constants
  2615. and variables are atomic. In the literature, restricting arguments to
  2616. be atomic expressions is called \emph{administrative normal form}, or
  2617. ANF for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2618. \index{administrative normal form} \index{ANF}
  2619. \ocaml{Actually, ANF
  2620. as defined in~\citep{Flanagan:1993cg}
  2621. refers to a more restricted form in which the defining expressions of
  2622. \code{let}s cannot themselves contain \code{lets}s. This essentially
  2623. corresponds to the \LangCVar{} language.}
  2624. We recommend implementing this pass with two mutually recursive
  2625. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  2626. \code{rco-atom} to subexpressions that need to become atomic and to
  2627. apply \code{rco-exp} to subexpressions that do not. Both functions
  2628. take an \LangVar{} expression as input. The \code{rco-exp} function
  2629. returns an expression. The \code{rco-atom} function returns two
  2630. things: an atomic expression and alist \ocaml{(i.e. list of pairs)} mapping temporary variables to
  2631. complex subexpressions. You can return multiple things from a function
  2632. using Racket's \key{values} form and you can receive multiple things
  2633. from a function call using the \key{define-values} form. If you are
  2634. not familiar with these features, review the Racket documentation.
  2635. Also, the
  2636. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  2637. form is useful for applying a function to each element of a list, in
  2638. the case where the function returns multiple values.
  2639. \index{for/lists}
  2640. \ocaml{OCaml: You can return multiple things from a function using a tuple
  2641. and binding the return value to a tuple pattern. Again, the \code{List.map}
  2642. function is handy.}
  2643. Returning to the example program \code{(+ 52 (- 10))}, the
  2644. subexpression \code{(- 10)} should be processed using the
  2645. \code{rco-atom} function because it is an argument of the \code{+} and
  2646. therefore needs to become atomic. The output of \code{rco-atom}
  2647. applied to \code{(- 10)} is as follows.
  2648. \begin{tabular}{lll}
  2649. \begin{minipage}{0.4\textwidth}
  2650. \begin{lstlisting}
  2651. (- 10)
  2652. \end{lstlisting}
  2653. \end{minipage}
  2654. &
  2655. $\Rightarrow$
  2656. &
  2657. \begin{minipage}{0.4\textwidth}
  2658. \begin{lstlisting}
  2659. tmp.1
  2660. ((tmp.1 . (- 10)))
  2661. \end{lstlisting}
  2662. \end{minipage}
  2663. \end{tabular}
  2664. Take special care of programs such as the following one that binds a
  2665. variable to an atomic expression. You should leave such variable
  2666. bindings unchanged, as shown in to the program on the right \\
  2667. \begin{tabular}{lll}
  2668. \begin{minipage}{0.4\textwidth}
  2669. % var_test_20.rkt
  2670. \begin{lstlisting}
  2671. (let ([a 42])
  2672. (let ([b a])
  2673. b))
  2674. \end{lstlisting}
  2675. \end{minipage}
  2676. &
  2677. $\Rightarrow$
  2678. &
  2679. \begin{minipage}{0.4\textwidth}
  2680. \begin{lstlisting}
  2681. (let ([a 42])
  2682. (let ([b a])
  2683. b))
  2684. \end{lstlisting}
  2685. \end{minipage}
  2686. \end{tabular} \\
  2687. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  2688. produce the following output with unnecessary temporary variables.\\
  2689. \begin{minipage}{0.4\textwidth}
  2690. \begin{lstlisting}
  2691. (let ([tmp.1 42])
  2692. (let ([a tmp.1])
  2693. (let ([tmp.2 a])
  2694. (let ([b tmp.2])
  2695. b))))
  2696. \end{lstlisting}
  2697. \end{minipage}
  2698. \begin{exercise}\normalfont
  2699. %
  2700. Implement the \code{remove-complex-opera*} function in
  2701. \code{compiler.rkt}. \ocaml{Fill in the RemoveComplexOperations submodule in \code{Chapter2.ml}.
  2702. Be sure to include a checker that re-traverses the target AST to make sure that
  2703. all primop arguments are indeed now atomic, and that we haven't broken any of the
  2704. other invariants we expect to hold of \LangInt{} programs at this point.
  2705. Fill in the {\tt pass} definition appropriately.
  2706. }
  2707. %
  2708. Create three new \LangInt{} programs that exercise the interesting
  2709. code in the \code{remove-complex-opera*} pass (Following the same file
  2710. name guidelines as before.).
  2711. %
  2712. In the \code{run-tests.rkt} script, add the following entry to the
  2713. list of \code{passes} and then run the script to test your compiler.
  2714. \begin{lstlisting}
  2715. (list "remove-complex" remove-complex-opera* interp-Rvar type-check-Rvar)
  2716. \end{lstlisting}
  2717. \begin{ocamlx}
  2718. In \code{Chapter2.ml}, add an additional entry to the {\tt passes} list:
  2719. \begin{lstlisting}[style=ocaml]
  2720. let passes =
  2721. PCons(initial_pass,
  2722. PCons(Uniquify.pass,
  2723. PCons(RemoveComplexOperands.pass, PNil)))
  2724. \end{lstlisting}
  2725. \end{ocamlx}
  2726. While debugging your compiler, it is often useful to see the
  2727. intermediate programs that are output from each pass. To print the
  2728. intermediate programs, place the following before the call to
  2729. \code{interp-tests} in \code{run-tests.rkt}.
  2730. \begin{lstlisting}
  2731. (debug-level 1)
  2732. \end{lstlisting}
  2733. \begin{ocamlx}
  2734. Adjust the assignment near the bottom of \code{Chapter2.ml}:
  2735. \begin{lstlisting}[style=ocaml]
  2736. let _ = Util.debug_level := 2
  2737. \end{lstlisting}
  2738. \end{ocamlx}
  2739. \end{exercise}
  2740. \section{Explicate Control}
  2741. \label{sec:explicate-control-Rvar}
  2742. The \code{explicate-control} pass compiles \LangVar{} programs into \LangCVar{}
  2743. programs that make the order of execution explicit in their
  2744. syntax. For now this amounts to flattening \key{let} constructs into a
  2745. sequence of assignment statements. For example, consider the following
  2746. \LangVar{} program.\\
  2747. % var_test_11.rkt
  2748. \begin{minipage}{0.96\textwidth}
  2749. \begin{lstlisting}
  2750. (let ([y (let ([x 20])
  2751. (+ x (let ([x 22]) x)))])
  2752. y)
  2753. \end{lstlisting}
  2754. \end{minipage}\\
  2755. %
  2756. The output of the previous pass and of \code{explicate-control} is
  2757. shown below. Recall that the right-hand-side of a \key{let} executes
  2758. before its body, so the order of evaluation for this program is to
  2759. assign \code{20} to \code{x.1}, \code{22} to \code{x.2}, and
  2760. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  2761. output of \code{explicate-control} makes this ordering explicit.\\
  2762. \begin{tabular}{lll}
  2763. \begin{minipage}{0.4\textwidth}
  2764. \begin{lstlisting}
  2765. (let ([y (let ([x.1 20])
  2766. (let ([x.2 22])
  2767. (+ x.1 x.2)))])
  2768. y)
  2769. \end{lstlisting}
  2770. \end{minipage}
  2771. &
  2772. $\Rightarrow$
  2773. &
  2774. \begin{minipage}{0.4\textwidth}
  2775. \begin{lstlisting}[language=C]
  2776. start:
  2777. x.1 = 20;
  2778. x.2 = 22;
  2779. y = (+ x.1 x.2);
  2780. return y;
  2781. \end{lstlisting}
  2782. \end{minipage}
  2783. \end{tabular}
  2784. %
  2785. \begin{figure}[tbp]
  2786. \begin{lstlisting}
  2787. (define (explicate-tail e)
  2788. (match e
  2789. [(Var x) ___]
  2790. [(Int n) (Return (Int n))]
  2791. [(Let x rhs body) ___]
  2792. [(Prim op es) ___]
  2793. [else (error "explicate-tail unhandled case" e)]))
  2794. (define (explicate-assign e x cont)
  2795. (match e
  2796. [(Var x) ___]
  2797. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  2798. [(Let y rhs body) ___]
  2799. [(Prim op es) ___]
  2800. [else (error "explicate-assign unhandled case" e)]))
  2801. (define (explicate-control p)
  2802. (match p
  2803. [(Program info body) ___]))
  2804. \end{lstlisting}
  2805. \caption{Skeleton for the \key{explicate-control} pass.}
  2806. \label{fig:explicate-control-Rvar}
  2807. \end{figure}
  2808. The organization of this pass depends on the notion of tail position
  2809. that we have alluded to earlier. Formally, \emph{tail
  2810. position}\index{tail position} in the context of \LangVar{} is
  2811. defined recursively by the following two rules.
  2812. \begin{enumerate}
  2813. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  2814. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  2815. \end{enumerate}
  2816. We recommend implementing \code{explicate-control} using two mutually
  2817. recursive functions, \code{explicate-tail} and
  2818. \code{explicate-assign}, as suggested in the skeleton code in
  2819. Figure~\ref{fig:explicate-control-Rvar}. The \code{explicate-tail}
  2820. function should be applied to expressions in tail position whereas the
  2821. \code{explicate-assign} should be applied to expressions that occur on
  2822. the right-hand-side of a \key{let}.
  2823. %
  2824. The \code{explicate-tail} function takes an \Exp{} in \LangVar{} as
  2825. input and produces a \Tail{} in \LangCVar{} (see
  2826. Figure~\ref{fig:c0-syntax}).
  2827. %
  2828. The \code{explicate-assign} function takes an \Exp{} in \LangVar{},
  2829. the variable that it is to be assigned to, and a \Tail{} in
  2830. \LangCVar{} for the code that will come after the assignment. The
  2831. \code{explicate-assign} function returns a $\Tail$ in \LangCVar{}.
  2832. The \code{explicate-assign} function is in accumulator-passing style
  2833. in that the \code{cont} parameter is used for accumulating the
  2834. output. The reader might be tempted to instead organize
  2835. \code{explicate-assign} in a more direct fashion, without the
  2836. \code{cont} parameter and perhaps using \code{append} to combine
  2837. statements. We warn against that alternative because the
  2838. accumulator-passing style is key to how we generate high-quality code
  2839. for conditional expressions in Chapter~\ref{ch:Rif}.
  2840. \begin{ocamlx}
  2841. Don't take this advice too seriously. Organize things in the cleanest way you
  2842. can find; it will always be possible to adjust your approach in later chapters.
  2843. \end{ocamlx}
  2844. \begin{exercise}\normalfont
  2845. %
  2846. Implement the \code{explicate-control} function in
  2847. \code{compiler.rkt}. \ocaml{Fill in the \code{ExplicateControl} submodule
  2848. of \code{Chapter2.ml} by implementing the \code{do\_program} function.
  2849. The checking field of this pass should invoke \code{CVar.check\_program},
  2850. which checks that the target code is properly bound (and also fills in
  2851. some information about the set of bound variables in the \code{'pinfo}
  2852. field of the program that will be useful in a later pass).}
  2853. %
  2854. Create three new \LangInt{} programs that
  2855. exercise the code in \code{explicate-control}.
  2856. %
  2857. In the \code{run-tests.rkt} script, add the following entry to the
  2858. list of \code{passes} and then run the script to test your compiler.
  2859. \begin{lstlisting}
  2860. (list "explicate control" explicate-control interp-Cvar type-check-Cvar)
  2861. \end{lstlisting}
  2862. \ocaml{Make the analogous change to the \code{passes} list in \code{Chapter2.ml}.}
  2863. \end{exercise}
  2864. \section{Select Instructions}
  2865. \label{sec:select-Rvar}
  2866. \index{instruction selection}
  2867. In the \code{select-instructions} pass we begin the work of
  2868. translating from \LangCVar{} to \LangXVar{}. The target language of
  2869. this pass is a variant of x86 that still uses variables, so we add an
  2870. AST node of the form $\VAR{\itm{var}}$ to the \Arg{} non-terminal of
  2871. the \LangXInt{} abstract syntax (Figure~\ref{fig:x86-int-ast}). \ocaml{Recall that
  2872. we use the same module to define \LangXInt{} and \LangXVar{}.}
  2873. We recommend implementing the \code{select-instructions} with
  2874. three auxiliary functions, one for each of the non-terminals of
  2875. \LangCVar{}: $\Atm$, $\Stmt$, and $\Tail$.
  2876. The cases for $\Atm$ are straightforward, variables stay
  2877. the same and integer constants are changed to immediates:
  2878. $\INT{n}$ changes to $\IMM{n}$.
  2879. Next we consider the cases for $\Stmt$, starting with arithmetic
  2880. operations. For example, consider the addition operation. We can use
  2881. the \key{addq} instruction, but it performs an in-place update. So we
  2882. could move $\itm{arg}_1$ into the left-hand side \itm{var} and then
  2883. add $\itm{arg}_2$ to \itm{var}. \\
  2884. \begin{tabular}{lll}
  2885. \begin{minipage}{0.4\textwidth}
  2886. \begin{lstlisting}
  2887. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{arg}_2$|);
  2888. \end{lstlisting}
  2889. \end{minipage}
  2890. &
  2891. $\Rightarrow$
  2892. &
  2893. \begin{minipage}{0.4\textwidth}
  2894. \begin{lstlisting}
  2895. movq |$\itm{arg}_1$|, |$\itm{var}$|
  2896. addq |$\itm{arg}_2$|, |$\itm{var}$|
  2897. \end{lstlisting}
  2898. \end{minipage}
  2899. \end{tabular} \\
  2900. %
  2901. There are also cases that require special care to avoid generating
  2902. needlessly complicated code. For example, if one of the arguments of
  2903. the addition is the same variable as the left-hand side of the
  2904. assignment, then there is no need for the extra move instruction. The
  2905. assignment statement can be translated into a single \key{addq}
  2906. instruction as follows.\\
  2907. \begin{tabular}{lll}
  2908. \begin{minipage}{0.4\textwidth}
  2909. \begin{lstlisting}
  2910. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{var}$|);
  2911. \end{lstlisting}
  2912. \end{minipage}
  2913. &
  2914. $\Rightarrow$
  2915. &
  2916. \begin{minipage}{0.4\textwidth}
  2917. \begin{lstlisting}
  2918. addq |$\itm{arg}_1$|, |$\itm{var}$|
  2919. \end{lstlisting}
  2920. \end{minipage}
  2921. \end{tabular}
  2922. The \key{read} operation does not have a direct counterpart in x86
  2923. assembly, so we provide this functionality with the function
  2924. \code{read\_int} in the file \code{runtime.c}, written in
  2925. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  2926. functionality in this file as the \emph{runtime system}\index{runtime
  2927. system}, or simply the \emph{runtime} for short. When compiling your
  2928. generated x86 assembly code, you need to compile \code{runtime.c} to
  2929. \code{runtime.o} (an ``object file'', using \code{gcc} option
  2930. \code{-c}) and link it into the executable. For our purposes of code
  2931. generation, all you need to do is translate an assignment of
  2932. \key{read} into a call to the \code{read\_int} function followed by a
  2933. move from \code{rax} to the left-hand-side variable. (Recall that the
  2934. return value of a function goes into \code{rax}.) \\
  2935. \begin{tabular}{lll}
  2936. \begin{minipage}{0.3\textwidth}
  2937. \begin{lstlisting}
  2938. |$\itm{var}$| = (read);
  2939. \end{lstlisting}
  2940. \end{minipage}
  2941. &
  2942. $\Rightarrow$
  2943. &
  2944. \begin{minipage}{0.3\textwidth}
  2945. \begin{lstlisting}
  2946. callq read_int
  2947. movq %rax, |$\itm{var}$|
  2948. \end{lstlisting}
  2949. \end{minipage}
  2950. \end{tabular}
  2951. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  2952. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  2953. assignment to the \key{rax} register followed by a jump to the
  2954. conclusion of the program (so the conclusion needs to be labeled).
  2955. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  2956. recursively and then append the resulting instructions.
  2957. \begin{exercise}
  2958. \normalfont Implement the \key{select-instructions} pass in
  2959. \code{compiler.rkt}. \ocaml{Fill out the \code{SelectInstructions} submodule
  2960. of \code{Chapter2.ml}. The checking field of this pass should invoke
  2961. \code{X86Int.CheckLabels.check\_program}, passing a list of externally
  2962. defined labels (just \code{["read\_int"]}).}
  2963. Create three new example programs that are
  2964. designed to exercise all of the interesting cases in this pass.
  2965. %
  2966. In the \code{run-tests.rkt} script, add the following entry to the
  2967. list of \code{passes} and then run the script to test your compiler.
  2968. \begin{lstlisting}
  2969. (list "instruction selection" select-instructions interp-pseudo-x86-0)
  2970. \end{lstlisting}
  2971. \ocaml{Make the analogous change to the \code{passes} list in \code{Chapter2.ml}.}
  2972. \end{exercise}
  2973. \section{Assign Homes}
  2974. \label{sec:assign-Rvar}
  2975. The \key{assign-homes} pass compiles \LangXVar{} programs to
  2976. \LangXVar{} programs that no longer use program variables.
  2977. Thus, the \key{assign-homes} pass is responsible for placing all of
  2978. the program variables in registers or on the stack. For runtime
  2979. efficiency, it is better to place variables in registers, but as there
  2980. are only 16 registers, some programs must necessarily resort to
  2981. placing some variables on the stack. In this chapter we focus on the
  2982. mechanics of placing variables on the stack. We study an algorithm for
  2983. placing variables in registers in
  2984. Chapter~\ref{ch:register-allocation-Rvar}.
  2985. Consider again the following \LangVar{} program from
  2986. Section~\ref{sec:remove-complex-opera-Rvar}.
  2987. % var_test_20.rkt
  2988. \begin{lstlisting}
  2989. (let ([a 42])
  2990. (let ([b a])
  2991. b))
  2992. \end{lstlisting}
  2993. The output of \code{select-instructions} is shown on the left and the
  2994. output of \code{assign-homes} on the right. In this example, we
  2995. assign variable \code{a} to stack location \code{-8(\%rbp)} and
  2996. variable \code{b} to location \code{-16(\%rbp)}.\\
  2997. \begin{tabular}{l}
  2998. \begin{minipage}{0.4\textwidth}
  2999. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3000. locals-types:
  3001. a : Integer, b : Integer
  3002. start:
  3003. movq $42, a
  3004. movq a, b
  3005. movq b, %rax
  3006. jmp conclusion
  3007. \end{lstlisting}
  3008. \end{minipage}
  3009. {$\Rightarrow$}
  3010. \begin{minipage}{0.4\textwidth}
  3011. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3012. stack-space: 16
  3013. start:
  3014. movq $42, -8(%rbp)
  3015. movq -8(%rbp), -16(%rbp)
  3016. movq -16(%rbp), %rax
  3017. jmp conclusion
  3018. \end{lstlisting}
  3019. \end{minipage}
  3020. \end{tabular}
  3021. The \code{locals-types} entry in the $\itm{info}$ of the
  3022. \code{X86Program} node is an alist mapping all the variables in the
  3023. program to their types (for now just \code{Integer}). The
  3024. \code{assign-homes} pass should replace all uses of those variables
  3025. with stack locations. As an aside, the \code{locals-types} entry is
  3026. computed by \code{type-check-Cvar} in the support code, which installs
  3027. it in the $\itm{info}$ field of the \code{CProgram} node, which should
  3028. be propagated to the \code{X86Program} node.
  3029. \ocaml{The locals sets is represented as a \code{unit Env.t}.}
  3030. In the process of assigning variables to stack locations, it is
  3031. convenient for you to compute and store the size of the frame (in
  3032. bytes) in the $\itm{info}$ field of the \key{X86Program} node, with
  3033. the key \code{stack-space}, which is needed later to generate the
  3034. conclusion of the \code{main} procedure. The x86-64 standard requires
  3035. the frame size to be a multiple of 16 bytes.\index{frame}
  3036. \ocaml{The \code{'pinfo} parameter should be instantiated with an \code{int}
  3037. representing the frame size.}
  3038. \begin{exercise}\normalfont
  3039. Implement the \key{assign-homes} pass in \code{compiler.rkt}, defining
  3040. auxiliary functions for the non-terminals \Arg{}, \Instr{}, and
  3041. \Block{}. \ocaml{Fill in the definition of submodule \code{AssignHomes}.}
  3042. We recommend that the auxiliary functions take an extra
  3043. parameter that is an alist \ocaml{(\code{arg Env.t})} mapping variable names to homes (stack
  3044. locations for now). \ocaml{Use the same checker as in the previous pass.}
  3045. %
  3046. In the \code{run-tests.rkt} script, add the following entry to the
  3047. list of \code{passes} and then run the script to test your compiler.
  3048. \begin{lstlisting}
  3049. (list "assign homes" assign-homes interp-x86-0)
  3050. \end{lstlisting}
  3051. \ocaml{Make the analogous change to the \code{passes} list in \code{Chapter2.ml}.}
  3052. \end{exercise}
  3053. \section{Patch Instructions}
  3054. \label{sec:patch-s0}
  3055. The \code{patch-instructions} pass compiles from \LangXVar{} to
  3056. \LangXInt{} by making sure that each instruction adheres to the
  3057. restriction that at most one argument of an instruction may be a
  3058. memory reference. \ocaml{It also ensures that no immediate operand
  3059. to an ordinary instruction exceeds 32 bits, by introducing \code{movabsq}
  3060. instructions as needed. \code{movabsq} is the sole instruction that
  3061. allows a 64-bit immediate source operand; its destination must be a register.}
  3062. We return to the following example.
  3063. % var_test_20.rkt
  3064. \begin{lstlisting}
  3065. (let ([a 42])
  3066. (let ([b a])
  3067. b))
  3068. \end{lstlisting}
  3069. The \key{assign-homes} pass produces the following output
  3070. for this program. \\
  3071. \begin{minipage}{0.5\textwidth}
  3072. \begin{lstlisting}
  3073. stack-space: 16
  3074. start:
  3075. movq $42, -8(%rbp)
  3076. movq -8(%rbp), -16(%rbp)
  3077. movq -16(%rbp), %rax
  3078. jmp conclusion
  3079. \end{lstlisting}
  3080. \end{minipage}\\
  3081. The second \key{movq} instruction is problematic because both
  3082. arguments are stack locations. We suggest fixing this problem by
  3083. moving from the source location to the register \key{rax} and then
  3084. from \key{rax} to the destination location, as follows.
  3085. \begin{lstlisting}
  3086. movq -8(%rbp), %rax
  3087. movq %rax, -16(%rbp)
  3088. \end{lstlisting}
  3089. \begin{exercise}
  3090. \normalfont Implement the \key{patch-instructions} pass in
  3091. \code{compiler.rkt}. \ocaml{This task has been done for you, in the \code{PatchInstructions} submodule
  3092. of \code{Chapter2}.}
  3093. Create three new example programs that are
  3094. designed to exercise all of the interesting cases in this pass.
  3095. %
  3096. In the \code{run-tests.rkt} script, add the following entry to the
  3097. list of \code{passes} and then run the script to test your compiler.
  3098. \begin{lstlisting}
  3099. (list "patch instructions" patch-instructions interp-x86-0)
  3100. \end{lstlisting}
  3101. \end{exercise}
  3102. \section{Print x86}
  3103. \label{sec:print-x86}
  3104. The last step of the compiler from \LangVar{} to x86 is to convert the
  3105. \LangXInt{} AST (defined in Figure~\ref{fig:x86-int-ast}) to the
  3106. string representation (defined in
  3107. Figure~\ref{fig:x86-int-concrete}). The Racket \key{format} and
  3108. \key{string-append} functions are useful in this regard. \ocaml{The \code{Printf}
  3109. library is useful here.} The main work
  3110. that this step needs to perform is to create the \key{main} function
  3111. and the standard instructions for its prelude and conclusion, as shown
  3112. in Figure~\ref{fig:p1-x86} of Section~\ref{sec:x86}. You will need to
  3113. know the amount of space needed for the stack frame, which you can
  3114. obtain from the \code{stack-space} entry in the $\itm{info}$ field of
  3115. the \key{X86Program} node.
  3116. When running on Mac OS X, you compiler should prefix an underscore to
  3117. labels like \key{main}. The Racket call \code{(system-type 'os)} is
  3118. useful for determining which operating system the compiler is running
  3119. on. It returns \code{'macosx}, \code{'unix}, or \code{'windows}.
  3120. \ocaml{There is a similar utility function \code{get\_ostype}
  3121. provided in the \texttt{utils.ml} module.}
  3122. \begin{exercise}\normalfont
  3123. %
  3124. Implement the \key{print-x86} pass in \code{compiler.rkt}.
  3125. \ocaml{This task has been done for you; the relevant printing
  3126. code is in module \code{X86Int}.}
  3127. %
  3128. In the \code{run-tests.rkt} script, add the following entry to the
  3129. list of \code{passes} and then run the script to test your compiler.
  3130. \begin{lstlisting}
  3131. (list "print x86" print-x86 #f)
  3132. \end{lstlisting}
  3133. %
  3134. Uncomment the call to the \key{compiler-tests} function
  3135. (Appendix~\ref{appendix:utilities}), which tests your complete
  3136. compiler by executing the generated x86 code. Compile the provided
  3137. \key{runtime.c} file to \key{runtime.o} using \key{gcc}. Run the
  3138. script to test your compiler.
  3139. \ocaml{The OCaml version packages the process of emitting, assembling,
  3140. linking, and executing the assembly code as just another pass
  3141. (the \code{execute\_pass} defined in \code{Chapter2.ml}).
  3142. To emit code but not process it further, you can use the
  3143. \code{emit\_pass} instead; note that in this case, the test driver
  3144. should be configured not to compare initial and final values (since
  3145. there will be no useful final value).}
  3146. \end{exercise}
  3147. \section{Challenge: Partial Evaluator for \LangVar{}}
  3148. \label{sec:pe-Rvar}
  3149. \index{partial evaluation}
  3150. This section describes optional challenge exercises that involve
  3151. adapting and improving the partial evaluator for \LangInt{} that was
  3152. introduced in Section~\ref{sec:partial-evaluation}.
  3153. \begin{exercise}\label{ex:pe-Rvar}
  3154. \normalfont
  3155. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  3156. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3157. instead of \LangInt{} programs. Recall that \LangVar{} adds \key{let} binding
  3158. and variables to the \LangInt{} language, so you will need to add cases for
  3159. them in the \code{pe-exp} function. Once complete, add the partial
  3160. evaluation pass to the front of your compiler and make sure that your
  3161. compiler still passes all of the tests.
  3162. \end{exercise}
  3163. The next exercise builds on Exercise~\ref{ex:pe-Rvar}.
  3164. \begin{exercise}
  3165. \normalfont
  3166. Improve on the partial evaluator by replacing the \code{pe-neg} and
  3167. \code{pe-add} auxiliary functions with functions that know more about
  3168. arithmetic. For example, your partial evaluator should translate
  3169. \[
  3170. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3171. \code{(+ 2 (read))}
  3172. \]
  3173. To accomplish this, the \code{pe-exp} function should produce output
  3174. in the form of the $\itm{residual}$ non-terminal of the following
  3175. grammar. The idea is that when processing an addition expression, we
  3176. can always produce either 1) an integer constant, 2) and addition
  3177. expression with an integer constant on the left-hand side but not the
  3178. right-hand side, or 3) or an addition expression in which neither
  3179. subexpression is a constant.
  3180. \[
  3181. \begin{array}{lcl}
  3182. \itm{inert} &::=& \Var \mid \LP\key{read}\RP \mid \LP\key{-} \;\Var\RP
  3183. \mid \LP\key{-} \;\LP\key{read}\RP\RP
  3184. \mid \LP\key{+} \; \itm{inert} \; \itm{inert}\RP\\
  3185. &\mid& \LP\key{let}~\LP\LS\Var~\itm{inert}\RS\RP~ \itm{inert} \RP \\
  3186. \itm{residual} &::=& \Int \mid \LP\key{+}\; \Int\; \itm{inert}\RP \mid \itm{inert}
  3187. \end{array}
  3188. \]
  3189. The \code{pe-add} and \code{pe-neg} functions may assume that their
  3190. inputs are $\itm{residual}$ expressions and they should return
  3191. $\itm{residual}$ expressions. Once the improvements are complete,
  3192. make sure that your compiler still passes all of the tests. After
  3193. all, fast code is useless if it produces incorrect results!
  3194. \end{exercise}
  3195. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3196. \chapter{Register Allocation}
  3197. \label{ch:register-allocation-Rvar}
  3198. \index{register allocation}
  3199. In Chapter~\ref{ch:Rvar} we learned how to store variables on the
  3200. stack. In this Chapter we learn how to improve the performance of the
  3201. generated code by placing some variables into registers. The CPU can
  3202. access a register in a single cycle, whereas accessing the stack can
  3203. take 10s to 100s of cycles. The program in Figure~\ref{fig:reg-eg}
  3204. serves as a running example. The source program is on the left and the
  3205. output of instruction selection is on the right. The program is almost
  3206. in the x86 assembly language but it still uses variables.
  3207. \begin{figure}
  3208. \begin{minipage}{0.45\textwidth}
  3209. Example \LangVar{} program:
  3210. % var_test_28.rkt
  3211. \begin{lstlisting}
  3212. (let ([v 1])
  3213. (let ([w 42])
  3214. (let ([x (+ v 7)])
  3215. (let ([y x])
  3216. (let ([z (+ x w)])
  3217. (+ z (- y)))))))
  3218. \end{lstlisting}
  3219. \end{minipage}
  3220. \begin{minipage}{0.45\textwidth}
  3221. After instruction selection:
  3222. \begin{lstlisting}
  3223. locals-types:
  3224. x : Integer, y : Integer,
  3225. z : Integer, t : Integer,
  3226. v : Integer, w : Integer
  3227. start:
  3228. movq $1, v
  3229. movq $42, w
  3230. movq v, x
  3231. addq $7, x
  3232. movq x, y
  3233. movq x, z
  3234. addq w, z
  3235. movq y, t
  3236. negq t
  3237. movq z, %rax
  3238. addq t, %rax
  3239. jmp conclusion
  3240. \end{lstlisting}
  3241. \end{minipage}
  3242. \caption{A running example for register allocation.}
  3243. \label{fig:reg-eg}
  3244. \end{figure}
  3245. The goal of register allocation is to fit as many variables into
  3246. registers as possible. Some programs have more variables than
  3247. registers so we cannot always map each variable to a different
  3248. register. Fortunately, it is common for different variables to be
  3249. needed during different periods of time during program execution, and
  3250. in such cases several variables can be mapped to the same register.
  3251. Consider variables \code{x} and \code{z} in Figure~\ref{fig:reg-eg}.
  3252. After the variable \code{x} is moved to \code{z} it is no longer
  3253. needed. Variable \code{z}, on the other hand, is used only after this
  3254. point, so \code{x} and \code{z} could share the same register. The
  3255. topic of Section~\ref{sec:liveness-analysis-Rvar} is how to compute
  3256. where a variable is needed. Once we have that information, we compute
  3257. which variables are needed at the same time, i.e., which ones
  3258. \emph{interfere} with each other, and represent this relation as an
  3259. undirected graph whose vertices are variables and edges indicate when
  3260. two variables interfere (Section~\ref{sec:build-interference}). We
  3261. then model register allocation as a graph coloring problem
  3262. (Section~\ref{sec:graph-coloring}).
  3263. If we run out of registers despite these efforts, we place the
  3264. remaining variables on the stack, similar to what we did in
  3265. Chapter~\ref{ch:Rvar}. It is common to use the verb \emph{spill}
  3266. for assigning a variable to a stack location. The decision to spill a
  3267. variable is handled as part of the graph coloring process
  3268. (Section~\ref{sec:graph-coloring}).
  3269. We make the simplifying assumption that each variable is assigned to
  3270. one location (a register or stack address). A more sophisticated
  3271. approach is to assign a variable to one or more locations in different
  3272. regions of the program. For example, if a variable is used many times
  3273. in short sequence and then only used again after many other
  3274. instructions, it could be more efficient to assign the variable to a
  3275. register during the initial sequence and then move it to the stack for
  3276. the rest of its lifetime. We refer the interested reader to
  3277. \citet{Cooper:2011aa} for more information about that approach.
  3278. % discuss prioritizing variables based on how much they are used.
  3279. \section{Registers and Calling Conventions}
  3280. \label{sec:calling-conventions}
  3281. \index{calling conventions}
  3282. As we perform register allocation, we need to be aware of the
  3283. \emph{calling conventions} \index{calling conventions} that govern how
  3284. functions calls are performed in x86.
  3285. %
  3286. Even though \LangVar{} does not include programmer-defined functions,
  3287. our generated code includes a \code{main} function that is called by
  3288. the operating system and our generated code contains calls to the
  3289. \code{read\_int} function.
  3290. Function calls require coordination between two pieces of code that
  3291. may be written by different programmers or generated by different
  3292. compilers. Here we follow the System V calling conventions that are
  3293. used by the GNU C compiler on Linux and
  3294. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  3295. %
  3296. The calling conventions include rules about how functions share the
  3297. use of registers. In particular, the caller is responsible for freeing
  3298. up some registers prior to the function call for use by the callee.
  3299. These are called the \emph{caller-saved registers}
  3300. \index{caller-saved registers}
  3301. and they are
  3302. \begin{lstlisting}
  3303. rax rcx rdx rsi rdi r8 r9 r10 r11
  3304. \end{lstlisting}
  3305. On the other hand, the callee is responsible for preserving the values
  3306. of the \emph{callee-saved registers}, \index{callee-saved registers}
  3307. which are
  3308. \begin{lstlisting}
  3309. rsp rbp rbx r12 r13 r14 r15
  3310. \end{lstlisting}
  3311. We can think about this caller/callee convention from two points of
  3312. view, the caller view and the callee view:
  3313. \begin{itemize}
  3314. \item The caller should assume that all the caller-saved registers get
  3315. overwritten with arbitrary values by the callee. On the other hand,
  3316. the caller can safely assume that all the callee-saved registers
  3317. contain the same values after the call that they did before the
  3318. call.
  3319. \item The callee can freely use any of the caller-saved registers.
  3320. However, if the callee wants to use a callee-saved register, the
  3321. callee must arrange to put the original value back in the register
  3322. prior to returning to the caller. This can be accomplished by saving
  3323. the value to the stack in the prelude of the function and restoring
  3324. the value in the conclusion of the function.
  3325. \end{itemize}
  3326. In x86, registers are also used for passing arguments to a function
  3327. and for the return value. In particular, the first six arguments to a
  3328. function are passed in the following six registers, in this order.
  3329. \begin{lstlisting}
  3330. rdi rsi rdx rcx r8 r9
  3331. \end{lstlisting}
  3332. If there are more than six arguments, then the convention is to use
  3333. space on the frame of the caller for the rest of the
  3334. arguments. However, in Chapter~\ref{ch:Rfun} we arrange never to
  3335. need more than six arguments. For now, the only function we care about
  3336. is \code{read\_int} and it takes zero arguments.
  3337. %
  3338. The register \code{rax} is used for the return value of a function.
  3339. The next question is how these calling conventions impact register
  3340. allocation. Consider the \LangVar{} program in
  3341. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  3342. example from the caller point of view and then from the callee point
  3343. of view.
  3344. The program makes two calls to the \code{read} function. Also, the
  3345. variable \code{x} is in use during the second call to \code{read}, so
  3346. we need to make sure that the value in \code{x} does not get
  3347. accidentally wiped out by the call to \code{read}. One obvious
  3348. approach is to save all the values in caller-saved registers to the
  3349. stack prior to each function call, and restore them after each
  3350. call. That way, if the register allocator chooses to assign \code{x}
  3351. to a caller-saved register, its value will be preserved across the
  3352. call to \code{read}. However, saving and restoring to the stack is
  3353. relatively slow. If \code{x} is not used many times, it may be better
  3354. to assign \code{x} to a stack location in the first place. Or better
  3355. yet, if we can arrange for \code{x} to be placed in a callee-saved
  3356. register, then it won't need to be saved and restored during function
  3357. calls.
  3358. The approach that we recommend for variables that are in use during a
  3359. function call is to either assign them to callee-saved registers or to
  3360. spill them to the stack. On the other hand, for variables that are not
  3361. in use during a function call, we try the following alternatives in
  3362. order 1) look for an available caller-saved register (to leave room
  3363. for other variables in the callee-saved register), 2) look for a
  3364. callee-saved register, and 3) spill the variable to the stack.
  3365. It is straightforward to implement this approach in a graph coloring
  3366. register allocator. First, we know which variables are in use during
  3367. every function call because we compute that information for every
  3368. instruction (Section~\ref{sec:liveness-analysis-Rvar}). Second, when we
  3369. build the interference graph (Section~\ref{sec:build-interference}),
  3370. we can place an edge between each of these variables and the
  3371. caller-saved registers in the interference graph. This will prevent
  3372. the graph coloring algorithm from assigning those variables to
  3373. caller-saved registers.
  3374. Returning to the example in
  3375. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  3376. generated x86 code on the right-hand side, focusing on the
  3377. \code{start} block. Notice that variable \code{x} is assigned to
  3378. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  3379. place during the second call to \code{read\_int}. Next, notice that
  3380. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  3381. because there are no function calls in the remainder of the block.
  3382. Next we analyze the example from the callee point of view, focusing on
  3383. the prelude and conclusion of the \code{main} function. As usual the
  3384. prelude begins with saving the \code{rbp} register to the stack and
  3385. setting the \code{rbp} to the current stack pointer. We now know why
  3386. it is necessary to save the \code{rbp}: it is a callee-saved register.
  3387. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  3388. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  3389. (\code{x}). The other callee-saved registers are not saved in the
  3390. prelude because they are not used. The prelude subtracts 8 bytes from
  3391. the \code{rsp} to make it 16-byte aligned and then jumps to the
  3392. \code{start} block. Shifting attention to the \code{conclusion}, we
  3393. see that \code{rbx} is restored from the stack with a \code{popq}
  3394. instruction. \index{prelude}\index{conclusion}
  3395. \begin{figure}[tp]
  3396. \begin{minipage}{0.45\textwidth}
  3397. Example \LangVar{} program:
  3398. %var_test_14.rkt
  3399. \begin{lstlisting}
  3400. (let ([x (read)])
  3401. (let ([y (read)])
  3402. (+ (+ x y) 42)))
  3403. \end{lstlisting}
  3404. \end{minipage}
  3405. \begin{minipage}{0.45\textwidth}
  3406. Generated x86 assembly:
  3407. \begin{lstlisting}
  3408. start:
  3409. callq read_int
  3410. movq %rax, %rbx
  3411. callq read_int
  3412. movq %rax, %rcx
  3413. addq %rcx, %rbx
  3414. movq %rbx, %rax
  3415. addq $42, %rax
  3416. jmp _conclusion
  3417. .globl main
  3418. main:
  3419. pushq %rbp
  3420. movq %rsp, %rbp
  3421. pushq %rbx
  3422. subq $8, %rsp
  3423. jmp start
  3424. conclusion:
  3425. addq $8, %rsp
  3426. popq %rbx
  3427. popq %rbp
  3428. retq
  3429. \end{lstlisting}
  3430. \end{minipage}
  3431. \caption{An example with function calls.}
  3432. \label{fig:example-calling-conventions}
  3433. \end{figure}
  3434. \clearpage
  3435. \section{Liveness Analysis}
  3436. \label{sec:liveness-analysis-Rvar}
  3437. \index{liveness analysis}
  3438. The \code{uncover-live} pass performs \emph{liveness analysis}, that
  3439. is, it discovers which variables are in-use in different regions of a
  3440. program.
  3441. %
  3442. A variable or register is \emph{live} at a program point if its
  3443. current value is used at some later point in the program. We
  3444. refer to variables and registers collectively as \emph{locations}.
  3445. %
  3446. Consider the following code fragment in which there are two writes to
  3447. \code{b}. Are \code{a} and \code{b} both live at the same time?
  3448. \begin{center}
  3449. \begin{minipage}{0.96\textwidth}
  3450. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  3451. movq $5, a
  3452. movq $30, b
  3453. movq a, c
  3454. movq $10, b
  3455. addq b, c
  3456. \end{lstlisting}
  3457. \end{minipage}
  3458. \end{center}
  3459. The answer is no because \code{a} is live from line 1 to 3 and
  3460. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  3461. line 2 is never used because it is overwritten (line 4) before the
  3462. next read (line 5).
  3463. \begin{wrapfigure}[19]{l}[1.0in]{0.6\textwidth}
  3464. \small
  3465. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  3466. A \emph{set} is an unordered collection of elements without duplicates.
  3467. \index{set}
  3468. \begin{description}
  3469. \item[$\LP\code{set}\,v\,\ldots\RP$] constructs a set containing the specified elements.
  3470. \item[$\LP\code{set-union}\,set_1\,set_2\RP$] returns the union of the two sets.
  3471. \item[$\LP\code{set-subtract}\,set_1\,set_2\RP$] returns the difference of the two sets.
  3472. \item[$\LP\code{set-member?}\,set\,v\RP$] is element $v$ in $set$?
  3473. \item[$\LP\code{set-count}\,set\RP$] how many unique elements are in $set$?
  3474. \item[$\LP\code{set->list}\,set\RP$] converts the set to a list.
  3475. \end{description}
  3476. \end{tcolorbox}
  3477. \end{wrapfigure}
  3478. The live locations can be computed by traversing the instruction
  3479. sequence back to front (i.e., backwards in execution order). Let
  3480. $I_1,\ldots, I_n$ be the instruction sequence. We write
  3481. $L_{\mathsf{after}}(k)$ for the set of live locations after
  3482. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  3483. locations before instruction $I_k$. The live locations after an
  3484. instruction are always the same as the live locations before the next
  3485. instruction. \index{live-after} \index{live-before}
  3486. \begin{equation} \label{eq:live-after-before-next}
  3487. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  3488. \end{equation}
  3489. To start things off, there are no live locations after the last
  3490. instruction, so
  3491. \begin{equation}\label{eq:live-last-empty}
  3492. L_{\mathsf{after}}(n) = \emptyset
  3493. \end{equation}
  3494. We then apply the following rule repeatedly, traversing the
  3495. instruction sequence back to front.
  3496. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  3497. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  3498. \end{equation}
  3499. where $W(k)$ are the locations written to by instruction $I_k$ and
  3500. $R(k)$ are the locations read by instruction $I_k$.
  3501. There is a special case for \code{jmp} instructions. The locations
  3502. that are live before a \code{jmp} should be the locations in
  3503. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  3504. maintaining an alist named \code{label->live} that maps each label to
  3505. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  3506. now the only \code{jmp} in a \LangXVar{} program is the one at the
  3507. end, to the conclusion. (For example, see Figure~\ref{fig:reg-eg}.)
  3508. The conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should
  3509. map \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  3510. Let us walk through the above example, applying these formulas
  3511. starting with the instruction on line 5. We collect the answers in
  3512. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  3513. \code{addq b, c} instruction is $\emptyset$ because it is the last
  3514. instruction (formula~\ref{eq:live-last-empty}). The
  3515. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  3516. because it reads from variables \code{b} and \code{c}
  3517. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  3518. \[
  3519. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  3520. \]
  3521. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  3522. the live-before set from line 5 to be the live-after set for this
  3523. instruction (formula~\ref{eq:live-after-before-next}).
  3524. \[
  3525. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  3526. \]
  3527. This move instruction writes to \code{b} and does not read from any
  3528. variables, so we have the following live-before set
  3529. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  3530. \[
  3531. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  3532. \]
  3533. The live-before for instruction \code{movq a, c}
  3534. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  3535. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  3536. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  3537. variable that is not live and does not read from a variable.
  3538. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  3539. because it writes to variable \code{a}.
  3540. \begin{figure}[tbp]
  3541. \begin{minipage}{0.45\textwidth}
  3542. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  3543. movq $5, a
  3544. movq $30, b
  3545. movq a, c
  3546. movq $10, b
  3547. addq b, c
  3548. \end{lstlisting}
  3549. \end{minipage}
  3550. \vrule\hspace{10pt}
  3551. \begin{minipage}{0.45\textwidth}
  3552. \begin{align*}
  3553. L_{\mathsf{before}}(1)= \emptyset,
  3554. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  3555. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  3556. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  3557. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  3558. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  3559. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  3560. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  3561. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  3562. L_{\mathsf{after}}(5)= \emptyset
  3563. \end{align*}
  3564. \end{minipage}
  3565. \caption{Example output of liveness analysis on a short example.}
  3566. \label{fig:liveness-example-0}
  3567. \end{figure}
  3568. \begin{exercise}\normalfont
  3569. Perform liveness analysis on the running example in
  3570. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  3571. sets for each instruction. Compare your answers to the solution
  3572. shown in Figure~\ref{fig:live-eg}.
  3573. \end{exercise}
  3574. \begin{figure}[tp]
  3575. \hspace{20pt}
  3576. \begin{minipage}{0.45\textwidth}
  3577. \begin{lstlisting}
  3578. |$\{\ttm{rsp}\}$|
  3579. movq $1, v
  3580. |$\{\ttm{v},\ttm{rsp}\}$|
  3581. movq $42, w
  3582. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  3583. movq v, x
  3584. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  3585. addq $7, x
  3586. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  3587. movq x, y
  3588. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  3589. movq x, z
  3590. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  3591. addq w, z
  3592. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  3593. movq y, t
  3594. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  3595. negq t
  3596. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  3597. movq z, %rax
  3598. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  3599. addq t, %rax
  3600. |$\{\ttm{rax},\ttm{rsp}\}$|
  3601. jmp conclusion
  3602. \end{lstlisting}
  3603. \end{minipage}
  3604. \caption{The running example annotated with live-after sets.}
  3605. \label{fig:live-eg}
  3606. \end{figure}
  3607. \begin{exercise}\normalfont
  3608. Implement the \code{uncover-live} pass. Store the sequence of
  3609. live-after sets in the $\itm{info}$ field of the \code{Block}
  3610. structure.
  3611. %
  3612. We recommend creating an auxiliary function that takes a list of
  3613. instructions and an initial live-after set (typically empty) and
  3614. returns the list of live-after sets.
  3615. %
  3616. We also recommend creating auxiliary functions to 1) compute the set
  3617. of locations that appear in an \Arg{}, 2) compute the locations read
  3618. by an instruction (the $R$ function), and 3) the locations written by
  3619. an instruction (the $W$ function). The \code{callq} instruction should
  3620. include all of the caller-saved registers in its write-set $W$ because
  3621. the calling convention says that those registers may be written to
  3622. during the function call. Likewise, the \code{callq} instruction
  3623. should include the appropriate argument-passing registers in its
  3624. read-set $R$, depending on the arity of the function being
  3625. called. (This is why the abstract syntax for \code{callq} includes the
  3626. arity.)
  3627. \end{exercise}
  3628. \clearpage
  3629. \section{Build the Interference Graph}
  3630. \label{sec:build-interference}
  3631. \begin{wrapfigure}[25]{r}[1.0in]{0.6\textwidth}
  3632. \small
  3633. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  3634. A \emph{graph} is a collection of vertices and edges where each
  3635. edge connects two vertices. A graph is \emph{directed} if each
  3636. edge points from a source to a target. Otherwise the graph is
  3637. \emph{undirected}.
  3638. \index{graph}\index{directed graph}\index{undirected graph}
  3639. \begin{description}
  3640. %% We currently don't use directed graphs. We instead use
  3641. %% directed multi-graphs. -Jeremy
  3642. %% \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  3643. %% directed graph from a list of edges. Each edge is a list
  3644. %% containing the source and target vertex.
  3645. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  3646. undirected graph from a list of edges. Each edge is represented by
  3647. a list containing two vertices.
  3648. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  3649. inserts a vertex into the graph.
  3650. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  3651. inserts an edge between the two vertices into the graph.
  3652. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  3653. returns a sequence of all the neighbors of the given vertex.
  3654. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  3655. returns a sequence of all the vertices in the graph.
  3656. \end{description}
  3657. \end{tcolorbox}
  3658. \end{wrapfigure}
  3659. Based on the liveness analysis, we know where each location is live.
  3660. However, during register allocation, we need to answer questions of
  3661. the specific form: are locations $u$ and $v$ live at the same time?
  3662. (And therefore cannot be assigned to the same register.) To make this
  3663. question more efficient to answer, we create an explicit data
  3664. structure, an \emph{interference graph}\index{interference graph}. An
  3665. interference graph is an undirected graph that has an edge between two
  3666. locations if they are live at the same time, that is, if they
  3667. interfere with each other.
  3668. An obvious way to compute the interference graph is to look at the set
  3669. of live locations between each instruction and the next and add an edge to the graph
  3670. for every pair of variables in the same set. This approach is less
  3671. than ideal for two reasons. First, it can be expensive because it
  3672. takes $O(n^2)$ time to consider at every pair in a set of $n$ live
  3673. locations. Second, in the special case where two locations hold the
  3674. same value (because one was assigned to the other), they can be live
  3675. at the same time without interfering with each other.
  3676. A better way to compute the interference graph is to focus on
  3677. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  3678. must not overwrite something in a live location. So for each
  3679. instruction, we create an edge between the locations being written to
  3680. and the live locations. (Except that one should not create self
  3681. edges.) Note that for the \key{callq} instruction, we consider all of
  3682. the caller-saved registers as being written to, so an edge is added
  3683. between every live variable and every caller-saved register. For
  3684. \key{movq}, we deal with the above-mentioned special case by not
  3685. adding an edge between a live variable $v$ and the destination if $v$
  3686. matches the source. So we have the following two rules.
  3687. \begin{enumerate}
  3688. \item If instruction $I_k$ is a move such as \key{movq} $s$\key{,}
  3689. $d$, then add the edge $(d,v)$ for every $v \in
  3690. L_{\mathsf{after}}(k)$ unless $v = d$ or $v = s$.
  3691. \item For any other instruction $I_k$, for every $d \in W(k)$
  3692. add an edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  3693. %% \item If instruction $I_k$ is an arithmetic instruction such as
  3694. %% \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  3695. %% L_{\mathsf{after}}(k)$ unless $v = d$.
  3696. %% \item If instruction $I_k$ is of the form \key{callq}
  3697. %% $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  3698. %% register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  3699. \end{enumerate}
  3700. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  3701. the above rules to each instruction. We highlight a few of the
  3702. instructions. The first instruction is \lstinline{movq $1, v} and the
  3703. live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies, so \code{v}
  3704. interferes with \code{rsp}.
  3705. %
  3706. The fourth instruction is \lstinline{addq $7, x} and the live-after
  3707. set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so $\ttm{x}$
  3708. interferes with \ttm{w} and \ttm{rsp}.
  3709. %
  3710. The next instruction is \lstinline{movq x, y} and the live-after set
  3711. is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1 applies, so \ttm{y}
  3712. interferes with \ttm{w} and \ttm{rsp} but not \ttm{x} because \ttm{x}
  3713. is the source of the move and therefore \ttm{x} and \ttm{y} hold the
  3714. same value. Figure~\ref{fig:interference-results} lists the
  3715. interference results for all of the instructions and the resulting
  3716. interference graph is shown in Figure~\ref{fig:interfere}.
  3717. \begin{figure}[tbp]
  3718. \begin{quote}
  3719. \begin{tabular}{ll}
  3720. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  3721. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  3722. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  3723. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  3724. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  3725. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  3726. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  3727. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  3728. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  3729. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  3730. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  3731. \lstinline!jmp conclusion!& no interference.
  3732. \end{tabular}
  3733. \end{quote}
  3734. \caption{Interference results for the running example.}
  3735. \label{fig:interference-results}
  3736. \end{figure}
  3737. \begin{figure}[tbp]
  3738. \large
  3739. \[
  3740. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3741. \node (rax) at (0,0) {$\ttm{rax}$};
  3742. \node (rsp) at (9,2) {$\ttm{rsp}$};
  3743. \node (t1) at (0,2) {$\ttm{t}$};
  3744. \node (z) at (3,2) {$\ttm{z}$};
  3745. \node (x) at (6,2) {$\ttm{x}$};
  3746. \node (y) at (3,0) {$\ttm{y}$};
  3747. \node (w) at (6,0) {$\ttm{w}$};
  3748. \node (v) at (9,0) {$\ttm{v}$};
  3749. \draw (t1) to (rax);
  3750. \draw (t1) to (z);
  3751. \draw (z) to (y);
  3752. \draw (z) to (w);
  3753. \draw (x) to (w);
  3754. \draw (y) to (w);
  3755. \draw (v) to (w);
  3756. \draw (v) to (rsp);
  3757. \draw (w) to (rsp);
  3758. \draw (x) to (rsp);
  3759. \draw (y) to (rsp);
  3760. \path[-.,bend left=15] (z) edge node {} (rsp);
  3761. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3762. \draw (rax) to (rsp);
  3763. \end{tikzpicture}
  3764. \]
  3765. \caption{The interference graph of the example program.}
  3766. \label{fig:interfere}
  3767. \end{figure}
  3768. %% Our next concern is to choose a data structure for representing the
  3769. %% interference graph. There are many choices for how to represent a
  3770. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  3771. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  3772. %% data structure is to study the algorithm that uses the data structure,
  3773. %% determine what operations need to be performed, and then choose the
  3774. %% data structure that provide the most efficient implementations of
  3775. %% those operations. Often times the choice of data structure can have an
  3776. %% effect on the time complexity of the algorithm, as it does here. If
  3777. %% you skim the next section, you will see that the register allocation
  3778. %% algorithm needs to ask the graph for all of its vertices and, given a
  3779. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  3780. %% correct choice of graph representation is that of an adjacency
  3781. %% list. There are helper functions in \code{utilities.rkt} for
  3782. %% representing graphs using the adjacency list representation:
  3783. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  3784. %% (Appendix~\ref{appendix:utilities}).
  3785. %% %
  3786. %% \margincomment{\footnotesize To do: change to use the
  3787. %% Racket graph library. \\ --Jeremy}
  3788. %% %
  3789. %% In particular, those functions use a hash table to map each vertex to
  3790. %% the set of adjacent vertices, and the sets are represented using
  3791. %% Racket's \key{set}, which is also a hash table.
  3792. \begin{exercise}\normalfont
  3793. Implement the compiler pass named \code{build-interference} according
  3794. to the algorithm suggested above. We recommend using the \code{graph}
  3795. package to create and inspect the interference graph. The output
  3796. graph of this pass should be stored in the $\itm{info}$ field of the
  3797. program, under the key \code{conflicts}.
  3798. \end{exercise}
  3799. \section{Graph Coloring via Sudoku}
  3800. \label{sec:graph-coloring}
  3801. \index{graph coloring}
  3802. \index{Sudoku}
  3803. \index{color}
  3804. We come to the main event, mapping variables to registers and stack
  3805. locations. Variables that interfere with each other must be mapped to
  3806. different locations. In terms of the interference graph, this means
  3807. that adjacent vertices must be mapped to different locations. If we
  3808. think of locations as colors, the register allocation problem becomes
  3809. the graph coloring problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  3810. The reader may be more familiar with the graph coloring problem than he
  3811. or she realizes; the popular game of Sudoku is an instance of the
  3812. graph coloring problem. The following describes how to build a graph
  3813. out of an initial Sudoku board.
  3814. \begin{itemize}
  3815. \item There is one vertex in the graph for each Sudoku square.
  3816. \item There is an edge between two vertices if the corresponding squares
  3817. are in the same row, in the same column, or if the squares are in
  3818. the same $3\times 3$ region.
  3819. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  3820. \item Based on the initial assignment of numbers to squares in the
  3821. Sudoku board, assign the corresponding colors to the corresponding
  3822. vertices in the graph.
  3823. \end{itemize}
  3824. If you can color the remaining vertices in the graph with the nine
  3825. colors, then you have also solved the corresponding game of Sudoku.
  3826. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  3827. the corresponding graph with colored vertices. We map the Sudoku
  3828. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  3829. sampling of the vertices (the colored ones) because showing edges for
  3830. all of the vertices would make the graph unreadable.
  3831. \begin{figure}[tbp]
  3832. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  3833. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  3834. \caption{A Sudoku game board and the corresponding colored graph.}
  3835. \label{fig:sudoku-graph}
  3836. \end{figure}
  3837. It turns out that some techniques for playing Sudoku correspond to
  3838. heuristics used in graph coloring algorithms. For example, one of the
  3839. basic techniques for Sudoku is called Pencil Marks. The idea is to use
  3840. a process of elimination to determine what numbers are no longer
  3841. available for a square and write down those numbers in the square
  3842. (writing very small). For example, if the number $1$ is assigned to a
  3843. square, then write the pencil mark $1$ in all the squares in the same
  3844. row, column, and region.
  3845. %
  3846. The Pencil Marks technique corresponds to the notion of
  3847. \emph{saturation}\index{saturation} due to \cite{Brelaz:1979eu}. The
  3848. saturation of a vertex, in Sudoku terms, is the set of numbers that
  3849. are no longer available. In graph terminology, we have the following
  3850. definition:
  3851. \begin{equation*}
  3852. \mathrm{saturation}(u) = \{ c \mid \exists v. v \in \mathrm{neighbors}(u)
  3853. \text{ and } \mathrm{color}(v) = c \}
  3854. \end{equation*}
  3855. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  3856. edge with $u$.
  3857. Using the Pencil Marks technique leads to a simple strategy for
  3858. filling in numbers: if there is a square with only one possible number
  3859. left, then choose that number! But what if there are no squares with
  3860. only one possibility left? One brute-force approach is to try them
  3861. all: choose the first one and if it ultimately leads to a solution,
  3862. great. If not, backtrack and choose the next possibility. One good
  3863. thing about Pencil Marks is that it reduces the degree of branching in
  3864. the search tree. Nevertheless, backtracking can be horribly time
  3865. consuming. One way to reduce the amount of backtracking is to use the
  3866. most-constrained-first heuristic. That is, when choosing a square,
  3867. always choose one with the fewest possibilities left (the vertex with
  3868. the highest saturation). The idea is that choosing highly constrained
  3869. squares earlier rather than later is better because later on there may
  3870. not be any possibilities left in the highly saturated squares.
  3871. However, register allocation is easier than Sudoku because the
  3872. register allocator can map variables to stack locations when the
  3873. registers run out. Thus, it makes sense to replace backtracking with
  3874. greedy search: make the best choice at the time and keep going. We
  3875. still wish to minimize the number of colors needed, so we use the
  3876. most-constrained-first heuristic in the greedy search.
  3877. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  3878. algorithm for register allocation based on saturation and the
  3879. most-constrained-first heuristic. It is roughly equivalent to the
  3880. DSATUR
  3881. algorithm~\citep{Brelaz:1979eu,Gebremedhin:1999fk,Omari:2006uq}. Just
  3882. as in Sudoku, the algorithm represents colors with integers. The
  3883. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  3884. for register allocation. The integers $k$ and larger correspond to
  3885. stack locations. The registers that are not used for register
  3886. allocation, such as \code{rax}, are assigned to negative integers. In
  3887. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  3888. %% One might wonder why we include registers at all in the liveness
  3889. %% analysis and interference graph. For example, we never allocate a
  3890. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  3891. %% leave them out. As we see in Chapter~\ref{ch:Rvec}, when we begin
  3892. %% to use register for passing arguments to functions, it will be
  3893. %% necessary for those registers to appear in the interference graph
  3894. %% because those registers will also be assigned to variables, and we
  3895. %% don't want those two uses to encroach on each other. Regarding
  3896. %% registers such as \code{rax} and \code{rsp} that are not used for
  3897. %% variables, we could omit them from the interference graph but that
  3898. %% would require adding special cases to our algorithm, which would
  3899. %% complicate the logic for little gain.
  3900. \begin{figure}[btp]
  3901. \centering
  3902. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  3903. Algorithm: DSATUR
  3904. Input: a graph |$G$|
  3905. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  3906. |$W \gets \mathrm{vertices}(G)$|
  3907. while |$W \neq \emptyset$| do
  3908. pick a vertex |$u$| from |$W$| with the highest saturation,
  3909. breaking ties randomly
  3910. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  3911. |$\mathrm{color}[u] \gets c$|
  3912. |$W \gets W - \{u\}$|
  3913. \end{lstlisting}
  3914. \caption{The saturation-based greedy graph coloring algorithm.}
  3915. \label{fig:satur-algo}
  3916. \end{figure}
  3917. With the DSATUR algorithm in hand, let us return to the running
  3918. example and consider how to color the interference graph in
  3919. Figure~\ref{fig:interfere}.
  3920. %
  3921. We start by assigning the register nodes to their own color. For
  3922. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  3923. assigned $-2$. The variables are not yet colored, so they are
  3924. annotated with a dash. We then update the saturation for vertices that
  3925. are adjacent to a register, obtaining the following annotated
  3926. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  3927. it interferes with both \code{rax} and \code{rsp}.
  3928. \[
  3929. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3930. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  3931. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  3932. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  3933. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  3934. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3935. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3936. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3937. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3938. \draw (t1) to (rax);
  3939. \draw (t1) to (z);
  3940. \draw (z) to (y);
  3941. \draw (z) to (w);
  3942. \draw (x) to (w);
  3943. \draw (y) to (w);
  3944. \draw (v) to (w);
  3945. \draw (v) to (rsp);
  3946. \draw (w) to (rsp);
  3947. \draw (x) to (rsp);
  3948. \draw (y) to (rsp);
  3949. \path[-.,bend left=15] (z) edge node {} (rsp);
  3950. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3951. \draw (rax) to (rsp);
  3952. \end{tikzpicture}
  3953. \]
  3954. The algorithm says to select a maximally saturated vertex. So we pick
  3955. $\ttm{t}$ and color it with the first available integer, which is
  3956. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  3957. and \ttm{rsp} because they interfere with $\ttm{t}$.
  3958. \[
  3959. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3960. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3961. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  3962. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  3963. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  3964. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3965. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3966. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3967. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3968. \draw (t1) to (rax);
  3969. \draw (t1) to (z);
  3970. \draw (z) to (y);
  3971. \draw (z) to (w);
  3972. \draw (x) to (w);
  3973. \draw (y) to (w);
  3974. \draw (v) to (w);
  3975. \draw (v) to (rsp);
  3976. \draw (w) to (rsp);
  3977. \draw (x) to (rsp);
  3978. \draw (y) to (rsp);
  3979. \path[-.,bend left=15] (z) edge node {} (rsp);
  3980. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3981. \draw (rax) to (rsp);
  3982. \end{tikzpicture}
  3983. \]
  3984. We repeat the process, selecting the next maximally saturated vertex,
  3985. which is \code{z}, and color it with the first available number, which
  3986. is $1$. We add $1$ to the saturation for the neighboring vertices
  3987. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  3988. \[
  3989. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3990. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3991. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3992. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3993. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3994. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3995. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3996. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3997. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3998. \draw (t1) to (rax);
  3999. \draw (t1) to (z);
  4000. \draw (z) to (y);
  4001. \draw (z) to (w);
  4002. \draw (x) to (w);
  4003. \draw (y) to (w);
  4004. \draw (v) to (w);
  4005. \draw (v) to (rsp);
  4006. \draw (w) to (rsp);
  4007. \draw (x) to (rsp);
  4008. \draw (y) to (rsp);
  4009. \path[-.,bend left=15] (z) edge node {} (rsp);
  4010. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4011. \draw (rax) to (rsp);
  4012. \end{tikzpicture}
  4013. \]
  4014. The most saturated vertices are now \code{w} and \code{y}. We color
  4015. \code{w} with the first available color, which is $0$.
  4016. \[
  4017. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4018. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4019. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4020. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4021. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4022. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4023. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  4024. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  4025. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4026. \draw (t1) to (rax);
  4027. \draw (t1) to (z);
  4028. \draw (z) to (y);
  4029. \draw (z) to (w);
  4030. \draw (x) to (w);
  4031. \draw (y) to (w);
  4032. \draw (v) to (w);
  4033. \draw (v) to (rsp);
  4034. \draw (w) to (rsp);
  4035. \draw (x) to (rsp);
  4036. \draw (y) to (rsp);
  4037. \path[-.,bend left=15] (z) edge node {} (rsp);
  4038. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4039. \draw (rax) to (rsp);
  4040. \end{tikzpicture}
  4041. \]
  4042. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  4043. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  4044. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  4045. and \code{z}, whose colors are $0$ and $1$ respectively.
  4046. \[
  4047. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4048. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4049. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4050. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4051. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4052. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4053. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4054. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4055. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4056. \draw (t1) to (rax);
  4057. \draw (t1) to (z);
  4058. \draw (z) to (y);
  4059. \draw (z) to (w);
  4060. \draw (x) to (w);
  4061. \draw (y) to (w);
  4062. \draw (v) to (w);
  4063. \draw (v) to (rsp);
  4064. \draw (w) to (rsp);
  4065. \draw (x) to (rsp);
  4066. \draw (y) to (rsp);
  4067. \path[-.,bend left=15] (z) edge node {} (rsp);
  4068. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4069. \draw (rax) to (rsp);
  4070. \end{tikzpicture}
  4071. \]
  4072. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  4073. \[
  4074. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4075. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4076. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4077. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4078. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4079. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4080. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4081. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4082. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4083. \draw (t1) to (rax);
  4084. \draw (t1) to (z);
  4085. \draw (z) to (y);
  4086. \draw (z) to (w);
  4087. \draw (x) to (w);
  4088. \draw (y) to (w);
  4089. \draw (v) to (w);
  4090. \draw (v) to (rsp);
  4091. \draw (w) to (rsp);
  4092. \draw (x) to (rsp);
  4093. \draw (y) to (rsp);
  4094. \path[-.,bend left=15] (z) edge node {} (rsp);
  4095. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4096. \draw (rax) to (rsp);
  4097. \end{tikzpicture}
  4098. \]
  4099. In the last step of the algorithm, we color \code{x} with $1$.
  4100. \[
  4101. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4102. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4103. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4104. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4105. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4106. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  4107. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4108. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4109. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4110. \draw (t1) to (rax);
  4111. \draw (t1) to (z);
  4112. \draw (z) to (y);
  4113. \draw (z) to (w);
  4114. \draw (x) to (w);
  4115. \draw (y) to (w);
  4116. \draw (v) to (w);
  4117. \draw (v) to (rsp);
  4118. \draw (w) to (rsp);
  4119. \draw (x) to (rsp);
  4120. \draw (y) to (rsp);
  4121. \path[-.,bend left=15] (z) edge node {} (rsp);
  4122. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4123. \draw (rax) to (rsp);
  4124. \end{tikzpicture}
  4125. \]
  4126. \begin{wrapfigure}[25]{r}[1.0in]{0.6\textwidth}
  4127. \small
  4128. \begin{tcolorbox}[title=Priority Queue]
  4129. A \emph{priority queue} is a collection of items in which the
  4130. removal of items is governed by priority. In a ``min'' queue,
  4131. lower priority items are removed first. An implementation is in
  4132. \code{priority\_queue.rkt} of the support code. \index{priority
  4133. queue} \index{minimum priority queue}
  4134. \begin{description}
  4135. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  4136. priority queue that uses the $\itm{cmp}$ predicate to determine
  4137. whether its first argument has lower or equal priority to its
  4138. second argument.
  4139. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  4140. items in the queue.
  4141. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  4142. the item into the queue and returns a handle for the item in the
  4143. queue.
  4144. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  4145. the lowest priority.
  4146. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  4147. notifies the queue that the priority has decreased for the item
  4148. associated with the given handle.
  4149. \end{description}
  4150. \end{tcolorbox}
  4151. \end{wrapfigure}
  4152. We recommend creating an auxiliary function named \code{color-graph}
  4153. that takes an interference graph and a list of all the variables in
  4154. the program. This function should return a mapping of variables to
  4155. their colors (represented as natural numbers). By creating this helper
  4156. function, you will be able to reuse it in Chapter~\ref{ch:Rfun}
  4157. when we add support for functions.
  4158. To prioritize the processing of highly saturated nodes inside the
  4159. \code{color-graph} function, we recommend using the priority queue
  4160. data structure (see the side bar on the right). In addition, you will
  4161. need to maintain a mapping from variables to their ``handles'' in the
  4162. priority queue so that you can notify the priority queue when their
  4163. saturation changes.
  4164. With the coloring complete, we finalize the assignment of variables to
  4165. registers and stack locations. We map the first $k$ colors to the $k$
  4166. registers and the rest of the colors to stack locations. Suppose for
  4167. the moment that we have just one register to use for register
  4168. allocation, \key{rcx}. Then we have the following map from colors to
  4169. locations.
  4170. \[
  4171. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  4172. \]
  4173. Composing this mapping with the coloring, we arrive at the following
  4174. assignment of variables to locations.
  4175. \begin{gather*}
  4176. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  4177. \ttm{w} \mapsto \key{\%rcx}, \,
  4178. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  4179. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  4180. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  4181. \ttm{t} \mapsto \key{\%rcx} \}
  4182. \end{gather*}
  4183. Adapt the code from the \code{assign-homes} pass
  4184. (Section~\ref{sec:assign-Rvar}) to replace the variables with their
  4185. assigned location. Applying the above assignment to our running
  4186. example, on the left, yields the program on the right.
  4187. % why frame size of 32? -JGS
  4188. \begin{center}
  4189. \begin{minipage}{0.3\textwidth}
  4190. \begin{lstlisting}
  4191. movq $1, v
  4192. movq $42, w
  4193. movq v, x
  4194. addq $7, x
  4195. movq x, y
  4196. movq x, z
  4197. addq w, z
  4198. movq y, t
  4199. negq t
  4200. movq z, %rax
  4201. addq t, %rax
  4202. jmp conclusion
  4203. \end{lstlisting}
  4204. \end{minipage}
  4205. $\Rightarrow\qquad$
  4206. \begin{minipage}{0.45\textwidth}
  4207. \begin{lstlisting}
  4208. movq $1, -8(%rbp)
  4209. movq $42, %rcx
  4210. movq -8(%rbp), -8(%rbp)
  4211. addq $7, -8(%rbp)
  4212. movq -8(%rbp), -16(%rbp)
  4213. movq -8(%rbp), -8(%rbp)
  4214. addq %rcx, -8(%rbp)
  4215. movq -16(%rbp), %rcx
  4216. negq %rcx
  4217. movq -8(%rbp), %rax
  4218. addq %rcx, %rax
  4219. jmp conclusion
  4220. \end{lstlisting}
  4221. \end{minipage}
  4222. \end{center}
  4223. \begin{exercise}\normalfont
  4224. %
  4225. Implement the compiler pass \code{allocate-registers}.
  4226. %
  4227. Create five programs that exercise all of the register allocation
  4228. algorithm, including spilling variables to the stack.
  4229. %
  4230. Replace \code{assign-homes} in the list of \code{passes} in the
  4231. \code{run-tests.rkt} script with the three new passes:
  4232. \code{uncover-live}, \code{build-interference}, and
  4233. \code{allocate-registers}.
  4234. %
  4235. Temporarily remove the \code{print-x86} pass from the list of passes
  4236. and the call to \code{compiler-tests}.
  4237. %
  4238. Run the script to test the register allocator.
  4239. \end{exercise}
  4240. \section{Patch Instructions}
  4241. \label{sec:patch-instructions}
  4242. The remaining step in the compilation to x86 is to ensure that the
  4243. instructions have at most one argument that is a memory access.
  4244. In the running example, the instruction \code{movq -8(\%rbp), -16(\%rbp)}
  4245. is problematic. The fix is to first move \code{-8(\%rbp)}
  4246. into \code{rax} and then move \code{rax} into \code{-16(\%rbp)}.
  4247. %
  4248. The two moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  4249. problematic, but they can be fixed by simply deleting them. In
  4250. general, we recommend deleting all the trivial moves whose source and
  4251. destination are the same location.
  4252. %
  4253. The following is the output of \code{patch-instructions} on the
  4254. running example.
  4255. \begin{center}
  4256. \begin{minipage}{0.4\textwidth}
  4257. \begin{lstlisting}
  4258. movq $1, -8(%rbp)
  4259. movq $42, %rcx
  4260. movq -8(%rbp), -8(%rbp)
  4261. addq $7, -8(%rbp)
  4262. movq -8(%rbp), -16(%rbp)
  4263. movq -8(%rbp), -8(%rbp)
  4264. addq %rcx, -8(%rbp)
  4265. movq -16(%rbp), %rcx
  4266. negq %rcx
  4267. movq -8(%rbp), %rax
  4268. addq %rcx, %rax
  4269. jmp conclusion
  4270. \end{lstlisting}
  4271. \end{minipage}
  4272. $\Rightarrow\qquad$
  4273. \begin{minipage}{0.45\textwidth}
  4274. \begin{lstlisting}
  4275. movq $1, -8(%rbp)
  4276. movq $42, %rcx
  4277. addq $7, -8(%rbp)
  4278. movq -8(%rbp), %rax
  4279. movq %rax, -16(%rbp)
  4280. addq %rcx, -8(%rbp)
  4281. movq -16(%rbp), %rcx
  4282. negq %rcx
  4283. movq -8(%rbp), %rax
  4284. addq %rcx, %rax
  4285. jmp conclusion
  4286. \end{lstlisting}
  4287. \end{minipage}
  4288. \end{center}
  4289. \begin{exercise}\normalfont
  4290. %
  4291. Implement the \code{patch-instructions} compiler pass.
  4292. %
  4293. Insert it after \code{allocate-registers} in the list of \code{passes}
  4294. in the \code{run-tests.rkt} script.
  4295. %
  4296. Run the script to test the \code{patch-instructions} pass.
  4297. \end{exercise}
  4298. \section{Print x86}
  4299. \label{sec:print-x86-reg-alloc}
  4300. \index{calling conventions}
  4301. \index{prelude}\index{conclusion}
  4302. Recall that the \code{print-x86} pass generates the prelude and
  4303. conclusion instructions to satisfy the x86 calling conventions
  4304. (Section~\ref{sec:calling-conventions}). With the addition of the
  4305. register allocator, the callee-saved registers used by the register
  4306. allocator must be saved in the prelude and restored in the conclusion.
  4307. In the \code{allocate-registers} pass, add an entry to the \itm{info}
  4308. of \code{X86Program} named \code{used-callee} that stores the set of
  4309. callee-saved registers that were assigned to variables. The
  4310. \code{print-x86} pass can then access this information to decide which
  4311. callee-saved registers need to be saved and restored.
  4312. %
  4313. When calculating the size of the frame to adjust the \code{rsp} in the
  4314. prelude, make sure to take into account the space used for saving the
  4315. callee-saved registers. Also, don't forget that the frame needs to be
  4316. a multiple of 16 bytes!
  4317. An overview of all of the passes involved in register allocation is
  4318. shown in Figure~\ref{fig:reg-alloc-passes}.
  4319. \begin{figure}[tbp]
  4320. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4321. \node (Rvar) at (0,2) {\large \LangVar{}};
  4322. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  4323. \node (Rvar-3) at (6,2) {\large \LangVar{}};
  4324. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  4325. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  4326. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  4327. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  4328. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  4329. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  4330. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  4331. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  4332. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvar-3);
  4333. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate-control} (Cvar-1);
  4334. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  4335. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  4336. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  4337. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4338. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  4339. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  4340. \end{tikzpicture}
  4341. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  4342. \label{fig:reg-alloc-passes}
  4343. \end{figure}
  4344. \begin{exercise}\normalfont
  4345. Update the \code{print-x86} pass as described in this section.
  4346. %
  4347. In the \code{run-tests.rkt} script, reinstate \code{print-x86} in the
  4348. list of passes and the call to \code{compiler-tests}.
  4349. %
  4350. Run the script to test the complete compiler for \LangVar{} that
  4351. performs register allocation.
  4352. \end{exercise}
  4353. \section{Challenge: Move Biasing}
  4354. \label{sec:move-biasing}
  4355. \index{move biasing}
  4356. This section describes an enhancement to the register allocator for
  4357. students looking for an extra challenge or who have a deeper interest
  4358. in register allocation.
  4359. To motivate the need for move biasing we return to the running example
  4360. but this time use all of the general purpose registers. So we have
  4361. the following mapping of color numbers to registers.
  4362. \[
  4363. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi} \}
  4364. \]
  4365. Using the same assignment of variables to color numbers that was
  4366. produced by the register allocator described in the last section, we
  4367. get the following program.
  4368. \begin{center}
  4369. \begin{minipage}{0.3\textwidth}
  4370. \begin{lstlisting}
  4371. movq $1, v
  4372. movq $42, w
  4373. movq v, x
  4374. addq $7, x
  4375. movq x, y
  4376. movq x, z
  4377. addq w, z
  4378. movq y, t
  4379. negq t
  4380. movq z, %rax
  4381. addq t, %rax
  4382. jmp conclusion
  4383. \end{lstlisting}
  4384. \end{minipage}
  4385. $\Rightarrow\qquad$
  4386. \begin{minipage}{0.45\textwidth}
  4387. \begin{lstlisting}
  4388. movq $1, %rdx
  4389. movq $42, %rcx
  4390. movq %rdx, %rdx
  4391. addq $7, %rdx
  4392. movq %rdx, %rsi
  4393. movq %rdx, %rdx
  4394. addq %rcx, %rdx
  4395. movq %rsi, %rcx
  4396. negq %rcx
  4397. movq %rdx, %rax
  4398. addq %rcx, %rax
  4399. jmp conclusion
  4400. \end{lstlisting}
  4401. \end{minipage}
  4402. \end{center}
  4403. In the above output code there are two \key{movq} instructions that
  4404. can be removed because their source and target are the same. However,
  4405. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  4406. register, we could instead remove three \key{movq} instructions. We
  4407. can accomplish this by taking into account which variables appear in
  4408. \key{movq} instructions with which other variables.
  4409. We say that two variables $p$ and $q$ are \emph{move
  4410. related}\index{move related} if they participate together in a
  4411. \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  4412. \key{movq} $q$\key{,} $p$. When the register allocator chooses a color
  4413. for a variable, it should prefer a color that has already been used
  4414. for a move-related variable (assuming that they do not interfere). Of
  4415. course, this preference should not override the preference for
  4416. registers over stack locations. This preference should be used as a
  4417. tie breaker when choosing between registers or when choosing between
  4418. stack locations.
  4419. We recommend representing the move relationships in a graph, similar
  4420. to how we represented interference. The following is the \emph{move
  4421. graph} for our running example.
  4422. \[
  4423. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4424. \node (rax) at (0,0) {$\ttm{rax}$};
  4425. \node (rsp) at (9,2) {$\ttm{rsp}$};
  4426. \node (t) at (0,2) {$\ttm{t}$};
  4427. \node (z) at (3,2) {$\ttm{z}$};
  4428. \node (x) at (6,2) {$\ttm{x}$};
  4429. \node (y) at (3,0) {$\ttm{y}$};
  4430. \node (w) at (6,0) {$\ttm{w}$};
  4431. \node (v) at (9,0) {$\ttm{v}$};
  4432. \draw (v) to (x);
  4433. \draw (x) to (y);
  4434. \draw (x) to (z);
  4435. \draw (y) to (t);
  4436. \end{tikzpicture}
  4437. \]
  4438. Now we replay the graph coloring, pausing to see the coloring of
  4439. \code{y}. Recall the following configuration. The most saturated vertices
  4440. were \code{w} and \code{y}.
  4441. \[
  4442. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4443. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4444. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4445. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  4446. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4447. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4448. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  4449. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  4450. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  4451. \draw (t1) to (rax);
  4452. \draw (t1) to (z);
  4453. \draw (z) to (y);
  4454. \draw (z) to (w);
  4455. \draw (x) to (w);
  4456. \draw (y) to (w);
  4457. \draw (v) to (w);
  4458. \draw (v) to (rsp);
  4459. \draw (w) to (rsp);
  4460. \draw (x) to (rsp);
  4461. \draw (y) to (rsp);
  4462. \path[-.,bend left=15] (z) edge node {} (rsp);
  4463. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4464. \draw (rax) to (rsp);
  4465. \end{tikzpicture}
  4466. \]
  4467. %
  4468. Last time we chose to color \code{w} with $0$. But this time we see
  4469. that \code{w} is not move related to any vertex, but \code{y} is move
  4470. related to \code{t}. So we choose to color \code{y} the same color as
  4471. \code{t}, $0$.
  4472. \[
  4473. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4474. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4475. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4476. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  4477. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4478. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4479. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  4480. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  4481. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  4482. \draw (t1) to (rax);
  4483. \draw (t1) to (z);
  4484. \draw (z) to (y);
  4485. \draw (z) to (w);
  4486. \draw (x) to (w);
  4487. \draw (y) to (w);
  4488. \draw (v) to (w);
  4489. \draw (v) to (rsp);
  4490. \draw (w) to (rsp);
  4491. \draw (x) to (rsp);
  4492. \draw (y) to (rsp);
  4493. \path[-.,bend left=15] (z) edge node {} (rsp);
  4494. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4495. \draw (rax) to (rsp);
  4496. \end{tikzpicture}
  4497. \]
  4498. Now \code{w} is the most saturated, so we color it $2$.
  4499. \[
  4500. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4501. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4502. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4503. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  4504. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4505. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  4506. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  4507. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  4508. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  4509. \draw (t1) to (rax);
  4510. \draw (t1) to (z);
  4511. \draw (z) to (y);
  4512. \draw (z) to (w);
  4513. \draw (x) to (w);
  4514. \draw (y) to (w);
  4515. \draw (v) to (w);
  4516. \draw (v) to (rsp);
  4517. \draw (w) to (rsp);
  4518. \draw (x) to (rsp);
  4519. \draw (y) to (rsp);
  4520. \path[-.,bend left=15] (z) edge node {} (rsp);
  4521. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4522. \draw (rax) to (rsp);
  4523. \end{tikzpicture}
  4524. \]
  4525. At this point, vertices \code{x} and \code{v} are most saturated, but
  4526. \code{x} is move related to \code{y} and \code{z}, so we color
  4527. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  4528. \[
  4529. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4530. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4531. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4532. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  4533. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4534. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  4535. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  4536. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  4537. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  4538. \draw (t1) to (rax);
  4539. \draw (t) to (z);
  4540. \draw (z) to (y);
  4541. \draw (z) to (w);
  4542. \draw (x) to (w);
  4543. \draw (y) to (w);
  4544. \draw (v) to (w);
  4545. \draw (v) to (rsp);
  4546. \draw (w) to (rsp);
  4547. \draw (x) to (rsp);
  4548. \draw (y) to (rsp);
  4549. \path[-.,bend left=15] (z) edge node {} (rsp);
  4550. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4551. \draw (rax) to (rsp);
  4552. \end{tikzpicture}
  4553. \]
  4554. So we have the following assignment of variables to registers.
  4555. \begin{gather*}
  4556. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  4557. \ttm{w} \mapsto \key{\%rsi}, \,
  4558. \ttm{x} \mapsto \key{\%rcx}, \,
  4559. \ttm{y} \mapsto \key{\%rcx}, \,
  4560. \ttm{z} \mapsto \key{\%rdx}, \,
  4561. \ttm{t} \mapsto \key{\%rcx} \}
  4562. \end{gather*}
  4563. We apply this register assignment to the running example, on the left,
  4564. to obtain the code in the middle. The \code{patch-instructions} then
  4565. removes the three trivial moves to obtain the code on the right.
  4566. \begin{minipage}{0.25\textwidth}
  4567. \begin{lstlisting}
  4568. movq $1, v
  4569. movq $42, w
  4570. movq v, x
  4571. addq $7, x
  4572. movq x, y
  4573. movq x, z
  4574. addq w, z
  4575. movq y, t
  4576. negq t
  4577. movq z, %rax
  4578. addq t, %rax
  4579. jmp conclusion
  4580. \end{lstlisting}
  4581. \end{minipage}
  4582. $\Rightarrow\qquad$
  4583. \begin{minipage}{0.25\textwidth}
  4584. \begin{lstlisting}
  4585. movq $1, %rcx
  4586. movq $42, %rsi
  4587. movq %rcx, %rcx
  4588. addq $7, %rcx
  4589. movq %rcx, %rcx
  4590. movq %rcx, %rdx
  4591. addq %rsi, %rdx
  4592. movq %rcx, %rcx
  4593. negq %rcx
  4594. movq %rdx, %rax
  4595. addq %rcx, %rax
  4596. jmp conclusion
  4597. \end{lstlisting}
  4598. \end{minipage}
  4599. $\Rightarrow\qquad$
  4600. \begin{minipage}{0.25\textwidth}
  4601. \begin{lstlisting}
  4602. movq $1, %rcx
  4603. movq $42, %rsi
  4604. addq $7, %rcx
  4605. movq %rcx, %rdx
  4606. addq %rsi, %rdx
  4607. negq %rcx
  4608. movq %rdx, %rax
  4609. addq %rcx, %rax
  4610. jmp conclusion
  4611. \end{lstlisting}
  4612. \end{minipage}
  4613. \begin{exercise}\normalfont
  4614. Change your implementation of \code{allocate-registers} to take move
  4615. biasing into account. Create two new tests that include at least one
  4616. opportunity for move biasing and visually inspect the output x86
  4617. programs to make sure that your move biasing is working properly. Make
  4618. sure that your compiler still passes all of the tests.
  4619. \end{exercise}
  4620. \margincomment{\footnotesize To do: another neat challenge would be to do
  4621. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  4622. %% \subsection{Output of the Running Example}
  4623. %% \label{sec:reg-alloc-output}
  4624. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  4625. the running example (Figure~\ref{fig:reg-eg}) with register allocation
  4626. and move biasing. To demonstrate both the use of registers and the
  4627. stack, we have limited the register allocator to use just two
  4628. registers: \code{rbx} and \code{rcx}. In the prelude\index{prelude}
  4629. of the \code{main} function, we push \code{rbx} onto the stack because
  4630. it is a callee-saved register and it was assigned to variable by the
  4631. register allocator. We subtract \code{8} from the \code{rsp} at the
  4632. end of the prelude to reserve space for the one spilled variable.
  4633. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  4634. Moving on the the \code{start} block, we see how the registers were
  4635. allocated. Variables \code{v}, \code{x}, and \code{y} were assigned to
  4636. \code{rbx} and variable \code{z} was assigned to \code{rcx}. Variable
  4637. \code{w} was spilled to the stack location \code{-16(\%rbp)}. Recall
  4638. that the prelude saved the callee-save register \code{rbx} onto the
  4639. stack. The spilled variables must be placed lower on the stack than
  4640. the saved callee-save registers, so in this case \code{w} is placed at
  4641. \code{-16(\%rbp)}.
  4642. In the \code{conclusion}\index{conclusion}, we undo the work that was
  4643. done in the prelude. We move the stack pointer up by \code{8} bytes
  4644. (the room for spilled variables), then we pop the old values of
  4645. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  4646. \code{retq} to return control to the operating system.
  4647. \begin{figure}[tbp]
  4648. % var_test_28.rkt
  4649. % (use-minimal-set-of-registers! #t)
  4650. % and only rbx rcx
  4651. % tmp 0 rbx
  4652. % z 1 rcx
  4653. % y 0 rbx
  4654. % w 2 16(%rbp)
  4655. % v 0 rbx
  4656. % x 0 rbx
  4657. \begin{lstlisting}
  4658. start:
  4659. movq $1, %rbx
  4660. movq $42, -16(%rbp)
  4661. addq $7, %rbx
  4662. movq %rbx, %rcx
  4663. addq -16(%rbp), %rcx
  4664. negq %rbx
  4665. movq %rcx, %rax
  4666. addq %rbx, %rax
  4667. jmp conclusion
  4668. .globl main
  4669. main:
  4670. pushq %rbp
  4671. movq %rsp, %rbp
  4672. pushq %rbx
  4673. subq $8, %rsp
  4674. jmp start
  4675. conclusion:
  4676. addq $8, %rsp
  4677. popq %rbx
  4678. popq %rbp
  4679. retq
  4680. \end{lstlisting}
  4681. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  4682. \label{fig:running-example-x86}
  4683. \end{figure}
  4684. % challenge: prioritize variables based on execution frequencies
  4685. % and the number of uses of a variable
  4686. % challenge: enhance the coloring algorithm using Chaitin's
  4687. % approach of prioritizing high-degree variables
  4688. % by removing low-degree variables (coloring them later)
  4689. % from the interference graph
  4690. \section{Further Reading}
  4691. \label{sec:register-allocation-further-reading}
  4692. Early register allocation algorithms were developed for Fortran
  4693. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  4694. of graph coloring began in the late 1970s and early 1980s with the
  4695. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  4696. algorithm is based on the following observation of
  4697. \citet{Kempe:1879aa} from the 1870s. If a graph $G$ has a vertex $v$
  4698. with degree lower than $k$, then $G$ is $k$ colorable if the subgraph
  4699. of $G$ with $v$ removed is also $k$ colorable. Suppose that the
  4700. subgraph is $k$ colorable. At worst the neighbors of $v$ are assigned
  4701. different colors, but since there are less than $k$ of them, there
  4702. will be one or more colors left over to use for coloring $v$ in $G$.
  4703. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  4704. less than $k$ from the graph and recursively colors the rest of the
  4705. graph. Upon returning from the recursion, it colors $v$ with one of
  4706. the available colors and returns. \citet{Chaitin:1982vn} augments
  4707. this algorithm to handle spilling as follows. If there are no vertices
  4708. of degree lower than $k$ then pick a vertex at random, spill it,
  4709. remove it from the graph, and proceed recursively to color the rest of
  4710. the graph.
  4711. Prior to coloring, \citet{Chaitin:1981vl} merge variables that are
  4712. move-related and that don't interfere with each other, a process
  4713. called \emph{coalescing}. While coalescing decreases the number of
  4714. moves, it can make the graph more difficult to
  4715. color. \citet{Briggs:1994kx} propose \emph{conservative coalescing} in
  4716. which two variables are merged only if they have fewer than $k$
  4717. neighbors of high degree. \citet{George:1996aa} observe that
  4718. conservative coalescing is sometimes too conservative and make it more
  4719. aggressive by iterating the coalescing with the removal of low-degree
  4720. vertices.
  4721. %
  4722. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  4723. also propose \emph{biased coloring} in which a variable is assigned to
  4724. the same color as another move-related variable if possible, as
  4725. discussed in Section~\ref{sec:move-biasing}.
  4726. %
  4727. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  4728. performs coalescing, graph coloring, and spill code insertion until
  4729. all variables have been assigned a location.
  4730. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  4731. spills variables that don't have to be: a high-degree variable can be
  4732. colorable if many of its neighbors are assigned the same color.
  4733. \citet{Briggs:1994kx} propose \emph{optimistic coloring}, in which a
  4734. high-degree vertex is not immediately spilled. Instead the decision is
  4735. deferred until after the recursive call, at which point it is apparent
  4736. whether there is actually an available color or not. We observe that
  4737. this algorithm is equivalent to the smallest-last ordering
  4738. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  4739. be registers and the rest to be stack locations.
  4740. %% biased coloring
  4741. Earlier editions of the compiler course at Indiana University
  4742. \citep{Dybvig:2010aa} were based on the algorithm of
  4743. \citet{Briggs:1994kx}.
  4744. The smallest-last ordering algorithm is one of many \emph{greedy}
  4745. coloring algorithms. A greedy coloring algorithm visits all the
  4746. vertices in a particular order and assigns each one the first
  4747. available color. An \emph{offline} greedy algorithm chooses the
  4748. ordering up-front, prior to assigning colors. The algorithm of
  4749. \citet{Chaitin:1981vl} should be considered offline because the vertex
  4750. ordering does not depend on the colors assigned, so the algorithm
  4751. could be split into two phases. Other orderings are possible. For
  4752. example, \citet{Chow:1984ys} order variables according an estimate of
  4753. runtime cost.
  4754. An \emph{online} greedy coloring algorithm uses information about the
  4755. current assignment of colors to influence the order in which the
  4756. remaining vertices are colored. The saturation-based algorithm
  4757. described in this chapter is one such algorithm. We choose to use
  4758. saturation-based coloring is because it is fun to introduce graph
  4759. coloring via Sudoku.
  4760. A register allocator may choose to map each variable to just one
  4761. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  4762. variable to one or more locations. The later can be achieved by
  4763. \emph{live range splitting}, where a variable is replaced by several
  4764. variables that each handle part of its live
  4765. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  4766. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  4767. %% replacement algorithm, bottom-up local
  4768. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  4769. %% Cooper: top-down (priority bassed), bottom-up
  4770. %% top-down
  4771. %% order variables by priority (estimated cost)
  4772. %% caveat: split variables into two groups:
  4773. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  4774. %% color the constrained ones first
  4775. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  4776. %% cite J. Cocke for an algorithm that colors variables
  4777. %% in a high-degree first ordering
  4778. %Register Allocation via Usage Counts, Freiburghouse CACM
  4779. \citet{Palsberg:2007si} observe that many of the interference graphs
  4780. that arise from Java programs in the JoeQ compiler are \emph{chordal},
  4781. that is, every cycle with four or more edges has an edge which is not
  4782. part of the cycle but which connects two vertices on the cycle. Such
  4783. graphs can be optimally colored by the greedy algorithm with a vertex
  4784. ordering determined by maximum cardinality search.
  4785. In situations where compile time is of utmost importance, such as in
  4786. just-in-time compilers, graph coloring algorithms can be too expensive
  4787. and the linear scan of \citet{Poletto:1999uq} may be more appropriate.
  4788. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4789. \chapter{Booleans and Control Flow}
  4790. \label{ch:Rif}
  4791. \index{Boolean}
  4792. \index{control flow}
  4793. \index{conditional expression}
  4794. The \LangInt{} and \LangVar{} languages only have a single kind of
  4795. value, integers. In this chapter we add a second kind of value, the
  4796. Booleans, to create the \LangIf{} language. The Boolean values
  4797. \emph{true} and \emph{false} are written \key{\#t} and \key{\#f}
  4798. respectively in Racket. The \LangIf{} language includes several
  4799. operations that involve Booleans (\key{and}, \key{not}, \key{eq?},
  4800. \key{<}, etc.) and the conditional \key{if} expression. With the
  4801. addition of \key{if}, programs can have non-trivial control flow which
  4802. impacts \code{explicate-control} and liveness analysis. Also, because
  4803. we now have two kinds of values, we need to handle programs that apply
  4804. an operation to the wrong kind of value, such as \code{(not 1)}.
  4805. There are two language design options for such situations. One option
  4806. is to signal an error and the other is to provide a wider
  4807. interpretation of the operation. The Racket language uses a mixture of
  4808. these two options, depending on the operation and the kind of
  4809. value. For example, the result of \code{(not 1)} in Racket is
  4810. \code{\#f} because Racket treats non-zero integers as if they were
  4811. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  4812. error in Racket because \code{car} expects a pair.
  4813. Typed Racket makes similar design choices as Racket, except much of
  4814. the error detection happens at compile time instead of run time. Typed
  4815. Racket accepts and runs \code{(not 1)}, producing \code{\#f}. But in
  4816. the case of \code{(car 1)}, Typed Racket reports a compile-time error
  4817. because Typed Racket expects the type of the argument to be of the
  4818. form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  4819. The \LangIf{} language performs type checking during compilation like
  4820. Typed Racket. In Chapter~\ref{ch:Rdyn} we study the
  4821. alternative choice, that is, a dynamically typed language like Racket.
  4822. The \LangIf{} language is a subset of Typed Racket; for some
  4823. operations we are more restrictive, for example, rejecting
  4824. \code{(not 1)}.
  4825. This chapter is organized as follows. We begin by defining the syntax
  4826. and interpreter for the \LangIf{} language
  4827. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  4828. checking and build a type checker for \LangIf{}
  4829. (Section~\ref{sec:type-check-Rif}). To compile \LangIf{} we need to
  4830. enlarge the intermediate language \LangCVar{} into \LangCIf{}
  4831. (Section~\ref{sec:Cif}) and \LangXInt{} into \LangXIf{}
  4832. (Section~\ref{sec:x86-if}). The remaining sections of this chapter
  4833. discuss how our compiler passes change to accommodate Booleans and
  4834. conditional control flow. There is one new pass, named \code{shrink},
  4835. that translates some operators into others, thereby reducing the
  4836. number of operators that need to be handled in later passes. The
  4837. largest changes occur in \code{explicate-control}, to translate
  4838. \code{if} expressions into control-flow graphs
  4839. (Section~\ref{sec:explicate-control-Rif}). Regarding register
  4840. allocation, the liveness analysis now has multiple basic blocks to
  4841. process and there is the interesting question of how to handle
  4842. conditional jumps.
  4843. \section{The \LangIf{} Language}
  4844. \label{sec:lang-if}
  4845. The concrete syntax of the \LangIf{} language is defined in
  4846. Figure~\ref{fig:Rif-concrete-syntax} and the abstract syntax is defined
  4847. in Figure~\ref{fig:Rif-syntax}. The \LangIf{} language includes all of
  4848. \LangVar{} (shown in gray), the Boolean literals \code{\#t} and
  4849. \code{\#f}, and the conditional \code{if} expression. We expand the
  4850. operators to include
  4851. \begin{enumerate}
  4852. \item subtraction on integers,
  4853. \item the logical operators \key{and}, \key{or} and \key{not},
  4854. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  4855. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  4856. comparing integers.
  4857. \end{enumerate}
  4858. We reorganize the abstract syntax for the primitive operations in
  4859. Figure~\ref{fig:Rif-syntax}, using only one grammar rule for all of
  4860. them. This means that the grammar no longer checks whether the arity
  4861. of an operators matches the number of arguments. That responsibility
  4862. is moved to the type checker for \LangIf{}, which we introduce in
  4863. Section~\ref{sec:type-check-Rif}.
  4864. \begin{figure}[tp]
  4865. \centering
  4866. \fbox{
  4867. \begin{minipage}{0.96\textwidth}
  4868. \[
  4869. \begin{array}{lcl}
  4870. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  4871. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  4872. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} } \mid \CSUB{\Exp}{\Exp} \\
  4873. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} } \\
  4874. &\mid& \itm{bool}
  4875. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  4876. \mid (\key{not}\;\Exp) \\
  4877. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} \\
  4878. \LangIf{} &::=& \Exp
  4879. \end{array}
  4880. \]
  4881. \end{minipage}
  4882. }
  4883. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  4884. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  4885. \label{fig:Rif-concrete-syntax}
  4886. \end{figure}
  4887. \begin{figure}[tp]
  4888. \centering
  4889. \fbox{
  4890. \begin{minipage}{0.96\textwidth}
  4891. \[
  4892. \begin{array}{lcl}
  4893. \itm{bool} &::=& \code{\#t} \mid \code{\#f} \\
  4894. \itm{cmp} &::= & \code{eq?} \mid \code{<} \mid \code{<=} \mid \code{>} \mid \code{>=} \\
  4895. \itm{op} &::= & \itm{cmp} \mid \code{read} \mid \code{+} \mid \code{-}
  4896. \mid \code{and} \mid \code{or} \mid \code{not} \\
  4897. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  4898. &\mid& \PRIM{\itm{op}}{\Exp\ldots}\\
  4899. &\mid& \BOOL{\itm{bool}} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4900. \LangIf{} &::=& \PROGRAM{\code{'()}}{\Exp}
  4901. \end{array}
  4902. \]
  4903. \end{minipage}
  4904. }
  4905. \caption{The abstract syntax of \LangIf{}.}
  4906. \label{fig:Rif-syntax}
  4907. \end{figure}
  4908. Figure~\ref{fig:interp-Rif} defines the interpreter for \LangIf{},
  4909. which inherits from the interpreter for \LangVar{}
  4910. (Figure~\ref{fig:interp-Rvar}). The literals \code{\#t} and \code{\#f}
  4911. evaluate to the corresponding Boolean values. The conditional
  4912. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  4913. \itm{cnd} and then either evaluates \itm{thn} or \itm{els} depending
  4914. on whether \itm{cnd} produced \code{\#t} or \code{\#f}. The logical
  4915. operations \code{not} and \code{and} behave as you might expect, but
  4916. note that the \code{and} operation is short-circuiting. That is, given
  4917. the expression $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not
  4918. evaluated if $e_1$ evaluates to \code{\#f}.
  4919. With the increase in the number of primitive operations, the
  4920. interpreter would become repetitive without some care. We refactor
  4921. the case for \code{Prim}, moving the code that differs with each
  4922. operation into the \code{interp-op} method shown in in
  4923. Figure~\ref{fig:interp-op-Rif}. We handle the \code{and} operation
  4924. separately because of its short-circuiting behavior.
  4925. \begin{figure}[tbp]
  4926. \begin{lstlisting}
  4927. (define interp-Rif-class
  4928. (class interp-Rvar-class
  4929. (super-new)
  4930. (define/public (interp-op op) ...)
  4931. (define/override ((interp-exp env) e)
  4932. (define recur (interp-exp env))
  4933. (match e
  4934. [(Bool b) b]
  4935. [(If cnd thn els)
  4936. (match (recur cnd)
  4937. [#t (recur thn)]
  4938. [#f (recur els)])]
  4939. [(Prim 'and (list e1 e2))
  4940. (match (recur e1)
  4941. [#t (match (recur e2) [#t #t] [#f #f])]
  4942. [#f #f])]
  4943. [(Prim op args)
  4944. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  4945. [else ((super interp-exp env) e)]))
  4946. ))
  4947. (define (interp-Rif p)
  4948. (send (new interp-Rif-class) interp-program p))
  4949. \end{lstlisting}
  4950. \caption{Interpreter for the \LangIf{} language. (See
  4951. Figure~\ref{fig:interp-op-Rif} for \code{interp-op}.)}
  4952. \label{fig:interp-Rif}
  4953. \end{figure}
  4954. \begin{figure}[tbp]
  4955. \begin{lstlisting}
  4956. (define/public (interp-op op)
  4957. (match op
  4958. ['+ fx+]
  4959. ['- fx-]
  4960. ['read read-fixnum]
  4961. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  4962. ['or (lambda (v1 v2)
  4963. (cond [(and (boolean? v1) (boolean? v2))
  4964. (or v1 v2)]))]
  4965. ['eq? (lambda (v1 v2)
  4966. (cond [(or (and (fixnum? v1) (fixnum? v2))
  4967. (and (boolean? v1) (boolean? v2))
  4968. (and (vector? v1) (vector? v2)))
  4969. (eq? v1 v2)]))]
  4970. ['< (lambda (v1 v2)
  4971. (cond [(and (fixnum? v1) (fixnum? v2))
  4972. (< v1 v2)]))]
  4973. ['<= (lambda (v1 v2)
  4974. (cond [(and (fixnum? v1) (fixnum? v2))
  4975. (<= v1 v2)]))]
  4976. ['> (lambda (v1 v2)
  4977. (cond [(and (fixnum? v1) (fixnum? v2))
  4978. (> v1 v2)]))]
  4979. ['>= (lambda (v1 v2)
  4980. (cond [(and (fixnum? v1) (fixnum? v2))
  4981. (>= v1 v2)]))]
  4982. [else (error 'interp-op "unknown operator")]))
  4983. \end{lstlisting}
  4984. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  4985. \label{fig:interp-op-Rif}
  4986. \end{figure}
  4987. \section{Type Checking \LangIf{} Programs}
  4988. \label{sec:type-check-Rif}
  4989. \index{type checking}
  4990. \index{semantic analysis}
  4991. It is helpful to think about type checking in two complementary
  4992. ways. A type checker predicts the type of value that will be produced
  4993. by each expression in the program. For \LangIf{}, we have just two types,
  4994. \key{Integer} and \key{Boolean}. So a type checker should predict that
  4995. \begin{lstlisting}
  4996. (+ 10 (- (+ 12 20)))
  4997. \end{lstlisting}
  4998. produces an \key{Integer} while
  4999. \begin{lstlisting}
  5000. (and (not #f) #t)
  5001. \end{lstlisting}
  5002. produces a \key{Boolean}.
  5003. Another way to think about type checking is that it enforces a set of
  5004. rules about which operators can be applied to which kinds of
  5005. values. For example, our type checker for \LangIf{} signals an error
  5006. for the below expression
  5007. \begin{lstlisting}
  5008. (not (+ 10 (- (+ 12 20))))
  5009. \end{lstlisting}
  5010. The subexpression \code{(+ 10 (- (+ 12 20)))} has type \key{Integer}
  5011. but the type checker enforces the rule that the argument of \code{not}
  5012. must be a \key{Boolean}.
  5013. We implement type checking using classes and methods because they
  5014. provide the open recursion needed to reuse code as we extend the type
  5015. checker in later chapters, analogous to the use of classes and methods
  5016. for the interpreters (Section~\ref{sec:extensible-interp}).
  5017. We separate the type checker for the \LangVar{} fragment into its own
  5018. class, shown in Figure~\ref{fig:type-check-Rvar}. The type checker for
  5019. \LangIf{} is shown in Figure~\ref{fig:type-check-Rif} and it inherits
  5020. from the type checker for \LangVar{}. These type checkers are in the
  5021. files \code{type-check-Rvar.rkt} and \code{type-check-Rif.rkt} of the
  5022. support code.
  5023. %
  5024. Each type checker is a structurally recursive function over the AST.
  5025. Given an input expression \code{e}, the type checker either signals an
  5026. error or returns an expression and its type (\key{Integer} or
  5027. \key{Boolean}). It returns an expression because there are situations
  5028. in which we want to change or update the expression.
  5029. Next we discuss the \code{match} cases in \code{type-check-exp} of
  5030. Figure~\ref{fig:type-check-Rvar}. The type of an integer constant is
  5031. \code{Integer}. To handle variables, the type checker uses the
  5032. environment \code{env} to map variables to types. Consider the case
  5033. for \key{let}. We type check the initializing expression to obtain
  5034. its type \key{T} and then associate type \code{T} with the variable
  5035. \code{x} in the environment used to type check the body of the
  5036. \key{let}. Thus, when the type checker encounters a use of variable
  5037. \code{x}, it can find its type in the environment. Regarding
  5038. primitive operators, we recursively analyze the arguments and then
  5039. invoke \code{type-check-op} to check whether the argument types are
  5040. allowed.
  5041. Several auxiliary methods are used in the type checker. The method
  5042. \code{operator-types} defines a dictionary that maps the operator
  5043. names to their parameter and return types. The \code{type-equal?}
  5044. method determines whether two types are equal, which for now simply
  5045. dispatches to \code{equal?} (deep equality). The
  5046. \code{check-type-equal?} method triggers an error if the two types are
  5047. not equal. The \code{type-check-op} method looks up the operator in
  5048. the \code{operator-types} dictionary and then checks whether the
  5049. argument types are equal to the parameter types. The result is the
  5050. return type of the operator.
  5051. \begin{figure}[tbp]
  5052. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5053. (define type-check-Rvar-class
  5054. (class object%
  5055. (super-new)
  5056. (define/public (operator-types)
  5057. '((+ . ((Integer Integer) . Integer))
  5058. (- . ((Integer) . Integer))
  5059. (read . (() . Integer))))
  5060. (define/public (type-equal? t1 t2) (equal? t1 t2))
  5061. (define/public (check-type-equal? t1 t2 e)
  5062. (unless (type-equal? t1 t2)
  5063. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  5064. (define/public (type-check-op op arg-types e)
  5065. (match (dict-ref (operator-types) op)
  5066. [`(,param-types . ,return-type)
  5067. (for ([at arg-types] [pt param-types])
  5068. (check-type-equal? at pt e))
  5069. return-type]
  5070. [else (error 'type-check-op "unrecognized ~a" op)]))
  5071. (define/public (type-check-exp env)
  5072. (lambda (e)
  5073. (match e
  5074. [(Int n) (values (Int n) 'Integer)]
  5075. [(Var x) (values (Var x) (dict-ref env x))]
  5076. [(Let x e body)
  5077. (define-values (e^ Te) ((type-check-exp env) e))
  5078. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  5079. (values (Let x e^ b) Tb)]
  5080. [(Prim op es)
  5081. (define-values (new-es ts)
  5082. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  5083. (values (Prim op new-es) (type-check-op op ts e))]
  5084. [else (error 'type-check-exp "couldn't match" e)])))
  5085. (define/public (type-check-program e)
  5086. (match e
  5087. [(Program info body)
  5088. (define-values (body^ Tb) ((type-check-exp '()) body))
  5089. (check-type-equal? Tb 'Integer body)
  5090. (Program info body^)]
  5091. [else (error 'type-check-Rvar "couldn't match ~a" e)]))
  5092. ))
  5093. (define (type-check-Rvar p)
  5094. (send (new type-check-Rvar-class) type-check-program p))
  5095. \end{lstlisting}
  5096. \caption{Type checker for the \LangVar{} language.}
  5097. \label{fig:type-check-Rvar}
  5098. \end{figure}
  5099. \begin{figure}[tbp]
  5100. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5101. (define type-check-Rif-class
  5102. (class type-check-Rvar-class
  5103. (super-new)
  5104. (inherit check-type-equal?)
  5105. (define/override (operator-types)
  5106. (append '((- . ((Integer Integer) . Integer))
  5107. (and . ((Boolean Boolean) . Boolean))
  5108. (or . ((Boolean Boolean) . Boolean))
  5109. (< . ((Integer Integer) . Boolean))
  5110. (<= . ((Integer Integer) . Boolean))
  5111. (> . ((Integer Integer) . Boolean))
  5112. (>= . ((Integer Integer) . Boolean))
  5113. (not . ((Boolean) . Boolean))
  5114. )
  5115. (super operator-types)))
  5116. (define/override (type-check-exp env)
  5117. (lambda (e)
  5118. (match e
  5119. [(Prim 'eq? (list e1 e2))
  5120. (define-values (e1^ T1) ((type-check-exp env) e1))
  5121. (define-values (e2^ T2) ((type-check-exp env) e2))
  5122. (check-type-equal? T1 T2 e)
  5123. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  5124. [(Bool b) (values (Bool b) 'Boolean)]
  5125. [(If cnd thn els)
  5126. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  5127. (define-values (thn^ Tt) ((type-check-exp env) thn))
  5128. (define-values (els^ Te) ((type-check-exp env) els))
  5129. (check-type-equal? Tc 'Boolean e)
  5130. (check-type-equal? Tt Te e)
  5131. (values (If cnd^ thn^ els^) Te)]
  5132. [else ((super type-check-exp env) e)])))
  5133. ))
  5134. (define (type-check-Rif p)
  5135. (send (new type-check-Rif-class) type-check-program p))
  5136. \end{lstlisting}
  5137. \caption{Type checker for the \LangIf{} language.}
  5138. \label{fig:type-check-Rif}
  5139. \end{figure}
  5140. Next we discuss the type checker for \LangIf{} in
  5141. Figure~\ref{fig:type-check-Rif}. The operator \code{eq?} requires the
  5142. two arguments to have the same type. The type of a Boolean constant is
  5143. \code{Boolean}. The condition of an \code{if} must be of
  5144. \code{Boolean} type and the two branches must have the same type. The
  5145. \code{operator-types} function adds dictionary entries for the other
  5146. new operators.
  5147. \begin{exercise}\normalfont
  5148. Create 10 new test programs in \LangIf{}. Half of the programs should
  5149. have a type error. For those programs, create an empty file with the
  5150. same base name but with file extension \code{.tyerr}. For example, if
  5151. the test \code{cond\_test\_14.rkt} is expected to error, then create
  5152. an empty file named \code{cond\_test\_14.tyerr}. This indicates to
  5153. \code{interp-tests} and \code{compiler-tests} that a type error is
  5154. expected. The other half of the test programs should not have type
  5155. errors.
  5156. In the \code{run-tests.rkt} script, change the second argument of
  5157. \code{interp-tests} and \code{compiler-tests} to
  5158. \code{type-check-Rif}, which causes the type checker to run prior to
  5159. the compiler passes. Temporarily change the \code{passes} to an empty
  5160. list and run the script, thereby checking that the new test programs
  5161. either type check or not as intended.
  5162. \end{exercise}
  5163. \section{The \LangCIf{} Intermediate Language}
  5164. \label{sec:Cif}
  5165. Figure~\ref{fig:c1-syntax} defines the abstract syntax of the
  5166. \LangCIf{} intermediate language. (The concrete syntax is in the
  5167. Appendix, Figure~\ref{fig:c1-concrete-syntax}.) Compared to
  5168. \LangCVar{}, the \LangCIf{} language adds logical and comparison
  5169. operators to the \Exp{} non-terminal and the literals \key{\#t} and
  5170. \key{\#f} to the \Arg{} non-terminal.
  5171. Regarding control flow, \LangCIf{} adds \key{goto} and \code{if}
  5172. statements to the \Tail{} non-terminal. The condition of an \code{if}
  5173. statement is a comparison operation and the branches are \code{goto}
  5174. statements, making it straightforward to compile \code{if} statements
  5175. to x86.
  5176. \begin{figure}[tp]
  5177. \fbox{
  5178. \begin{minipage}{0.96\textwidth}
  5179. \small
  5180. \[
  5181. \begin{array}{lcl}
  5182. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  5183. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  5184. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  5185. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  5186. &\mid& \UNIOP{\key{'not}}{\Atm}
  5187. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  5188. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  5189. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  5190. \mid \GOTO{\itm{label}} \\
  5191. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  5192. \LangCIf{} & ::= & \gray{\CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}}
  5193. \end{array}
  5194. \]
  5195. \end{minipage}
  5196. }
  5197. \caption{The abstract syntax of \LangCIf{}, an extension of \LangCVar{}
  5198. (Figure~\ref{fig:c0-syntax}).}
  5199. \label{fig:c1-syntax}
  5200. \end{figure}
  5201. \section{The \LangXIf{} Language}
  5202. \label{sec:x86-if}
  5203. \index{x86} To implement the new logical operations, the comparison
  5204. operations, and the \key{if} expression, we need to delve further into
  5205. the x86 language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1}
  5206. define the concrete and abstract syntax for the \LangXIf{} subset
  5207. of x86, which includes instructions for logical operations,
  5208. comparisons, and conditional jumps.
  5209. One challenge is that x86 does not provide an instruction that
  5210. directly implements logical negation (\code{not} in \LangIf{} and
  5211. \LangCIf{}). However, the \code{xorq} instruction can be used to
  5212. encode \code{not}. The \key{xorq} instruction takes two arguments,
  5213. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  5214. bit of its arguments, and writes the results into its second argument.
  5215. Recall the truth table for exclusive-or:
  5216. \begin{center}
  5217. \begin{tabular}{l|cc}
  5218. & 0 & 1 \\ \hline
  5219. 0 & 0 & 1 \\
  5220. 1 & 1 & 0
  5221. \end{tabular}
  5222. \end{center}
  5223. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  5224. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  5225. for the bit $1$, the result is the opposite of the second bit. Thus,
  5226. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  5227. the first argument:
  5228. \[
  5229. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  5230. \qquad\Rightarrow\qquad
  5231. \begin{array}{l}
  5232. \key{movq}~ \Arg\key{,} \Var\\
  5233. \key{xorq}~ \key{\$1,} \Var
  5234. \end{array}
  5235. \]
  5236. \begin{figure}[tp]
  5237. \fbox{
  5238. \begin{minipage}{0.96\textwidth}
  5239. \[
  5240. \begin{array}{lcl}
  5241. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  5242. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  5243. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} } \mid \key{\%}\itm{bytereg}\\
  5244. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  5245. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \mid
  5246. \key{subq} \; \Arg\key{,} \Arg \mid
  5247. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid } \\
  5248. && \gray{ \key{callq} \; \itm{label} \mid
  5249. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} } \\
  5250. && \gray{ \itm{label}\key{:}\; \Instr }
  5251. \mid \key{xorq}~\Arg\key{,}~\Arg
  5252. \mid \key{cmpq}~\Arg\key{,}~\Arg \mid \\
  5253. && \key{set}cc~\Arg
  5254. \mid \key{movzbq}~\Arg\key{,}~\Arg
  5255. \mid \key{j}cc~\itm{label}
  5256. \\
  5257. \LangXIf{} &::= & \gray{ \key{.globl main} }\\
  5258. & & \gray{ \key{main:} \; \Instr\ldots }
  5259. \end{array}
  5260. \]
  5261. \end{minipage}
  5262. }
  5263. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  5264. \label{fig:x86-1-concrete}
  5265. \end{figure}
  5266. \begin{figure}[tp]
  5267. \fbox{
  5268. \begin{minipage}{0.98\textwidth}
  5269. \small
  5270. \[
  5271. \begin{array}{lcl}
  5272. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  5273. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  5274. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}}
  5275. \mid \BYTEREG{\itm{bytereg}} \\
  5276. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  5277. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  5278. \mid \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  5279. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  5280. \mid \UNIINSTR{\code{negq}}{\Arg} } \\
  5281. &\mid& \gray{ \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  5282. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  5283. &\mid& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  5284. \mid \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  5285. &\mid& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  5286. \mid \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  5287. &\mid& \JMPIF{\itm{cc}}{\itm{label}} \\
  5288. \Block &::= & \gray{\BLOCK{\itm{info}}{\LP\Instr\ldots\RP}} \\
  5289. \LangXIf{} &::= & \gray{\XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}}
  5290. \end{array}
  5291. \]
  5292. \end{minipage}
  5293. }
  5294. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  5295. \label{fig:x86-1}
  5296. \end{figure}
  5297. Next we consider the x86 instructions that are relevant for compiling
  5298. the comparison operations. The \key{cmpq} instruction compares its two
  5299. arguments to determine whether one argument is less than, equal, or
  5300. greater than the other argument. The \key{cmpq} instruction is unusual
  5301. regarding the order of its arguments and where the result is
  5302. placed. The argument order is backwards: if you want to test whether
  5303. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  5304. \key{cmpq} is placed in the special EFLAGS register. This register
  5305. cannot be accessed directly but it can be queried by a number of
  5306. instructions, including the \key{set} instruction. The instruction
  5307. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  5308. depending on whether the comparison comes out according to the
  5309. condition code \itm{cc} (\key{e} for equal, \key{l} for less, \key{le}
  5310. for less-or-equal, \key{g} for greater, \key{ge} for
  5311. greater-or-equal). The \key{set} instruction has an annoying quirk in
  5312. that its destination argument must be single byte register, such as
  5313. \code{al} (L for lower bits) or \code{ah} (H for higher bits), which
  5314. are part of the \code{rax} register. Thankfully, the \key{movzbq}
  5315. instruction can be used to move from a single byte register to a
  5316. normal 64-bit register. The abstract syntax for the \code{set}
  5317. instruction differs from the concrete syntax in that it separates the
  5318. instruction name from the condition code.
  5319. The x86 instruction for conditional jump is relevant to the
  5320. compilation of \key{if} expressions. The instruction
  5321. $\key{j}\itm{cc}~\itm{label}$ updates the program counter to point to
  5322. the instruction after \itm{label} depending on whether the result in
  5323. the EFLAGS register matches the condition code \itm{cc}, otherwise the
  5324. jump instruction falls through to the next instruction. Like the
  5325. abstract syntax for \code{set}, the abstract syntax for conditional
  5326. jump separates the instruction name from the condition code. For
  5327. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  5328. the conditional jump instruction relies on the EFLAGS register, it is
  5329. common for it to be immediately preceded by a \key{cmpq} instruction
  5330. to set the EFLAGS register.
  5331. \section{Shrink the \LangIf{} Language}
  5332. \label{sec:shrink-Rif}
  5333. The \LangIf{} language includes several operators that are easily
  5334. expressible with other operators. For example, subtraction is
  5335. expressible using addition and negation.
  5336. \[
  5337. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  5338. \]
  5339. Several of the comparison operations are expressible using less-than
  5340. and logical negation.
  5341. \[
  5342. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  5343. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  5344. \]
  5345. The \key{let} is needed in the above translation to ensure that
  5346. expression $e_1$ is evaluated before $e_2$.
  5347. By performing these translations in the front-end of the compiler, the
  5348. later passes of the compiler do not need to deal with these operators,
  5349. making the passes shorter.
  5350. %% On the other hand, sometimes
  5351. %% these translations make it more difficult to generate the most
  5352. %% efficient code with respect to the number of instructions. However,
  5353. %% these differences typically do not affect the number of accesses to
  5354. %% memory, which is the primary factor that determines execution time on
  5355. %% modern computer architectures.
  5356. \begin{exercise}\normalfont
  5357. Implement the pass \code{shrink} to remove subtraction, \key{and},
  5358. \key{or}, \key{<=}, \key{>}, and \key{>=} from the language by
  5359. translating them to other constructs in \LangIf{}.
  5360. %
  5361. Create six test programs that involve these operators.
  5362. %
  5363. In the \code{run-tests.rkt} script, add the following entry for
  5364. \code{shrink} to the list of passes (it should be the only pass at
  5365. this point).
  5366. \begin{lstlisting}
  5367. (list "shrink" shrink interp-Rif type-check-Rif)
  5368. \end{lstlisting}
  5369. This instructs \code{interp-tests} to run the intepreter
  5370. \code{interp-Rif} and the type checker \code{type-check-Rif} on the
  5371. output of \code{shrink}.
  5372. %
  5373. Run the script to test your compiler on all the test programs.
  5374. \end{exercise}
  5375. \section{Uniquify Variables}
  5376. \label{sec:uniquify-Rif}
  5377. Add cases to \code{uniquify-exp} to handle Boolean constants and
  5378. \code{if} expressions.
  5379. \begin{exercise}\normalfont
  5380. Update the \code{uniquify-exp} for \LangIf{} and add the following
  5381. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  5382. \begin{lstlisting}
  5383. (list "uniquify" uniquify interp-Rif type-check-Rif)
  5384. \end{lstlisting}
  5385. Run the script to test your compiler.
  5386. \end{exercise}
  5387. \section{Remove Complex Operands}
  5388. \label{sec:remove-complex-opera-Rif}
  5389. The output language for this pass is \LangIfANF{}
  5390. (Figure~\ref{fig:Rif-anf-syntax}), the administrative normal form of
  5391. \LangIf{}. The \code{Bool} form is an atomic expressions but
  5392. \code{If} is not. All three sub-expressions of an \code{If} are
  5393. allowed to be complex expressions but the operands of \code{not} and
  5394. the comparisons must be atoms.
  5395. Add cases for \code{Bool} and \code{If} to the \code{rco-exp} and
  5396. \code{rco-atom} functions according to whether the output needs to be
  5397. \Exp{} or \Atm{} as specified in the grammar for \LangIfANF{}.
  5398. Regarding \code{If}, it is particularly important to \textbf{not}
  5399. replace its condition with a temporary variable because that would
  5400. interfere with the generation of high-quality output in the
  5401. \code{explicate-control} pass.
  5402. \begin{figure}[tp]
  5403. \centering
  5404. \fbox{
  5405. \begin{minipage}{0.96\textwidth}
  5406. \[
  5407. \begin{array}{rcl}
  5408. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} } \mid \BOOL{\itm{bool}}\\
  5409. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  5410. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  5411. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  5412. &\mid& \UNIOP{\key{not}}{\Atm} \\
  5413. &\mid& \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} \\
  5414. R^{\dagger}_2 &::=& \PROGRAM{\code{()}}{\Exp}
  5415. \end{array}
  5416. \]
  5417. \end{minipage}
  5418. }
  5419. \caption{\LangIfANF{} is \LangIf{} in administrative normal form (ANF).}
  5420. \label{fig:Rif-anf-syntax}
  5421. \end{figure}
  5422. \begin{exercise}\normalfont
  5423. %
  5424. Add cases for Boolean constants and \code{if} to the \code{rco-atom}
  5425. and \code{rco-exp} functions in \code{compiler.rkt}.
  5426. %
  5427. Create three new \LangInt{} programs that exercise the interesting
  5428. code in this pass.
  5429. %
  5430. In the \code{run-tests.rkt} script, add the following entry to the
  5431. list of \code{passes} and then run the script to test your compiler.
  5432. \begin{lstlisting}
  5433. (list "remove-complex" remove-complex-opera* interp-Rif type-check-Rif)
  5434. \end{lstlisting}
  5435. \end{exercise}
  5436. \section{Explicate Control}
  5437. \label{sec:explicate-control-Rif}
  5438. Recall that the purpose of \code{explicate-control} is to make the
  5439. order of evaluation explicit in the syntax of the program. With the
  5440. addition of \key{if} this get more interesting.
  5441. As a motivating example, consider the following program that has an
  5442. \key{if} expression nested in the predicate of another \key{if}.
  5443. % cond_test_41.rkt
  5444. \begin{center}
  5445. \begin{minipage}{0.96\textwidth}
  5446. \begin{lstlisting}
  5447. (let ([x (read)])
  5448. (let ([y (read)])
  5449. (if (if (< x 1) (eq? x 0) (eq? x 2))
  5450. (+ y 2)
  5451. (+ y 10))))
  5452. \end{lstlisting}
  5453. \end{minipage}
  5454. \end{center}
  5455. %
  5456. The naive way to compile \key{if} and the comparison would be to
  5457. handle each of them in isolation, regardless of their context. Each
  5458. comparison would be translated into a \key{cmpq} instruction followed
  5459. by a couple instructions to move the result from the EFLAGS register
  5460. into a general purpose register or stack location. Each \key{if} would
  5461. be translated into a \key{cmpq} instruction followed by a conditional
  5462. jump. The generated code for the inner \key{if} in the above example
  5463. would be as follows.
  5464. \begin{center}
  5465. \begin{minipage}{0.96\textwidth}
  5466. \begin{lstlisting}
  5467. ...
  5468. cmpq $1, x ;; (< x 1)
  5469. setl %al
  5470. movzbq %al, tmp
  5471. cmpq $1, tmp ;; (if ...)
  5472. je then_branch_1
  5473. jmp else_branch_1
  5474. ...
  5475. \end{lstlisting}
  5476. \end{minipage}
  5477. \end{center}
  5478. However, if we take context into account we can do better and reduce
  5479. the use of \key{cmpq} instructions for accessing the EFLAG register.
  5480. Our goal will be compile \key{if} expressions so that the relevant
  5481. comparison instruction appears directly before the conditional jump.
  5482. For example, we want to generate the following code for the inner
  5483. \code{if}.
  5484. \begin{center}
  5485. \begin{minipage}{0.96\textwidth}
  5486. \begin{lstlisting}
  5487. ...
  5488. cmpq $1, x
  5489. je then_branch_1
  5490. jmp else_branch_1
  5491. ...
  5492. \end{lstlisting}
  5493. \end{minipage}
  5494. \end{center}
  5495. One way to achieve this is to reorganize the code at the level of
  5496. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  5497. the following code.
  5498. \begin{center}
  5499. \begin{minipage}{0.96\textwidth}
  5500. \begin{lstlisting}
  5501. (let ([x (read)])
  5502. (let ([y (read)])
  5503. (if (< x 1)
  5504. (if (eq? x 0)
  5505. (+ y 2)
  5506. (+ y 10))
  5507. (if (eq? x 2)
  5508. (+ y 2)
  5509. (+ y 10)))))
  5510. \end{lstlisting}
  5511. \end{minipage}
  5512. \end{center}
  5513. Unfortunately, this approach duplicates the two branches from the
  5514. outer \code{if} and a compiler must never duplicate code!
  5515. We need a way to perform the above transformation but without
  5516. duplicating code. That is, we need a way for different parts of a
  5517. program to refer to the same piece of code. At the level of x86
  5518. assembly this is straightforward because we can label the code for
  5519. each branch and insert jumps in all the places that need to execute
  5520. the branch. In our intermediate language, we need to move away from
  5521. abstract syntax \emph{trees} and instead use \emph{graphs}. In
  5522. particular, we use a standard program representation called a
  5523. \emph{control flow graph} (CFG), due to Frances Elizabeth
  5524. \citet{Allen:1970uq}. \index{control-flow graph} Each vertex is a
  5525. labeled sequence of code, called a \emph{basic block}, and each edge
  5526. represents a jump to another block. The \key{CProgram} construct of
  5527. \LangCVar{} and \LangCIf{} contains a control flow graph represented
  5528. as an alist mapping labels to basic blocks. Each basic block is
  5529. represented by the $\Tail$ non-terminal.
  5530. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  5531. \code{remove-complex-opera*} pass and then the
  5532. \code{explicate-control} pass on the example program. We walk through
  5533. the output program and then discuss the algorithm.
  5534. %
  5535. Following the order of evaluation in the output of
  5536. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  5537. and then the comparison \lstinline{(< x 1)} in the predicate of the
  5538. inner \key{if}. In the output of \code{explicate-control}, in the
  5539. block labeled \code{start}, is two assignment statements followed by a
  5540. \code{if} statement that branches to \code{block40} or
  5541. \code{block41}. The blocks associated with those labels contain the
  5542. translations of the code \lstinline{(eq? x 0)} and \lstinline{(eq? x 2)},
  5543. respectively. In particular, we start \code{block40} with the
  5544. comparison \lstinline{(eq? x 0)} and then branch to \code{block38} or
  5545. \code{block39}, the two branches of the outer \key{if}, i.e.,
  5546. \lstinline{(+ y 2)} and \lstinline{(+ y 10)}. The story for
  5547. \code{block41} is similar.
  5548. \begin{figure}[tbp]
  5549. \begin{tabular}{lll}
  5550. \begin{minipage}{0.4\textwidth}
  5551. % cond_test_41.rkt
  5552. \begin{lstlisting}
  5553. (let ([x (read)])
  5554. (let ([y (read)])
  5555. (if (if (< x 1)
  5556. (eq? x 0)
  5557. (eq? x 2))
  5558. (+ y 2)
  5559. (+ y 10))))
  5560. \end{lstlisting}
  5561. \hspace{40pt}$\Downarrow$
  5562. \begin{lstlisting}
  5563. (let ([x (read)])
  5564. (let ([y (read)])
  5565. (if (if (< x 1)
  5566. (eq? x 0)
  5567. (eq? x 2))
  5568. (+ y 2)
  5569. (+ y 10))))
  5570. \end{lstlisting}
  5571. \end{minipage}
  5572. &
  5573. $\Rightarrow$
  5574. &
  5575. \begin{minipage}{0.55\textwidth}
  5576. \begin{lstlisting}
  5577. start:
  5578. x = (read);
  5579. y = (read);
  5580. if (< x 1) goto block40;
  5581. else goto block41;
  5582. block40:
  5583. if (eq? x 0) goto block38;
  5584. else goto block39;
  5585. block41:
  5586. if (eq? x 2) goto block38;
  5587. else goto block39;
  5588. block38:
  5589. return (+ y 2);
  5590. block39:
  5591. return (+ y 10);
  5592. \end{lstlisting}
  5593. \end{minipage}
  5594. \end{tabular}
  5595. \caption{Translation from \LangIf{} to \LangCIf{}
  5596. via the \code{explicate-control}.}
  5597. \label{fig:explicate-control-s1-38}
  5598. \end{figure}
  5599. %% The nice thing about the output of \code{explicate-control} is that
  5600. %% there are no unnecessary comparisons and every comparison is part of a
  5601. %% conditional jump.
  5602. %% The down-side of this output is that it includes
  5603. %% trivial blocks, such as the blocks labeled \code{block92} through
  5604. %% \code{block95}, that only jump to another block. We discuss a solution
  5605. %% to this problem in Section~\ref{sec:opt-jumps}.
  5606. Recall that in Section~\ref{sec:explicate-control-Rvar} we implement
  5607. \code{explicate-control} for \LangVar{} using two mutually recursive
  5608. functions, \code{explicate-tail} and \code{explicate-assign}. The
  5609. former function translates expressions in tail position whereas the
  5610. later function translates expressions on the right-hand-side of a
  5611. \key{let}. With the addition of \key{if} expression in \LangIf{} we
  5612. have a new kind of position to deal with: the predicate position of
  5613. the \key{if}. We need another function, \code{explicate-pred}, that
  5614. takes an \LangIf{} expression and two blocks for the then-branch and
  5615. else-branch. The output of \code{explicate-pred} is a block.
  5616. %
  5617. In the following paragraphs we discuss specific cases in the
  5618. \code{explicate-pred} function as well as additions to the
  5619. \code{explicate-tail} and \code{explicate-assign} functions.
  5620. \begin{figure}[tbp]
  5621. \begin{lstlisting}
  5622. (define (explicate-pred cnd thn els)
  5623. (match cnd
  5624. [(Var x) ___]
  5625. [(Let x rhs body) ___]
  5626. [(Prim 'not (list e)) ___]
  5627. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  5628. (IfStmt (Prim op arg*) (force (block->goto thn))
  5629. (force (block->goto els)))]
  5630. [(Bool b) (if b thn els)]
  5631. [(If cnd^ thn^ els^) ___]
  5632. [else (error "explicate-pred unhandled case" cnd)]))
  5633. \end{lstlisting}
  5634. \caption{Skeleton for the \key{explicate-pred} auxiliary function.}
  5635. \label{fig:explicate-pred}
  5636. \end{figure}
  5637. The skeleton for the \code{explicate-pred} function is given in
  5638. Figure~\ref{fig:explicate-pred}. It has a case for every expression
  5639. that can have type \code{Boolean}. We detail a few cases here and
  5640. leave the rest for the reader. The input to this function is an
  5641. expression and two blocks, \code{thn} and \code{els}, for the two
  5642. branches of the enclosing \key{if}.
  5643. %
  5644. Consider the case for Boolean constants in
  5645. Figure~\ref{fig:explicate-pred}. We perform a kind of partial
  5646. evaluation\index{partial evaluation} and output either the \code{thn}
  5647. or \code{els} branch depending on whether the constant is true or
  5648. false. This case demonstrates that we sometimes discard the \code{thn}
  5649. or \code{els} blocks that are input to \code{explicate-pred}.
  5650. The case for \key{if} in \code{explicate-pred} is particularly
  5651. illuminating because it deals with the challenges we discussed above
  5652. regarding nested \key{if} expressions
  5653. (Figure~\ref{fig:explicate-control-s1-38}). The \lstinline{thn^} and
  5654. \lstinline{els^} branches of the \key{if} inherit their context from
  5655. the current one, that is, predicate context. So you should recursively
  5656. apply \code{explicate-pred} to the \lstinline{thn^} and
  5657. \lstinline{els^} branches. For both of those recursive calls, pass
  5658. \code{thn} and \code{els} as the extra parameters. Thus, \code{thn}
  5659. and \code{els} may get used twice, once inside each recursive call. As
  5660. discussed above, to avoid duplicating code, we need to add them to the
  5661. control-flow graph so that we can instead refer to them by name and
  5662. execute them with a \key{goto}. However, as we saw in the cases above
  5663. for Boolean constants, the blocks \code{thn} and \code{els} may not
  5664. get used at all and we don't want to prematurely add them to the
  5665. control-flow graph if they end up being discarded.
  5666. The solution to this conundrum is to use \emph{lazy
  5667. evaluation}\index{lazy evaluation}\citep{Friedman:1976aa} to delay
  5668. adding the blocks to the control-flow graph until the points where we
  5669. know they will be used. Racket provides support for lazy evaluation
  5670. with the
  5671. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  5672. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  5673. \index{delay} creates a \emph{promise}\index{promise} in which the
  5674. evaluation of the expressions is postponed. When \key{(force}
  5675. $p$\key{)}\index{force} is applied to a promise $p$ for the first
  5676. time, the expressions $e_1 \ldots e_n$ are evaluated and the result of
  5677. $e_n$ is cached in the promise and returned. If \code{force} is
  5678. applied again to the same promise, then the cached result is returned.
  5679. If \code{force} is applied to an argument that is not a promise,
  5680. \code{force} simply returns the argument.
  5681. We use lazy evaluation for the input and output blocks of the
  5682. functions \code{explicate-pred} and \code{explicate-assign} and for
  5683. the output block of \code{explicate-tail}. So instead of taking and
  5684. returning blocks, they take and return promises. Furthermore, when we
  5685. come to a situation in which we a block might be used more than once,
  5686. as in the case for \code{if} in \code{explicate-pred}, we transform
  5687. the promise into a new promise that will add the block to the
  5688. control-flow graph and return a \code{goto}. The following auxiliary
  5689. function named \code{block->goto} accomplishes this task. It begins
  5690. with \code{delay} to create a promise. When forced, this promise will
  5691. force the original promise. If that returns a \code{goto} (because the
  5692. block was already added to the control-flow graph), then we return the
  5693. \code{goto}. Otherwise we add the block to the control-flow graph with
  5694. another auxiliary function named \code{add-node}. That function
  5695. returns the label for the new block, which we use to create a
  5696. \code{goto}.
  5697. \begin{lstlisting}
  5698. (define (block->goto block)
  5699. (delay
  5700. (define b (force block))
  5701. (match b
  5702. [(Goto label) (Goto label)]
  5703. [else (Goto (add-node b))])))
  5704. \end{lstlisting}
  5705. Returning to the discussion of \code{explicate-pred}
  5706. (Figure~\ref{fig:explicate-pred}), consider the case for comparison
  5707. operators. This is one of the base cases of the recursive function so
  5708. we translate the comparison to an \code{if} statement. We apply
  5709. \code{block->goto} to \code{thn} and \code{els} to obtain two promises
  5710. that will add then to the control-flow graph, which we can immediately
  5711. \code{force} to obtain the two goto's that form the branches of the
  5712. \code{if} statement.
  5713. %% Getting back to the case for \code{if} in \code{explicate-pred}, we
  5714. %% make the recursive calls to \code{explicate-pred} on the ``then'' and
  5715. %% ``else'' branches with the arguments \code{(block->goto} $B_1$\code{)}
  5716. %% and \code{(block->goto} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  5717. %% results from the two recursive calls. We complete the case for
  5718. %% \code{if} by recursively apply \code{explicate-pred} to the condition
  5719. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  5720. %% the result $B_5$.
  5721. %% \[
  5722. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  5723. %% \quad\Rightarrow\quad
  5724. %% B_5
  5725. %% \]
  5726. The \code{explicate-tail} and \code{explicate-assign} functions need
  5727. additional cases for Boolean constants and \key{if}.
  5728. %
  5729. In the cases for \code{if}, the two branches inherit the current
  5730. context, so in \code{explicate-tail} they are in tail position and in
  5731. \code{explicate-assign} they are in assignment position. The
  5732. \code{cont} parameter of \code{explicate-assign} is used in both
  5733. recursive calls, so make sure to use \code{block->goto} on it.
  5734. %% In the case for \code{if} in \code{explicate-tail}, the two branches
  5735. %% inherit the current context, so they are in tail position. Thus, the
  5736. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  5737. %% \code{explicate-tail}.
  5738. %% %
  5739. %% We need to pass $B_0$ as the accumulator argument for both of these
  5740. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  5741. %% Thus, we first apply \code{block->goto} to $B_0$ so that it gets added
  5742. %% to the control-flow graph and obtain a promised goto $G_0$.
  5743. %% %
  5744. %% Let $B_1$ be the result of \code{explicate-tail} on the ``then''
  5745. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate-tail}
  5746. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  5747. %% \code{explicate-pred} to the condition of the \key{if}, $B_1$, and
  5748. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  5749. %% \[
  5750. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  5751. %% \]
  5752. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  5753. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  5754. %% should not be confused with the labels for the blocks that appear in
  5755. %% the generated code. We initially construct unlabeled blocks; we only
  5756. %% attach labels to blocks when we add them to the control-flow graph, as
  5757. %% we see in the next case.
  5758. %% Next consider the case for \key{if} in the \code{explicate-assign}
  5759. %% function. The context of the \key{if} is an assignment to some
  5760. %% variable $x$ and then the control continues to some promised block
  5761. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  5762. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  5763. %% apply \code{block->goto} to it and obtain a promised goto $G_1$. The
  5764. %% branches of the \key{if} inherit the current context, so they are in
  5765. %% assignment positions. Let $B_2$ be the result of applying
  5766. %% \code{explicate-assign} to the ``then'' branch, variable $x$, and
  5767. %% $G_1$. Let $B_3$ be the result of applying \code{explicate-assign} to
  5768. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  5769. %% the result of applying \code{explicate-pred} to the predicate
  5770. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  5771. %% translates to the promise $B_4$.
  5772. %% \[
  5773. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  5774. %% \]
  5775. %% This completes the description of \code{explicate-control} for \LangIf{}.
  5776. The way in which the \code{shrink} pass transforms logical operations
  5777. such as \code{and} and \code{or} can impact the quality of code
  5778. generated by \code{explicate-control}. For example, consider the
  5779. following program.
  5780. % cond_test_21.rkt
  5781. \begin{lstlisting}
  5782. (if (and (eq? (read) 0) (eq? (read) 1))
  5783. 0
  5784. 42)
  5785. \end{lstlisting}
  5786. The \code{and} operation should transform into something that the
  5787. \code{explicate-pred} function can still analyze and descend through to
  5788. reach the underlying \code{eq?} conditions. Ideally, your
  5789. \code{explicate-control} pass should generate code similar to the
  5790. following for the above program.
  5791. \begin{center}
  5792. \begin{lstlisting}
  5793. start:
  5794. tmp1 = (read);
  5795. if (eq? tmp1 0) goto block40;
  5796. else goto block39;
  5797. block40:
  5798. tmp2 = (read);
  5799. if (eq? tmp2 1) goto block38;
  5800. else goto block39;
  5801. block38:
  5802. return 0;
  5803. block39:
  5804. return 42;
  5805. \end{lstlisting}
  5806. \end{center}
  5807. \begin{exercise}\normalfont
  5808. Implement the pass \code{explicate-control} by adding the cases for
  5809. Boolean constants and \key{if} to the \code{explicate-tail} and
  5810. \code{explicate-assign}. Implement the auxiliary function
  5811. \code{explicate-pred} for predicate contexts.
  5812. %
  5813. Create test cases that exercise all of the new cases in the code for
  5814. this pass.
  5815. %
  5816. Add the following entry to the list of \code{passes} in
  5817. \code{run-tests.rkt} and then run this script to test your compiler.
  5818. \begin{lstlisting}
  5819. (list "explicate-control" explicate-control interp-Cif type-check-Cif)
  5820. \end{lstlisting}
  5821. \end{exercise}
  5822. \section{Select Instructions}
  5823. \label{sec:select-Rif}
  5824. \index{instruction selection}
  5825. The \code{select-instructions} pass translate \LangCIf{} to
  5826. \LangXIfVar{}. Recall that we implement this pass using three
  5827. auxiliary functions, one for each of the non-terminals $\Atm$,
  5828. $\Stmt$, and $\Tail$.
  5829. For $\Atm$, we have new cases for the Booleans. We take the usual
  5830. approach of encoding them as integers, with true as 1 and false as 0.
  5831. \[
  5832. \key{\#t} \Rightarrow \key{1}
  5833. \qquad
  5834. \key{\#f} \Rightarrow \key{0}
  5835. \]
  5836. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  5837. be implemented in terms of \code{xorq} as we discussed at the
  5838. beginning of this section. Given an assignment
  5839. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  5840. if the left-hand side $\itm{var}$ is
  5841. the same as $\Atm$, then just the \code{xorq} suffices.
  5842. \[
  5843. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  5844. \quad\Rightarrow\quad
  5845. \key{xorq}~\key{\$}1\key{,}~\Var
  5846. \]
  5847. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  5848. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  5849. x86. Then we have
  5850. \[
  5851. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  5852. \quad\Rightarrow\quad
  5853. \begin{array}{l}
  5854. \key{movq}~\Arg\key{,}~\Var\\
  5855. \key{xorq}~\key{\$}1\key{,}~\Var
  5856. \end{array}
  5857. \]
  5858. Next consider the cases for \code{eq?} and less-than comparison.
  5859. Translating these operations to x86 is slightly involved due to the
  5860. unusual nature of the \key{cmpq} instruction discussed above. We
  5861. recommend translating an assignment from \code{eq?} into the following
  5862. sequence of three instructions. \\
  5863. \begin{tabular}{lll}
  5864. \begin{minipage}{0.4\textwidth}
  5865. \begin{lstlisting}
  5866. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  5867. \end{lstlisting}
  5868. \end{minipage}
  5869. &
  5870. $\Rightarrow$
  5871. &
  5872. \begin{minipage}{0.4\textwidth}
  5873. \begin{lstlisting}
  5874. cmpq |$\Arg_2$|, |$\Arg_1$|
  5875. sete %al
  5876. movzbq %al, |$\Var$|
  5877. \end{lstlisting}
  5878. \end{minipage}
  5879. \end{tabular} \\
  5880. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  5881. and \key{if} statements. Both are straightforward to translate to
  5882. x86. A \key{goto} becomes a jump instruction.
  5883. \[
  5884. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  5885. \]
  5886. An \key{if} statement becomes a compare instruction followed by a
  5887. conditional jump (for the ``then'' branch) and the fall-through is to
  5888. a regular jump (for the ``else'' branch).\\
  5889. \begin{tabular}{lll}
  5890. \begin{minipage}{0.4\textwidth}
  5891. \begin{lstlisting}
  5892. if (eq? |$\Atm_1$| |$\Atm_2$|) goto |$\ell_1$|;
  5893. else goto |$\ell_2$|;
  5894. \end{lstlisting}
  5895. \end{minipage}
  5896. &
  5897. $\Rightarrow$
  5898. &
  5899. \begin{minipage}{0.4\textwidth}
  5900. \begin{lstlisting}
  5901. cmpq |$\Arg_2$|, |$\Arg_1$|
  5902. je |$\ell_1$|
  5903. jmp |$\ell_2$|
  5904. \end{lstlisting}
  5905. \end{minipage}
  5906. \end{tabular} \\
  5907. \begin{exercise}\normalfont
  5908. Expand your \code{select-instructions} pass to handle the new features
  5909. of the \LangIf{} language.
  5910. %
  5911. Add the following entry to the list of \code{passes} in
  5912. \code{run-tests.rkt}
  5913. \begin{lstlisting}
  5914. (list "select-instructions" select-instructions interp-pseudo-x86-1)
  5915. \end{lstlisting}
  5916. %
  5917. Run the script to test your compiler on all the test programs.
  5918. \end{exercise}
  5919. \section{Register Allocation}
  5920. \label{sec:register-allocation-Rif}
  5921. \index{register allocation}
  5922. The changes required for \LangIf{} affect liveness analysis, building the
  5923. interference graph, and assigning homes, but the graph coloring
  5924. algorithm itself does not change.
  5925. \subsection{Liveness Analysis}
  5926. \label{sec:liveness-analysis-Rif}
  5927. \index{liveness analysis}
  5928. Recall that for \LangVar{} we implemented liveness analysis for a single
  5929. basic block (Section~\ref{sec:liveness-analysis-Rvar}). With the
  5930. addition of \key{if} expressions to \LangIf{}, \code{explicate-control}
  5931. produces many basic blocks arranged in a control-flow graph. We
  5932. recommend that you create a new auxiliary function named
  5933. \code{uncover-live-CFG} that applies liveness analysis to a
  5934. control-flow graph.
  5935. The first question we is: what order should we process the basic
  5936. blocks in the control-flow graph? Recall that to perform liveness
  5937. analysis on a basic block we need to know its live-after set. If a
  5938. basic block has no successors (i.e. no out-edges in the control flow
  5939. graph), then it has an empty live-after set and we can immediately
  5940. apply liveness analysis to it. If a basic block has some successors,
  5941. then we need to complete liveness analysis on those blocks first. In
  5942. graph theory, a sequence of nodes is in \emph{topological
  5943. order}\index{topological order} if each vertex comes before its
  5944. successors. We need the opposite, so we can transpose the graph
  5945. before computing a topological order.
  5946. %
  5947. Use the \code{tsort} and \code{transpose} functions of the Racket
  5948. \code{graph} package to accomplish this.
  5949. %
  5950. As an aside, a topological ordering is only guaranteed to exist if the
  5951. graph does not contain any cycles. That is indeed the case for the
  5952. control-flow graphs that we generate from \LangIf{} programs.
  5953. However, in Chapter~\ref{ch:Rwhile} we add loops to \LangLoop{} and
  5954. learn how to handle cycles in the control-flow graph.
  5955. You'll need to construct a directed graph to represent the
  5956. control-flow graph. Do not use the \code{directed-graph} of the
  5957. \code{graph} package because that only allows at most one edge between
  5958. each pair of vertices, but a control-flow graph may have multiple
  5959. edges between a pair of vertices. The \code{multigraph.rkt} file in
  5960. the support code implements a graph representation that allows
  5961. multiple edges between a pair of vertices.
  5962. The next question is how to analyze jump instructions. Recall that in
  5963. Section~\ref{sec:liveness-analysis-Rvar} we maintain an alist named
  5964. \code{label->live} that maps each label to the set of live locations
  5965. at the beginning of its block. We use \code{label->live} to determine
  5966. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  5967. that we have many basic blocks, \code{label->live} needs to be updated
  5968. as we process the blocks. In particular, after performing liveness
  5969. analysis on a block, we take the live-before set of its first
  5970. instruction and associate that with the block's label in the
  5971. \code{label->live}.
  5972. In \LangXIfVar{} we also have the conditional jump
  5973. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  5974. this instruction is particularly interesting because during
  5975. compilation we do not know which way a conditional jump will go. So
  5976. we do not know whether to use the live-before set for the following
  5977. instruction or the live-before set for the $\itm{label}$. However,
  5978. there is no harm to the correctness of the compiler if we classify
  5979. more locations as live than the ones that are truly live during a
  5980. particular execution of the instruction. Thus, we can take the union
  5981. of the live-before sets from the following instruction and from the
  5982. mapping for $\itm{label}$ in \code{label->live}.
  5983. The auxiliary functions for computing the variables in an
  5984. instruction's argument and for computing the variables read-from ($R$)
  5985. or written-to ($W$) by an instruction need to be updated to handle the
  5986. new kinds of arguments and instructions in \LangXIfVar{}.
  5987. \begin{exercise}\normalfont
  5988. Update the \code{uncover-live} pass and implement the
  5989. \code{uncover-live-CFG} auxiliary function to apply liveness analysis
  5990. to the control-flow graph. Add the following entry to the list of
  5991. \code{passes} in the \code{run-tests.rkt} script.
  5992. \begin{lstlisting}
  5993. (list "uncover-live" uncover-live interp-pseudo-x86-1)
  5994. \end{lstlisting}
  5995. \end{exercise}
  5996. \subsection{Build the Interference Graph}
  5997. \label{sec:build-interference-Rif}
  5998. Many of the new instructions in \LangXIfVar{} can be handled in the
  5999. same way as the instructions in \LangXVar{}. Thus, if your code was
  6000. already quite general, it will not need to be changed to handle the
  6001. new instructions. If you code is not general enough, we recommend that
  6002. you change your code to be more general. For example, you can factor
  6003. out the computing of the the read and write sets for each kind of
  6004. instruction into two auxiliary functions.
  6005. Note that the \key{movzbq} instruction requires some special care,
  6006. similar to the \key{movq} instruction. See rule number 1 in
  6007. Section~\ref{sec:build-interference}.
  6008. \begin{exercise}\normalfont
  6009. Update the \code{build-interference} pass for \LangXIfVar{} and add the
  6010. following entries to the list of \code{passes} in the
  6011. \code{run-tests.rkt} script.
  6012. \begin{lstlisting}
  6013. (list "build-interference" build-interference interp-pseudo-x86-1)
  6014. (list "allocate-registers" allocate-registers interp-x86-1)
  6015. \end{lstlisting}
  6016. Run the script to test your compiler on all the \LangIf{} test
  6017. programs.
  6018. \end{exercise}
  6019. \section{Patch Instructions}
  6020. The second argument of the \key{cmpq} instruction must not be an
  6021. immediate value (such as an integer). So if you are comparing two
  6022. immediates, we recommend inserting a \key{movq} instruction to put the
  6023. second argument in \key{rax}. Also, recall that instructions may have
  6024. at most one memory reference.
  6025. %
  6026. The second argument of the \key{movzbq} must be a register.
  6027. %
  6028. There are no special restrictions on the jump instructions.
  6029. \begin{exercise}\normalfont
  6030. %
  6031. Update \code{patch-instructions} pass for \LangXIfVar{}.
  6032. %
  6033. Add the following entry to the list of \code{passes} in
  6034. \code{run-tests.rkt} and then run this script to test your compiler.
  6035. \begin{lstlisting}
  6036. (list "patch-instructions" patch-instructions interp-x86-1)
  6037. \end{lstlisting}
  6038. \end{exercise}
  6039. the \begin{figure}[tbp]
  6040. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6041. \node (Rif) at (0,2) {\large \LangIf{}};
  6042. \node (Rif-2) at (3,2) {\large \LangIf{}};
  6043. \node (Rif-3) at (6,2) {\large \LangIf{}};
  6044. \node (Rif-4) at (9,2) {\large \LangIf{}};
  6045. \node (Rif-5) at (12,2) {\large \LangIf{}};
  6046. \node (C1-1) at (3,0) {\large \LangCIf{}};
  6047. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  6048. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  6049. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  6050. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  6051. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  6052. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  6053. \path[->,bend left=15] (Rif) edge [above] node {\ttfamily\footnotesize type-check} (Rif-2);
  6054. \path[->,bend left=15] (Rif-2) edge [above] node {\ttfamily\footnotesize shrink} (Rif-3);
  6055. \path[->,bend left=15] (Rif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Rif-4);
  6056. \path[->,bend left=15] (Rif-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rif-5);
  6057. \path[->,bend left=15] (Rif-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C1-1);
  6058. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select-instructions} (x86-2);
  6059. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6060. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  6061. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6062. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  6063. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86 } (x86-5);
  6064. \end{tikzpicture}
  6065. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  6066. \label{fig:Rif-passes}
  6067. \end{figure}
  6068. Figure~\ref{fig:Rif-passes} lists all the passes needed for the
  6069. compilation of \LangIf{}.
  6070. \section{An Example Translation}
  6071. Figure~\ref{fig:if-example-x86} shows a simple example program in
  6072. \LangIf{} translated to x86, showing the results of
  6073. \code{explicate-control}, \code{select-instructions}, and the final
  6074. x86 assembly code.
  6075. \begin{figure}[tbp]
  6076. \begin{tabular}{lll}
  6077. \begin{minipage}{0.4\textwidth}
  6078. % cond_test_20.rkt
  6079. \begin{lstlisting}
  6080. (if (eq? (read) 1) 42 0)
  6081. \end{lstlisting}
  6082. $\Downarrow$
  6083. \begin{lstlisting}
  6084. start:
  6085. tmp7951 = (read);
  6086. if (eq? tmp7951 1)
  6087. goto block7952;
  6088. else
  6089. goto block7953;
  6090. block7952:
  6091. return 42;
  6092. block7953:
  6093. return 0;
  6094. \end{lstlisting}
  6095. $\Downarrow$
  6096. \begin{lstlisting}
  6097. start:
  6098. callq read_int
  6099. movq %rax, tmp7951
  6100. cmpq $1, tmp7951
  6101. je block7952
  6102. jmp block7953
  6103. block7953:
  6104. movq $0, %rax
  6105. jmp conclusion
  6106. block7952:
  6107. movq $42, %rax
  6108. jmp conclusion
  6109. \end{lstlisting}
  6110. \end{minipage}
  6111. &
  6112. $\Rightarrow\qquad$
  6113. \begin{minipage}{0.4\textwidth}
  6114. \begin{lstlisting}
  6115. start:
  6116. callq read_int
  6117. movq %rax, %rcx
  6118. cmpq $1, %rcx
  6119. je block7952
  6120. jmp block7953
  6121. block7953:
  6122. movq $0, %rax
  6123. jmp conclusion
  6124. block7952:
  6125. movq $42, %rax
  6126. jmp conclusion
  6127. .globl main
  6128. main:
  6129. pushq %rbp
  6130. movq %rsp, %rbp
  6131. pushq %r13
  6132. pushq %r12
  6133. pushq %rbx
  6134. pushq %r14
  6135. subq $0, %rsp
  6136. jmp start
  6137. conclusion:
  6138. addq $0, %rsp
  6139. popq %r14
  6140. popq %rbx
  6141. popq %r12
  6142. popq %r13
  6143. popq %rbp
  6144. retq
  6145. \end{lstlisting}
  6146. \end{minipage}
  6147. \end{tabular}
  6148. \caption{Example compilation of an \key{if} expression to x86.}
  6149. \label{fig:if-example-x86}
  6150. \end{figure}
  6151. \section{Challenge: Remove Jumps}
  6152. \label{sec:opt-jumps}
  6153. %% Recall that in the example output of \code{explicate-control} in
  6154. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  6155. %% \code{block60} are trivial blocks, they do nothing but jump to another
  6156. %% block. The first goal of this challenge assignment is to remove those
  6157. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  6158. %% \code{explicate-control} on the left and shows the result of bypassing
  6159. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  6160. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  6161. %% \code{block55}. The optimized code on the right of
  6162. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  6163. %% \code{then} branch jumping directly to \code{block55}. The story is
  6164. %% similar for the \code{else} branch, as well as for the two branches in
  6165. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  6166. %% have been optimized in this way, there are no longer any jumps to
  6167. %% blocks \code{block57} through \code{block60}, so they can be removed.
  6168. %% \begin{figure}[tbp]
  6169. %% \begin{tabular}{lll}
  6170. %% \begin{minipage}{0.4\textwidth}
  6171. %% \begin{lstlisting}
  6172. %% block62:
  6173. %% tmp54 = (read);
  6174. %% if (eq? tmp54 2) then
  6175. %% goto block59;
  6176. %% else
  6177. %% goto block60;
  6178. %% block61:
  6179. %% tmp53 = (read);
  6180. %% if (eq? tmp53 0) then
  6181. %% goto block57;
  6182. %% else
  6183. %% goto block58;
  6184. %% block60:
  6185. %% goto block56;
  6186. %% block59:
  6187. %% goto block55;
  6188. %% block58:
  6189. %% goto block56;
  6190. %% block57:
  6191. %% goto block55;
  6192. %% block56:
  6193. %% return (+ 700 77);
  6194. %% block55:
  6195. %% return (+ 10 32);
  6196. %% start:
  6197. %% tmp52 = (read);
  6198. %% if (eq? tmp52 1) then
  6199. %% goto block61;
  6200. %% else
  6201. %% goto block62;
  6202. %% \end{lstlisting}
  6203. %% \end{minipage}
  6204. %% &
  6205. %% $\Rightarrow$
  6206. %% &
  6207. %% \begin{minipage}{0.55\textwidth}
  6208. %% \begin{lstlisting}
  6209. %% block62:
  6210. %% tmp54 = (read);
  6211. %% if (eq? tmp54 2) then
  6212. %% goto block55;
  6213. %% else
  6214. %% goto block56;
  6215. %% block61:
  6216. %% tmp53 = (read);
  6217. %% if (eq? tmp53 0) then
  6218. %% goto block55;
  6219. %% else
  6220. %% goto block56;
  6221. %% block56:
  6222. %% return (+ 700 77);
  6223. %% block55:
  6224. %% return (+ 10 32);
  6225. %% start:
  6226. %% tmp52 = (read);
  6227. %% if (eq? tmp52 1) then
  6228. %% goto block61;
  6229. %% else
  6230. %% goto block62;
  6231. %% \end{lstlisting}
  6232. %% \end{minipage}
  6233. %% \end{tabular}
  6234. %% \caption{Optimize jumps by removing trivial blocks.}
  6235. %% \label{fig:optimize-jumps}
  6236. %% \end{figure}
  6237. %% The name of this pass is \code{optimize-jumps}. We recommend
  6238. %% implementing this pass in two phases. The first phrase builds a hash
  6239. %% table that maps labels to possibly improved labels. The second phase
  6240. %% changes the target of each \code{goto} to use the improved label. If
  6241. %% the label is for a trivial block, then the hash table should map the
  6242. %% label to the first non-trivial block that can be reached from this
  6243. %% label by jumping through trivial blocks. If the label is for a
  6244. %% non-trivial block, then the hash table should map the label to itself;
  6245. %% we do not want to change jumps to non-trivial blocks.
  6246. %% The first phase can be accomplished by constructing an empty hash
  6247. %% table, call it \code{short-cut}, and then iterating over the control
  6248. %% flow graph. Each time you encouter a block that is just a \code{goto},
  6249. %% then update the hash table, mapping the block's source to the target
  6250. %% of the \code{goto}. Also, the hash table may already have mapped some
  6251. %% labels to the block's source, to you must iterate through the hash
  6252. %% table and update all of those so that they instead map to the target
  6253. %% of the \code{goto}.
  6254. %% For the second phase, we recommend iterating through the $\Tail$ of
  6255. %% each block in the program, updating the target of every \code{goto}
  6256. %% according to the mapping in \code{short-cut}.
  6257. %% \begin{exercise}\normalfont
  6258. %% Implement the \code{optimize-jumps} pass as a transformation from
  6259. %% \LangCIf{} to \LangCIf{}, coming after the \code{explicate-control} pass.
  6260. %% Check that \code{optimize-jumps} removes trivial blocks in a few
  6261. %% example programs. Then check that your compiler still passes all of
  6262. %% your tests.
  6263. %% \end{exercise}
  6264. There is an opportunity for optimizing jumps that is apparent in the
  6265. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  6266. ends with a jump to \code{block7953} and there are no other jumps to
  6267. \code{block7953} in the rest of the program. In this situation we can
  6268. avoid the runtime overhead of this jump by merging \code{block7953}
  6269. into the preceding block, in this case the \code{start} block.
  6270. Figure~\ref{fig:remove-jumps} shows the output of
  6271. \code{select-instructions} on the left and the result of this
  6272. optimization on the right.
  6273. \begin{figure}[tbp]
  6274. \begin{tabular}{lll}
  6275. \begin{minipage}{0.5\textwidth}
  6276. % cond_test_20.rkt
  6277. \begin{lstlisting}
  6278. start:
  6279. callq read_int
  6280. movq %rax, tmp7951
  6281. cmpq $1, tmp7951
  6282. je block7952
  6283. jmp block7953
  6284. block7953:
  6285. movq $0, %rax
  6286. jmp conclusion
  6287. block7952:
  6288. movq $42, %rax
  6289. jmp conclusion
  6290. \end{lstlisting}
  6291. \end{minipage}
  6292. &
  6293. $\Rightarrow\qquad$
  6294. \begin{minipage}{0.4\textwidth}
  6295. \begin{lstlisting}
  6296. start:
  6297. callq read_int
  6298. movq %rax, tmp7951
  6299. cmpq $1, tmp7951
  6300. je block7952
  6301. movq $0, %rax
  6302. jmp conclusion
  6303. block7952:
  6304. movq $42, %rax
  6305. jmp conclusion
  6306. \end{lstlisting}
  6307. \end{minipage}
  6308. \end{tabular}
  6309. \caption{Merging basic blocks by removing unnecessary jumps.}
  6310. \label{fig:remove-jumps}
  6311. \end{figure}
  6312. \begin{exercise}\normalfont
  6313. %
  6314. Implement a pass named \code{remove-jumps} that merges basic blocks
  6315. into their preceding basic block, when there is only one preceding
  6316. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  6317. %
  6318. In the \code{run-tests.rkt} script, add the following entry to the
  6319. list of \code{passes} between \code{allocate-registers}
  6320. and \code{patch-instructions}.
  6321. \begin{lstlisting}
  6322. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  6323. \end{lstlisting}
  6324. Run this script to test your compiler.
  6325. %
  6326. Check that \code{remove-jumps} accomplishes the goal of merging basic
  6327. blocks on several test programs.
  6328. \end{exercise}
  6329. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6330. \chapter{Tuples and Garbage Collection}
  6331. \label{ch:Rvec}
  6332. \index{tuple}
  6333. \index{vector}
  6334. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  6335. all the IR grammars are spelled out! \\ --Jeremy}
  6336. \margincomment{\scriptsize Be more explicit about how to deal with
  6337. the root stack. \\ --Jeremy}
  6338. In this chapter we study the implementation of mutable tuples, called
  6339. vectors in Racket. This language feature is the first to use the
  6340. computer's \emph{heap}\index{heap} because the lifetime of a Racket
  6341. tuple is indefinite, that is, a tuple lives forever from the
  6342. programmer's viewpoint. Of course, from an implementer's viewpoint, it
  6343. is important to reclaim the space associated with a tuple when it is
  6344. no longer needed, which is why we also study \emph{garbage collection}
  6345. \emph{garbage collection} techniques in this chapter.
  6346. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  6347. interpreter and type checker. The \LangVec{} language extends the \LangIf{}
  6348. language of Chapter~\ref{ch:Rif} with vectors and Racket's
  6349. \code{void} value. The reason for including the later is that the
  6350. \code{vector-set!} operation returns a value of type
  6351. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  6352. called the \code{Unit} type in the programming languages
  6353. literature. Racket's \code{Void} type is inhabited by a single value
  6354. \code{void} which corresponds to \code{unit} or \code{()} in the
  6355. literature~\citep{Pierce:2002hj}.}.
  6356. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  6357. copying live objects back and forth between two halves of the
  6358. heap. The garbage collector requires coordination with the compiler so
  6359. that it can see all of the \emph{root} pointers, that is, pointers in
  6360. registers or on the procedure call stack.
  6361. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  6362. discuss all the necessary changes and additions to the compiler
  6363. passes, including a new compiler pass named \code{expose-allocation}.
  6364. \section{The \LangVec{} Language}
  6365. \label{sec:r3}
  6366. Figure~\ref{fig:Rvec-concrete-syntax} defines the concrete syntax for
  6367. \LangVec{} and Figure~\ref{fig:Rvec-syntax} defines the abstract syntax. The
  6368. \LangVec{} language includes three new forms: \code{vector} for creating a
  6369. tuple, \code{vector-ref} for reading an element of a tuple, and
  6370. \code{vector-set!} for writing to an element of a tuple. The program
  6371. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  6372. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  6373. the 3-tuple, demonstrating that tuples are first-class values. The
  6374. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  6375. of the \key{if} is taken. The element at index $0$ of \code{t} is
  6376. \code{40}, to which we add \code{2}, the element at index $0$ of the
  6377. 1-tuple. So the result of the program is \code{42}.
  6378. \begin{figure}[tbp]
  6379. \centering
  6380. \fbox{
  6381. \begin{minipage}{0.96\textwidth}
  6382. \[
  6383. \begin{array}{lcl}
  6384. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  6385. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \key{Void}\\
  6386. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  6387. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  6388. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6389. \mid \LP\key{and}\;\Exp\;\Exp\RP
  6390. \mid \LP\key{or}\;\Exp\;\Exp\RP
  6391. \mid \LP\key{not}\;\Exp\RP } \\
  6392. &\mid& \gray{ \LP\itm{cmp}\;\Exp\;\Exp\RP
  6393. \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  6394. &\mid& \LP\key{vector}\;\Exp\ldots\RP
  6395. \mid \LP\key{vector-length}\;\Exp\RP \\
  6396. &\mid& \LP\key{vector-ref}\;\Exp\;\Int\RP
  6397. \mid \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP \\
  6398. &\mid& \LP\key{void}\RP \mid \LP\key{has-type}~\Exp~\Type\RP\\
  6399. \LangVec{} &::=& \Exp
  6400. \end{array}
  6401. \]
  6402. \end{minipage}
  6403. }
  6404. \caption{The concrete syntax of \LangVec{}, extending \LangIf{}
  6405. (Figure~\ref{fig:Rif-concrete-syntax}).}
  6406. \label{fig:Rvec-concrete-syntax}
  6407. \end{figure}
  6408. \begin{figure}[tbp]
  6409. \begin{lstlisting}
  6410. (let ([t (vector 40 #t (vector 2))])
  6411. (if (vector-ref t 1)
  6412. (+ (vector-ref t 0)
  6413. (vector-ref (vector-ref t 2) 0))
  6414. 44))
  6415. \end{lstlisting}
  6416. \caption{Example program that creates tuples and reads from them.}
  6417. \label{fig:vector-eg}
  6418. \end{figure}
  6419. \begin{figure}[tp]
  6420. \centering
  6421. \fbox{
  6422. \begin{minipage}{0.96\textwidth}
  6423. \[
  6424. \begin{array}{lcl}
  6425. \itm{op} &::=& \ldots \mid \code{vector} \mid \code{vector-length} \\
  6426. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6427. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots}
  6428. \mid \BOOL{\itm{bool}}
  6429. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6430. &\mid& \VECREF{\Exp}{\INT{\Int}}\\
  6431. &\mid& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  6432. &\mid& \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP \\
  6433. \LangVec{} &::=& \PROGRAM{\key{'()}}{\Exp}
  6434. \end{array}
  6435. \]
  6436. \end{minipage}
  6437. }
  6438. \caption{The abstract syntax of \LangVec{}.}
  6439. \label{fig:Rvec-syntax}
  6440. \end{figure}
  6441. \index{allocate}
  6442. \index{heap allocate}
  6443. Tuples are our first encounter with heap-allocated data, which raises
  6444. several interesting issues. First, variable binding performs a
  6445. shallow-copy when dealing with tuples, which means that different
  6446. variables can refer to the same tuple, that is, different variables
  6447. can be \emph{aliases} for the same entity. Consider the following
  6448. example in which both \code{t1} and \code{t2} refer to the same tuple.
  6449. Thus, the mutation through \code{t2} is visible when referencing the
  6450. tuple from \code{t1}, so the result of this program is \code{42}.
  6451. \index{alias}\index{mutation}
  6452. \begin{center}
  6453. \begin{minipage}{0.96\textwidth}
  6454. \begin{lstlisting}
  6455. (let ([t1 (vector 3 7)])
  6456. (let ([t2 t1])
  6457. (let ([_ (vector-set! t2 0 42)])
  6458. (vector-ref t1 0))))
  6459. \end{lstlisting}
  6460. \end{minipage}
  6461. \end{center}
  6462. The next issue concerns the lifetime of tuples. Of course, they are
  6463. created by the \code{vector} form, but when does their lifetime end?
  6464. Notice that \LangVec{} does not include an operation for deleting
  6465. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  6466. of static scoping. For example, the following program returns
  6467. \code{42} even though the variable \code{w} goes out of scope prior to
  6468. the \code{vector-ref} that reads from the vector it was bound to.
  6469. \begin{center}
  6470. \begin{minipage}{0.96\textwidth}
  6471. \begin{lstlisting}
  6472. (let ([v (vector (vector 44))])
  6473. (let ([x (let ([w (vector 42)])
  6474. (let ([_ (vector-set! v 0 w)])
  6475. 0))])
  6476. (+ x (vector-ref (vector-ref v 0) 0))))
  6477. \end{lstlisting}
  6478. \end{minipage}
  6479. \end{center}
  6480. From the perspective of programmer-observable behavior, tuples live
  6481. forever. Of course, if they really lived forever, then many programs
  6482. would run out of memory.\footnote{The \LangVec{} language does not have
  6483. looping or recursive functions, so it is nigh impossible to write a
  6484. program in \LangVec{} that will run out of memory. However, we add
  6485. recursive functions in the next Chapter!} A Racket implementation
  6486. must therefore perform automatic garbage collection.
  6487. Figure~\ref{fig:interp-Rvec} shows the definitional interpreter for the
  6488. \LangVec{} language. We define the \code{vector}, \code{vector-length},
  6489. \code{vector-ref}, and \code{vector-set!} operations for \LangVec{} in
  6490. terms of the corresponding operations in Racket. One subtle point is
  6491. that the \code{vector-set!} operation returns the \code{\#<void>}
  6492. value. The \code{\#<void>} value can be passed around just like other
  6493. values inside an \LangVec{} program and a \code{\#<void>} value can be
  6494. compared for equality with another \code{\#<void>} value. However,
  6495. there are no other operations specific to the the \code{\#<void>}
  6496. value in \LangVec{}. In contrast, Racket defines the \code{void?} predicate
  6497. that returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  6498. otherwise.
  6499. \begin{figure}[tbp]
  6500. \begin{lstlisting}
  6501. (define interp-Rvec-class
  6502. (class interp-Rif-class
  6503. (super-new)
  6504. (define/override (interp-op op)
  6505. (match op
  6506. ['eq? (lambda (v1 v2)
  6507. (cond [(or (and (fixnum? v1) (fixnum? v2))
  6508. (and (boolean? v1) (boolean? v2))
  6509. (and (vector? v1) (vector? v2))
  6510. (and (void? v1) (void? v2)))
  6511. (eq? v1 v2)]))]
  6512. ['vector vector]
  6513. ['vector-length vector-length]
  6514. ['vector-ref vector-ref]
  6515. ['vector-set! vector-set!]
  6516. [else (super interp-op op)]
  6517. ))
  6518. (define/override ((interp-exp env) e)
  6519. (define recur (interp-exp env))
  6520. (match e
  6521. [(HasType e t) (recur e)]
  6522. [(Void) (void)]
  6523. [else ((super interp-exp env) e)]
  6524. ))
  6525. ))
  6526. (define (interp-Rvec p)
  6527. (send (new interp-Rvec-class) interp-program p))
  6528. \end{lstlisting}
  6529. \caption{Interpreter for the \LangVec{} language.}
  6530. \label{fig:interp-Rvec}
  6531. \end{figure}
  6532. Figure~\ref{fig:type-check-Rvec} shows the type checker for \LangVec{}, which
  6533. deserves some explanation. When allocating a vector, we need to know
  6534. which elements of the vector are pointers (i.e. are also vectors). We
  6535. can obtain this information during type checking. The type checker in
  6536. Figure~\ref{fig:type-check-Rvec} not only computes the type of an
  6537. expression, it also wraps every \key{vector} creation with the form
  6538. $(\key{HasType}~e~T)$, where $T$ is the vector's type.
  6539. %
  6540. To create the s-expression for the \code{Vector} type in
  6541. Figure~\ref{fig:type-check-Rvec}, we use the
  6542. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  6543. operator} \code{,@} to insert the list \code{t*} without its usual
  6544. start and end parentheses. \index{unquote-slicing}
  6545. \begin{figure}[tp]
  6546. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6547. (define type-check-Rvec-class
  6548. (class type-check-Rif-class
  6549. (super-new)
  6550. (inherit check-type-equal?)
  6551. (define/override (type-check-exp env)
  6552. (lambda (e)
  6553. (define recur (type-check-exp env))
  6554. (match e
  6555. [(Void) (values (Void) 'Void)]
  6556. [(Prim 'vector es)
  6557. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  6558. (define t `(Vector ,@t*))
  6559. (values (HasType (Prim 'vector e*) t) t)]
  6560. [(Prim 'vector-ref (list e1 (Int i)))
  6561. (define-values (e1^ t) (recur e1))
  6562. (match t
  6563. [`(Vector ,ts ...)
  6564. (unless (and (0 . <= . i) (i . < . (length ts)))
  6565. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  6566. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  6567. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  6568. [(Prim 'vector-set! (list e1 (Int i) arg) )
  6569. (define-values (e-vec t-vec) (recur e1))
  6570. (define-values (e-arg^ t-arg) (recur arg))
  6571. (match t-vec
  6572. [`(Vector ,ts ...)
  6573. (unless (and (0 . <= . i) (i . < . (length ts)))
  6574. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  6575. (check-type-equal? (list-ref ts i) t-arg e)
  6576. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  6577. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  6578. [(Prim 'vector-length (list e))
  6579. (define-values (e^ t) (recur e))
  6580. (match t
  6581. [`(Vector ,ts ...)
  6582. (values (Prim 'vector-length (list e^)) 'Integer)]
  6583. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  6584. [(Prim 'eq? (list arg1 arg2))
  6585. (define-values (e1 t1) (recur arg1))
  6586. (define-values (e2 t2) (recur arg2))
  6587. (match* (t1 t2)
  6588. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  6589. [(other wise) (check-type-equal? t1 t2 e)])
  6590. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  6591. [(HasType (Prim 'vector es) t)
  6592. ((type-check-exp env) (Prim 'vector es))]
  6593. [(HasType e1 t)
  6594. (define-values (e1^ t^) (recur e1))
  6595. (check-type-equal? t t^ e)
  6596. (values (HasType e1^ t) t)]
  6597. [else ((super type-check-exp env) e)]
  6598. )))
  6599. ))
  6600. (define (type-check-Rvec p)
  6601. (send (new type-check-Rvec-class) type-check-program p))
  6602. \end{lstlisting}
  6603. \caption{Type checker for the \LangVec{} language.}
  6604. \label{fig:type-check-Rvec}
  6605. \end{figure}
  6606. \section{Garbage Collection}
  6607. \label{sec:GC}
  6608. Here we study a relatively simple algorithm for garbage collection
  6609. that is the basis of state-of-the-art garbage
  6610. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  6611. particular, we describe a two-space copying
  6612. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  6613. perform the
  6614. copy~\citep{Cheney:1970aa}.
  6615. \index{copying collector}
  6616. \index{two-space copying collector}
  6617. Figure~\ref{fig:copying-collector} gives a
  6618. coarse-grained depiction of what happens in a two-space collector,
  6619. showing two time steps, prior to garbage collection (on the top) and
  6620. after garbage collection (on the bottom). In a two-space collector,
  6621. the heap is divided into two parts named the FromSpace and the
  6622. ToSpace. Initially, all allocations go to the FromSpace until there is
  6623. not enough room for the next allocation request. At that point, the
  6624. garbage collector goes to work to make more room.
  6625. \index{ToSpace}
  6626. \index{FromSpace}
  6627. The garbage collector must be careful not to reclaim tuples that will
  6628. be used by the program in the future. Of course, it is impossible in
  6629. general to predict what a program will do, but we can over approximate
  6630. the will-be-used tuples by preserving all tuples that could be
  6631. accessed by \emph{any} program given the current computer state. A
  6632. program could access any tuple whose address is in a register or on
  6633. the procedure call stack. These addresses are called the \emph{root
  6634. set}\index{root set}. In addition, a program could access any tuple that is
  6635. transitively reachable from the root set. Thus, it is safe for the
  6636. garbage collector to reclaim the tuples that are not reachable in this
  6637. way.
  6638. So the goal of the garbage collector is twofold:
  6639. \begin{enumerate}
  6640. \item preserve all tuple that are reachable from the root set via a
  6641. path of pointers, that is, the \emph{live} tuples, and
  6642. \item reclaim the memory of everything else, that is, the
  6643. \emph{garbage}.
  6644. \end{enumerate}
  6645. A copying collector accomplishes this by copying all of the live
  6646. objects from the FromSpace into the ToSpace and then performs a sleight
  6647. of hand, treating the ToSpace as the new FromSpace and the old
  6648. FromSpace as the new ToSpace. In the example of
  6649. Figure~\ref{fig:copying-collector}, there are three pointers in the
  6650. root set, one in a register and two on the stack. All of the live
  6651. objects have been copied to the ToSpace (the right-hand side of
  6652. Figure~\ref{fig:copying-collector}) in a way that preserves the
  6653. pointer relationships. For example, the pointer in the register still
  6654. points to a 2-tuple whose first element is a 3-tuple and whose second
  6655. element is a 2-tuple. There are four tuples that are not reachable
  6656. from the root set and therefore do not get copied into the ToSpace.
  6657. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  6658. created by a well-typed program in \LangVec{} because it contains a
  6659. cycle. However, creating cycles will be possible once we get to \LangAny{}.
  6660. We design the garbage collector to deal with cycles to begin with so
  6661. we will not need to revisit this issue.
  6662. \begin{figure}[tbp]
  6663. \centering
  6664. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  6665. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  6666. \caption{A copying collector in action.}
  6667. \label{fig:copying-collector}
  6668. \end{figure}
  6669. There are many alternatives to copying collectors (and their bigger
  6670. siblings, the generational collectors) when its comes to garbage
  6671. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  6672. reference counting~\citep{Collins:1960aa}. The strengths of copying
  6673. collectors are that allocation is fast (just a comparison and pointer
  6674. increment), there is no fragmentation, cyclic garbage is collected,
  6675. and the time complexity of collection only depends on the amount of
  6676. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  6677. main disadvantages of a two-space copying collector is that it uses a
  6678. lot of space and takes a long time to perform the copy, though these
  6679. problems are ameliorated in generational collectors. Racket and
  6680. Scheme programs tend to allocate many small objects and generate a lot
  6681. of garbage, so copying and generational collectors are a good fit.
  6682. Garbage collection is an active research topic, especially concurrent
  6683. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  6684. developing new techniques and revisiting old
  6685. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  6686. meet every year at the International Symposium on Memory Management to
  6687. present these findings.
  6688. \subsection{Graph Copying via Cheney's Algorithm}
  6689. \label{sec:cheney}
  6690. \index{Cheney's algorithm}
  6691. Let us take a closer look at the copying of the live objects. The
  6692. allocated objects and pointers can be viewed as a graph and we need to
  6693. copy the part of the graph that is reachable from the root set. To
  6694. make sure we copy all of the reachable vertices in the graph, we need
  6695. an exhaustive graph traversal algorithm, such as depth-first search or
  6696. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  6697. such algorithms take into account the possibility of cycles by marking
  6698. which vertices have already been visited, so as to ensure termination
  6699. of the algorithm. These search algorithms also use a data structure
  6700. such as a stack or queue as a to-do list to keep track of the vertices
  6701. that need to be visited. We use breadth-first search and a trick
  6702. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  6703. and copying tuples into the ToSpace.
  6704. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  6705. copy progresses. The queue is represented by a chunk of contiguous
  6706. memory at the beginning of the ToSpace, using two pointers to track
  6707. the front and the back of the queue. The algorithm starts by copying
  6708. all tuples that are immediately reachable from the root set into the
  6709. ToSpace to form the initial queue. When we copy a tuple, we mark the
  6710. old tuple to indicate that it has been visited. We discuss how this
  6711. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  6712. pointers inside the copied tuples in the queue still point back to the
  6713. FromSpace. Once the initial queue has been created, the algorithm
  6714. enters a loop in which it repeatedly processes the tuple at the front
  6715. of the queue and pops it off the queue. To process a tuple, the
  6716. algorithm copies all the tuple that are directly reachable from it to
  6717. the ToSpace, placing them at the back of the queue. The algorithm then
  6718. updates the pointers in the popped tuple so they point to the newly
  6719. copied tuples.
  6720. \begin{figure}[tbp]
  6721. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  6722. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  6723. \label{fig:cheney}
  6724. \end{figure}
  6725. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  6726. tuple whose second element is $42$ to the back of the queue. The other
  6727. pointer goes to a tuple that has already been copied, so we do not
  6728. need to copy it again, but we do need to update the pointer to the new
  6729. location. This can be accomplished by storing a \emph{forwarding
  6730. pointer} to the new location in the old tuple, back when we initially
  6731. copied the tuple into the ToSpace. This completes one step of the
  6732. algorithm. The algorithm continues in this way until the front of the
  6733. queue is empty, that is, until the front catches up with the back.
  6734. \subsection{Data Representation}
  6735. \label{sec:data-rep-gc}
  6736. The garbage collector places some requirements on the data
  6737. representations used by our compiler. First, the garbage collector
  6738. needs to distinguish between pointers and other kinds of data. There
  6739. are several ways to accomplish this.
  6740. \begin{enumerate}
  6741. \item Attached a tag to each object that identifies what type of
  6742. object it is~\citep{McCarthy:1960dz}.
  6743. \item Store different types of objects in different
  6744. regions~\citep{Steele:1977ab}.
  6745. \item Use type information from the program to either generate
  6746. type-specific code for collecting or to generate tables that can
  6747. guide the
  6748. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  6749. \end{enumerate}
  6750. Dynamically typed languages, such as Lisp, need to tag objects
  6751. anyways, so option 1 is a natural choice for those languages.
  6752. However, \LangVec{} is a statically typed language, so it would be
  6753. unfortunate to require tags on every object, especially small and
  6754. pervasive objects like integers and Booleans. Option 3 is the
  6755. best-performing choice for statically typed languages, but comes with
  6756. a relatively high implementation complexity. To keep this chapter
  6757. within a 2-week time budget, we recommend a combination of options 1
  6758. and 2, using separate strategies for the stack and the heap.
  6759. Regarding the stack, we recommend using a separate stack for pointers,
  6760. which we call a \emph{root stack}\index{root stack} (a.k.a. ``shadow
  6761. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  6762. is, when a local variable needs to be spilled and is of type
  6763. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  6764. stack instead of the normal procedure call stack. Furthermore, we
  6765. always spill vector-typed variables if they are live during a call to
  6766. the collector, thereby ensuring that no pointers are in registers
  6767. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  6768. example from Figure~\ref{fig:copying-collector} and contrasts it with
  6769. the data layout using a root stack. The root stack contains the two
  6770. pointers from the regular stack and also the pointer in the second
  6771. register.
  6772. \begin{figure}[tbp]
  6773. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  6774. \caption{Maintaining a root stack to facilitate garbage collection.}
  6775. \label{fig:shadow-stack}
  6776. \end{figure}
  6777. The problem of distinguishing between pointers and other kinds of data
  6778. also arises inside of each tuple on the heap. We solve this problem by
  6779. attaching a tag, an extra 64-bits, to each
  6780. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  6781. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  6782. that we have drawn the bits in a big-endian way, from right-to-left,
  6783. with bit location 0 (the least significant bit) on the far right,
  6784. which corresponds to the direction of the x86 shifting instructions
  6785. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  6786. is dedicated to specifying which elements of the tuple are pointers,
  6787. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  6788. indicates there is a pointer and a 0 bit indicates some other kind of
  6789. data. The pointer mask starts at bit location 7. We have limited
  6790. tuples to a maximum size of 50 elements, so we just need 50 bits for
  6791. the pointer mask. The tag also contains two other pieces of
  6792. information. The length of the tuple (number of elements) is stored in
  6793. bits location 1 through 6. Finally, the bit at location 0 indicates
  6794. whether the tuple has yet to be copied to the ToSpace. If the bit has
  6795. value 1, then this tuple has not yet been copied. If the bit has
  6796. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  6797. of a pointer are always zero anyways because our tuples are 8-byte
  6798. aligned.)
  6799. \begin{figure}[tbp]
  6800. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  6801. \caption{Representation of tuples in the heap.}
  6802. \label{fig:tuple-rep}
  6803. \end{figure}
  6804. \subsection{Implementation of the Garbage Collector}
  6805. \label{sec:organize-gz}
  6806. \index{prelude}
  6807. An implementation of the copying collector is provided in the
  6808. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  6809. interface to the garbage collector that is used by the compiler. The
  6810. \code{initialize} function creates the FromSpace, ToSpace, and root
  6811. stack and should be called in the prelude of the \code{main}
  6812. function. The arguments of \code{initialize} are the root stack size
  6813. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  6814. good choice for both. The \code{initialize} function puts the address
  6815. of the beginning of the FromSpace into the global variable
  6816. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  6817. the address that is 1-past the last element of the FromSpace. (We use
  6818. half-open intervals to represent chunks of
  6819. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  6820. points to the first element of the root stack.
  6821. As long as there is room left in the FromSpace, your generated code
  6822. can allocate tuples simply by moving the \code{free\_ptr} forward.
  6823. %
  6824. The amount of room left in FromSpace is the difference between the
  6825. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  6826. function should be called when there is not enough room left in the
  6827. FromSpace for the next allocation. The \code{collect} function takes
  6828. a pointer to the current top of the root stack (one past the last item
  6829. that was pushed) and the number of bytes that need to be
  6830. allocated. The \code{collect} function performs the copying collection
  6831. and leaves the heap in a state such that the next allocation will
  6832. succeed.
  6833. \begin{figure}[tbp]
  6834. \begin{lstlisting}
  6835. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  6836. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  6837. int64_t* free_ptr;
  6838. int64_t* fromspace_begin;
  6839. int64_t* fromspace_end;
  6840. int64_t** rootstack_begin;
  6841. \end{lstlisting}
  6842. \caption{The compiler's interface to the garbage collector.}
  6843. \label{fig:gc-header}
  6844. \end{figure}
  6845. %% \begin{exercise}
  6846. %% In the file \code{runtime.c} you will find the implementation of
  6847. %% \code{initialize} and a partial implementation of \code{collect}.
  6848. %% The \code{collect} function calls another function, \code{cheney},
  6849. %% to perform the actual copy, and that function is left to the reader
  6850. %% to implement. The following is the prototype for \code{cheney}.
  6851. %% \begin{lstlisting}
  6852. %% static void cheney(int64_t** rootstack_ptr);
  6853. %% \end{lstlisting}
  6854. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  6855. %% rootstack (which is an array of pointers). The \code{cheney} function
  6856. %% also communicates with \code{collect} through the global
  6857. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  6858. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  6859. %% the ToSpace:
  6860. %% \begin{lstlisting}
  6861. %% static int64_t* tospace_begin;
  6862. %% static int64_t* tospace_end;
  6863. %% \end{lstlisting}
  6864. %% The job of the \code{cheney} function is to copy all the live
  6865. %% objects (reachable from the root stack) into the ToSpace, update
  6866. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  6867. %% update the root stack so that it points to the objects in the
  6868. %% ToSpace, and finally to swap the global pointers for the FromSpace
  6869. %% and ToSpace.
  6870. %% \end{exercise}
  6871. %% \section{Compiler Passes}
  6872. %% \label{sec:code-generation-gc}
  6873. The introduction of garbage collection has a non-trivial impact on our
  6874. compiler passes. We introduce a new compiler pass named
  6875. \code{expose-allocation}. We make
  6876. significant changes to \code{select-instructions},
  6877. \code{build-interference}, \code{allocate-registers}, and
  6878. \code{print-x86} and make minor changes in several more passes. The
  6879. following program will serve as our running example. It creates two
  6880. tuples, one nested inside the other. Both tuples have length one. The
  6881. program accesses the element in the inner tuple tuple via two vector
  6882. references.
  6883. % tests/s2_17.rkt
  6884. \begin{lstlisting}
  6885. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  6886. \end{lstlisting}
  6887. \section{Shrink}
  6888. \label{sec:shrink-Rvec}
  6889. Recall that the \code{shrink} pass translates the primitives operators
  6890. into a smaller set of primitives. Because this pass comes after type
  6891. checking, but before the passes that require the type information in
  6892. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  6893. to wrap \code{HasType} around each AST node that it generates.
  6894. \section{Expose Allocation}
  6895. \label{sec:expose-allocation}
  6896. The pass \code{expose-allocation} lowers the \code{vector} creation
  6897. form into a conditional call to the collector followed by the
  6898. allocation. We choose to place the \code{expose-allocation} pass
  6899. before \code{remove-complex-opera*} because the code generated by
  6900. \code{expose-allocation} contains complex operands. We also place
  6901. \code{expose-allocation} before \code{explicate-control} because
  6902. \code{expose-allocation} introduces new variables using \code{let},
  6903. but \code{let} is gone after \code{explicate-control}.
  6904. The output of \code{expose-allocation} is a language \LangAlloc{} that
  6905. extends \LangVec{} with the three new forms that we use in the translation
  6906. of the \code{vector} form.
  6907. \[
  6908. \begin{array}{lcl}
  6909. \Exp &::=& \cdots
  6910. \mid (\key{collect} \,\itm{int})
  6911. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  6912. \mid (\key{global-value} \,\itm{name})
  6913. \end{array}
  6914. \]
  6915. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  6916. $n$ bytes. It will become a call to the \code{collect} function in
  6917. \code{runtime.c} in \code{select-instructions}. The
  6918. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  6919. \index{allocate}
  6920. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  6921. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  6922. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  6923. a global variable, such as \code{free\_ptr}.
  6924. In the following, we show the transformation for the \code{vector}
  6925. form into 1) a sequence of let-bindings for the initializing
  6926. expressions, 2) a conditional call to \code{collect}, 3) a call to
  6927. \code{allocate}, and 4) the initialization of the vector. In the
  6928. following, \itm{len} refers to the length of the vector and
  6929. \itm{bytes} is how many total bytes need to be allocated for the
  6930. vector, which is 8 for the tag plus \itm{len} times 8.
  6931. \begin{lstlisting}
  6932. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  6933. |$\Longrightarrow$|
  6934. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  6935. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  6936. (global-value fromspace_end))
  6937. (void)
  6938. (collect |\itm{bytes}|))])
  6939. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  6940. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  6941. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  6942. |$v$|) ... )))) ...)
  6943. \end{lstlisting}
  6944. In the above, we suppressed all of the \code{has-type} forms in the
  6945. output for the sake of readability. The placement of the initializing
  6946. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  6947. sequence of \code{vector-set!} is important, as those expressions may
  6948. trigger garbage collection and we cannot have an allocated but
  6949. uninitialized tuple on the heap during a collection.
  6950. Figure~\ref{fig:expose-alloc-output} shows the output of the
  6951. \code{expose-allocation} pass on our running example.
  6952. \begin{figure}[tbp]
  6953. % tests/s2_17.rkt
  6954. \begin{lstlisting}
  6955. (vector-ref
  6956. (vector-ref
  6957. (let ([vecinit7976
  6958. (let ([vecinit7972 42])
  6959. (let ([collectret7974
  6960. (if (< (+ (global-value free_ptr) 16)
  6961. (global-value fromspace_end))
  6962. (void)
  6963. (collect 16)
  6964. )])
  6965. (let ([alloc7971 (allocate 1 (Vector Integer))])
  6966. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  6967. alloc7971)
  6968. )
  6969. )
  6970. )
  6971. ])
  6972. (let ([collectret7978
  6973. (if (< (+ (global-value free_ptr) 16)
  6974. (global-value fromspace_end))
  6975. (void)
  6976. (collect 16)
  6977. )])
  6978. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  6979. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  6980. alloc7975)
  6981. )
  6982. )
  6983. )
  6984. 0)
  6985. 0)
  6986. \end{lstlisting}
  6987. \caption{Output of the \code{expose-allocation} pass, minus
  6988. all of the \code{has-type} forms.}
  6989. \label{fig:expose-alloc-output}
  6990. \end{figure}
  6991. \section{Remove Complex Operands}
  6992. \label{sec:remove-complex-opera-Rvec}
  6993. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  6994. should all be treated as complex operands.
  6995. %% A new case for
  6996. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  6997. %% handled carefully to prevent the \code{Prim} node from being separated
  6998. %% from its enclosing \code{HasType}.
  6999. Figure~\ref{fig:Rvec-anf-syntax}
  7000. shows the grammar for the output language \LangVecANF{} of this
  7001. pass, which is \LangVec{} in administrative normal form.
  7002. \begin{figure}[tp]
  7003. \centering
  7004. \fbox{
  7005. \begin{minipage}{0.96\textwidth}
  7006. \small
  7007. \[
  7008. \begin{array}{rcl}
  7009. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }
  7010. \mid \VOID{} \\
  7011. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  7012. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  7013. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  7014. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  7015. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  7016. &\mid& \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  7017. \mid \LP\key{GlobalValue}~\Var\RP\\
  7018. % &\mid& \LP\key{HasType}~\Exp~\Type\RP \\
  7019. R^{\dagger}_3 &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  7020. \end{array}
  7021. \]
  7022. \end{minipage}
  7023. }
  7024. \caption{\LangVecANF{} is \LangVec{} in administrative normal form (ANF).}
  7025. \label{fig:Rvec-anf-syntax}
  7026. \end{figure}
  7027. \section{Explicate Control and the \LangCVec{} language}
  7028. \label{sec:explicate-control-r3}
  7029. \begin{figure}[tp]
  7030. \fbox{
  7031. \begin{minipage}{0.96\textwidth}
  7032. \small
  7033. \[
  7034. \begin{array}{lcl}
  7035. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  7036. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  7037. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  7038. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  7039. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  7040. &\mid& \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  7041. &\mid& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  7042. &\mid& \LP\key{Prim}~\key{'vector-set!}\,\LP\Atm\,\INT{\Int}\,\Atm\RP\RP\\
  7043. &\mid& \LP\key{GlobalValue} \,\Var\RP \mid \LP\key{Void}\RP\\
  7044. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  7045. \mid \LP\key{Collect} \,\itm{int}\RP \\
  7046. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  7047. \mid \GOTO{\itm{label}} } \\
  7048. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  7049. \LangCVec{} & ::= & \gray{ \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }
  7050. \end{array}
  7051. \]
  7052. \end{minipage}
  7053. }
  7054. \caption{The abstract syntax of \LangCVec{}, extending \LangCIf{}
  7055. (Figure~\ref{fig:c1-syntax}).}
  7056. \label{fig:c2-syntax}
  7057. \end{figure}
  7058. The output of \code{explicate-control} is a program in the
  7059. intermediate language \LangCVec{}, whose abstract syntax is defined in
  7060. Figure~\ref{fig:c2-syntax}. (The concrete syntax is defined in
  7061. Figure~\ref{fig:c2-concrete-syntax} of the Appendix.) The new forms
  7062. of \LangCVec{} include the \key{allocate}, \key{vector-ref}, and
  7063. \key{vector-set!}, and \key{global-value} expressions and the
  7064. \code{collect} statement. The \code{explicate-control} pass can treat
  7065. these new forms much like the other expression forms that we've
  7066. already encoutered.
  7067. \section{Select Instructions and the \LangXGlobal{} Language}
  7068. \label{sec:select-instructions-gc}
  7069. \index{instruction selection}
  7070. %% void (rep as zero)
  7071. %% allocate
  7072. %% collect (callq collect)
  7073. %% vector-ref
  7074. %% vector-set!
  7075. %% global (postpone)
  7076. In this pass we generate x86 code for most of the new operations that
  7077. were needed to compile tuples, including \code{Allocate},
  7078. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  7079. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  7080. the later has a different concrete syntax (see
  7081. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  7082. \index{x86}
  7083. The \code{vector-ref} and \code{vector-set!} forms translate into
  7084. \code{movq} instructions. (The plus one in the offset is to get past
  7085. the tag at the beginning of the tuple representation.)
  7086. \begin{lstlisting}
  7087. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  7088. |$\Longrightarrow$|
  7089. movq |$\itm{vec}'$|, %r11
  7090. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  7091. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  7092. |$\Longrightarrow$|
  7093. movq |$\itm{vec}'$|, %r11
  7094. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  7095. movq $0, |$\itm{lhs'}$|
  7096. \end{lstlisting}
  7097. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  7098. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  7099. register \code{r11} ensures that offset expression
  7100. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  7101. removing \code{r11} from consideration by the register allocating.
  7102. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  7103. \code{rax}. Then the generated code for \code{vector-set!} would be
  7104. \begin{lstlisting}
  7105. movq |$\itm{vec}'$|, %rax
  7106. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  7107. movq $0, |$\itm{lhs}'$|
  7108. \end{lstlisting}
  7109. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  7110. \code{patch-instructions} would insert a move through \code{rax}
  7111. as follows.
  7112. \begin{lstlisting}
  7113. movq |$\itm{vec}'$|, %rax
  7114. movq |$\itm{arg}'$|, %rax
  7115. movq %rax, |$8(n+1)$|(%rax)
  7116. movq $0, |$\itm{lhs}'$|
  7117. \end{lstlisting}
  7118. But the above sequence of instructions does not work because we're
  7119. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  7120. $\itm{arg}'$) at the same time!
  7121. We compile the \code{allocate} form to operations on the
  7122. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  7123. is the next free address in the FromSpace, so we copy it into
  7124. \code{r11} and then move it forward by enough space for the tuple
  7125. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  7126. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  7127. initialize the \itm{tag} and finally copy the address in \code{r11} to
  7128. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  7129. tag is organized. We recommend using the Racket operations
  7130. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  7131. during compilation. The type annotation in the \code{vector} form is
  7132. used to determine the pointer mask region of the tag.
  7133. \begin{lstlisting}
  7134. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  7135. |$\Longrightarrow$|
  7136. movq free_ptr(%rip), %r11
  7137. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  7138. movq $|$\itm{tag}$|, 0(%r11)
  7139. movq %r11, |$\itm{lhs}'$|
  7140. \end{lstlisting}
  7141. The \code{collect} form is compiled to a call to the \code{collect}
  7142. function in the runtime. The arguments to \code{collect} are 1) the
  7143. top of the root stack and 2) the number of bytes that need to be
  7144. allocated. We use another dedicated register, \code{r15}, to
  7145. store the pointer to the top of the root stack. So \code{r15} is not
  7146. available for use by the register allocator.
  7147. \begin{lstlisting}
  7148. (collect |$\itm{bytes}$|)
  7149. |$\Longrightarrow$|
  7150. movq %r15, %rdi
  7151. movq $|\itm{bytes}|, %rsi
  7152. callq collect
  7153. \end{lstlisting}
  7154. \begin{figure}[tp]
  7155. \fbox{
  7156. \begin{minipage}{0.96\textwidth}
  7157. \[
  7158. \begin{array}{lcl}
  7159. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)} \\
  7160. \LangXGlobal{} &::= & \gray{ \key{.globl main} }\\
  7161. & & \gray{ \key{main:} \; \Instr\ldots }
  7162. \end{array}
  7163. \]
  7164. \end{minipage}
  7165. }
  7166. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  7167. \label{fig:x86-2-concrete}
  7168. \end{figure}
  7169. \begin{figure}[tp]
  7170. \fbox{
  7171. \begin{minipage}{0.96\textwidth}
  7172. \small
  7173. \[
  7174. \begin{array}{lcl}
  7175. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  7176. \mid \BYTEREG{\Reg}} \\
  7177. &\mid& (\key{Global}~\Var) \\
  7178. \LangXGlobal{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  7179. \end{array}
  7180. \]
  7181. \end{minipage}
  7182. }
  7183. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  7184. \label{fig:x86-2}
  7185. \end{figure}
  7186. The concrete and abstract syntax of the \LangXGlobal{} language is
  7187. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  7188. differs from \LangXIf{} just in the addition of the form for global
  7189. variables.
  7190. %
  7191. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  7192. \code{select-instructions} pass on the running example.
  7193. \begin{figure}[tbp]
  7194. \centering
  7195. % tests/s2_17.rkt
  7196. \begin{minipage}[t]{0.5\textwidth}
  7197. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7198. block35:
  7199. movq free_ptr(%rip), alloc9024
  7200. addq $16, free_ptr(%rip)
  7201. movq alloc9024, %r11
  7202. movq $131, 0(%r11)
  7203. movq alloc9024, %r11
  7204. movq vecinit9025, 8(%r11)
  7205. movq $0, initret9026
  7206. movq alloc9024, %r11
  7207. movq 8(%r11), tmp9034
  7208. movq tmp9034, %r11
  7209. movq 8(%r11), %rax
  7210. jmp conclusion
  7211. block36:
  7212. movq $0, collectret9027
  7213. jmp block35
  7214. block38:
  7215. movq free_ptr(%rip), alloc9020
  7216. addq $16, free_ptr(%rip)
  7217. movq alloc9020, %r11
  7218. movq $3, 0(%r11)
  7219. movq alloc9020, %r11
  7220. movq vecinit9021, 8(%r11)
  7221. movq $0, initret9022
  7222. movq alloc9020, vecinit9025
  7223. movq free_ptr(%rip), tmp9031
  7224. movq tmp9031, tmp9032
  7225. addq $16, tmp9032
  7226. movq fromspace_end(%rip), tmp9033
  7227. cmpq tmp9033, tmp9032
  7228. jl block36
  7229. jmp block37
  7230. block37:
  7231. movq %r15, %rdi
  7232. movq $16, %rsi
  7233. callq 'collect
  7234. jmp block35
  7235. block39:
  7236. movq $0, collectret9023
  7237. jmp block38
  7238. \end{lstlisting}
  7239. \end{minipage}
  7240. \begin{minipage}[t]{0.45\textwidth}
  7241. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7242. start:
  7243. movq $42, vecinit9021
  7244. movq free_ptr(%rip), tmp9028
  7245. movq tmp9028, tmp9029
  7246. addq $16, tmp9029
  7247. movq fromspace_end(%rip), tmp9030
  7248. cmpq tmp9030, tmp9029
  7249. jl block39
  7250. jmp block40
  7251. block40:
  7252. movq %r15, %rdi
  7253. movq $16, %rsi
  7254. callq 'collect
  7255. jmp block38
  7256. \end{lstlisting}
  7257. \end{minipage}
  7258. \caption{Output of the \code{select-instructions} pass.}
  7259. \label{fig:select-instr-output-gc}
  7260. \end{figure}
  7261. \clearpage
  7262. \section{Register Allocation}
  7263. \label{sec:reg-alloc-gc}
  7264. \index{register allocation}
  7265. As discussed earlier in this chapter, the garbage collector needs to
  7266. access all the pointers in the root set, that is, all variables that
  7267. are vectors. It will be the responsibility of the register allocator
  7268. to make sure that:
  7269. \begin{enumerate}
  7270. \item the root stack is used for spilling vector-typed variables, and
  7271. \item if a vector-typed variable is live during a call to the
  7272. collector, it must be spilled to ensure it is visible to the
  7273. collector.
  7274. \end{enumerate}
  7275. The later responsibility can be handled during construction of the
  7276. interference graph, by adding interference edges between the call-live
  7277. vector-typed variables and all the callee-saved registers. (They
  7278. already interfere with the caller-saved registers.) The type
  7279. information for variables is in the \code{Program} form, so we
  7280. recommend adding another parameter to the \code{build-interference}
  7281. function to communicate this alist.
  7282. The spilling of vector-typed variables to the root stack can be
  7283. handled after graph coloring, when choosing how to assign the colors
  7284. (integers) to registers and stack locations. The \code{Program} output
  7285. of this pass changes to also record the number of spills to the root
  7286. stack.
  7287. % build-interference
  7288. %
  7289. % callq
  7290. % extra parameter for var->type assoc. list
  7291. % update 'program' and 'if'
  7292. % allocate-registers
  7293. % allocate spilled vectors to the rootstack
  7294. % don't change color-graph
  7295. \section{Print x86}
  7296. \label{sec:print-x86-gc}
  7297. \index{prelude}\index{conclusion}
  7298. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  7299. \code{print-x86} pass on the running example. In the prelude and
  7300. conclusion of the \code{main} function, we treat the root stack very
  7301. much like the regular stack in that we move the root stack pointer
  7302. (\code{r15}) to make room for the spills to the root stack, except
  7303. that the root stack grows up instead of down. For the running
  7304. example, there was just one spill so we increment \code{r15} by 8
  7305. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  7306. One issue that deserves special care is that there may be a call to
  7307. \code{collect} prior to the initializing assignments for all the
  7308. variables in the root stack. We do not want the garbage collector to
  7309. accidentally think that some uninitialized variable is a pointer that
  7310. needs to be followed. Thus, we zero-out all locations on the root
  7311. stack in the prelude of \code{main}. In
  7312. Figure~\ref{fig:print-x86-output-gc}, the instruction
  7313. %
  7314. \lstinline{movq $0, (%r15)}
  7315. %
  7316. accomplishes this task. The garbage collector tests each root to see
  7317. if it is null prior to dereferencing it.
  7318. \begin{figure}[htbp]
  7319. \begin{minipage}[t]{0.5\textwidth}
  7320. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7321. block35:
  7322. movq free_ptr(%rip), %rcx
  7323. addq $16, free_ptr(%rip)
  7324. movq %rcx, %r11
  7325. movq $131, 0(%r11)
  7326. movq %rcx, %r11
  7327. movq -8(%r15), %rax
  7328. movq %rax, 8(%r11)
  7329. movq $0, %rdx
  7330. movq %rcx, %r11
  7331. movq 8(%r11), %rcx
  7332. movq %rcx, %r11
  7333. movq 8(%r11), %rax
  7334. jmp conclusion
  7335. block36:
  7336. movq $0, %rcx
  7337. jmp block35
  7338. block38:
  7339. movq free_ptr(%rip), %rcx
  7340. addq $16, free_ptr(%rip)
  7341. movq %rcx, %r11
  7342. movq $3, 0(%r11)
  7343. movq %rcx, %r11
  7344. movq %rbx, 8(%r11)
  7345. movq $0, %rdx
  7346. movq %rcx, -8(%r15)
  7347. movq free_ptr(%rip), %rcx
  7348. addq $16, %rcx
  7349. movq fromspace_end(%rip), %rdx
  7350. cmpq %rdx, %rcx
  7351. jl block36
  7352. movq %r15, %rdi
  7353. movq $16, %rsi
  7354. callq collect
  7355. jmp block35
  7356. block39:
  7357. movq $0, %rcx
  7358. jmp block38
  7359. \end{lstlisting}
  7360. \end{minipage}
  7361. \begin{minipage}[t]{0.45\textwidth}
  7362. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7363. start:
  7364. movq $42, %rbx
  7365. movq free_ptr(%rip), %rdx
  7366. addq $16, %rdx
  7367. movq fromspace_end(%rip), %rcx
  7368. cmpq %rcx, %rdx
  7369. jl block39
  7370. movq %r15, %rdi
  7371. movq $16, %rsi
  7372. callq collect
  7373. jmp block38
  7374. .globl main
  7375. main:
  7376. pushq %rbp
  7377. movq %rsp, %rbp
  7378. pushq %r13
  7379. pushq %r12
  7380. pushq %rbx
  7381. pushq %r14
  7382. subq $0, %rsp
  7383. movq $16384, %rdi
  7384. movq $16384, %rsi
  7385. callq initialize
  7386. movq rootstack_begin(%rip), %r15
  7387. movq $0, (%r15)
  7388. addq $8, %r15
  7389. jmp start
  7390. conclusion:
  7391. subq $8, %r15
  7392. addq $0, %rsp
  7393. popq %r14
  7394. popq %rbx
  7395. popq %r12
  7396. popq %r13
  7397. popq %rbp
  7398. retq
  7399. \end{lstlisting}
  7400. \end{minipage}
  7401. \caption{Output of the \code{print-x86} pass.}
  7402. \label{fig:print-x86-output-gc}
  7403. \end{figure}
  7404. \begin{figure}[p]
  7405. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7406. \node (Rvec) at (0,2) {\large \LangVec{}};
  7407. \node (Rvec-2) at (3,2) {\large \LangVec{}};
  7408. \node (Rvec-3) at (6,2) {\large \LangVec{}};
  7409. \node (Rvec-4) at (9,2) {\large \LangVec{}};
  7410. \node (Rvec-5) at (12,2) {\large \LangAlloc{}};
  7411. \node (C2-4) at (3,0) {\large \LangCVec{}};
  7412. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  7413. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  7414. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  7415. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  7416. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  7417. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  7418. %\path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize type-check} (Rvec-2);
  7419. \path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize shrink} (Rvec-2);
  7420. \path[->,bend left=15] (Rvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Rvec-3);
  7421. \path[->,bend left=15] (Rvec-3) edge [above] node {\ttfamily\footnotesize expose-alloc.} (Rvec-4);
  7422. \path[->,bend left=15] (Rvec-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvec-5);
  7423. \path[->,bend left=20] (Rvec-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-4);
  7424. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select-instr.} (x86-2);
  7425. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  7426. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  7427. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7428. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  7429. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  7430. \end{tikzpicture}
  7431. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  7432. \label{fig:Rvec-passes}
  7433. \end{figure}
  7434. Figure~\ref{fig:Rvec-passes} gives an overview of all the passes needed
  7435. for the compilation of \LangVec{}.
  7436. \section{Challenge: Simple Structures}
  7437. \label{sec:simple-structures}
  7438. \index{struct}
  7439. \index{structure}
  7440. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  7441. \LangStruct{}, which extends \LangVec{} with support for simple structures.
  7442. Recall that a \code{struct} in Typed Racket is a user-defined data
  7443. type that contains named fields and that is heap allocated, similar to
  7444. a vector. The following is an example of a structure definition, in
  7445. this case the definition of a \code{point} type.
  7446. \begin{lstlisting}
  7447. (struct point ([x : Integer] [y : Integer]) #:mutable)
  7448. \end{lstlisting}
  7449. \begin{figure}[tbp]
  7450. \centering
  7451. \fbox{
  7452. \begin{minipage}{0.96\textwidth}
  7453. \[
  7454. \begin{array}{lcl}
  7455. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7456. \mid (\key{Vector}\;\Type \ldots) \mid \key{Void} } \mid \Var \\
  7457. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  7458. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  7459. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  7460. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  7461. \mid (\key{and}\;\Exp\;\Exp)
  7462. \mid (\key{or}\;\Exp\;\Exp)
  7463. \mid (\key{not}\;\Exp) } \\
  7464. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  7465. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  7466. &\mid& \gray{ (\key{vector}\;\Exp \ldots)
  7467. \mid (\key{vector-ref}\;\Exp\;\Int) } \\
  7468. &\mid& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  7469. &\mid& \gray{ (\key{void}) } \mid (\Var\;\Exp \ldots)\\
  7470. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  7471. \LangStruct{} &::=& \Def \ldots \; \Exp
  7472. \end{array}
  7473. \]
  7474. \end{minipage}
  7475. }
  7476. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  7477. (Figure~\ref{fig:Rvec-concrete-syntax}).}
  7478. \label{fig:r3s-concrete-syntax}
  7479. \end{figure}
  7480. An instance of a structure is created using function call syntax, with
  7481. the name of the structure in the function position:
  7482. \begin{lstlisting}
  7483. (point 7 12)
  7484. \end{lstlisting}
  7485. Function-call syntax is also used to read the value in a field of a
  7486. structure. The function name is formed by the structure name, a dash,
  7487. and the field name. The following example uses \code{point-x} and
  7488. \code{point-y} to access the \code{x} and \code{y} fields of two point
  7489. instances.
  7490. \begin{center}
  7491. \begin{lstlisting}
  7492. (let ([pt1 (point 7 12)])
  7493. (let ([pt2 (point 4 3)])
  7494. (+ (- (point-x pt1) (point-x pt2))
  7495. (- (point-y pt1) (point-y pt2)))))
  7496. \end{lstlisting}
  7497. \end{center}
  7498. Similarly, to write to a field of a structure, use its set function,
  7499. whose name starts with \code{set-}, followed by the structure name,
  7500. then a dash, then the field name, and concluded with an exclamation
  7501. mark. The following example uses \code{set-point-x!} to change the
  7502. \code{x} field from \code{7} to \code{42}.
  7503. \begin{center}
  7504. \begin{lstlisting}
  7505. (let ([pt (point 7 12)])
  7506. (let ([_ (set-point-x! pt 42)])
  7507. (point-x pt)))
  7508. \end{lstlisting}
  7509. \end{center}
  7510. \begin{exercise}\normalfont
  7511. Extend your compiler with support for simple structures, compiling
  7512. \LangStruct{} to x86 assembly code. Create five new test cases that use
  7513. structures and test your compiler.
  7514. \end{exercise}
  7515. \section{Challenge: Generational Collection}
  7516. The copying collector described in Section~\ref{sec:GC} can incur
  7517. significant runtime overhead because the call to \code{collect} takes
  7518. time proportional to all of the live data. One way to reduce this
  7519. overhead is to reduce how much data is inspected in each call to
  7520. \code{collect}. In particular, researchers have observed that recently
  7521. allocated data is more likely to become garbage then data that has
  7522. survived one or more previous calls to \code{collect}. This insight
  7523. motivated the creation of \emph{generational garbage collectors}
  7524. \index{generational garbage collector} that
  7525. 1) segregates data according to its age into two or more generations,
  7526. 2) allocates less space for younger generations, so collecting them is
  7527. faster, and more space for the older generations, and 3) performs
  7528. collection on the younger generations more frequently then for older
  7529. generations~\citep{Wilson:1992fk}.
  7530. For this challenge assignment, the goal is to adapt the copying
  7531. collector implemented in \code{runtime.c} to use two generations, one
  7532. for young data and one for old data. Each generation consists of a
  7533. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  7534. \code{collect} function to use the two generations.
  7535. \begin{enumerate}
  7536. \item Copy the young generation's FromSpace to its ToSpace then switch
  7537. the role of the ToSpace and FromSpace
  7538. \item If there is enough space for the requested number of bytes in
  7539. the young FromSpace, then return from \code{collect}.
  7540. \item If there is not enough space in the young FromSpace for the
  7541. requested bytes, then move the data from the young generation to the
  7542. old one with the following steps:
  7543. \begin{enumerate}
  7544. \item If there is enough room in the old FromSpace, copy the young
  7545. FromSpace to the old FromSpace and then return.
  7546. \item If there is not enough room in the old FromSpace, then collect
  7547. the old generation by copying the old FromSpace to the old ToSpace
  7548. and swap the roles of the old FromSpace and ToSpace.
  7549. \item If there is enough room now, copy the young FromSpace to the
  7550. old FromSpace and return. Otherwise, allocate a larger FromSpace
  7551. and ToSpace for the old generation. Copy the young FromSpace and
  7552. the old FromSpace into the larger FromSpace for the old
  7553. generation and then return.
  7554. \end{enumerate}
  7555. \end{enumerate}
  7556. We recommend that you generalize the \code{cheney} function so that it
  7557. can be used for all the copies mentioned above: between the young
  7558. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  7559. between the young FromSpace and old FromSpace. This can be
  7560. accomplished by adding parameters to \code{cheney} that replace its
  7561. use of the global variables \code{fromspace\_begin},
  7562. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  7563. Note that the collection of the young generation does not traverse the
  7564. old generation. This introduces a potential problem: there may be
  7565. young data that is only reachable through pointers in the old
  7566. generation. If these pointers are not taken into account, the
  7567. collector could throw away young data that is live! One solution,
  7568. called \emph{pointer recording}, is to maintain a set of all the
  7569. pointers from the old generation into the new generation and consider
  7570. this set as part of the root set. To maintain this set, the compiler
  7571. must insert extra instructions around every \code{vector-set!}. If the
  7572. vector being modified is in the old generation, and if the value being
  7573. written is a pointer into the new generation, than that pointer must
  7574. be added to the set. Also, if the value being overwritten was a
  7575. pointer into the new generation, then that pointer should be removed
  7576. from the set.
  7577. \begin{exercise}\normalfont
  7578. Adapt the \code{collect} function in \code{runtime.c} to implement
  7579. generational garbage collection, as outlined in this section.
  7580. Update the code generation for \code{vector-set!} to implement
  7581. pointer recording. Make sure that your new compiler and runtime
  7582. passes your test suite.
  7583. \end{exercise}
  7584. % Further Reading
  7585. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7586. \chapter{Functions}
  7587. \label{ch:Rfun}
  7588. \index{function}
  7589. This chapter studies the compilation of functions similar to those
  7590. found in the C language. This corresponds to a subset of Typed Racket
  7591. in which only top-level function definitions are allowed. This kind of
  7592. function is an important stepping stone to implementing
  7593. lexically-scoped functions, that is, \key{lambda} abstractions, which
  7594. is the topic of Chapter~\ref{ch:Rlam}.
  7595. \section{The \LangFun{} Language}
  7596. The concrete and abstract syntax for function definitions and function
  7597. application is shown in Figures~\ref{fig:Rfun-concrete-syntax} and
  7598. \ref{fig:Rfun-syntax}, where we define the \LangFun{} language. Programs in
  7599. \LangFun{} begin with zero or more function definitions. The function
  7600. names from these definitions are in-scope for the entire program,
  7601. including all other function definitions (so the ordering of function
  7602. definitions does not matter). The concrete syntax for function
  7603. application\index{function application} is $(\Exp \; \Exp \ldots)$
  7604. where the first expression must
  7605. evaluate to a function and the rest are the arguments.
  7606. The abstract syntax for function application is
  7607. $\APPLY{\Exp}{\Exp\ldots}$.
  7608. %% The syntax for function application does not include an explicit
  7609. %% keyword, which is error prone when using \code{match}. To alleviate
  7610. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  7611. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  7612. Functions are first-class in the sense that a function pointer
  7613. \index{function pointer} is data and can be stored in memory or passed
  7614. as a parameter to another function. Thus, we introduce a function
  7615. type, written
  7616. \begin{lstlisting}
  7617. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  7618. \end{lstlisting}
  7619. for a function whose $n$ parameters have the types $\Type_1$ through
  7620. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  7621. these functions (with respect to Racket functions) is that they are
  7622. not lexically scoped. That is, the only external entities that can be
  7623. referenced from inside a function body are other globally-defined
  7624. functions. The syntax of \LangFun{} prevents functions from being nested
  7625. inside each other.
  7626. \begin{figure}[tp]
  7627. \centering
  7628. \fbox{
  7629. \begin{minipage}{0.96\textwidth}
  7630. \small
  7631. \[
  7632. \begin{array}{lcl}
  7633. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  7634. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void} } \mid (\Type \ldots \; \key{->}\; \Type) \\
  7635. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  7636. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  7637. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  7638. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  7639. \mid (\key{and}\;\Exp\;\Exp)
  7640. \mid (\key{or}\;\Exp\;\Exp)
  7641. \mid (\key{not}\;\Exp)} \\
  7642. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  7643. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  7644. (\key{vector-ref}\;\Exp\;\Int)} \\
  7645. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  7646. \mid \LP\key{has-type}~\Exp~\Type\RP } \\
  7647. &\mid& \LP\Exp \; \Exp \ldots\RP \\
  7648. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  7649. \LangFun{} &::=& \Def \ldots \; \Exp
  7650. \end{array}
  7651. \]
  7652. \end{minipage}
  7653. }
  7654. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-concrete-syntax}).}
  7655. \label{fig:Rfun-concrete-syntax}
  7656. \end{figure}
  7657. \begin{figure}[tp]
  7658. \centering
  7659. \fbox{
  7660. \begin{minipage}{0.96\textwidth}
  7661. \small
  7662. \[
  7663. \begin{array}{lcl}
  7664. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  7665. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  7666. &\mid& \gray{ \BOOL{\itm{bool}}
  7667. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  7668. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP }
  7669. \mid \APPLY{\Exp}{\Exp\ldots}\\
  7670. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}\\
  7671. \LangFun{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  7672. \end{array}
  7673. \]
  7674. \end{minipage}
  7675. }
  7676. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-syntax}).}
  7677. \label{fig:Rfun-syntax}
  7678. \end{figure}
  7679. The program in Figure~\ref{fig:Rfun-function-example} is a
  7680. representative example of defining and using functions in \LangFun{}. We
  7681. define a function \code{map-vec} that applies some other function
  7682. \code{f} to both elements of a vector and returns a new
  7683. vector containing the results. We also define a function \code{add1}.
  7684. The program applies
  7685. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  7686. \code{(vector 1 42)}, from which we return the \code{42}.
  7687. \begin{figure}[tbp]
  7688. \begin{lstlisting}
  7689. (define (map-vec [f : (Integer -> Integer)]
  7690. [v : (Vector Integer Integer)])
  7691. : (Vector Integer Integer)
  7692. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  7693. (define (add1 [x : Integer]) : Integer
  7694. (+ x 1))
  7695. (vector-ref (map-vec add1 (vector 0 41)) 1)
  7696. \end{lstlisting}
  7697. \caption{Example of using functions in \LangFun{}.}
  7698. \label{fig:Rfun-function-example}
  7699. \end{figure}
  7700. The definitional interpreter for \LangFun{} is in
  7701. Figure~\ref{fig:interp-Rfun}. The case for the \code{ProgramDefsExp} form is
  7702. responsible for setting up the mutual recursion between the top-level
  7703. function definitions. We use the classic back-patching \index{back-patching}
  7704. approach that uses mutable variables and makes two passes over the function
  7705. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  7706. top-level environment using a mutable cons cell for each function
  7707. definition. Note that the \code{lambda} value for each function is
  7708. incomplete; it does not yet include the environment. Once the
  7709. top-level environment is constructed, we then iterate over it and
  7710. update the \code{lambda} values to use the top-level environment.
  7711. \begin{figure}[tp]
  7712. \begin{lstlisting}
  7713. (define interp-Rfun-class
  7714. (class interp-Rvec-class
  7715. (super-new)
  7716. (define/override ((interp-exp env) e)
  7717. (define recur (interp-exp env))
  7718. (match e
  7719. [(Var x) (unbox (dict-ref env x))]
  7720. [(Let x e body)
  7721. (define new-env (dict-set env x (box (recur e))))
  7722. ((interp-exp new-env) body)]
  7723. [(Apply fun args)
  7724. (define fun-val (recur fun))
  7725. (define arg-vals (for/list ([e args]) (recur e)))
  7726. (match fun-val
  7727. [`(function (,xs ...) ,body ,fun-env)
  7728. (define params-args (for/list ([x xs] [arg arg-vals])
  7729. (cons x (box arg))))
  7730. (define new-env (append params-args fun-env))
  7731. ((interp-exp new-env) body)]
  7732. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  7733. [else ((super interp-exp env) e)]
  7734. ))
  7735. (define/public (interp-def d)
  7736. (match d
  7737. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  7738. (cons f (box `(function ,xs ,body ())))]))
  7739. (define/override (interp-program p)
  7740. (match p
  7741. [(ProgramDefsExp info ds body)
  7742. (let ([top-level (for/list ([d ds]) (interp-def d))])
  7743. (for/list ([f (in-dict-values top-level)])
  7744. (set-box! f (match (unbox f)
  7745. [`(function ,xs ,body ())
  7746. `(function ,xs ,body ,top-level)])))
  7747. ((interp-exp top-level) body))]))
  7748. ))
  7749. (define (interp-Rfun p)
  7750. (send (new interp-Rfun-class) interp-program p))
  7751. \end{lstlisting}
  7752. \caption{Interpreter for the \LangFun{} language.}
  7753. \label{fig:interp-Rfun}
  7754. \end{figure}
  7755. \margincomment{TODO: explain type checker}
  7756. The type checker for \LangFun{} is is in Figure~\ref{fig:type-check-Rfun}.
  7757. \begin{figure}[tp]
  7758. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7759. (define type-check-Rfun-class
  7760. (class type-check-Rvec-class
  7761. (super-new)
  7762. (inherit check-type-equal?)
  7763. (define/public (type-check-apply env e es)
  7764. (define-values (e^ ty) ((type-check-exp env) e))
  7765. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  7766. ((type-check-exp env) e)))
  7767. (match ty
  7768. [`(,ty^* ... -> ,rt)
  7769. (for ([arg-ty ty*] [param-ty ty^*])
  7770. (check-type-equal? arg-ty param-ty (Apply e es)))
  7771. (values e^ e* rt)]))
  7772. (define/override (type-check-exp env)
  7773. (lambda (e)
  7774. (match e
  7775. [(FunRef f)
  7776. (values (FunRef f) (dict-ref env f))]
  7777. [(Apply e es)
  7778. (define-values (e^ es^ rt) (type-check-apply env e es))
  7779. (values (Apply e^ es^) rt)]
  7780. [(Call e es)
  7781. (define-values (e^ es^ rt) (type-check-apply env e es))
  7782. (values (Call e^ es^) rt)]
  7783. [else ((super type-check-exp env) e)])))
  7784. (define/public (type-check-def env)
  7785. (lambda (e)
  7786. (match e
  7787. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  7788. (define new-env (append (map cons xs ps) env))
  7789. (define-values (body^ ty^) ((type-check-exp new-env) body))
  7790. (check-type-equal? ty^ rt body)
  7791. (Def f p:t* rt info body^)])))
  7792. (define/public (fun-def-type d)
  7793. (match d
  7794. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  7795. (define/override (type-check-program e)
  7796. (match e
  7797. [(ProgramDefsExp info ds body)
  7798. (define new-env (for/list ([d ds])
  7799. (cons (Def-name d) (fun-def-type d))))
  7800. (define ds^ (for/list ([d ds]) ((type-check-def new-env) d)))
  7801. (define-values (body^ ty) ((type-check-exp new-env) body))
  7802. (check-type-equal? ty 'Integer body)
  7803. (ProgramDefsExp info ds^ body^)]))))
  7804. (define (type-check-Rfun p)
  7805. (send (new type-check-Rfun-class) type-check-program p))
  7806. \end{lstlisting}
  7807. \caption{Type checker for the \LangFun{} language.}
  7808. \label{fig:type-check-Rfun}
  7809. \end{figure}
  7810. \section{Functions in x86}
  7811. \label{sec:fun-x86}
  7812. \margincomment{\tiny Make sure callee-saved registers are discussed
  7813. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  7814. \margincomment{\tiny Talk about the return address on the
  7815. stack and what callq and retq does.\\ --Jeremy }
  7816. The x86 architecture provides a few features to support the
  7817. implementation of functions. We have already seen that x86 provides
  7818. labels so that one can refer to the location of an instruction, as is
  7819. needed for jump instructions. Labels can also be used to mark the
  7820. beginning of the instructions for a function. Going further, we can
  7821. obtain the address of a label by using the \key{leaq} instruction and
  7822. PC-relative addressing. For example, the following puts the
  7823. address of the \code{add1} label into the \code{rbx} register.
  7824. \begin{lstlisting}
  7825. leaq add1(%rip), %rbx
  7826. \end{lstlisting}
  7827. The instruction pointer register \key{rip} (aka. the program counter
  7828. \index{program counter}) always points to the next instruction to be
  7829. executed. When combined with an label, as in \code{add1(\%rip)}, the
  7830. linker computes the distance $d$ between the address of \code{add1}
  7831. and where the \code{rip} would be at that moment and then changes
  7832. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  7833. the address of \code{add1}.
  7834. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  7835. jump to a function whose location is given by a label. To support
  7836. function calls in this chapter we instead will be jumping to a
  7837. function whose location is given by an address in a register, that is,
  7838. we need to make an \emph{indirect function call}. The x86 syntax for
  7839. this is a \code{callq} instruction but with an asterisk before the
  7840. register name.\index{indirect function call}
  7841. \begin{lstlisting}
  7842. callq *%rbx
  7843. \end{lstlisting}
  7844. \subsection{Calling Conventions}
  7845. \index{calling conventions}
  7846. The \code{callq} instruction provides partial support for implementing
  7847. functions: it pushes the return address on the stack and it jumps to
  7848. the target. However, \code{callq} does not handle
  7849. \begin{enumerate}
  7850. \item parameter passing,
  7851. \item pushing frames on the procedure call stack and popping them off,
  7852. or
  7853. \item determining how registers are shared by different functions.
  7854. \end{enumerate}
  7855. Regarding (1) parameter passing, recall that the following six
  7856. registers are used to pass arguments to a function, in this order.
  7857. \begin{lstlisting}
  7858. rdi rsi rdx rcx r8 r9
  7859. \end{lstlisting}
  7860. If there are
  7861. more than six arguments, then the convention is to use space on the
  7862. frame of the caller for the rest of the arguments. However, to ease
  7863. the implementation of efficient tail calls
  7864. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  7865. arguments.
  7866. %
  7867. Also recall that the register \code{rax} is for the return value of
  7868. the function.
  7869. \index{prelude}\index{conclusion}
  7870. Regarding (2) frames \index{frame} and the procedure call stack,
  7871. \index{procedure call stack} recall from Section~\ref{sec:x86} that
  7872. the stack grows down, with each function call using a chunk of space
  7873. called a frame. The caller sets the stack pointer, register
  7874. \code{rsp}, to the last data item in its frame. The callee must not
  7875. change anything in the caller's frame, that is, anything that is at or
  7876. above the stack pointer. The callee is free to use locations that are
  7877. below the stack pointer.
  7878. Recall that we are storing variables of vector type on the root stack.
  7879. So the prelude needs to move the root stack pointer \code{r15} up and
  7880. the conclusion needs to move the root stack pointer back down. Also,
  7881. the prelude must initialize to \code{0} this frame's slots in the root
  7882. stack to signal to the garbage collector that those slots do not yet
  7883. contain a pointer to a vector. Otherwise the garbage collector will
  7884. interpret the garbage bits in those slots as memory addresses and try
  7885. to traverse them, causing serious mayhem!
  7886. Regarding (3) the sharing of registers between different functions,
  7887. recall from Section~\ref{sec:calling-conventions} that the registers
  7888. are divided into two groups, the caller-saved registers and the
  7889. callee-saved registers. The caller should assume that all the
  7890. caller-saved registers get overwritten with arbitrary values by the
  7891. callee. That is why we recommend in
  7892. Section~\ref{sec:calling-conventions} that variables that are live
  7893. during a function call should not be assigned to caller-saved
  7894. registers.
  7895. On the flip side, if the callee wants to use a callee-saved register,
  7896. the callee must save the contents of those registers on their stack
  7897. frame and then put them back prior to returning to the caller. That
  7898. is why we recommended in Section~\ref{sec:calling-conventions} that if
  7899. the register allocator assigns a variable to a callee-saved register,
  7900. then the prelude of the \code{main} function must save that register
  7901. to the stack and the conclusion of \code{main} must restore it. This
  7902. recommendation now generalizes to all functions.
  7903. Also recall that the base pointer, register \code{rbp}, is used as a
  7904. point-of-reference within a frame, so that each local variable can be
  7905. accessed at a fixed offset from the base pointer
  7906. (Section~\ref{sec:x86}).
  7907. %
  7908. Figure~\ref{fig:call-frames} shows the general layout of the caller
  7909. and callee frames.
  7910. \begin{figure}[tbp]
  7911. \centering
  7912. \begin{tabular}{r|r|l|l} \hline
  7913. Caller View & Callee View & Contents & Frame \\ \hline
  7914. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  7915. 0(\key{\%rbp}) & & old \key{rbp} \\
  7916. -8(\key{\%rbp}) & & callee-saved $1$ \\
  7917. \ldots & & \ldots \\
  7918. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  7919. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  7920. \ldots & & \ldots \\
  7921. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  7922. %% & & \\
  7923. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  7924. %% & \ldots & \ldots \\
  7925. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  7926. \hline
  7927. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  7928. & 0(\key{\%rbp}) & old \key{rbp} \\
  7929. & -8(\key{\%rbp}) & callee-saved $1$ \\
  7930. & \ldots & \ldots \\
  7931. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  7932. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  7933. & \ldots & \ldots \\
  7934. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  7935. \end{tabular}
  7936. \caption{Memory layout of caller and callee frames.}
  7937. \label{fig:call-frames}
  7938. \end{figure}
  7939. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  7940. %% local variables and for storing the values of callee-saved registers
  7941. %% (we shall refer to all of these collectively as ``locals''), and that
  7942. %% at the beginning of a function we move the stack pointer \code{rsp}
  7943. %% down to make room for them.
  7944. %% We recommend storing the local variables
  7945. %% first and then the callee-saved registers, so that the local variables
  7946. %% can be accessed using \code{rbp} the same as before the addition of
  7947. %% functions.
  7948. %% To make additional room for passing arguments, we shall
  7949. %% move the stack pointer even further down. We count how many stack
  7950. %% arguments are needed for each function call that occurs inside the
  7951. %% body of the function and find their maximum. Adding this number to the
  7952. %% number of locals gives us how much the \code{rsp} should be moved at
  7953. %% the beginning of the function. In preparation for a function call, we
  7954. %% offset from \code{rsp} to set up the stack arguments. We put the first
  7955. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  7956. %% so on.
  7957. %% Upon calling the function, the stack arguments are retrieved by the
  7958. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  7959. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  7960. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  7961. %% the layout of the caller and callee frames. Notice how important it is
  7962. %% that we correctly compute the maximum number of arguments needed for
  7963. %% function calls; if that number is too small then the arguments and
  7964. %% local variables will smash into each other!
  7965. \subsection{Efficient Tail Calls}
  7966. \label{sec:tail-call}
  7967. In general, the amount of stack space used by a program is determined
  7968. by the longest chain of nested function calls. That is, if function
  7969. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  7970. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  7971. $n$ can grow quite large in the case of recursive or mutually
  7972. recursive functions. However, in some cases we can arrange to use only
  7973. constant space, i.e. $O(1)$, instead of $O(n)$.
  7974. If a function call is the last action in a function body, then that
  7975. call is said to be a \emph{tail call}\index{tail call}.
  7976. For example, in the following
  7977. program, the recursive call to \code{tail-sum} is a tail call.
  7978. \begin{center}
  7979. \begin{lstlisting}
  7980. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  7981. (if (eq? n 0)
  7982. r
  7983. (tail-sum (- n 1) (+ n r))))
  7984. (+ (tail-sum 5 0) 27)
  7985. \end{lstlisting}
  7986. \end{center}
  7987. At a tail call, the frame of the caller is no longer needed, so we
  7988. can pop the caller's frame before making the tail call. With this
  7989. approach, a recursive function that only makes tail calls will only
  7990. use $O(1)$ stack space. Functional languages like Racket typically
  7991. rely heavily on recursive functions, so they typically guarantee that
  7992. all tail calls will be optimized in this way.
  7993. \index{frame}
  7994. However, some care is needed with regards to argument passing in tail
  7995. calls. As mentioned above, for arguments beyond the sixth, the
  7996. convention is to use space in the caller's frame for passing
  7997. arguments. But for a tail call we pop the caller's frame and can no
  7998. longer use it. Another alternative is to use space in the callee's
  7999. frame for passing arguments. However, this option is also problematic
  8000. because the caller and callee's frame overlap in memory. As we begin
  8001. to copy the arguments from their sources in the caller's frame, the
  8002. target locations in the callee's frame might overlap with the sources
  8003. for later arguments! We solve this problem by not using the stack for
  8004. passing more than six arguments but instead using the heap, as we
  8005. describe in the Section~\ref{sec:limit-functions-r4}.
  8006. As mentioned above, for a tail call we pop the caller's frame prior to
  8007. making the tail call. The instructions for popping a frame are the
  8008. instructions that we usually place in the conclusion of a
  8009. function. Thus, we also need to place such code immediately before
  8010. each tail call. These instructions include restoring the callee-saved
  8011. registers, so it is good that the argument passing registers are all
  8012. caller-saved registers.
  8013. One last note regarding which instruction to use to make the tail
  8014. call. When the callee is finished, it should not return to the current
  8015. function, but it should return to the function that called the current
  8016. one. Thus, the return address that is already on the stack is the
  8017. right one, and we should not use \key{callq} to make the tail call, as
  8018. that would unnecessarily overwrite the return address. Instead we can
  8019. simply use the \key{jmp} instruction. Like the indirect function call,
  8020. we write an \emph{indirect jump}\index{indirect jump} with a register
  8021. prefixed with an asterisk. We recommend using \code{rax} to hold the
  8022. jump target because the preceding conclusion overwrites just about
  8023. everything else.
  8024. \begin{lstlisting}
  8025. jmp *%rax
  8026. \end{lstlisting}
  8027. \section{Shrink \LangFun{}}
  8028. \label{sec:shrink-r4}
  8029. The \code{shrink} pass performs a minor modification to ease the
  8030. later passes. This pass introduces an explicit \code{main} function
  8031. and changes the top \code{ProgramDefsExp} form to
  8032. \code{ProgramDefs} as follows.
  8033. \begin{lstlisting}
  8034. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  8035. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  8036. \end{lstlisting}
  8037. where $\itm{mainDef}$ is
  8038. \begin{lstlisting}
  8039. (Def 'main '() 'Integer '() |$\Exp'$|)
  8040. \end{lstlisting}
  8041. \section{Reveal Functions and the \LangFunRef{} language}
  8042. \label{sec:reveal-functions-r4}
  8043. The syntax of \LangFun{} is inconvenient for purposes of compilation in one
  8044. respect: it conflates the use of function names and local
  8045. variables. This is a problem because we need to compile the use of a
  8046. function name differently than the use of a local variable; we need to
  8047. use \code{leaq} to convert the function name (a label in x86) to an
  8048. address in a register. Thus, it is a good idea to create a new pass
  8049. that changes function references from just a symbol $f$ to
  8050. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  8051. output language, \LangFunRef{}, is defined in Figure~\ref{fig:f1-syntax}.
  8052. The concrete syntax for a function reference is $\CFUNREF{f}$.
  8053. \begin{figure}[tp]
  8054. \centering
  8055. \fbox{
  8056. \begin{minipage}{0.96\textwidth}
  8057. \[
  8058. \begin{array}{lcl}
  8059. \Exp &::=& \ldots \mid \FUNREF{\Var}\\
  8060. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  8061. \LangFunRef{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  8062. \end{array}
  8063. \]
  8064. \end{minipage}
  8065. }
  8066. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  8067. (Figure~\ref{fig:Rfun-syntax}).}
  8068. \label{fig:f1-syntax}
  8069. \end{figure}
  8070. %% Distinguishing between calls in tail position and non-tail position
  8071. %% requires the pass to have some notion of context. We recommend using
  8072. %% two mutually recursive functions, one for processing expressions in
  8073. %% tail position and another for the rest.
  8074. Placing this pass after \code{uniquify} will make sure that there are
  8075. no local variables and functions that share the same name. On the
  8076. other hand, \code{reveal-functions} needs to come before the
  8077. \code{explicate-control} pass because that pass helps us compile
  8078. \code{FunRef} forms into assignment statements.
  8079. \section{Limit Functions}
  8080. \label{sec:limit-functions-r4}
  8081. Recall that we wish to limit the number of function parameters to six
  8082. so that we do not need to use the stack for argument passing, which
  8083. makes it easier to implement efficient tail calls. However, because
  8084. the input language \LangFun{} supports arbitrary numbers of function
  8085. arguments, we have some work to do!
  8086. This pass transforms functions and function calls that involve more
  8087. than six arguments to pass the first five arguments as usual, but it
  8088. packs the rest of the arguments into a vector and passes it as the
  8089. sixth argument.
  8090. Each function definition with too many parameters is transformed as
  8091. follows.
  8092. \begin{lstlisting}
  8093. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  8094. |$\Rightarrow$|
  8095. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  8096. \end{lstlisting}
  8097. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  8098. the occurrences of the later parameters with vector references.
  8099. \begin{lstlisting}
  8100. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  8101. \end{lstlisting}
  8102. For function calls with too many arguments, the \code{limit-functions}
  8103. pass transforms them in the following way.
  8104. \begin{tabular}{lll}
  8105. \begin{minipage}{0.2\textwidth}
  8106. \begin{lstlisting}
  8107. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  8108. \end{lstlisting}
  8109. \end{minipage}
  8110. &
  8111. $\Rightarrow$
  8112. &
  8113. \begin{minipage}{0.4\textwidth}
  8114. \begin{lstlisting}
  8115. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  8116. \end{lstlisting}
  8117. \end{minipage}
  8118. \end{tabular}
  8119. \section{Remove Complex Operands}
  8120. \label{sec:rco-r4}
  8121. The primary decisions to make for this pass is whether to classify
  8122. \code{FunRef} and \code{Apply} as either atomic or complex
  8123. expressions. Recall that a simple expression will eventually end up as
  8124. just an immediate argument of an x86 instruction. Function
  8125. application will be translated to a sequence of instructions, so
  8126. \code{Apply} must be classified as complex expression.
  8127. On the other hand, the arguments of \code{Apply} should be
  8128. atomic expressions.
  8129. %
  8130. Regarding \code{FunRef}, as discussed above, the function label needs
  8131. to be converted to an address using the \code{leaq} instruction. Thus,
  8132. even though \code{FunRef} seems rather simple, it needs to be
  8133. classified as a complex expression so that we generate an assignment
  8134. statement with a left-hand side that can serve as the target of the
  8135. \code{leaq}. Figure~\ref{fig:Rfun-anf-syntax} defines the
  8136. output language \LangFunANF{} of this pass.
  8137. \begin{figure}[tp]
  8138. \centering
  8139. \fbox{
  8140. \begin{minipage}{0.96\textwidth}
  8141. \small
  8142. \[
  8143. \begin{array}{rcl}
  8144. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  8145. \mid \VOID{} } \\
  8146. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  8147. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  8148. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  8149. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  8150. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  8151. &\mid& \gray{ \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  8152. \mid \LP\key{GlobalValue}~\Var\RP }\\
  8153. &\mid& \FUNREF{\Var} \mid \APPLY{\Atm}{\Atm\ldots}\\
  8154. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  8155. R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  8156. \end{array}
  8157. \]
  8158. \end{minipage}
  8159. }
  8160. \caption{\LangFunANF{} is \LangFun{} in administrative normal form (ANF).}
  8161. \label{fig:Rfun-anf-syntax}
  8162. \end{figure}
  8163. \section{Explicate Control and the \LangCFun{} language}
  8164. \label{sec:explicate-control-r4}
  8165. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  8166. output of \key{explicate-control}. (The concrete syntax is given in
  8167. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.) The auxiliary
  8168. functions for assignment and tail contexts should be updated with
  8169. cases for \code{Apply} and \code{FunRef} and the function for
  8170. predicate context should be updated for \code{Apply} but not
  8171. \code{FunRef}. (A \code{FunRef} can't be a Boolean.) In assignment
  8172. and predicate contexts, \code{Apply} becomes \code{Call}, whereas in
  8173. tail position \code{Apply} becomes \code{TailCall}. We recommend
  8174. defining a new auxiliary function for processing function definitions.
  8175. This code is similar to the case for \code{Program} in \LangVec{}. The
  8176. top-level \code{explicate-control} function that handles the
  8177. \code{ProgramDefs} form of \LangFun{} can then apply this new function to
  8178. all the function definitions.
  8179. \begin{figure}[tp]
  8180. \fbox{
  8181. \begin{minipage}{0.96\textwidth}
  8182. \small
  8183. \[
  8184. \begin{array}{lcl}
  8185. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  8186. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  8187. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  8188. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  8189. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  8190. &\mid& \gray{ \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP } \\
  8191. &\mid& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  8192. &\mid& \gray{ \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP }\\
  8193. &\mid& \gray{ \LP\key{GlobalValue} \,\Var\RP \mid \LP\key{Void}\RP }\\
  8194. &\mid& \FUNREF{\itm{label}} \mid \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  8195. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  8196. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  8197. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  8198. \mid \GOTO{\itm{label}} } \\
  8199. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  8200. &\mid& \TAILCALL{\Atm}{\Atm\ldots} \\
  8201. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  8202. \LangCFun{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  8203. \end{array}
  8204. \]
  8205. \end{minipage}
  8206. }
  8207. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  8208. \label{fig:c3-syntax}
  8209. \end{figure}
  8210. \section{Select Instructions and the \LangXIndCall{} Language}
  8211. \label{sec:select-r4}
  8212. \index{instruction selection}
  8213. The output of select instructions is a program in the \LangXIndCall{}
  8214. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  8215. \index{x86}
  8216. \begin{figure}[tp]
  8217. \fbox{
  8218. \begin{minipage}{0.96\textwidth}
  8219. \small
  8220. \[
  8221. \begin{array}{lcl}
  8222. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)}
  8223. \mid \LP\key{fun-ref}\; \itm{label}\RP\\
  8224. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  8225. \Instr &::=& \ldots
  8226. \mid \key{callq}\;\key{*}\Arg \mid \key{tailjmp}\;\Arg
  8227. \mid \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  8228. \Block &::= & \Instr\ldots \\
  8229. \Def &::= & \LP\key{define} \; \LP\itm{label}\RP \;\LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\RP\\
  8230. \LangXIndCall{} &::= & \Def\ldots
  8231. \end{array}
  8232. \]
  8233. \end{minipage}
  8234. }
  8235. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  8236. \label{fig:x86-3-concrete}
  8237. \end{figure}
  8238. \begin{figure}[tp]
  8239. \fbox{
  8240. \begin{minipage}{0.96\textwidth}
  8241. \small
  8242. \[
  8243. \begin{array}{lcl}
  8244. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  8245. \mid \BYTEREG{\Reg} } \\
  8246. &\mid& \gray{ (\key{Global}~\Var) } \mid \FUNREF{\itm{label}} \\
  8247. \Instr &::=& \ldots \mid \INDCALLQ{\Arg}{\itm{int}}
  8248. \mid \TAILJMP{\Arg}{\itm{int}}\\
  8249. &\mid& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  8250. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  8251. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  8252. \LangXIndCall{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  8253. \end{array}
  8254. \]
  8255. \end{minipage}
  8256. }
  8257. \caption{The abstract syntax of \LangXIndCall{} (extends
  8258. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  8259. \label{fig:x86-3}
  8260. \end{figure}
  8261. An assignment of a function reference to a variable becomes a
  8262. load-effective-address instruction as follows: \\
  8263. \begin{tabular}{lcl}
  8264. \begin{minipage}{0.35\textwidth}
  8265. \begin{lstlisting}
  8266. |$\itm{lhs}$| = (fun-ref |$f$|);
  8267. \end{lstlisting}
  8268. \end{minipage}
  8269. &
  8270. $\Rightarrow$\qquad\qquad
  8271. &
  8272. \begin{minipage}{0.3\textwidth}
  8273. \begin{lstlisting}
  8274. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  8275. \end{lstlisting}
  8276. \end{minipage}
  8277. \end{tabular} \\
  8278. Regarding function definitions, we need to remove the parameters and
  8279. instead perform parameter passing using the conventions discussed in
  8280. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  8281. registers. We recommend turning the parameters into local variables
  8282. and generating instructions at the beginning of the function to move
  8283. from the argument passing registers to these local variables.
  8284. \begin{lstlisting}
  8285. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  8286. |$\Rightarrow$|
  8287. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  8288. \end{lstlisting}
  8289. The $G'$ control-flow graph is the same as $G$ except that the
  8290. \code{start} block is modified to add the instructions for moving from
  8291. the argument registers to the parameter variables. So the \code{start}
  8292. block of $G$ shown on the left is changed to the code on the right.
  8293. \begin{center}
  8294. \begin{minipage}{0.3\textwidth}
  8295. \begin{lstlisting}
  8296. start:
  8297. |$\itm{instr}_1$|
  8298. |$\vdots$|
  8299. |$\itm{instr}_n$|
  8300. \end{lstlisting}
  8301. \end{minipage}
  8302. $\Rightarrow$
  8303. \begin{minipage}{0.3\textwidth}
  8304. \begin{lstlisting}
  8305. start:
  8306. movq %rdi, |$x_1$|
  8307. movq %rsi, |$x_2$|
  8308. |$\vdots$|
  8309. |$\itm{instr}_1$|
  8310. |$\vdots$|
  8311. |$\itm{instr}_n$|
  8312. \end{lstlisting}
  8313. \end{minipage}
  8314. \end{center}
  8315. By changing the parameters to local variables, we are giving the
  8316. register allocator control over which registers or stack locations to
  8317. use for them. If you implemented the move-biasing challenge
  8318. (Section~\ref{sec:move-biasing}), the register allocator will try to
  8319. assign the parameter variables to the corresponding argument register,
  8320. in which case the \code{patch-instructions} pass will remove the
  8321. \code{movq} instruction. This happens in the example translation in
  8322. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  8323. the \code{add} function.
  8324. %
  8325. Also, note that the register allocator will perform liveness analysis
  8326. on this sequence of move instructions and build the interference
  8327. graph. So, for example, $x_1$ will be marked as interfering with
  8328. \code{rsi} and that will prevent the assignment of $x_1$ to
  8329. \code{rsi}, which is good, because that would overwrite the argument
  8330. that needs to move into $x_2$.
  8331. Next, consider the compilation of function calls. In the mirror image
  8332. of handling the parameters of function definitions, the arguments need
  8333. to be moved to the argument passing registers. The function call
  8334. itself is performed with an indirect function call. The return value
  8335. from the function is stored in \code{rax}, so it needs to be moved
  8336. into the \itm{lhs}.
  8337. \begin{lstlisting}
  8338. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  8339. |$\Rightarrow$|
  8340. movq |$\itm{arg}_1$|, %rdi
  8341. movq |$\itm{arg}_2$|, %rsi
  8342. |$\vdots$|
  8343. callq *|\itm{fun}|
  8344. movq %rax, |\itm{lhs}|
  8345. \end{lstlisting}
  8346. The \code{IndirectCallq} AST node includes an integer for the arity of
  8347. the function, i.e., the number of parameters. That information is
  8348. useful in the \code{uncover-live} pass for determining which
  8349. argument-passing registers are potentially read during the call.
  8350. For tail calls, the parameter passing is the same as non-tail calls:
  8351. generate instructions to move the arguments into to the argument
  8352. passing registers. After that we need to pop the frame from the
  8353. procedure call stack. However, we do not yet know how big the frame
  8354. is; that gets determined during register allocation. So instead of
  8355. generating those instructions here, we invent a new instruction that
  8356. means ``pop the frame and then do an indirect jump'', which we name
  8357. \code{TailJmp}. The abstract syntax for this instruction includes an
  8358. argument that specifies where to jump and an integer that represents
  8359. the arity of the function being called.
  8360. Recall that in Section~\ref{sec:explicate-control-Rvar} we recommended
  8361. using the label \code{start} for the initial block of a program, and
  8362. in Section~\ref{sec:select-Rvar} we recommended labeling the conclusion
  8363. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  8364. can be compiled to an assignment to \code{rax} followed by a jump to
  8365. \code{conclusion}. With the addition of function definitions, we will
  8366. have a starting block and conclusion for each function, but their
  8367. labels need to be unique. We recommend prepending the function's name
  8368. to \code{start} and \code{conclusion}, respectively, to obtain unique
  8369. labels. (Alternatively, one could \code{gensym} labels for the start
  8370. and conclusion and store them in the $\itm{info}$ field of the
  8371. function definition.)
  8372. \section{Register Allocation}
  8373. \label{sec:register-allocation-r4}
  8374. \subsection{Liveness Analysis}
  8375. \label{sec:liveness-analysis-r4}
  8376. \index{liveness analysis}
  8377. %% The rest of the passes need only minor modifications to handle the new
  8378. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  8379. %% \code{leaq}.
  8380. The \code{IndirectCallq} instruction should be treated like
  8381. \code{Callq} regarding its written locations $W$, in that they should
  8382. include all the caller-saved registers. Recall that the reason for
  8383. that is to force call-live variables to be assigned to callee-saved
  8384. registers or to be spilled to the stack.
  8385. Regarding the set of read locations $R$ the arity field of
  8386. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  8387. argument-passing registers should be considered as read by those
  8388. instructions.
  8389. \subsection{Build Interference Graph}
  8390. \label{sec:build-interference-r4}
  8391. With the addition of function definitions, we compute an interference
  8392. graph for each function (not just one for the whole program).
  8393. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  8394. spill vector-typed variables that are live during a call to the
  8395. \code{collect}. With the addition of functions to our language, we
  8396. need to revisit this issue. Many functions perform allocation and
  8397. therefore have calls to the collector inside of them. Thus, we should
  8398. not only spill a vector-typed variable when it is live during a call
  8399. to \code{collect}, but we should spill the variable if it is live
  8400. during any function call. Thus, in the \code{build-interference} pass,
  8401. we recommend adding interference edges between call-live vector-typed
  8402. variables and the callee-saved registers (in addition to the usual
  8403. addition of edges between call-live variables and the caller-saved
  8404. registers).
  8405. \subsection{Allocate Registers}
  8406. The primary change to the \code{allocate-registers} pass is adding an
  8407. auxiliary function for handling definitions (the \Def{} non-terminal
  8408. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  8409. logic is the same as described in
  8410. Chapter~\ref{ch:register-allocation-Rvar}, except now register
  8411. allocation is performed many times, once for each function definition,
  8412. instead of just once for the whole program.
  8413. \section{Patch Instructions}
  8414. In \code{patch-instructions}, you should deal with the x86
  8415. idiosyncrasy that the destination argument of \code{leaq} must be a
  8416. register. Additionally, you should ensure that the argument of
  8417. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  8418. code generation more convenient, because we trample many registers
  8419. before the tail call (as explained in the next section).
  8420. \section{Print x86}
  8421. For the \code{print-x86} pass, the cases for \code{FunRef} and
  8422. \code{IndirectCallq} are straightforward: output their concrete
  8423. syntax.
  8424. \begin{lstlisting}
  8425. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  8426. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  8427. \end{lstlisting}
  8428. The \code{TailJmp} node requires a bit work. A straightforward
  8429. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  8430. before the jump we need to pop the current frame. This sequence of
  8431. instructions is the same as the code for the conclusion of a function,
  8432. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  8433. Regarding function definitions, you will need to generate a prelude
  8434. and conclusion for each one. This code is similar to the prelude and
  8435. conclusion that you generated for the \code{main} function in
  8436. Chapter~\ref{ch:Rvec}. To review, the prelude of every function
  8437. should carry out the following steps.
  8438. \begin{enumerate}
  8439. \item Start with \code{.global} and \code{.align} directives followed
  8440. by the label for the function. (See Figure~\ref{fig:add-fun} for an
  8441. example.)
  8442. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  8443. pointer.
  8444. \item Push to the stack all of the callee-saved registers that were
  8445. used for register allocation.
  8446. \item Move the stack pointer \code{rsp} down by the size of the stack
  8447. frame for this function, which depends on the number of regular
  8448. spills. (Aligned to 16 bytes.)
  8449. \item Move the root stack pointer \code{r15} up by the size of the
  8450. root-stack frame for this function, which depends on the number of
  8451. spilled vectors. \label{root-stack-init}
  8452. \item Initialize to zero all of the entries in the root-stack frame.
  8453. \item Jump to the start block.
  8454. \end{enumerate}
  8455. The prelude of the \code{main} function has one additional task: call
  8456. the \code{initialize} function to set up the garbage collector and
  8457. move the value of the global \code{rootstack\_begin} in
  8458. \code{r15}. This should happen before step \ref{root-stack-init}
  8459. above, which depends on \code{r15}.
  8460. The conclusion of every function should do the following.
  8461. \begin{enumerate}
  8462. \item Move the stack pointer back up by the size of the stack frame
  8463. for this function.
  8464. \item Restore the callee-saved registers by popping them from the
  8465. stack.
  8466. \item Move the root stack pointer back down by the size of the
  8467. root-stack frame for this function.
  8468. \item Restore \code{rbp} by popping it from the stack.
  8469. \item Return to the caller with the \code{retq} instruction.
  8470. \end{enumerate}
  8471. \begin{exercise}\normalfont
  8472. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  8473. Create 5 new programs that use functions, including examples that pass
  8474. functions and return functions from other functions, recursive
  8475. functions, functions that create vectors, and functions that make tail
  8476. calls. Test your compiler on these new programs and all of your
  8477. previously created test programs.
  8478. \end{exercise}
  8479. \begin{figure}[tbp]
  8480. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8481. \node (Rfun) at (0,2) {\large \LangFun{}};
  8482. \node (Rfun-1) at (3,2) {\large \LangFun{}};
  8483. \node (Rfun-2) at (6,2) {\large \LangFun{}};
  8484. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  8485. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  8486. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  8487. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  8488. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  8489. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  8490. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  8491. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  8492. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  8493. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  8494. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  8495. \path[->,bend left=15] (Rfun) edge [above] node
  8496. {\ttfamily\footnotesize shrink} (Rfun-1);
  8497. \path[->,bend left=15] (Rfun-1) edge [above] node
  8498. {\ttfamily\footnotesize uniquify} (Rfun-2);
  8499. \path[->,bend left=15] (Rfun-2) edge [right] node
  8500. {\ttfamily\footnotesize ~~reveal-functions} (F1-1);
  8501. \path[->,bend left=15] (F1-1) edge [below] node
  8502. {\ttfamily\footnotesize limit-functions} (F1-2);
  8503. \path[->,bend right=15] (F1-2) edge [above] node
  8504. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  8505. \path[->,bend right=15] (F1-3) edge [above] node
  8506. {\ttfamily\footnotesize remove-complex.} (F1-4);
  8507. \path[->,bend left=15] (F1-4) edge [right] node
  8508. {\ttfamily\footnotesize explicate-control} (C3-2);
  8509. \path[->,bend right=15] (C3-2) edge [left] node
  8510. {\ttfamily\footnotesize select-instr.} (x86-2);
  8511. \path[->,bend left=15] (x86-2) edge [left] node
  8512. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  8513. \path[->,bend right=15] (x86-2-1) edge [below] node
  8514. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  8515. \path[->,bend right=15] (x86-2-2) edge [left] node
  8516. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  8517. \path[->,bend left=15] (x86-3) edge [above] node
  8518. {\ttfamily\footnotesize patch-instr.} (x86-4);
  8519. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  8520. \end{tikzpicture}
  8521. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  8522. \label{fig:Rfun-passes}
  8523. \end{figure}
  8524. Figure~\ref{fig:Rfun-passes} gives an overview of the passes for
  8525. compiling \LangFun{} to x86.
  8526. \section{An Example Translation}
  8527. \label{sec:functions-example}
  8528. Figure~\ref{fig:add-fun} shows an example translation of a simple
  8529. function in \LangFun{} to x86. The figure also includes the results of the
  8530. \code{explicate-control} and \code{select-instructions} passes.
  8531. \begin{figure}[htbp]
  8532. \begin{tabular}{ll}
  8533. \begin{minipage}{0.5\textwidth}
  8534. % s3_2.rkt
  8535. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  8536. (define (add [x : Integer] [y : Integer])
  8537. : Integer
  8538. (+ x y))
  8539. (add 40 2)
  8540. \end{lstlisting}
  8541. $\Downarrow$
  8542. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  8543. (define (add86 [x87 : Integer]
  8544. [y88 : Integer]) : Integer
  8545. add86start:
  8546. return (+ x87 y88);
  8547. )
  8548. (define (main) : Integer ()
  8549. mainstart:
  8550. tmp89 = (fun-ref add86);
  8551. (tail-call tmp89 40 2)
  8552. )
  8553. \end{lstlisting}
  8554. \end{minipage}
  8555. &
  8556. $\Rightarrow$
  8557. \begin{minipage}{0.5\textwidth}
  8558. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  8559. (define (add86) : Integer
  8560. add86start:
  8561. movq %rdi, x87
  8562. movq %rsi, y88
  8563. movq x87, %rax
  8564. addq y88, %rax
  8565. jmp add11389conclusion
  8566. )
  8567. (define (main) : Integer
  8568. mainstart:
  8569. leaq (fun-ref add86), tmp89
  8570. movq $40, %rdi
  8571. movq $2, %rsi
  8572. tail-jmp tmp89
  8573. )
  8574. \end{lstlisting}
  8575. $\Downarrow$
  8576. \end{minipage}
  8577. \end{tabular}
  8578. \begin{tabular}{ll}
  8579. \begin{minipage}{0.3\textwidth}
  8580. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  8581. .globl add86
  8582. .align 16
  8583. add86:
  8584. pushq %rbp
  8585. movq %rsp, %rbp
  8586. jmp add86start
  8587. add86start:
  8588. movq %rdi, %rax
  8589. addq %rsi, %rax
  8590. jmp add86conclusion
  8591. add86conclusion:
  8592. popq %rbp
  8593. retq
  8594. \end{lstlisting}
  8595. \end{minipage}
  8596. &
  8597. \begin{minipage}{0.5\textwidth}
  8598. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  8599. .globl main
  8600. .align 16
  8601. main:
  8602. pushq %rbp
  8603. movq %rsp, %rbp
  8604. movq $16384, %rdi
  8605. movq $16384, %rsi
  8606. callq initialize
  8607. movq rootstack_begin(%rip), %r15
  8608. jmp mainstart
  8609. mainstart:
  8610. leaq add86(%rip), %rcx
  8611. movq $40, %rdi
  8612. movq $2, %rsi
  8613. movq %rcx, %rax
  8614. popq %rbp
  8615. jmp *%rax
  8616. mainconclusion:
  8617. popq %rbp
  8618. retq
  8619. \end{lstlisting}
  8620. \end{minipage}
  8621. \end{tabular}
  8622. \caption{Example compilation of a simple function to x86.}
  8623. \label{fig:add-fun}
  8624. \end{figure}
  8625. % Challenge idea: inlining! (simple version)
  8626. % Further Reading
  8627. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8628. \chapter{Lexically Scoped Functions}
  8629. \label{ch:Rlam}
  8630. \index{lambda}
  8631. \index{lexical scoping}
  8632. This chapter studies lexically scoped functions as they appear in
  8633. functional languages such as Racket. By lexical scoping we mean that a
  8634. function's body may refer to variables whose binding site is outside
  8635. of the function, in an enclosing scope.
  8636. %
  8637. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  8638. \LangLam{}, which extends \LangFun{} with anonymous functions using the
  8639. \key{lambda} form. The body of the \key{lambda}, refers to three
  8640. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  8641. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  8642. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  8643. parameter of function \code{f}. The \key{lambda} is returned from the
  8644. function \code{f}. The main expression of the program includes two
  8645. calls to \code{f} with different arguments for \code{x}, first
  8646. \code{5} then \code{3}. The functions returned from \code{f} are bound
  8647. to variables \code{g} and \code{h}. Even though these two functions
  8648. were created by the same \code{lambda}, they are really different
  8649. functions because they use different values for \code{x}. Applying
  8650. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  8651. \code{15} produces \code{22}. The result of this program is \code{42}.
  8652. \begin{figure}[btp]
  8653. % s4_6.rkt
  8654. \begin{lstlisting}
  8655. (define (f [x : Integer]) : (Integer -> Integer)
  8656. (let ([y 4])
  8657. (lambda: ([z : Integer]) : Integer
  8658. (+ x (+ y z)))))
  8659. (let ([g (f 5)])
  8660. (let ([h (f 3)])
  8661. (+ (g 11) (h 15))))
  8662. \end{lstlisting}
  8663. \caption{Example of a lexically scoped function.}
  8664. \label{fig:lexical-scoping}
  8665. \end{figure}
  8666. The approach that we take for implementing lexically scoped
  8667. functions is to compile them into top-level function definitions,
  8668. translating from \LangLam{} into \LangFun{}. However, the compiler will need to
  8669. provide special treatment for variable occurrences such as \code{x}
  8670. and \code{y} in the body of the \code{lambda} of
  8671. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function may not
  8672. refer to variables defined outside of it. To identify such variable
  8673. occurrences, we review the standard notion of free variable.
  8674. \begin{definition}
  8675. A variable is \emph{free in expression} $e$ if the variable occurs
  8676. inside $e$ but does not have an enclosing binding in $e$.\index{free
  8677. variable}
  8678. \end{definition}
  8679. For example, in the expression \code{(+ x (+ y z))} the variables
  8680. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  8681. only \code{x} and \code{y} are free in the following expression
  8682. because \code{z} is bound by the \code{lambda}.
  8683. \begin{lstlisting}
  8684. (lambda: ([z : Integer]) : Integer
  8685. (+ x (+ y z)))
  8686. \end{lstlisting}
  8687. So the free variables of a \code{lambda} are the ones that will need
  8688. special treatment. We need to arrange for some way to transport, at
  8689. runtime, the values of those variables from the point where the
  8690. \code{lambda} was created to the point where the \code{lambda} is
  8691. applied. An efficient solution to the problem, due to
  8692. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  8693. free variables together with the function pointer for the lambda's
  8694. code, an arrangement called a \emph{flat closure} (which we shorten to
  8695. just ``closure''). \index{closure}\index{flat closure} Fortunately,
  8696. we have all the ingredients to make closures, Chapter~\ref{ch:Rvec}
  8697. gave us vectors and Chapter~\ref{ch:Rfun} gave us function
  8698. pointers. The function pointer resides at index $0$ and the
  8699. values for the free variables will fill in the rest of the vector.
  8700. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  8701. how closures work. It's a three-step dance. The program first calls
  8702. function \code{f}, which creates a closure for the \code{lambda}. The
  8703. closure is a vector whose first element is a pointer to the top-level
  8704. function that we will generate for the \code{lambda}, the second
  8705. element is the value of \code{x}, which is \code{5}, and the third
  8706. element is \code{4}, the value of \code{y}. The closure does not
  8707. contain an element for \code{z} because \code{z} is not a free
  8708. variable of the \code{lambda}. Creating the closure is step 1 of the
  8709. dance. The closure is returned from \code{f} and bound to \code{g}, as
  8710. shown in Figure~\ref{fig:closures}.
  8711. %
  8712. The second call to \code{f} creates another closure, this time with
  8713. \code{3} in the second slot (for \code{x}). This closure is also
  8714. returned from \code{f} but bound to \code{h}, which is also shown in
  8715. Figure~\ref{fig:closures}.
  8716. \begin{figure}[tbp]
  8717. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  8718. \caption{Example closure representation for the \key{lambda}'s
  8719. in Figure~\ref{fig:lexical-scoping}.}
  8720. \label{fig:closures}
  8721. \end{figure}
  8722. Continuing with the example, consider the application of \code{g} to
  8723. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  8724. obtain the function pointer in the first element of the closure and
  8725. call it, passing in the closure itself and then the regular arguments,
  8726. in this case \code{11}. This technique for applying a closure is step
  8727. 2 of the dance.
  8728. %
  8729. But doesn't this \code{lambda} only take 1 argument, for parameter
  8730. \code{z}? The third and final step of the dance is generating a
  8731. top-level function for a \code{lambda}. We add an additional
  8732. parameter for the closure and we insert a \code{let} at the beginning
  8733. of the function for each free variable, to bind those variables to the
  8734. appropriate elements from the closure parameter.
  8735. %
  8736. This three-step dance is known as \emph{closure conversion}. We
  8737. discuss the details of closure conversion in
  8738. Section~\ref{sec:closure-conversion} and the code generated from the
  8739. example in Section~\ref{sec:example-lambda}. But first we define the
  8740. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  8741. \section{The \LangLam{} Language}
  8742. \label{sec:r5}
  8743. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  8744. functions and lexical scoping, is defined in
  8745. Figures~\ref{fig:Rlam-concrete-syntax} and ~\ref{fig:Rlam-syntax}. It adds
  8746. the \key{lambda} form to the grammar for \LangFun{}, which already has
  8747. syntax for function application.
  8748. \begin{figure}[tp]
  8749. \centering
  8750. \fbox{
  8751. \begin{minipage}{0.96\textwidth}
  8752. \small
  8753. \[
  8754. \begin{array}{lcl}
  8755. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  8756. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}
  8757. \mid (\Type\ldots \; \key{->}\; \Type)} \\
  8758. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  8759. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  8760. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  8761. &\mid& \gray{\key{\#t} \mid \key{\#f}
  8762. \mid (\key{and}\;\Exp\;\Exp)
  8763. \mid (\key{or}\;\Exp\;\Exp)
  8764. \mid (\key{not}\;\Exp) } \\
  8765. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  8766. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  8767. (\key{vector-ref}\;\Exp\;\Int)} \\
  8768. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  8769. \mid (\Exp \; \Exp\ldots) } \\
  8770. &\mid& \LP \key{procedure-arity}~\Exp\RP \\
  8771. &\mid& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  8772. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  8773. \LangLam{} &::=& \gray{\Def\ldots \; \Exp}
  8774. \end{array}
  8775. \]
  8776. \end{minipage}
  8777. }
  8778. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-concrete-syntax})
  8779. with \key{lambda}.}
  8780. \label{fig:Rlam-concrete-syntax}
  8781. \end{figure}
  8782. \begin{figure}[tp]
  8783. \centering
  8784. \fbox{
  8785. \begin{minipage}{0.96\textwidth}
  8786. \small
  8787. \[
  8788. \begin{array}{lcl}
  8789. \itm{op} &::=& \ldots \mid \code{procedure-arity} \\
  8790. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  8791. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  8792. &\mid& \gray{ \BOOL{\itm{bool}}
  8793. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  8794. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  8795. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  8796. &\mid& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  8797. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  8798. \LangLam{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  8799. \end{array}
  8800. \]
  8801. \end{minipage}
  8802. }
  8803. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-syntax}).}
  8804. \label{fig:Rlam-syntax}
  8805. \end{figure}
  8806. \index{interpreter}
  8807. \label{sec:interp-Rlambda}
  8808. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  8809. \LangLam{}. The case for \key{lambda} saves the current environment
  8810. inside the returned \key{lambda}. Then the case for \key{Apply} uses
  8811. the environment from the \key{lambda}, the \code{lam-env}, when
  8812. interpreting the body of the \key{lambda}. The \code{lam-env}
  8813. environment is extended with the mapping of parameters to argument
  8814. values.
  8815. \begin{figure}[tbp]
  8816. \begin{lstlisting}
  8817. (define interp-Rlambda-class
  8818. (class interp-Rfun-class
  8819. (super-new)
  8820. (define/override (interp-op op)
  8821. (match op
  8822. ['procedure-arity
  8823. (lambda (v)
  8824. (match v
  8825. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  8826. [else (error 'interp-op "expected a function, not ~a" v)]))]
  8827. [else (super interp-op op)]))
  8828. (define/override ((interp-exp env) e)
  8829. (define recur (interp-exp env))
  8830. (match e
  8831. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  8832. `(function ,xs ,body ,env)]
  8833. [else ((super interp-exp env) e)]))
  8834. ))
  8835. (define (interp-Rlambda p)
  8836. (send (new interp-Rlambda-class) interp-program p))
  8837. \end{lstlisting}
  8838. \caption{Interpreter for \LangLam{}.}
  8839. \label{fig:interp-Rlambda}
  8840. \end{figure}
  8841. \label{sec:type-check-r5}
  8842. \index{type checking}
  8843. Figure~\ref{fig:type-check-Rlambda} shows how to type check the new
  8844. \key{lambda} form. The body of the \key{lambda} is checked in an
  8845. environment that includes the current environment (because it is
  8846. lexically scoped) and also includes the \key{lambda}'s parameters. We
  8847. require the body's type to match the declared return type.
  8848. \begin{figure}[tbp]
  8849. \begin{lstlisting}
  8850. (define (type-check-Rlambda env)
  8851. (lambda (e)
  8852. (match e
  8853. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  8854. (define-values (new-body bodyT)
  8855. ((type-check-exp (append (map cons xs Ts) env)) body))
  8856. (define ty `(,@Ts -> ,rT))
  8857. (cond
  8858. [(equal? rT bodyT)
  8859. (values (HasType (Lambda params rT new-body) ty) ty)]
  8860. [else
  8861. (error "mismatch in return type" bodyT rT)])]
  8862. ...
  8863. )))
  8864. \end{lstlisting}
  8865. \caption{Type checking the \key{lambda}'s in \LangLam{}.}
  8866. \label{fig:type-check-Rlambda}
  8867. \end{figure}
  8868. \section{Reveal Functions and the $F_2$ language}
  8869. \label{sec:reveal-functions-r5}
  8870. To support the \code{procedure-arity} operator we need to communicate
  8871. the arity of a function to the point of closure creation. We can
  8872. accomplish this by replacing the $\FUNREF{\Var}$ struct with one that
  8873. has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$. The
  8874. output of this pass is the language $F_2$, whose syntax is defined in
  8875. Figure~\ref{fig:f2-syntax}.
  8876. \begin{figure}[tp]
  8877. \centering
  8878. \fbox{
  8879. \begin{minipage}{0.96\textwidth}
  8880. \[
  8881. \begin{array}{lcl}
  8882. \Exp &::=& \ldots \mid \FUNREFARITY{\Var}{\Int}\\
  8883. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  8884. F_2 &::=& \gray{\PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}}
  8885. \end{array}
  8886. \]
  8887. \end{minipage}
  8888. }
  8889. \caption{The abstract syntax $F_2$, an extension of \LangLam{}
  8890. (Figure~\ref{fig:Rlam-syntax}).}
  8891. \label{fig:f2-syntax}
  8892. \end{figure}
  8893. \section{Closure Conversion}
  8894. \label{sec:closure-conversion}
  8895. \index{closure conversion}
  8896. The compiling of lexically-scoped functions into top-level function
  8897. definitions is accomplished in the pass \code{convert-to-closures}
  8898. that comes after \code{reveal-functions} and before
  8899. \code{limit-functions}.
  8900. As usual, we implement the pass as a recursive function over the
  8901. AST. All of the action is in the cases for \key{Lambda} and
  8902. \key{Apply}. We transform a \key{Lambda} expression into an expression
  8903. that creates a closure, that is, a vector whose first element is a
  8904. function pointer and the rest of the elements are the free variables
  8905. of the \key{Lambda}. We use the struct \code{Closure} here instead of
  8906. using \code{vector} so that we can distinguish closures from vectors
  8907. in Section~\ref{sec:optimize-closures} and to record the arity. In
  8908. the generated code below, the \itm{name} is a unique symbol generated
  8909. to identify the function and the \itm{arity} is the number of
  8910. parameters (the length of \itm{ps}).
  8911. \begin{lstlisting}
  8912. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  8913. |$\Rightarrow$|
  8914. (Closure |\itm{arity}| (cons (FunRef |\itm{name}|) |\itm{fvs}|))
  8915. \end{lstlisting}
  8916. In addition to transforming each \key{Lambda} into a \key{Closure}, we
  8917. create a top-level function definition for each \key{Lambda}, as
  8918. shown below.\\
  8919. \begin{minipage}{0.8\textwidth}
  8920. \begin{lstlisting}
  8921. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  8922. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  8923. ...
  8924. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  8925. |\itm{body'}|)...))
  8926. \end{lstlisting}
  8927. \end{minipage}\\
  8928. The \code{clos} parameter refers to the closure. Translate the type
  8929. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  8930. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The types
  8931. $\itm{fvts}$ are the types of the free variables in the lambda and the
  8932. underscore \code{\_} is a dummy type that we use because it is rather
  8933. difficult to give a type to the function in the closure's
  8934. type.\footnote{To give an accurate type to a closure, we would need to
  8935. add existential types to the type checker~\citep{Minamide:1996ys}.}
  8936. The dummy type is considered to be equal to any other type during type
  8937. checking. The sequence of \key{Let} forms bind the free variables to
  8938. their values obtained from the closure.
  8939. Closure conversion turns functions into vectors, so the type
  8940. annotations in the program must also be translated. We recommend
  8941. defining a auxiliary recursive function for this purpose. Function
  8942. types should be translated as follows.
  8943. \begin{lstlisting}
  8944. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  8945. |$\Rightarrow$|
  8946. (Vector ((Vector _) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  8947. \end{lstlisting}
  8948. The above type says that the first thing in the vector is a function
  8949. pointer. The first parameter of the function pointer is a vector (a
  8950. closure) and the rest of the parameters are the ones from the original
  8951. function, with types $T'_1, \ldots, T'_n$. The \code{Vector} type for
  8952. the closure omits the types of the free variables because 1) those
  8953. types are not available in this context and 2) we do not need them in
  8954. the code that is generated for function application.
  8955. We transform function application into code that retrieves the
  8956. function pointer from the closure and then calls the function, passing
  8957. in the closure as the first argument. We bind $e'$ to a temporary
  8958. variable to avoid code duplication.
  8959. \begin{lstlisting}
  8960. (Apply |$e$| |\itm{es}|)
  8961. |$\Rightarrow$|
  8962. (Let |\itm{tmp}| |$e'$|
  8963. (Apply (Prim 'vector-ref (list (Var |\itm{tmp}|) (Int 0))) (cons |\itm{tmp}| |\itm{es'}|)))
  8964. \end{lstlisting}
  8965. There is also the question of what to do with references top-level
  8966. function definitions. To maintain a uniform translation of function
  8967. application, we turn function references into closures.
  8968. \begin{tabular}{lll}
  8969. \begin{minipage}{0.3\textwidth}
  8970. \begin{lstlisting}
  8971. (FunRefArity |$f$| |$n$|)
  8972. \end{lstlisting}
  8973. \end{minipage}
  8974. &
  8975. $\Rightarrow$
  8976. &
  8977. \begin{minipage}{0.5\textwidth}
  8978. \begin{lstlisting}
  8979. (Closure |$n$| (FunRef |$f$|) '())
  8980. \end{lstlisting}
  8981. \end{minipage}
  8982. \end{tabular} \\
  8983. %
  8984. The top-level function definitions need to be updated as well to take
  8985. an extra closure parameter.
  8986. \section{An Example Translation}
  8987. \label{sec:example-lambda}
  8988. Figure~\ref{fig:lexical-functions-example} shows the result of
  8989. \code{reveal-functions} and \code{convert-to-closures} for the example
  8990. program demonstrating lexical scoping that we discussed at the
  8991. beginning of this chapter.
  8992. \begin{figure}[tbp]
  8993. \begin{minipage}{0.8\textwidth}
  8994. % tests/lambda_test_6.rkt
  8995. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8996. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  8997. (let ([y8 4])
  8998. (lambda: ([z9 : Integer]) : Integer
  8999. (+ x7 (+ y8 z9)))))
  9000. (define (main) : Integer
  9001. (let ([g0 ((fun-ref-arity f6 1) 5)])
  9002. (let ([h1 ((fun-ref-arity f6 1) 3)])
  9003. (+ (g0 11) (h1 15)))))
  9004. \end{lstlisting}
  9005. $\Rightarrow$
  9006. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9007. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  9008. (let ([y8 4])
  9009. (closure 1 (list (fun-ref lambda2) x7 y8))))
  9010. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  9011. (let ([x7 (vector-ref fvs3 1)])
  9012. (let ([y8 (vector-ref fvs3 2)])
  9013. (+ x7 (+ y8 z9)))))
  9014. (define (main) : Integer
  9015. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6)))])
  9016. ((vector-ref clos5 0) clos5 5))])
  9017. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6)))])
  9018. ((vector-ref clos6 0) clos6 3))])
  9019. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  9020. \end{lstlisting}
  9021. \end{minipage}
  9022. \caption{Example of closure conversion.}
  9023. \label{fig:lexical-functions-example}
  9024. \end{figure}
  9025. \begin{exercise}\normalfont
  9026. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  9027. Create 5 new programs that use \key{lambda} functions and make use of
  9028. lexical scoping. Test your compiler on these new programs and all of
  9029. your previously created test programs.
  9030. \end{exercise}
  9031. \section{Expose Allocation}
  9032. \label{sec:expose-allocation-r5}
  9033. Compile the $\CLOSURE{\itm{arity}}{\LP\Exp\ldots\RP}$ form into code
  9034. that allocates and initializes a vector, similar to the translation of
  9035. the \code{vector} operator in Section~\ref{sec:expose-allocation}.
  9036. The only difference is replacing the use of
  9037. \ALLOC{\itm{len}}{\itm{type}} with
  9038. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  9039. \section{Explicate Control and \LangCLam{}}
  9040. \label{sec:explicate-r5}
  9041. The output language of \code{explicate-control} is \LangCLam{} whose
  9042. abstract syntax is defined in Figure~\ref{fig:c4-syntax}. The only
  9043. difference with respect to \LangCFun{} is the addition of the
  9044. \code{AllocateClosure} form to the grammar for $\Exp$. The handling
  9045. of \code{AllocateClosure} in the \code{explicate-control} pass is
  9046. similar to the handling of other expressions such as primitive
  9047. operators.
  9048. \begin{figure}[tp]
  9049. \fbox{
  9050. \begin{minipage}{0.96\textwidth}
  9051. \small
  9052. \[
  9053. \begin{array}{lcl}
  9054. \Exp &::= & \ldots
  9055. \mid \ALLOCCLOS{\Int}{\Type}{\Int} \\
  9056. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  9057. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  9058. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  9059. \mid \GOTO{\itm{label}} } \\
  9060. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  9061. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  9062. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  9063. \LangCLam{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  9064. \end{array}
  9065. \]
  9066. \end{minipage}
  9067. }
  9068. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  9069. \label{fig:c4-syntax}
  9070. \end{figure}
  9071. \section{Select Instructions}
  9072. \label{sec:select-instructions-Rlambda}
  9073. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  9074. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  9075. (Section~\ref{sec:select-instructions-gc}). The only difference is
  9076. that you should place the \itm{arity} in the tag that is stored at
  9077. position $0$ of the vector. Recall that in
  9078. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  9079. was not used. We store the arity in the $5$ bits starting at position
  9080. $58$.
  9081. Compile the \code{procedure-arity} operator into a sequence of
  9082. instructions that access the tag from position $0$ of the vector and
  9083. extract the $5$-bits starting at position $58$ from the tag.
  9084. \begin{figure}[p]
  9085. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9086. \node (Rfun) at (0,2) {\large \LangFun{}};
  9087. \node (Rfun-2) at (3,2) {\large \LangFun{}};
  9088. \node (Rfun-3) at (6,2) {\large \LangFun{}};
  9089. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  9090. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  9091. \node (F1-3) at (6,0) {\large $F_1$};
  9092. \node (F1-4) at (3,0) {\large $F_1$};
  9093. \node (F1-5) at (0,0) {\large $F_1$};
  9094. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  9095. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  9096. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  9097. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  9098. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  9099. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  9100. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  9101. \path[->,bend left=15] (Rfun) edge [above] node
  9102. {\ttfamily\footnotesize shrink} (Rfun-2);
  9103. \path[->,bend left=15] (Rfun-2) edge [above] node
  9104. {\ttfamily\footnotesize uniquify} (Rfun-3);
  9105. \path[->,bend left=15] (Rfun-3) edge [right] node
  9106. {\ttfamily\footnotesize reveal-functions} (F1-1);
  9107. \path[->,bend left=15] (F1-1) edge [below] node
  9108. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  9109. \path[->,bend right=15] (F1-2) edge [above] node
  9110. {\ttfamily\footnotesize limit-fun.} (F1-3);
  9111. \path[->,bend right=15] (F1-3) edge [above] node
  9112. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9113. \path[->,bend right=15] (F1-4) edge [above] node
  9114. {\ttfamily\footnotesize remove-complex.} (F1-5);
  9115. \path[->,bend right=15] (F1-5) edge [right] node
  9116. {\ttfamily\footnotesize explicate-control} (C3-2);
  9117. \path[->,bend left=15] (C3-2) edge [left] node
  9118. {\ttfamily\footnotesize select-instr.} (x86-2);
  9119. \path[->,bend right=15] (x86-2) edge [left] node
  9120. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  9121. \path[->,bend right=15] (x86-2-1) edge [below] node
  9122. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  9123. \path[->,bend right=15] (x86-2-2) edge [left] node
  9124. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  9125. \path[->,bend left=15] (x86-3) edge [above] node
  9126. {\ttfamily\footnotesize patch-instr.} (x86-4);
  9127. \path[->,bend left=15] (x86-4) edge [right] node
  9128. {\ttfamily\footnotesize print-x86} (x86-5);
  9129. \end{tikzpicture}
  9130. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  9131. functions.}
  9132. \label{fig:Rlambda-passes}
  9133. \end{figure}
  9134. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  9135. for the compilation of \LangLam{}.
  9136. \clearpage
  9137. \section{Challenge: Optimize Closures}
  9138. \label{sec:optimize-closures}
  9139. In this chapter we compiled lexically-scoped functions into a
  9140. relatively efficient representation: flat closures. However, even this
  9141. representation comes with some overhead. For example, consider the
  9142. following program with a function \code{tail-sum} that does not have
  9143. any free variables and where all the uses of \code{tail-sum} are in
  9144. applications where we know that only \code{tail-sum} is being applied
  9145. (and not any other functions).
  9146. \begin{center}
  9147. \begin{minipage}{0.95\textwidth}
  9148. \begin{lstlisting}
  9149. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  9150. (if (eq? n 0)
  9151. r
  9152. (tail-sum (- n 1) (+ n r))))
  9153. (+ (tail-sum 5 0) 27)
  9154. \end{lstlisting}
  9155. \end{minipage}
  9156. \end{center}
  9157. As described in this chapter, we uniformly apply closure conversion to
  9158. all functions, obtaining the following output for this program.
  9159. \begin{center}
  9160. \begin{minipage}{0.95\textwidth}
  9161. \begin{lstlisting}
  9162. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [r3 : Integer]) : Integer
  9163. (if (eq? n2 0)
  9164. r3
  9165. (let ([clos4 (closure (list (fun-ref tail_sum1)))])
  9166. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 r3)))))
  9167. (define (main) : Integer
  9168. (+ (let ([clos6 (closure (list (fun-ref tail_sum1)))])
  9169. ((vector-ref clos6 0) clos6 5 0)) 27))
  9170. \end{lstlisting}
  9171. \end{minipage}
  9172. \end{center}
  9173. In the previous Chapter, there would be no allocation in the program
  9174. and the calls to \code{tail-sum} would be direct calls. In contrast,
  9175. the above program allocates memory for each \code{closure} and the
  9176. calls to \code{tail-sum} are indirect. These two differences incur
  9177. considerable overhead in a program such as this one, where the
  9178. allocations and indirect calls occur inside a tight loop.
  9179. One might think that this problem is trivial to solve: can't we just
  9180. recognize calls of the form \code{((fun-ref $f$) $e_1 \ldots e_n$)}
  9181. and compile them to direct calls \code{((fun-ref $f$) $e'_1 \ldots
  9182. e'_n$)} instead of treating it like a call to a closure? We would
  9183. also drop the \code{fvs5} parameter of \code{tail\_sum1}.
  9184. %
  9185. However, this problem is not so trivial because a global function may
  9186. ``escape'' and become involved in applications that also involve
  9187. closures. Consider the following example in which the application
  9188. \code{(f 41)} needs to be compiled into a closure application, because
  9189. the \code{lambda} may get bound to \code{f}, but the \code{add1}
  9190. function might also get bound to \code{f}.
  9191. \begin{lstlisting}
  9192. (define (add1 [x : Integer]) : Integer
  9193. (+ x 1))
  9194. (let ([y (read)])
  9195. (let ([f (if (eq? (read) 0)
  9196. add1
  9197. (lambda: ([x : Integer]) : Integer (- x y)))])
  9198. (f 41)))
  9199. \end{lstlisting}
  9200. If a global function name is used in any way other than as the
  9201. operator in a direct call, then we say that the function
  9202. \emph{escapes}. If a global function does not escape, then we do not
  9203. need to perform closure conversion on the function.
  9204. \begin{exercise}\normalfont
  9205. Implement an auxiliary function for detecting which global
  9206. functions escape. Using that function, implement an improved version
  9207. of closure conversion that does not apply closure conversion to
  9208. global functions that do not escape but instead compiles them as
  9209. regular functions. Create several new test cases that check whether
  9210. you properly detect whether global functions escape or not.
  9211. \end{exercise}
  9212. So far we have reduced the overhead of calling global functions, but
  9213. it would also be nice to reduce the overhead of calling a
  9214. \code{lambda} when we can determine at compile time which
  9215. \code{lambda} will be called. We refer to such calls as \emph{known
  9216. calls}. Consider the following example in which a \code{lambda} is
  9217. bound to \code{f} and then applied.
  9218. \begin{lstlisting}
  9219. (let ([y (read)])
  9220. (let ([f (lambda: ([x : Integer]) : Integer
  9221. (+ x y))])
  9222. (f 21)))
  9223. \end{lstlisting}
  9224. Closure conversion compiles \code{(f 21)} into an indirect call:
  9225. \begin{lstlisting}
  9226. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  9227. (let ([y2 (vector-ref fvs6 1)])
  9228. (+ x3 y2)))
  9229. (define (main) : Integer
  9230. (let ([y2 (read)])
  9231. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  9232. ((vector-ref f4 0) f4 21))))
  9233. \end{lstlisting}
  9234. but we can instead compile the application \code{(f 21)} into a direct call
  9235. to \code{lambda5}:
  9236. \begin{lstlisting}
  9237. (define (main) : Integer
  9238. (let ([y2 (read)])
  9239. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  9240. ((fun-ref lambda5) f4 21))))
  9241. \end{lstlisting}
  9242. The problem of determining which lambda will be called from a
  9243. particular application is quite challenging in general and the topic
  9244. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  9245. following exercise we recommend that you compile an application to a
  9246. direct call when the operator is a variable and the variable is
  9247. \code{let}-bound to a closure. This can be accomplished by maintaining
  9248. an environment mapping \code{let}-bound variables to function names.
  9249. Extend the environment whenever you encounter a closure on the
  9250. right-hand side of a \code{let}, mapping the \code{let}-bound variable
  9251. to the name of the global function for the closure. This pass should
  9252. come after closure conversion.
  9253. \begin{exercise}\normalfont
  9254. Implement a compiler pass, named \code{optimize-known-calls}, that
  9255. compiles known calls into direct calls. Verify that your compiler is
  9256. successful in this regard on several example programs.
  9257. \end{exercise}
  9258. These exercises only scratches the surface of optimizing of
  9259. closures. A good next step for the interested reader is to look at the
  9260. work of \citet{Keep:2012ab}.
  9261. \section{Further Reading}
  9262. The notion of lexically scoped anonymous functions predates modern
  9263. computers by about a decade. They were invented by
  9264. \citet{Church:1932aa}, who proposed the $\lambda$ calculus as a
  9265. foundation for logic. Anonymous functions were included in the
  9266. LISP~\citep{McCarthy:1960dz} programming language but were initially
  9267. dynamically scoped. The Scheme dialect of LISP adopted lexical scoping
  9268. and \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently
  9269. compile Scheme programs. However, environments were represented as
  9270. linked lists, so variable lookup was linear in the size of the
  9271. environment. In this chapter we represent environments using flat
  9272. closures, which were invented by
  9273. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  9274. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  9275. closures, variable lookup is constant time but the time to create a
  9276. closure is proportional to the number of its free variables. Flat
  9277. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  9278. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  9279. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9280. \chapter{Dynamic Typing}
  9281. \label{ch:Rdyn}
  9282. \index{dynamic typing}
  9283. In this chapter we discuss the compilation of \LangDyn{}, a dynamically
  9284. typed language that is a subset of Racket. This is in contrast to the
  9285. previous chapters, which have studied the compilation of Typed
  9286. Racket. In dynamically typed languages such as \LangDyn{}, a given
  9287. expression may produce a value of a different type each time it is
  9288. executed. Consider the following example with a conditional \code{if}
  9289. expression that may return a Boolean or an integer depending on the
  9290. input to the program.
  9291. % part of dynamic_test_25.rkt
  9292. \begin{lstlisting}
  9293. (not (if (eq? (read) 1) #f 0))
  9294. \end{lstlisting}
  9295. Languages that allow expressions to produce different kinds of values
  9296. are called \emph{polymorphic}, a word composed of the Greek roots
  9297. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  9298. are several kinds of polymorphism in programming languages, such as
  9299. subtype polymorphism and parametric
  9300. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  9301. study in this chapter does not have a special name but it is the kind
  9302. that arises in dynamically typed languages.
  9303. Another characteristic of dynamically typed languages is that
  9304. primitive operations, such as \code{not}, are often defined to operate
  9305. on many different types of values. In fact, in Racket, the \code{not}
  9306. operator produces a result for any kind of value: given \code{\#f} it
  9307. returns \code{\#t} and given anything else it returns \code{\#f}.
  9308. Furthermore, even when primitive operations restrict their inputs to
  9309. values of a certain type, this restriction is enforced at runtime
  9310. instead of during compilation. For example, the following vector
  9311. reference results in a run-time contract violation because the index
  9312. must be in integer, not a Boolean such as \code{\#t}.
  9313. \begin{lstlisting}
  9314. (vector-ref (vector 42) #t)
  9315. \end{lstlisting}
  9316. \begin{figure}[tp]
  9317. \centering
  9318. \fbox{
  9319. \begin{minipage}{0.97\textwidth}
  9320. \[
  9321. \begin{array}{rcl}
  9322. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  9323. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp}
  9324. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} \\
  9325. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  9326. &\mid& \key{\#t} \mid \key{\#f}
  9327. \mid \CBINOP{\key{and}}{\Exp}{\Exp}
  9328. \mid \CBINOP{\key{or}}{\Exp}{\Exp}
  9329. \mid \CUNIOP{\key{not}}{\Exp} \\
  9330. &\mid& \LP\itm{cmp}\;\Exp\;\Exp\RP \mid \CIF{\Exp}{\Exp}{\Exp} \\
  9331. &\mid& \LP\key{vector}\;\Exp\ldots\RP \mid
  9332. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  9333. &\mid& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \mid \LP\key{void}\RP \\
  9334. &\mid& \LP\Exp \; \Exp\ldots\RP
  9335. \mid \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  9336. & \mid & \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP\\
  9337. & \mid & \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \mid \LP\key{void?}\;\Exp\RP \\
  9338. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  9339. \LangDyn{} &::=& \Def\ldots\; \Exp
  9340. \end{array}
  9341. \]
  9342. \end{minipage}
  9343. }
  9344. \caption{Syntax of \LangDyn{}, an untyped language (a subset of Racket).}
  9345. \label{fig:r7-concrete-syntax}
  9346. \end{figure}
  9347. \begin{figure}[tp]
  9348. \centering
  9349. \fbox{
  9350. \begin{minipage}{0.96\textwidth}
  9351. \small
  9352. \[
  9353. \begin{array}{lcl}
  9354. \Exp &::=& \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  9355. &\mid& \PRIM{\itm{op}}{\Exp\ldots} \\
  9356. &\mid& \BOOL{\itm{bool}}
  9357. \mid \IF{\Exp}{\Exp}{\Exp} \\
  9358. &\mid& \VOID{} \mid \APPLY{\Exp}{\Exp\ldots} \\
  9359. &\mid& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  9360. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  9361. \LangDyn{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  9362. \end{array}
  9363. \]
  9364. \end{minipage}
  9365. }
  9366. \caption{The abstract syntax of \LangDyn{}.}
  9367. \label{fig:r7-syntax}
  9368. \end{figure}
  9369. The concrete and abstract syntax of \LangDyn{}, our subset of Racket, is
  9370. defined in Figures~\ref{fig:r7-concrete-syntax} and
  9371. \ref{fig:r7-syntax}.
  9372. %
  9373. There is no type checker for \LangDyn{} because it is not a statically
  9374. typed language (it's dynamically typed!).
  9375. The definitional interpreter for \LangDyn{} is presented in
  9376. Figure~\ref{fig:interp-Rdyn} and its auxiliary functions are defined i
  9377. Figure~\ref{fig:interp-Rdyn-aux}. Consider the match case for
  9378. \code{(Int n)}. Instead of simply returning the integer \code{n} (as
  9379. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Rvar}), the
  9380. interpreter for \LangDyn{} creates a \emph{tagged value}\index{tagged
  9381. value} that combines an underlying value with a tag that identifies
  9382. what kind of value it is. We define the following struct
  9383. to represented tagged values.
  9384. \begin{lstlisting}
  9385. (struct Tagged (value tag) #:transparent)
  9386. \end{lstlisting}
  9387. The tags are \code{Integer}, \code{Boolean}, \code{Void},
  9388. \code{Vector}, and \code{Procedure}. Tags are closely related to types
  9389. but don't always capture all the information that a type does. For
  9390. example, a vector of type \code{(Vector Any Any)} is tagged with
  9391. \code{Vector} and a procedure of type \code{(Any Any -> Any)}
  9392. is tagged with \code{Procedure}.
  9393. Next consider the match case for \code{vector-ref}. The
  9394. \code{check-tag} auxiliary function (Figure~\ref{fig:interp-Rdyn-aux})
  9395. is used to ensure that the first argument is a vector and the second
  9396. is an integer. If they are not, a \code{trapped-error} is raised.
  9397. Recall from Section~\ref{sec:interp-Rint} that when a definition
  9398. interpreter raises a \code{trapped-error} error, the compiled code
  9399. must also signal an error by exiting with return code \code{255}. A
  9400. \code{trapped-error} is also raised if the index is not less than
  9401. length of the vector.
  9402. \begin{figure}[tbp]
  9403. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9404. (define ((interp-Rdyn-exp env) ast)
  9405. (define recur (interp-Rdyn-exp env))
  9406. (match ast
  9407. [(Var x) (lookup x env)]
  9408. [(Int n) (Tagged n 'Integer)]
  9409. [(Bool b) (Tagged b 'Boolean)]
  9410. [(Lambda xs rt body)
  9411. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  9412. [(Prim 'vector es)
  9413. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  9414. [(Prim 'vector-ref (list e1 e2))
  9415. (define vec (recur e1)) (define i (recur e2))
  9416. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  9417. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  9418. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  9419. (vector-ref (Tagged-value vec) (Tagged-value i))]
  9420. [(Prim 'vector-set! (list e1 e2 e3))
  9421. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  9422. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  9423. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  9424. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  9425. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  9426. (Tagged (void) 'Void)]
  9427. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  9428. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  9429. [(Prim 'or (list e1 e2))
  9430. (define v1 (recur e1))
  9431. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  9432. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  9433. [(Prim op (list e1))
  9434. #:when (set-member? type-predicates op)
  9435. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  9436. [(Prim op es)
  9437. (define args (map recur es))
  9438. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  9439. (unless (for/or ([expected-tags (op-tags op)])
  9440. (equal? expected-tags tags))
  9441. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  9442. (tag-value
  9443. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  9444. [(If q t f)
  9445. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  9446. [(Apply f es)
  9447. (define new-f (recur f)) (define args (map recur es))
  9448. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  9449. (match f-val
  9450. [`(function ,xs ,body ,lam-env)
  9451. (unless (eq? (length xs) (length args))
  9452. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  9453. (define new-env (append (map cons xs args) lam-env))
  9454. ((interp-Rdyn-exp new-env) body)]
  9455. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  9456. \end{lstlisting}
  9457. \caption{Interpreter for the \LangDyn{} language.}
  9458. \label{fig:interp-Rdyn}
  9459. \end{figure}
  9460. \begin{figure}[tbp]
  9461. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9462. (define (interp-op op)
  9463. (match op
  9464. ['+ fx+]
  9465. ['- fx-]
  9466. ['read read-fixnum]
  9467. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  9468. ['< (lambda (v1 v2)
  9469. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  9470. ['<= (lambda (v1 v2)
  9471. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  9472. ['> (lambda (v1 v2)
  9473. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  9474. ['>= (lambda (v1 v2)
  9475. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  9476. ['boolean? boolean?]
  9477. ['integer? fixnum?]
  9478. ['void? void?]
  9479. ['vector? vector?]
  9480. ['vector-length vector-length]
  9481. ['procedure? (match-lambda
  9482. [`(functions ,xs ,body ,env) #t] [else #f])]
  9483. [else (error 'interp-op "unknown operator" op)]))
  9484. (define (op-tags op)
  9485. (match op
  9486. ['+ '((Integer Integer))]
  9487. ['- '((Integer Integer) (Integer))]
  9488. ['read '(())]
  9489. ['not '((Boolean))]
  9490. ['< '((Integer Integer))]
  9491. ['<= '((Integer Integer))]
  9492. ['> '((Integer Integer))]
  9493. ['>= '((Integer Integer))]
  9494. ['vector-length '((Vector))]))
  9495. (define type-predicates
  9496. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  9497. (define (tag-value v)
  9498. (cond [(boolean? v) (Tagged v 'Boolean)]
  9499. [(fixnum? v) (Tagged v 'Integer)]
  9500. [(procedure? v) (Tagged v 'Procedure)]
  9501. [(vector? v) (Tagged v 'Vector)]
  9502. [(void? v) (Tagged v 'Void)]
  9503. [else (error 'tag-value "unidentified value ~a" v)]))
  9504. (define (check-tag val expected ast)
  9505. (define tag (Tagged-tag val))
  9506. (unless (eq? tag expected)
  9507. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  9508. \end{lstlisting}
  9509. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  9510. \label{fig:interp-Rdyn-aux}
  9511. \end{figure}
  9512. \clearpage
  9513. \section{Representation of Tagged Values}
  9514. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  9515. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  9516. values at the bit level. Because almost every operation in \LangDyn{}
  9517. involves manipulating tagged values, the representation must be
  9518. efficient. Recall that all of our values are 64 bits. We shall steal
  9519. the 3 right-most bits to encode the tag. We use $001$ to identify
  9520. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  9521. and $101$ for the void value. We define the following auxiliary
  9522. function for mapping types to tag codes.
  9523. \begin{align*}
  9524. \itm{tagof}(\key{Integer}) &= 001 \\
  9525. \itm{tagof}(\key{Boolean}) &= 100 \\
  9526. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  9527. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  9528. \itm{tagof}(\key{Void}) &= 101
  9529. \end{align*}
  9530. This stealing of 3 bits comes at some price: our integers are reduced
  9531. to ranging from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  9532. affect vectors and procedures because those values are addresses, and
  9533. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  9534. they are always $000$. Thus, we do not lose information by overwriting
  9535. the rightmost 3 bits with the tag and we can simply zero-out the tag
  9536. to recover the original address.
  9537. To make tagged values into first-class entities, we can give them a
  9538. type, called \code{Any}, and define operations such as \code{Inject}
  9539. and \code{Project} for creating and using them, yielding the \LangAny{}
  9540. intermediate language. We describe how to compile \LangDyn{} to \LangAny{} in
  9541. Section~\ref{sec:compile-r7} but first we describe the \LangAny{} language
  9542. in greater detail.
  9543. \section{The \LangAny{} Language}
  9544. \label{sec:Rany-lang}
  9545. \begin{figure}[tp]
  9546. \centering
  9547. \fbox{
  9548. \begin{minipage}{0.96\textwidth}
  9549. \small
  9550. \[
  9551. \begin{array}{lcl}
  9552. \Type &::= & \ldots \mid \key{Any} \\
  9553. \itm{op} &::= & \ldots \mid \code{any-vector-length}
  9554. \mid \code{any-vector-ref} \mid \code{any-vector-set!}\\
  9555. &\mid& \code{boolean?} \mid \code{integer?} \mid \code{vector?}
  9556. \mid \code{procedure?} \mid \code{void?} \\
  9557. \Exp &::=& \ldots
  9558. \mid \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  9559. &\mid& \INJECT{\Exp}{\FType} \mid \PROJECT{\Exp}{\FType} \\
  9560. \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  9561. \LangAny{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  9562. \end{array}
  9563. \]
  9564. \end{minipage}
  9565. }
  9566. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Rlam-syntax}).}
  9567. \label{fig:Rany-syntax}
  9568. \end{figure}
  9569. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Rany-syntax}.
  9570. (The concrete syntax of \LangAny{} is in the Appendix,
  9571. Figure~\ref{fig:Rany-concrete-syntax}.) The $\INJECT{e}{T}$ form
  9572. converts the value produced by expression $e$ of type $T$ into a
  9573. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  9574. produced by expression $e$ into a value of type $T$ or else halts the
  9575. program if the type tag is not equivalent to $T$.
  9576. %
  9577. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  9578. restricted to a flat type $\FType$, which simplifies the
  9579. implementation and corresponds with what is needed for compiling \LangDyn{}.
  9580. The \code{any-vector} operators adapt the vector operations so that
  9581. they can be applied to a value of type \code{Any}. They also
  9582. generalize the vector operations in that the index is not restricted
  9583. to be a literal integer in the grammar but is allowed to be any
  9584. expression.
  9585. The type predicates such as \key{boolean?} expect their argument to
  9586. produce a tagged value; they return \key{\#t} if the tag corresponds
  9587. to the predicate and they return \key{\#f} otherwise.
  9588. The type checker for \LangAny{} is shown in
  9589. Figures~\ref{fig:type-check-Rany-part-1} and
  9590. \ref{fig:type-check-Rany-part-2} and uses the auxiliary functions in
  9591. Figure~\ref{fig:type-check-Rany-aux}.
  9592. %
  9593. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Rany} and the
  9594. auxiliary functions \code{apply-inject} and \code{apply-project} are
  9595. in Figure~\ref{fig:apply-project}.
  9596. \begin{figure}[btp]
  9597. \begin{lstlisting}[basicstyle=\ttfamily\small]
  9598. (define type-check-Rany-class
  9599. (class type-check-Rlambda-class
  9600. (super-new)
  9601. (inherit check-type-equal?)
  9602. (define/override (type-check-exp env)
  9603. (lambda (e)
  9604. (define recur (type-check-exp env))
  9605. (match e
  9606. [(Inject e1 ty)
  9607. (unless (flat-ty? ty)
  9608. (error 'type-check "may only inject from flat type, not ~a" ty))
  9609. (define-values (new-e1 e-ty) (recur e1))
  9610. (check-type-equal? e-ty ty e)
  9611. (values (Inject new-e1 ty) 'Any)]
  9612. [(Project e1 ty)
  9613. (unless (flat-ty? ty)
  9614. (error 'type-check "may only project to flat type, not ~a" ty))
  9615. (define-values (new-e1 e-ty) (recur e1))
  9616. (check-type-equal? e-ty 'Any e)
  9617. (values (Project new-e1 ty) ty)]
  9618. [(Prim 'any-vector-length (list e1))
  9619. (define-values (e1^ t1) (recur e1))
  9620. (check-type-equal? t1 'Any e)
  9621. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  9622. [(Prim 'any-vector-ref (list e1 e2))
  9623. (define-values (e1^ t1) (recur e1))
  9624. (define-values (e2^ t2) (recur e2))
  9625. (check-type-equal? t1 'Any e)
  9626. (check-type-equal? t2 'Integer e)
  9627. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  9628. [(Prim 'any-vector-set! (list e1 e2 e3))
  9629. (define-values (e1^ t1) (recur e1))
  9630. (define-values (e2^ t2) (recur e2))
  9631. (define-values (e3^ t3) (recur e3))
  9632. (check-type-equal? t1 'Any e)
  9633. (check-type-equal? t2 'Integer e)
  9634. (check-type-equal? t3 'Any e)
  9635. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  9636. \end{lstlisting}
  9637. \caption{Type checker for the \LangAny{} language, part 1.}
  9638. \label{fig:type-check-Rany-part-1}
  9639. \end{figure}
  9640. \begin{figure}[btp]
  9641. \begin{lstlisting}[basicstyle=\ttfamily\small]
  9642. [(ValueOf e ty)
  9643. (define-values (new-e e-ty) (recur e))
  9644. (values (ValueOf new-e ty) ty)]
  9645. [(Prim pred (list e1))
  9646. #:when (set-member? (type-predicates) pred)
  9647. (define-values (new-e1 e-ty) (recur e1))
  9648. (check-type-equal? e-ty 'Any e)
  9649. (values (Prim pred (list new-e1)) 'Boolean)]
  9650. [(If cnd thn els)
  9651. (define-values (cnd^ Tc) (recur cnd))
  9652. (define-values (thn^ Tt) (recur thn))
  9653. (define-values (els^ Te) (recur els))
  9654. (check-type-equal? Tc 'Boolean cnd)
  9655. (check-type-equal? Tt Te e)
  9656. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  9657. [(Exit) (values (Exit) '_)]
  9658. [(Prim 'eq? (list arg1 arg2))
  9659. (define-values (e1 t1) (recur arg1))
  9660. (define-values (e2 t2) (recur arg2))
  9661. (match* (t1 t2)
  9662. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  9663. [(other wise) (check-type-equal? t1 t2 e)])
  9664. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  9665. [else ((super type-check-exp env) e)])))
  9666. ))
  9667. \end{lstlisting}
  9668. \caption{Type checker for the \LangAny{} language, part 2.}
  9669. \label{fig:type-check-Rany-part-2}
  9670. \end{figure}
  9671. \begin{figure}[tbp]
  9672. \begin{lstlisting}
  9673. (define/override (operator-types)
  9674. (append
  9675. '((integer? . ((Any) . Boolean))
  9676. (vector? . ((Any) . Boolean))
  9677. (procedure? . ((Any) . Boolean))
  9678. (void? . ((Any) . Boolean))
  9679. (tag-of-any . ((Any) . Integer))
  9680. (make-any . ((_ Integer) . Any))
  9681. )
  9682. (super operator-types)))
  9683. (define/public (type-predicates)
  9684. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  9685. (define/public (combine-types t1 t2)
  9686. (match (list t1 t2)
  9687. [(list '_ t2) t2]
  9688. [(list t1 '_) t1]
  9689. [(list `(Vector ,ts1 ...)
  9690. `(Vector ,ts2 ...))
  9691. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  9692. (combine-types t1 t2)))]
  9693. [(list `(,ts1 ... -> ,rt1)
  9694. `(,ts2 ... -> ,rt2))
  9695. `(,@(for/list ([t1 ts1] [t2 ts2])
  9696. (combine-types t1 t2))
  9697. -> ,(combine-types rt1 rt2))]
  9698. [else t1]))
  9699. (define/public (flat-ty? ty)
  9700. (match ty
  9701. [(or `Integer `Boolean '_ `Void) #t]
  9702. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  9703. [`(,ts ... -> ,rt)
  9704. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  9705. [else #f]))
  9706. \end{lstlisting}
  9707. \caption{Auxiliary methods for type checking \LangAny{}.}
  9708. \label{fig:type-check-Rany-aux}
  9709. \end{figure}
  9710. \begin{figure}[btp]
  9711. \begin{lstlisting}
  9712. (define interp-Rany-class
  9713. (class interp-Rlambda-class
  9714. (super-new)
  9715. (define/override (interp-op op)
  9716. (match op
  9717. ['boolean? (match-lambda
  9718. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  9719. [else #f])]
  9720. ['integer? (match-lambda
  9721. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  9722. [else #f])]
  9723. ['vector? (match-lambda
  9724. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  9725. [else #f])]
  9726. ['procedure? (match-lambda
  9727. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  9728. [else #f])]
  9729. ['eq? (match-lambda*
  9730. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  9731. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  9732. [ls (apply (super interp-op op) ls)])]
  9733. ['any-vector-ref (lambda (v i)
  9734. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  9735. ['any-vector-set! (lambda (v i a)
  9736. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  9737. ['any-vector-length (lambda (v)
  9738. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  9739. [else (super interp-op op)]))
  9740. (define/override ((interp-exp env) e)
  9741. (define recur (interp-exp env))
  9742. (match e
  9743. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  9744. [(Project e ty2) (apply-project (recur e) ty2)]
  9745. [else ((super interp-exp env) e)]))
  9746. ))
  9747. (define (interp-Rany p)
  9748. (send (new interp-Rany-class) interp-program p))
  9749. \end{lstlisting}
  9750. \caption{Interpreter for \LangAny{}.}
  9751. \label{fig:interp-Rany}
  9752. \end{figure}
  9753. \begin{figure}[tbp]
  9754. \begin{lstlisting}
  9755. (define/public (apply-inject v tg) (Tagged v tg))
  9756. (define/public (apply-project v ty2)
  9757. (define tag2 (any-tag ty2))
  9758. (match v
  9759. [(Tagged v1 tag1)
  9760. (cond
  9761. [(eq? tag1 tag2)
  9762. (match ty2
  9763. [`(Vector ,ts ...)
  9764. (define l1 ((interp-op 'vector-length) v1))
  9765. (cond
  9766. [(eq? l1 (length ts)) v1]
  9767. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  9768. l1 (length ts))])]
  9769. [`(,ts ... -> ,rt)
  9770. (match v1
  9771. [`(function ,xs ,body ,env)
  9772. (cond [(eq? (length xs) (length ts)) v1]
  9773. [else
  9774. (error 'apply-project "arity mismatch ~a != ~a"
  9775. (length xs) (length ts))])]
  9776. [else (error 'apply-project "expected function not ~a" v1)])]
  9777. [else v1])]
  9778. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  9779. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  9780. \end{lstlisting}
  9781. \caption{Auxiliary functions for injection and projection.}
  9782. \label{fig:apply-project}
  9783. \end{figure}
  9784. \clearpage
  9785. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  9786. \label{sec:compile-r7}
  9787. The \code{cast-insert} pass compiles from \LangDyn{} to \LangAny{}.
  9788. Figure~\ref{fig:compile-r7-Rany} shows the compilation of many of the
  9789. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  9790. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  9791. an expression $e'$ in \LangAny{} that has type \key{Any}. For example, the
  9792. first row in Figure~\ref{fig:compile-r7-Rany} shows the compilation of
  9793. the Boolean \code{\#t}, which must be injected to produce an
  9794. expression of type \key{Any}.
  9795. %
  9796. The second row of Figure~\ref{fig:compile-r7-Rany}, the compilation of
  9797. addition, is representative of compilation for many primitive
  9798. operations: the arguments have type \key{Any} and must be projected to
  9799. \key{Integer} before the addition can be performed.
  9800. The compilation of \key{lambda} (third row of
  9801. Figure~\ref{fig:compile-r7-Rany}) shows what happens when we need to
  9802. produce type annotations: we simply use \key{Any}.
  9803. %
  9804. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  9805. has to account for some differences in behavior between \LangDyn{} and
  9806. \LangAny{}. The \LangDyn{} language is more permissive than \LangAny{} regarding what
  9807. kind of values can be used in various places. For example, the
  9808. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  9809. the arguments need not be of the same type (in that case the
  9810. result is \code{\#f}).
  9811. \begin{figure}[btp]
  9812. \centering
  9813. \begin{tabular}{|lll|} \hline
  9814. \begin{minipage}{0.27\textwidth}
  9815. \begin{lstlisting}
  9816. #t
  9817. \end{lstlisting}
  9818. \end{minipage}
  9819. &
  9820. $\Rightarrow$
  9821. &
  9822. \begin{minipage}{0.65\textwidth}
  9823. \begin{lstlisting}
  9824. (inject #t Boolean)
  9825. \end{lstlisting}
  9826. \end{minipage}
  9827. \\[2ex]\hline
  9828. \begin{minipage}{0.27\textwidth}
  9829. \begin{lstlisting}
  9830. (+ |$e_1$| |$e_2$|)
  9831. \end{lstlisting}
  9832. \end{minipage}
  9833. &
  9834. $\Rightarrow$
  9835. &
  9836. \begin{minipage}{0.65\textwidth}
  9837. \begin{lstlisting}
  9838. (inject
  9839. (+ (project |$e'_1$| Integer)
  9840. (project |$e'_2$| Integer))
  9841. Integer)
  9842. \end{lstlisting}
  9843. \end{minipage}
  9844. \\[2ex]\hline
  9845. \begin{minipage}{0.27\textwidth}
  9846. \begin{lstlisting}
  9847. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  9848. \end{lstlisting}
  9849. \end{minipage}
  9850. &
  9851. $\Rightarrow$
  9852. &
  9853. \begin{minipage}{0.65\textwidth}
  9854. \begin{lstlisting}
  9855. (inject
  9856. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  9857. (Any|$\ldots$|Any -> Any))
  9858. \end{lstlisting}
  9859. \end{minipage}
  9860. \\[2ex]\hline
  9861. \begin{minipage}{0.27\textwidth}
  9862. \begin{lstlisting}
  9863. (|$e_0$| |$e_1 \ldots e_n$|)
  9864. \end{lstlisting}
  9865. \end{minipage}
  9866. &
  9867. $\Rightarrow$
  9868. &
  9869. \begin{minipage}{0.65\textwidth}
  9870. \begin{lstlisting}
  9871. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  9872. \end{lstlisting}
  9873. \end{minipage}
  9874. \\[2ex]\hline
  9875. \begin{minipage}{0.27\textwidth}
  9876. \begin{lstlisting}
  9877. (vector-ref |$e_1$| |$e_2$|)
  9878. \end{lstlisting}
  9879. \end{minipage}
  9880. &
  9881. $\Rightarrow$
  9882. &
  9883. \begin{minipage}{0.65\textwidth}
  9884. \begin{lstlisting}
  9885. (any-vector-ref |$e_1'$| |$e_2'$|)
  9886. \end{lstlisting}
  9887. \end{minipage}
  9888. \\[2ex]\hline
  9889. \begin{minipage}{0.27\textwidth}
  9890. \begin{lstlisting}
  9891. (if |$e_1$| |$e_2$| |$e_3$|)
  9892. \end{lstlisting}
  9893. \end{minipage}
  9894. &
  9895. $\Rightarrow$
  9896. &
  9897. \begin{minipage}{0.65\textwidth}
  9898. \begin{lstlisting}
  9899. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  9900. \end{lstlisting}
  9901. \end{minipage}
  9902. \\[2ex]\hline
  9903. \begin{minipage}{0.27\textwidth}
  9904. \begin{lstlisting}
  9905. (eq? |$e_1$| |$e_2$|)
  9906. \end{lstlisting}
  9907. \end{minipage}
  9908. &
  9909. $\Rightarrow$
  9910. &
  9911. \begin{minipage}{0.65\textwidth}
  9912. \begin{lstlisting}
  9913. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  9914. \end{lstlisting}
  9915. \end{minipage}
  9916. \\[2ex]\hline
  9917. \begin{minipage}{0.27\textwidth}
  9918. \begin{lstlisting}
  9919. (not |$e_1$|)
  9920. \end{lstlisting}
  9921. \end{minipage}
  9922. &
  9923. $\Rightarrow$
  9924. &
  9925. \begin{minipage}{0.65\textwidth}
  9926. \begin{lstlisting}
  9927. (if (eq? |$e'_1$| (inject #f Boolean))
  9928. (inject #t Boolean) (inject #f Boolean))
  9929. \end{lstlisting}
  9930. \end{minipage}
  9931. \\[2ex]\hline
  9932. \end{tabular}
  9933. \caption{Cast Insertion}
  9934. \label{fig:compile-r7-Rany}
  9935. \end{figure}
  9936. \section{Reveal Casts}
  9937. \label{sec:reveal-casts-Rany}
  9938. % TODO: define R'_6
  9939. In the \code{reveal-casts} pass we recommend compiling \code{project}
  9940. into an \code{if} expression that checks whether the value's tag
  9941. matches the target type; if it does, the value is converted to a value
  9942. of the target type by removing the tag; if it does not, the program
  9943. exits. To perform these actions we need a new primitive operation,
  9944. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  9945. The \code{tag-of-any} operation retrieves the type tag from a tagged
  9946. value of type \code{Any}. The \code{ValueOf} form retrieves the
  9947. underlying value from a tagged value. The \code{ValueOf} form
  9948. includes the type for the underlying value which is used by the type
  9949. checker. Finally, the \code{Exit} form ends the execution of the
  9950. program.
  9951. If the target type of the projection is \code{Boolean} or
  9952. \code{Integer}, then \code{Project} can be translated as follows.
  9953. \begin{center}
  9954. \begin{minipage}{1.0\textwidth}
  9955. \begin{lstlisting}
  9956. (Project |$e$| |$\FType$|)
  9957. |$\Rightarrow$|
  9958. (Let |$\itm{tmp}$| |$e'$|
  9959. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  9960. (Int |$\itm{tagof}(\FType)$|)))
  9961. (ValueOf |$\itm{tmp}$| |$\FType$|)
  9962. (Exit)))
  9963. \end{lstlisting}
  9964. \end{minipage}
  9965. \end{center}
  9966. If the target type of the projection is a vector or function type,
  9967. then there is a bit more work to do. For vectors, check that the
  9968. length of the vector type matches the length of the vector (using the
  9969. \code{vector-length} primitive). For functions, check that the number
  9970. of parameters in the function type matches the function's arity (using
  9971. \code{procedure-arity}).
  9972. Regarding \code{inject}, we recommend compiling it to a slightly
  9973. lower-level primitive operation named \code{make-any}. This operation
  9974. takes a tag instead of a type.
  9975. \begin{center}
  9976. \begin{minipage}{1.0\textwidth}
  9977. \begin{lstlisting}
  9978. (Inject |$e$| |$\FType$|)
  9979. |$\Rightarrow$|
  9980. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  9981. \end{lstlisting}
  9982. \end{minipage}
  9983. \end{center}
  9984. The type predicates (\code{boolean?}, etc.) can be translated into
  9985. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  9986. translation of \code{Project}.
  9987. The \code{any-vector-ref} and \code{any-vector-set!} operations
  9988. combine the projection action with the vector operation. Also, the
  9989. read and write operations allow arbitrary expressions for the index so
  9990. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany-part-1})
  9991. cannot guarantee that the index is within bounds. Thus, we insert code
  9992. to perform bounds checking at runtime. The translation for
  9993. \code{any-vector-ref} is as follows and the other two operations are
  9994. translated in a similar way.
  9995. \begin{lstlisting}
  9996. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  9997. |$\Rightarrow$|
  9998. (Let |$v$| |$e'_1$|
  9999. (Let |$i$| |$e'_2$|
  10000. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  10001. (If (Prim '< (list (Var |$i$|)
  10002. (Prim 'any-vector-length (list (Var |$v$|)))))
  10003. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  10004. (Exit))))
  10005. \end{lstlisting}
  10006. \section{Remove Complex Operands}
  10007. \label{sec:rco-Rany}
  10008. The \code{ValueOf} and \code{Exit} forms are both complex expressions.
  10009. The subexpression of \code{ValueOf} must be atomic.
  10010. \section{Explicate Control and \LangCAny{}}
  10011. \label{sec:explicate-Rany}
  10012. The output of \code{explicate-control} is the \LangCAny{} language whose
  10013. syntax is defined in Figure~\ref{fig:c5-syntax}. The \code{ValueOf}
  10014. form that we added to \LangAny{} remains an expression and the \code{Exit}
  10015. expression becomes a $\Tail$. Also, note that the index argument of
  10016. \code{vector-ref} and \code{vector-set!} is an $\Atm$ instead
  10017. of an integer, as in \LangCVec{} (Figure~\ref{fig:c2-syntax}).
  10018. \begin{figure}[tp]
  10019. \fbox{
  10020. \begin{minipage}{0.96\textwidth}
  10021. \small
  10022. \[
  10023. \begin{array}{lcl}
  10024. \Exp &::= & \ldots
  10025. \mid \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  10026. &\mid& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  10027. &\mid& \VALUEOF{\Exp}{\FType} \\
  10028. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  10029. \mid \LP\key{Collect} \,\itm{int}\RP }\\
  10030. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  10031. \mid \GOTO{\itm{label}} } \\
  10032. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  10033. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  10034. \mid \LP\key{Exit}\RP \\
  10035. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  10036. \LangCLam{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  10037. \end{array}
  10038. \]
  10039. \end{minipage}
  10040. }
  10041. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  10042. \label{fig:c5-syntax}
  10043. \end{figure}
  10044. \section{Select Instructions}
  10045. \label{sec:select-Rany}
  10046. In the \code{select-instructions} pass we translate the primitive
  10047. operations on the \code{Any} type to x86 instructions that involve
  10048. manipulating the 3 tag bits of the tagged value.
  10049. \paragraph{Make-any}
  10050. We recommend compiling the \key{make-any} primitive as follows if the
  10051. tag is for \key{Integer} or \key{Boolean}. The \key{salq} instruction
  10052. shifts the destination to the left by the number of bits specified its
  10053. source argument (in this case $3$, the length of the tag) and it
  10054. preserves the sign of the integer. We use the \key{orq} instruction to
  10055. combine the tag and the value to form the tagged value. \\
  10056. \begin{lstlisting}
  10057. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  10058. |$\Rightarrow$|
  10059. movq |$e'$|, |\itm{lhs'}|
  10060. salq $3, |\itm{lhs'}|
  10061. orq $|$\itm{tag}$|, |\itm{lhs'}|
  10062. \end{lstlisting}
  10063. The instruction selection for vectors and procedures is different
  10064. because their is no need to shift them to the left. The rightmost 3
  10065. bits are already zeros as described at the beginning of this
  10066. chapter. So we just combine the value and the tag using \key{orq}. \\
  10067. \begin{lstlisting}
  10068. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  10069. |$\Rightarrow$|
  10070. movq |$e'$|, |\itm{lhs'}|
  10071. orq $|$\itm{tag}$|, |\itm{lhs'}|
  10072. \end{lstlisting}
  10073. \paragraph{Tag-of-any}
  10074. Recall that the \code{tag-of-any} operation extracts the type tag from
  10075. a value of type \code{Any}. The type tag is the bottom three bits, so
  10076. we obtain the tag by taking the bitwise-and of the value with $111$
  10077. ($7$ in decimal).
  10078. \begin{lstlisting}
  10079. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  10080. |$\Rightarrow$|
  10081. movq |$e'$|, |\itm{lhs'}|
  10082. andq $7, |\itm{lhs'}|
  10083. \end{lstlisting}
  10084. \paragraph{ValueOf}
  10085. Like \key{make-any}, the instructions for \key{ValueOf} are different
  10086. depending on whether the type $T$ is a pointer (vector or procedure)
  10087. or not (Integer or Boolean). The following shows the instruction
  10088. selection for Integer and Boolean. We produce an untagged value by
  10089. shifting it to the right by 3 bits.
  10090. \begin{lstlisting}
  10091. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  10092. |$\Rightarrow$|
  10093. movq |$e'$|, |\itm{lhs'}|
  10094. sarq $3, |\itm{lhs'}|
  10095. \end{lstlisting}
  10096. %
  10097. In the case for vectors and procedures, there is no need to
  10098. shift. Instead we just need to zero-out the rightmost 3 bits. We
  10099. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  10100. decimal) and apply \code{bitwise-not} to obtain $\ldots 11111000$ (-8
  10101. in decimal) which we \code{movq} into the destination $\itm{lhs}$. We
  10102. then apply \code{andq} with the tagged value to get the desired
  10103. result. \\
  10104. \begin{lstlisting}
  10105. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  10106. |$\Rightarrow$|
  10107. movq $|$-8$|, |\itm{lhs'}|
  10108. andq |$e'$|, |\itm{lhs'}|
  10109. \end{lstlisting}
  10110. %% \paragraph{Type Predicates} We leave it to the reader to
  10111. %% devise a sequence of instructions to implement the type predicates
  10112. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  10113. \paragraph{Any-vector-length}
  10114. \begin{lstlisting}
  10115. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$a_1$|)))
  10116. |$\Longrightarrow$|
  10117. movq |$\neg 111$|, %r11
  10118. andq |$a_1'$|, %r11
  10119. movq 0(%r11), %r11
  10120. andq $126, %r11
  10121. sarq $1, %r11
  10122. movq %r11, |$\itm{lhs'}$|
  10123. \end{lstlisting}
  10124. \paragraph{Any-vector-ref}
  10125. The index may be an arbitrary atom so instead of computing the offset
  10126. at compile time, instructions need to be generated to compute the
  10127. offset at runtime as follows. Note the use of the new instruction
  10128. \code{imulq}.
  10129. \begin{center}
  10130. \begin{minipage}{0.96\textwidth}
  10131. \begin{lstlisting}
  10132. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$a_1$| |$a_2$|)))
  10133. |$\Longrightarrow$|
  10134. movq |$\neg 111$|, %r11
  10135. andq |$a_1'$|, %r11
  10136. movq |$a_2'$|, %rax
  10137. addq $1, %rax
  10138. imulq $8, %rax
  10139. addq %rax, %r11
  10140. movq 0(%r11) |$\itm{lhs'}$|
  10141. \end{lstlisting}
  10142. \end{minipage}
  10143. \end{center}
  10144. \paragraph{Any-vector-set!}
  10145. The code generation for \code{any-vector-set!} is similar to the other
  10146. \code{any-vector} operations.
  10147. \section{Register Allocation for \LangAny{}}
  10148. \label{sec:register-allocation-Rany}
  10149. \index{register allocation}
  10150. There is an interesting interaction between tagged values and garbage
  10151. collection that has an impact on register allocation. A variable of
  10152. type \code{Any} might refer to a vector and therefore it might be a
  10153. root that needs to be inspected and copied during garbage
  10154. collection. Thus, we need to treat variables of type \code{Any} in a
  10155. similar way to variables of type \code{Vector} for purposes of
  10156. register allocation. In particular,
  10157. \begin{itemize}
  10158. \item If a variable of type \code{Any} is live during a function call,
  10159. then it must be spilled. This can be accomplished by changing
  10160. \code{build-interference} to mark all variables of type \code{Any}
  10161. that are live after a \code{callq} as interfering with all the
  10162. registers.
  10163. \item If a variable of type \code{Any} is spilled, it must be spilled
  10164. to the root stack instead of the normal procedure call stack.
  10165. \end{itemize}
  10166. Another concern regarding the root stack is that the garbage collector
  10167. needs to differentiate between (1) plain old pointers to tuples, (2) a
  10168. tagged value that points to a tuple, and (3) a tagged value that is
  10169. not a tuple. We enable this differentiation by choosing not to use the
  10170. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  10171. reserved for identifying plain old pointers to tuples. That way, if
  10172. one of the first three bits is set, then we have a tagged value and
  10173. inspecting the tag can differentiation between vectors ($010$) and the
  10174. other kinds of values.
  10175. \begin{exercise}\normalfont
  10176. Expand your compiler to handle \LangAny{} as discussed in the last few
  10177. sections. Create 5 new programs that use the \code{Any} type and the
  10178. new operations (\code{inject}, \code{project}, \code{boolean?},
  10179. etc.). Test your compiler on these new programs and all of your
  10180. previously created test programs.
  10181. \end{exercise}
  10182. \begin{exercise}\normalfont
  10183. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  10184. Create tests for \LangDyn{} by adapting ten of your previous test programs
  10185. by removing type annotations. Add 5 more tests programs that
  10186. specifically rely on the language being dynamically typed. That is,
  10187. they should not be legal programs in a statically typed language, but
  10188. nevertheless, they should be valid \LangDyn{} programs that run to
  10189. completion without error.
  10190. \end{exercise}
  10191. \begin{figure}[p]
  10192. \begin{tikzpicture}[baseline=(current bounding box.center)]
  10193. \node (Rfun) at (0,4) {\large \LangDyn{}};
  10194. \node (Rfun-2) at (3,4) {\large \LangDyn{}};
  10195. \node (Rfun-3) at (6,4) {\large \LangDyn{}};
  10196. \node (Rfun-4) at (9,4) {\large \LangDynFunRef{}};
  10197. \node (Rfun-5) at (9,2) {\large \LangAnyFunRef{}};
  10198. \node (Rfun-6) at (12,2) {\large \LangAnyFunRef{}};
  10199. \node (Rfun-7) at (12,0) {\large \LangAnyFunRef{}};
  10200. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  10201. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  10202. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  10203. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  10204. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  10205. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  10206. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  10207. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  10208. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  10209. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  10210. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  10211. \path[->,bend left=15] (Rfun) edge [above] node
  10212. {\ttfamily\footnotesize shrink} (Rfun-2);
  10213. \path[->,bend left=15] (Rfun-2) edge [above] node
  10214. {\ttfamily\footnotesize uniquify} (Rfun-3);
  10215. \path[->,bend left=15] (Rfun-3) edge [above] node
  10216. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  10217. \path[->,bend right=15] (Rfun-4) edge [left] node
  10218. {\ttfamily\footnotesize cast-insert} (Rfun-5);
  10219. \path[->,bend left=15] (Rfun-5) edge [above] node
  10220. {\ttfamily\footnotesize check-bounds} (Rfun-6);
  10221. \path[->,bend left=15] (Rfun-6) edge [left] node
  10222. {\ttfamily\footnotesize reveal-casts} (Rfun-7);
  10223. \path[->,bend left=15] (Rfun-7) edge [below] node
  10224. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  10225. \path[->,bend right=15] (F1-2) edge [above] node
  10226. {\ttfamily\footnotesize limit-fun.} (F1-3);
  10227. \path[->,bend right=15] (F1-3) edge [above] node
  10228. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  10229. \path[->,bend right=15] (F1-4) edge [above] node
  10230. {\ttfamily\footnotesize remove-complex.} (F1-5);
  10231. \path[->,bend right=15] (F1-5) edge [right] node
  10232. {\ttfamily\footnotesize explicate-control} (C3-2);
  10233. \path[->,bend left=15] (C3-2) edge [left] node
  10234. {\ttfamily\footnotesize select-instr.} (x86-2);
  10235. \path[->,bend right=15] (x86-2) edge [left] node
  10236. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  10237. \path[->,bend right=15] (x86-2-1) edge [below] node
  10238. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  10239. \path[->,bend right=15] (x86-2-2) edge [left] node
  10240. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  10241. \path[->,bend left=15] (x86-3) edge [above] node
  10242. {\ttfamily\footnotesize patch-instr.} (x86-4);
  10243. \path[->,bend left=15] (x86-4) edge [right] node
  10244. {\ttfamily\footnotesize print-x86} (x86-5);
  10245. \end{tikzpicture}
  10246. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  10247. \label{fig:Rdyn-passes}
  10248. \end{figure}
  10249. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  10250. for the compilation of \LangDyn{}.
  10251. % Further Reading
  10252. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10253. \chapter{Loops and Assignment}
  10254. \label{ch:Rwhile}
  10255. % TODO: define R'_8
  10256. % TODO: multi-graph
  10257. In this chapter we study two features that are the hallmarks of
  10258. imperative programming languages: loops and assignments to local
  10259. variables. The following example demonstrates these new features by
  10260. computing the sum of the first five positive integers.
  10261. % similar to loop_test_1.rkt
  10262. \begin{lstlisting}
  10263. (let ([sum 0])
  10264. (let ([i 5])
  10265. (begin
  10266. (while (> i 0)
  10267. (begin
  10268. (set! sum (+ sum i))
  10269. (set! i (- i 1))))
  10270. sum)))
  10271. \end{lstlisting}
  10272. The \code{while} loop consists of a condition and a body.
  10273. %
  10274. The \code{set!} consists of a variable and a right-hand-side expression.
  10275. %
  10276. The primary purpose of both the \code{while} loop and \code{set!} is
  10277. to cause side effects, so it is convenient to also include in a
  10278. language feature for sequencing side effects: the \code{begin}
  10279. expression. It consists of one or more subexpressions that are
  10280. evaluated left-to-right.
  10281. \section{The \LangLoop{} Language}
  10282. \begin{figure}[tp]
  10283. \centering
  10284. \fbox{
  10285. \begin{minipage}{0.96\textwidth}
  10286. \small
  10287. \[
  10288. \begin{array}{lcl}
  10289. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  10290. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  10291. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  10292. &\mid& \gray{\key{\#t} \mid \key{\#f}
  10293. \mid (\key{and}\;\Exp\;\Exp)
  10294. \mid (\key{or}\;\Exp\;\Exp)
  10295. \mid (\key{not}\;\Exp) } \\
  10296. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  10297. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  10298. (\key{vector-ref}\;\Exp\;\Int)} \\
  10299. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  10300. \mid (\Exp \; \Exp\ldots) } \\
  10301. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP
  10302. \mid \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  10303. &\mid& \CSETBANG{\Var}{\Exp}
  10304. \mid \CBEGIN{\Exp\ldots}{\Exp}
  10305. \mid \CWHILE{\Exp}{\Exp} \\
  10306. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  10307. \LangLoop{} &::=& \gray{\Def\ldots \; \Exp}
  10308. \end{array}
  10309. \]
  10310. \end{minipage}
  10311. }
  10312. \caption{The concrete syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-concrete-syntax}).}
  10313. \label{fig:Rwhile-concrete-syntax}
  10314. \end{figure}
  10315. \begin{figure}[tp]
  10316. \centering
  10317. \fbox{
  10318. \begin{minipage}{0.96\textwidth}
  10319. \small
  10320. \[
  10321. \begin{array}{lcl}
  10322. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  10323. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  10324. &\mid& \gray{ \BOOL{\itm{bool}}
  10325. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  10326. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  10327. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  10328. &\mid& \gray{ \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp} }\\
  10329. &\mid& \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  10330. \mid \WHILE{\Exp}{\Exp} \\
  10331. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  10332. \LangLoop{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  10333. \end{array}
  10334. \]
  10335. \end{minipage}
  10336. }
  10337. \caption{The abstract syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-syntax}).}
  10338. \label{fig:Rwhile-syntax}
  10339. \end{figure}
  10340. The concrete syntax of \LangLoop{} is defined in
  10341. Figure~\ref{fig:Rwhile-concrete-syntax} and its abstract syntax is defined
  10342. in Figure~\ref{fig:Rwhile-syntax}.
  10343. %
  10344. The definitional interpreter for \LangLoop{} is shown in
  10345. Figure~\ref{fig:interp-Rwhile}. We add three new cases for \code{SetBang},
  10346. \code{WhileLoop}, and \code{Begin} and we make changes to the cases
  10347. for \code{Var}, \code{Let}, and \code{Apply} regarding variables. To
  10348. support assignment to variables and to make their lifetimes indefinite
  10349. (see the second example in Section~\ref{sec:assignment-scoping}), we
  10350. box the value that is bound to each variable (in \code{Let}) and
  10351. function parameter (in \code{Apply}). The case for \code{Var} unboxes
  10352. the value.
  10353. %
  10354. Now to discuss the new cases. For \code{SetBang}, we lookup the
  10355. variable in the environment to obtain a boxed value and then we change
  10356. it using \code{set-box!} to the result of evaluating the right-hand
  10357. side. The result value of a \code{SetBang} is \code{void}.
  10358. %
  10359. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  10360. if the result is true, 2) evaluate the body.
  10361. The result value of a \code{while} loop is also \code{void}.
  10362. %
  10363. Finally, the $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  10364. subexpressions \itm{es} for their effects and then evaluates
  10365. and returns the result from \itm{body}.
  10366. \begin{figure}[tbp]
  10367. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10368. (define interp-Rwhile-class
  10369. (class interp-Rany-class
  10370. (super-new)
  10371. (define/override ((interp-exp env) e)
  10372. (define recur (interp-exp env))
  10373. (match e
  10374. [(SetBang x rhs)
  10375. (set-box! (lookup x env) (recur rhs))]
  10376. [(WhileLoop cnd body)
  10377. (define (loop)
  10378. (cond [(recur cnd) (recur body) (loop)]
  10379. [else (void)]))
  10380. (loop)]
  10381. [(Begin es body)
  10382. (for ([e es]) (recur e))
  10383. (recur body)]
  10384. [else ((super interp-exp env) e)]))
  10385. ))
  10386. (define (interp-Rwhile p)
  10387. (send (new interp-Rwhile-class) interp-program p))
  10388. \end{lstlisting}
  10389. \caption{Interpreter for \LangLoop{}.}
  10390. \label{fig:interp-Rwhile}
  10391. \end{figure}
  10392. The type checker for \LangLoop{} is define in
  10393. Figure~\ref{fig:type-check-Rwhile}. For \code{SetBang}, the type of the
  10394. variable and the right-hand-side must agree. The result type is
  10395. \code{Void}. For the \code{WhileLoop}, the condition must be a
  10396. \code{Boolean}. The result type is also \code{Void}. For
  10397. \code{Begin}, the result type is the type of its last subexpression.
  10398. \begin{figure}[tbp]
  10399. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10400. (define type-check-Rwhile-class
  10401. (class type-check-Rany-class
  10402. (super-new)
  10403. (inherit check-type-equal?)
  10404. (define/override (type-check-exp env)
  10405. (lambda (e)
  10406. (define recur (type-check-exp env))
  10407. (match e
  10408. [(SetBang x rhs)
  10409. (define-values (rhs^ rhsT) (recur rhs))
  10410. (define varT (dict-ref env x))
  10411. (check-type-equal? rhsT varT e)
  10412. (values (SetBang x rhs^) 'Void)]
  10413. [(WhileLoop cnd body)
  10414. (define-values (cnd^ Tc) (recur cnd))
  10415. (check-type-equal? Tc 'Boolean e)
  10416. (define-values (body^ Tbody) ((type-check-exp env) body))
  10417. (values (WhileLoop cnd^ body^) 'Void)]
  10418. [(Begin es body)
  10419. (define-values (es^ ts)
  10420. (for/lists (l1 l2) ([e es]) (recur e)))
  10421. (define-values (body^ Tbody) (recur body))
  10422. (values (Begin es^ body^) Tbody)]
  10423. [else ((super type-check-exp env) e)])))
  10424. ))
  10425. (define (type-check-Rwhile p)
  10426. (send (new type-check-Rwhile-class) type-check-program p))
  10427. \end{lstlisting}
  10428. \caption{Type checking \key{SetBang}, \key{WhileLoop},
  10429. and \code{Begin} in \LangLoop{}.}
  10430. \label{fig:type-check-Rwhile}
  10431. \end{figure}
  10432. At first glance, the translation of these language features to x86
  10433. seems straightforward because the \LangCFun{} intermediate language already
  10434. supports all of the ingredients that we need: assignment, \code{goto},
  10435. conditional branching, and sequencing. However, there are two
  10436. complications that arise which we discuss in the next two
  10437. sections. After that we introduce one new compiler pass and the
  10438. changes necessary to the existing passes.
  10439. \section{Assignment and Lexically Scoped Functions}
  10440. \label{sec:assignment-scoping}
  10441. The addition of assignment raises a problem with our approach to
  10442. implementing lexically-scoped functions. Consider the following
  10443. example in which function \code{f} has a free variable \code{x} that
  10444. is changed after \code{f} is created but before the call to \code{f}.
  10445. % loop_test_11.rkt
  10446. \begin{lstlisting}
  10447. (let ([x 0])
  10448. (let ([y 0])
  10449. (let ([z 20])
  10450. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  10451. (begin
  10452. (set! x 10)
  10453. (set! y 12)
  10454. (f y))))))
  10455. \end{lstlisting}
  10456. The correct output for this example is \code{42} because the call to
  10457. \code{f} is required to use the current value of \code{x} (which is
  10458. \code{10}). Unfortunately, the closure conversion pass
  10459. (Section~\ref{sec:closure-conversion}) generates code for the
  10460. \code{lambda} that copies the old value of \code{x} into a
  10461. closure. Thus, if we naively add support for assignment to our current
  10462. compiler, the output of this program would be \code{32}.
  10463. A first attempt at solving this problem would be to save a pointer to
  10464. \code{x} in the closure and change the occurrences of \code{x} inside
  10465. the lambda to dereference the pointer. Of course, this would require
  10466. assigning \code{x} to the stack and not to a register. However, the
  10467. problem goes a bit deeper. Consider the following example in which we
  10468. create a counter abstraction by creating a pair of functions that
  10469. share the free variable \code{x}.
  10470. % similar to loop_test_10.rkt
  10471. \begin{lstlisting}
  10472. (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  10473. (vector
  10474. (lambda: () : Integer x)
  10475. (lambda: () : Void (set! x (+ 1 x)))))
  10476. (let ([counter (f 0)])
  10477. (let ([get (vector-ref counter 0)])
  10478. (let ([inc (vector-ref counter 1)])
  10479. (begin
  10480. (inc)
  10481. (get)))))
  10482. \end{lstlisting}
  10483. In this example, the lifetime of \code{x} extends beyond the lifetime
  10484. of the call to \code{f}. Thus, if we were to store \code{x} on the
  10485. stack frame for the call to \code{f}, it would be gone by the time we
  10486. call \code{inc} and \code{get}, leaving us with dangling pointers for
  10487. \code{x}. This example demonstrates that when a variable occurs free
  10488. inside a \code{lambda}, its lifetime becomes indefinite. Thus, the
  10489. value of the variable needs to live on the heap. The verb ``box'' is
  10490. often used for allocating a single value on the heap, producing a
  10491. pointer, and ``unbox'' for dereferencing the pointer.
  10492. We recommend solving these problems by ``boxing'' the local variables
  10493. that are in the intersection of 1) variables that appear on the
  10494. left-hand-side of a \code{set!} and 2) variables that occur free
  10495. inside a \code{lambda}. We shall introduce a new pass named
  10496. \code{convert-assignments} in Section~\ref{sec:convert-assignments} to
  10497. perform this translation. But before diving into the compiler passes,
  10498. we one more problem to discuss.
  10499. \section{Cyclic Control Flow and Dataflow Analysis}
  10500. \label{sec:dataflow-analysis}
  10501. Up until this point the control-flow graphs generated in
  10502. \code{explicate-control} were guaranteed to be acyclic. However, each
  10503. \code{while} loop introduces a cycle in the control-flow graph.
  10504. But does that matter?
  10505. %
  10506. Indeed it does. Recall that for register allocation, the compiler
  10507. performs liveness analysis to determine which variables can share the
  10508. same register. In Section~\ref{sec:liveness-analysis-Rif} we analyze
  10509. the control-flow graph in reverse topological order, but topological
  10510. order is only well-defined for acyclic graphs.
  10511. Let us return to the example of computing the sum of the first five
  10512. positive integers. Here is the program after instruction selection but
  10513. before register allocation.
  10514. \begin{center}
  10515. \begin{minipage}{0.45\textwidth}
  10516. \begin{lstlisting}
  10517. (define (main) : Integer
  10518. mainstart:
  10519. movq $0, sum1
  10520. movq $5, i2
  10521. jmp block5
  10522. block5:
  10523. movq i2, tmp3
  10524. cmpq tmp3, $0
  10525. jl block7
  10526. jmp block8
  10527. \end{lstlisting}
  10528. \end{minipage}
  10529. \begin{minipage}{0.45\textwidth}
  10530. \begin{lstlisting}
  10531. block7:
  10532. addq i2, sum1
  10533. movq $1, tmp4
  10534. negq tmp4
  10535. addq tmp4, i2
  10536. jmp block5
  10537. block8:
  10538. movq $27, %rax
  10539. addq sum1, %rax
  10540. jmp mainconclusion
  10541. )
  10542. \end{lstlisting}
  10543. \end{minipage}
  10544. \end{center}
  10545. Recall that liveness analysis works backwards, starting at the end
  10546. of each function. For this example we could start with \code{block8}
  10547. because we know what is live at the beginning of the conclusion,
  10548. just \code{rax} and \code{rsp}. So the live-before set
  10549. for \code{block8} is $\{\ttm{rsp},\ttm{sum1}\}$.
  10550. %
  10551. Next we might try to analyze \code{block5} or \code{block7}, but
  10552. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  10553. we are stuck.
  10554. The way out of this impasse comes from the realization that one can
  10555. perform liveness analysis starting with an empty live-after set to
  10556. compute an under-approximation of the live-before set. By
  10557. \emph{under-approximation}, we mean that the set only contains
  10558. variables that are really live, but it may be missing some. Next, the
  10559. under-approximations for each block can be improved by 1) updating the
  10560. live-after set for each block using the approximate live-before sets
  10561. from the other blocks and 2) perform liveness analysis again on each
  10562. block. In fact, by iterating this process, the under-approximations
  10563. eventually become the correct solutions!
  10564. %
  10565. This approach of iteratively analyzing a control-flow graph is
  10566. applicable to many static analysis problems and goes by the name
  10567. \emph{dataflow analysis}\index{dataflow analysis}. It was invented by
  10568. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  10569. Washington.
  10570. Let us apply this approach to the above example. We use the empty set
  10571. for the initial live-before set for each block. Let $m_0$ be the
  10572. following mapping from label names to sets of locations (variables and
  10573. registers).
  10574. \begin{center}
  10575. \begin{lstlisting}
  10576. mainstart: {}
  10577. block5: {}
  10578. block7: {}
  10579. block8: {}
  10580. \end{lstlisting}
  10581. \end{center}
  10582. Using the above live-before approximations, we determine the
  10583. live-after for each block and then apply liveness analysis to each
  10584. block. This produces our next approximation $m_1$ of the live-before
  10585. sets.
  10586. \begin{center}
  10587. \begin{lstlisting}
  10588. mainstart: {}
  10589. block5: {i2}
  10590. block7: {i2, sum1}
  10591. block8: {rsp, sum1}
  10592. \end{lstlisting}
  10593. \end{center}
  10594. For the second round, the live-after for \code{mainstart} is the
  10595. current live-before for \code{block5}, which is \code{\{i2\}}. So the
  10596. liveness analysis for \code{mainstart} computes the empty set. The
  10597. live-after for \code{block5} is the union of the live-before sets for
  10598. \code{block7} and \code{block8}, which is \code{\{i2 , rsp, sum1\}}.
  10599. So the liveness analysis for \code{block5} computes \code{\{i2 , rsp,
  10600. sum1\}}. The live-after for \code{block7} is the live-before for
  10601. \code{block5} (from the previous iteration), which is \code{\{i2\}}.
  10602. So the liveness analysis for \code{block7} remains \code{\{i2,
  10603. sum1\}}. Together these yield the following approximation $m_2$ of
  10604. the live-before sets.
  10605. \begin{center}
  10606. \begin{lstlisting}
  10607. mainstart: {}
  10608. block5: {i2, rsp, sum1}
  10609. block7: {i2, sum1}
  10610. block8: {rsp, sum1}
  10611. \end{lstlisting}
  10612. \end{center}
  10613. In the preceding iteration, only \code{block5} changed, so we can
  10614. limit our attention to \code{mainstart} and \code{block7}, the two
  10615. blocks that jump to \code{block5}. As a result, the live-before sets
  10616. for \code{mainstart} and \code{block7} are updated to include
  10617. \code{rsp}, yielding the following approximation $m_3$.
  10618. \begin{center}
  10619. \begin{lstlisting}
  10620. mainstart: {rsp}
  10621. block5: {i2, rsp, sum1}
  10622. block7: {i2, rsp, sum1}
  10623. block8: {rsp, sum1}
  10624. \end{lstlisting}
  10625. \end{center}
  10626. Because \code{block7} changed, we analyze \code{block5} once more, but
  10627. its live-before set remains \code{\{ i2, rsp, sum1 \}}. At this point
  10628. our approximations have converged, so $m_3$ is the solution.
  10629. This iteration process is guaranteed to converge to a solution by the
  10630. Kleene Fixed-Point Theorem, a general theorem about functions on
  10631. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  10632. any collection that comes with a partial ordering $\sqsubseteq$ on its
  10633. elements, a least element $\bot$ (pronounced bottom), and a join
  10634. operator $\sqcup$.\index{lattice}\index{bottom}\index{partial
  10635. ordering}\index{join}\footnote{Technically speaking, we will be
  10636. working with join semi-lattices.} When two elements are ordered $m_i
  10637. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  10638. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  10639. approximation than $m_i$. The bottom element $\bot$ represents the
  10640. complete lack of information, i.e., the worst approximation. The join
  10641. operator takes two lattice elements and combines their information,
  10642. i.e., it produces the least upper bound of the two.\index{least upper
  10643. bound}
  10644. A dataflow analysis typically involves two lattices: one lattice to
  10645. represent abstract states and another lattice that aggregates the
  10646. abstract states of all the blocks in the control-flow graph. For
  10647. liveness analysis, an abstract state is a set of locations. We form
  10648. the lattice $L$ by taking its elements to be sets of locations, the
  10649. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  10650. set, and the join operator to be set union.
  10651. %
  10652. We form a second lattice $M$ by taking its elements to be mappings
  10653. from the block labels to sets of locations (elements of $L$). We
  10654. order the mappings point-wise, using the ordering of $L$. So given any
  10655. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  10656. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  10657. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  10658. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  10659. We can think of one iteration of liveness analysis as being a function
  10660. $f$ on the lattice $M$. It takes a mapping as input and computes a new
  10661. mapping.
  10662. \[
  10663. f(m_i) = m_{i+1}
  10664. \]
  10665. Next let us think for a moment about what a final solution $m_s$
  10666. should look like. If we perform liveness analysis using the solution
  10667. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  10668. solution should be a \emph{fixed point} of the function $f$.\index{fixed point}
  10669. \[
  10670. f(m_s) = m_s
  10671. \]
  10672. Furthermore, the solution should only include locations that are
  10673. forced to be there by performing liveness analysis on the program, so
  10674. the solution should be the \emph{least} fixed point.\index{least fixed point}
  10675. The Kleene Fixed-Point Theorem states that if a function $f$ is
  10676. monotone (better inputs produce better outputs), then the least fixed
  10677. point of $f$ is the least upper bound of the \emph{ascending Kleene
  10678. chain} obtained by starting at $\bot$ and iterating $f$ as
  10679. follows.\index{Kleene Fixed-Point Theorem}
  10680. \[
  10681. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10682. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  10683. \]
  10684. When a lattice contains only finitely-long ascending chains, then
  10685. every Kleene chain tops out at some fixed point after a number of
  10686. iterations of $f$. So that fixed point is also a least upper
  10687. bound of the chain.
  10688. \[
  10689. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10690. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  10691. \]
  10692. The liveness analysis is indeed a monotone function and the lattice
  10693. $M$ only has finitely-long ascending chains because there are only a
  10694. finite number of variables and blocks in the program. Thus we are
  10695. guaranteed that iteratively applying liveness analysis to all blocks
  10696. in the program will eventually produce the least fixed point solution.
  10697. Next let us consider dataflow analysis in general and discuss the
  10698. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  10699. %
  10700. The algorithm has four parameters: the control-flow graph \code{G}, a
  10701. function \code{transfer} that applies the analysis to one block, the
  10702. \code{bottom} and \code{join} operator for the lattice of abstract
  10703. states. The algorithm begins by creating the bottom mapping,
  10704. represented by a hash table. It then pushes all of the nodes in the
  10705. control-flow graph onto the work list (a queue). The algorithm repeats
  10706. the \code{while} loop as long as there are items in the work list. In
  10707. each iteration, a node is popped from the work list and processed. The
  10708. \code{input} for the node is computed by taking the join of the
  10709. abstract states of all the predecessor nodes. The \code{transfer}
  10710. function is then applied to obtain the \code{output} abstract
  10711. state. If the output differs from the previous state for this block,
  10712. the mapping for this block is updated and its successor nodes are
  10713. pushed onto the work list.
  10714. \begin{figure}[tb]
  10715. \begin{lstlisting}
  10716. (define (analyze-dataflow G transfer bottom join)
  10717. (define mapping (make-hash))
  10718. (for ([v (in-vertices G)])
  10719. (dict-set! mapping v bottom))
  10720. (define worklist (make-queue))
  10721. (for ([v (in-vertices G)])
  10722. (enqueue! worklist v))
  10723. (define trans-G (transpose G))
  10724. (while (not (queue-empty? worklist))
  10725. (define node (dequeue! worklist))
  10726. (define input (for/fold ([state bottom])
  10727. ([pred (in-neighbors trans-G node)])
  10728. (join state (dict-ref mapping pred))))
  10729. (define output (transfer node input))
  10730. (cond [(not (equal? output (dict-ref mapping node)))
  10731. (dict-set! mapping node output)
  10732. (for ([v (in-neighbors G node)])
  10733. (enqueue! worklist v))]))
  10734. mapping)
  10735. \end{lstlisting}
  10736. \caption{Generic work list algorithm for dataflow analysis}
  10737. \label{fig:generic-dataflow}
  10738. \end{figure}
  10739. Having discussed the two complications that arise from adding support
  10740. for assignment and loops, we turn to discussing the one new compiler
  10741. pass and the significant changes to existing passes.
  10742. \section{Convert Assignments}
  10743. \label{sec:convert-assignments}
  10744. Recall that in Section~\ref{sec:assignment-scoping} we learned that
  10745. the combination of assignments and lexically-scoped functions requires
  10746. that we box those variables that are both assigned-to and that appear
  10747. free inside a \code{lambda}. The purpose of the
  10748. \code{convert-assignments} pass is to carry out that transformation.
  10749. We recommend placing this pass after \code{uniquify} but before
  10750. \code{reveal-functions}.
  10751. Consider again the first example from
  10752. Section~\ref{sec:assignment-scoping}:
  10753. \begin{lstlisting}
  10754. (let ([x 0])
  10755. (let ([y 0])
  10756. (let ([z 20])
  10757. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  10758. (begin
  10759. (set! x 10)
  10760. (set! y 12)
  10761. (f y))))))
  10762. \end{lstlisting}
  10763. The variables \code{x} and \code{y} are assigned-to. The variables
  10764. \code{x} and \code{z} occur free inside the \code{lambda}. Thus,
  10765. variable \code{x} needs to be boxed but not \code{y} and \code{z}.
  10766. The boxing of \code{x} consists of three transformations: initialize
  10767. \code{x} with a vector, replace reads from \code{x} with
  10768. \code{vector-ref}'s, and replace each \code{set!} on \code{x} with a
  10769. \code{vector-set!}. The output of \code{convert-assignments} for this
  10770. example is as follows.
  10771. \begin{lstlisting}
  10772. (define (main) : Integer
  10773. (let ([x0 (vector 0)])
  10774. (let ([y1 0])
  10775. (let ([z2 20])
  10776. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  10777. (+ a3 (+ (vector-ref x0 0) z2)))])
  10778. (begin
  10779. (vector-set! x0 0 10)
  10780. (set! y1 12)
  10781. (f4 y1)))))))
  10782. \end{lstlisting}
  10783. \paragraph{Assigned \& Free}
  10784. We recommend defining an auxiliary function named
  10785. \code{assigned\&free} that takes an expression and simultaneously
  10786. computes 1) a set of assigned variables $A$, 2) a set $F$ of variables
  10787. that occur free within lambda's, and 3) a new version of the
  10788. expression that records which bound variables occurred in the
  10789. intersection of $A$ and $F$. You can use the struct
  10790. \code{AssignedFree} to do this. Consider the case for
  10791. $\LET{x}{\itm{rhs}}{\itm{body}}$. Suppose the the recursive call on
  10792. $\itm{rhs}$ produces $\itm{rhs}'$, $A_r$, and $F_r$ and the recursive
  10793. call on the $\itm{body}$ produces $\itm{body}'$, $A_b$, and $F_b$. If
  10794. $x$ is in $A_b\cap F_b$, then transforms the \code{Let} as follows.
  10795. \begin{lstlisting}
  10796. (Let |$x$| |$rhs$| |$body$|)
  10797. |$\Rightarrow$|
  10798. (Let (AssignedFree |$x$|) |$rhs'$| |$body'$|)
  10799. \end{lstlisting}
  10800. If $x$ is not in $A_b\cap F_b$ then omit the use of \code{AssignedFree}.
  10801. The set of assigned variables for this \code{Let} is
  10802. $A_r \cup (A_b - \{x\})$
  10803. and the set of variables free in lambda's is
  10804. $F_r \cup (F_b - \{x\})$.
  10805. The case for $\SETBANG{x}{\itm{rhs}}$ is straightforward but
  10806. important. Recursively process \itm{rhs} to obtain \itm{rhs'}, $A_r$,
  10807. and $F_r$. The result is $\SETBANG{x}{\itm{rhs'}}$, $\{x\} \cup A_r$,
  10808. and $F_r$.
  10809. The case for $\LAMBDA{\itm{params}}{T}{\itm{body}}$ is a bit more
  10810. involved. Let \itm{body'}, $A_b$, and $F_b$ be the result of
  10811. recursively processing \itm{body}. Wrap each of parameter that occurs
  10812. in $A_b \cap F_b$ with \code{AssignedFree} to produce \itm{params'}.
  10813. Let $P$ be the set of parameter names in \itm{params}. The result is
  10814. $\LAMBDA{\itm{params'}}{T}{\itm{body'}}$, $A_b - P$, and $(F_b \cup
  10815. \mathrm{FV}(\itm{body})) - P$, where $\mathrm{FV}$ computes the free
  10816. variables of an expression (see Chapter~\ref{ch:Rlam}).
  10817. \paragraph{Convert Assignments}
  10818. Next we discuss the \code{convert-assignment} pass with its auxiliary
  10819. functions for expressions and definitions. The function for
  10820. expressions, \code{cnvt-assign-exp}, should take an expression and a
  10821. set of assigned-and-free variables (obtained from the result of
  10822. \code{assigned\&free}. In the case for $\VAR{x}$, if $x$ is
  10823. assigned-and-free, then unbox it by translating $\VAR{x}$ to a
  10824. \code{vector-ref}.
  10825. \begin{lstlisting}
  10826. (Var |$x$|)
  10827. |$\Rightarrow$|
  10828. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  10829. \end{lstlisting}
  10830. %
  10831. In the case for $\LET{\LP\code{AssignedFree}\,
  10832. x\RP}{\itm{rhs}}{\itm{body}}$, recursively process \itm{rhs} to
  10833. obtain \itm{rhs'}. Next, recursively process \itm{body} to obtain
  10834. \itm{body'} but with $x$ added to the set of assigned-and-free
  10835. variables. Translate the let-expression as follows to bind $x$ to a
  10836. boxed value.
  10837. \begin{lstlisting}
  10838. (Let (AssignedFree |$x$|) |$rhs$| |$body$|)
  10839. |$\Rightarrow$|
  10840. (Let |$x$| (Prim 'vector (list |$rhs'$|)) |$body'$|)
  10841. \end{lstlisting}
  10842. %
  10843. In the case for $\SETBANG{x}{\itm{rhs}}$, recursively process
  10844. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in the assigned-and-free
  10845. variables, translate the \code{set!} into a \code{vector-set!}
  10846. as follows.
  10847. \begin{lstlisting}
  10848. (SetBang |$x$| |$\itm{rhs}$|)
  10849. |$\Rightarrow$|
  10850. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  10851. \end{lstlisting}
  10852. %
  10853. The case for \code{Lambda} is non-trivial, but it is similar to the
  10854. case for function definitions, which we discuss next.
  10855. The auxiliary function for definitions, \code{cnvt-assign-def},
  10856. applies assignment conversion to function definitions.
  10857. We translate a function definition as follows.
  10858. \begin{lstlisting}
  10859. (Def |$f$| |$\itm{params}$| |$T$| |$\itm{info}$| |$\itm{body_1}$|)
  10860. |$\Rightarrow$|
  10861. (Def |$f$| |$\itm{params'}$| |$T$| |$\itm{info}$| |$\itm{body_4}$|)
  10862. \end{lstlisting}
  10863. So it remains to explain \itm{params'} and $\itm{body}_4$.
  10864. Let \itm{body_2}, $A_b$, and $F_b$ be the result of
  10865. \code{assigned\&free} on $\itm{body_1}$.
  10866. Let $P$ be the parameter names in \itm{params}.
  10867. We then apply \code{cnvt-assign-exp} to $\itm{body_2}$ to
  10868. obtain \itm{body_3}, passing $A_b \cap F_b \cap P$
  10869. as the set of assigned-and-free variables.
  10870. Finally, we obtain \itm{body_4} by wrapping \itm{body_3}
  10871. in a sequence of let-expressions that box the parameters
  10872. that are in $A_b \cap F_b$.
  10873. %
  10874. Regarding \itm{params'}, change the names of the parameters that are
  10875. in $A_b \cap F_b$ to maintain uniqueness (and so the let-bound
  10876. variables can retain the original names). Recall the second example in
  10877. Section~\ref{sec:assignment-scoping} involving a counter
  10878. abstraction. The following is the output of assignment version for
  10879. function \code{f}.
  10880. \begin{lstlisting}
  10881. (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  10882. (vector
  10883. (lambda: () : Integer x1)
  10884. (lambda: () : Void (set! x1 (+ 1 x1)))))
  10885. |$\Rightarrow$|
  10886. (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  10887. (let ([x1 (vector param_x1)])
  10888. (vector (lambda: () : Integer (vector-ref x1 0))
  10889. (lambda: () : Void
  10890. (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  10891. \end{lstlisting}
  10892. \section{Remove Complex Operands}
  10893. \label{sec:rco-loop}
  10894. The three new language forms, \code{while}, \code{set!}, and
  10895. \code{begin} are all complex expressions and their subexpressions are
  10896. allowed to be complex. Figure~\ref{fig:Rfun-anf-syntax} defines the
  10897. output language \LangFunANF{} of this pass.
  10898. \begin{figure}[tp]
  10899. \centering
  10900. \fbox{
  10901. \begin{minipage}{0.96\textwidth}
  10902. \small
  10903. \[
  10904. \begin{array}{rcl}
  10905. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  10906. \mid \VOID{} } \\
  10907. \Exp &::=& \ldots \mid \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  10908. &\mid& \WHILE{\Exp}{\Exp} \mid \SETBANG{\Var}{\Exp}
  10909. \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  10910. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  10911. R^{\dagger}_8 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  10912. \end{array}
  10913. \]
  10914. \end{minipage}
  10915. }
  10916. \caption{\LangLoopANF{} is \LangLoop{} in administrative normal form (ANF).}
  10917. \label{fig:Rwhile-anf-syntax}
  10918. \end{figure}
  10919. As usual, when a complex expression appears in a grammar position that
  10920. needs to be atomic, such as the argument of a primitive operator, we
  10921. must introduce a temporary variable and bind it to the complex
  10922. expression. This approach applies, unchanged, to handle the new
  10923. language forms. For example, in the following code there are two
  10924. \code{begin} expressions appearing as arguments to \code{+}. The
  10925. output of \code{rco-exp} is shown below, in which the \code{begin}
  10926. expressions have been bound to temporary variables. Recall that
  10927. \code{let} expressions in \LangLoopANF{} are allowed to have
  10928. arbitrary expressions in their right-hand-side expression, so it is
  10929. fine to place \code{begin} there.
  10930. \begin{lstlisting}
  10931. (let ([x0 10])
  10932. (let ([y1 0])
  10933. (+ (+ (begin (set! y1 (read)) x0)
  10934. (begin (set! x0 (read)) y1))
  10935. x0)))
  10936. |$\Rightarrow$|
  10937. (let ([x0 10])
  10938. (let ([y1 0])
  10939. (let ([tmp2 (begin (set! y1 (read)) x0)])
  10940. (let ([tmp3 (begin (set! x0 (read)) y1)])
  10941. (let ([tmp4 (+ tmp2 tmp3)])
  10942. (+ tmp4 x0))))))
  10943. \end{lstlisting}
  10944. \section{Explicate Control and \LangCLoop{}}
  10945. \label{sec:explicate-loop}
  10946. Recall that in the \code{explicate-control} pass we define one helper
  10947. function for each kind of position in the program. For the \LangVar{}
  10948. language of integers and variables we needed kinds of positions:
  10949. assignment and tail. The \code{if} expressions of \LangIf{} introduced
  10950. predicate positions. For \LangLoop{}, the \code{begin} expression introduces
  10951. yet another kind of position: effect position. Except for the last
  10952. subexpression, the subexpressions inside a \code{begin} are evaluated
  10953. only for their effect. Their result values are discarded. We can
  10954. generate better code by taking this fact into account.
  10955. The output language of \code{explicate-control} is \LangCLoop{}
  10956. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  10957. \LangCLam{}. The only syntactic difference is that \code{Call},
  10958. \code{vector-set!}, and \code{read} may also appear as statements.
  10959. The most significant difference between \LangCLam{} and \LangCLoop{}
  10960. is that the control-flow graphs of the later may contain cycles.
  10961. \begin{figure}[tp]
  10962. \fbox{
  10963. \begin{minipage}{0.96\textwidth}
  10964. \small
  10965. \[
  10966. \begin{array}{lcl}
  10967. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  10968. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  10969. &\mid& \CALL{\Atm}{\LP\Atm\ldots\RP} \mid \READ{}\\
  10970. &\mid& \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP \\
  10971. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  10972. \LangCLoop{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  10973. \end{array}
  10974. \]
  10975. \end{minipage}
  10976. }
  10977. \caption{The abstract syntax of \LangCLoop{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  10978. \label{fig:c7-syntax}
  10979. \end{figure}
  10980. The new auxiliary function \code{explicate-effect} takes an expression
  10981. (in an effect position) and a promise of a continuation block. The
  10982. function returns a promise for a $\Tail$ that includes the generated
  10983. code for the input expression followed by the continuation block. If
  10984. the expression is obviously pure, that is, never causes side effects,
  10985. then the expression can be removed, so the result is just the
  10986. continuation block.
  10987. %
  10988. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  10989. case. First, you will need a fresh label $\itm{loop}$ for the top of
  10990. the loop. Recursively process the \itm{body} (in effect position)
  10991. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  10992. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  10993. \itm{body'} as the then-branch and the continuation block as the
  10994. else-branch. The result should be added to the control-flow graph with
  10995. the label \itm{loop}. The result for the whole \code{while} loop is a
  10996. \code{goto} to the \itm{loop} label. Note that the loop should only be
  10997. added to the control-flow graph if the loop is indeed used, which can
  10998. be accomplished using \code{delay}.
  10999. The auxiliary functions for tail, assignment, and predicate positions
  11000. need to be updated. The three new language forms, \code{while},
  11001. \code{set!}, and \code{begin}, can appear in assignment and tail
  11002. positions. Only \code{begin} may appear in predicate positions; the
  11003. other two have result type \code{Void}.
  11004. \section{Select Instructions}
  11005. \label{sec:select-instructions-loop}
  11006. Only three small additions are needed in the
  11007. \code{select-instructions} pass to handle the changes to \LangCLoop{}. That
  11008. is, \code{Call}, \code{read}, and \code{vector-set!} may now appear as
  11009. stand-alone statements instead of only appearing on the right-hand
  11010. side of an assignment statement. The code generation is nearly
  11011. identical; just leave off the instruction for moving the result into
  11012. the left-hand side.
  11013. \section{Register Allocation}
  11014. \label{sec:register-allocation-loop}
  11015. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  11016. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  11017. which complicates the liveness analysis needed for register
  11018. allocation.
  11019. \subsection{Liveness Analysis}
  11020. \label{sec:liveness-analysis-r8}
  11021. We recommend using the generic \code{analyze-dataflow} function that
  11022. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  11023. perform liveness analysis, replacing the code in
  11024. \code{uncover-live-CFG} that processed the basic blocks in topological
  11025. order (Section~\ref{sec:liveness-analysis-Rif}).
  11026. The \code{analyze-dataflow} function has four parameters.
  11027. \begin{enumerate}
  11028. \item The first parameter \code{G} should be a directed graph from the
  11029. \code{racket/graph} package (see the sidebar in
  11030. Section~\ref{sec:build-interference}) that represents the
  11031. control-flow graph.
  11032. \item The second parameter \code{transfer} is a function that applies
  11033. liveness analysis to a basic block. It takes two parameters: the
  11034. label for the block to analyze and the live-after set for that
  11035. block. The transfer function should return the live-before set for
  11036. the block. Also, as a side-effect, it should update the block's
  11037. $\itm{info}$ with the liveness information for each instruction. To
  11038. implement the \code{transfer} function, you should be able to reuse
  11039. the code you already have for analyzing basic blocks.
  11040. \item The third and fourth parameters of \code{analyze-dataflow} are
  11041. \code{bottom} and \code{join} for the lattice of abstract states,
  11042. i.e. sets of locations. The bottom of the lattice is the empty set
  11043. \code{(set)} and the join operator is \code{set-union}.
  11044. \end{enumerate}
  11045. \begin{figure}[p]
  11046. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11047. \node (Rfun) at (0,2) {\large \LangLoop{}};
  11048. \node (Rfun-2) at (3,2) {\large \LangLoop{}};
  11049. \node (Rfun-3) at (6,2) {\large \LangLoop{}};
  11050. \node (Rfun-4) at (9,2) {\large \LangLoopFunRef{}};
  11051. \node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  11052. \node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  11053. \node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  11054. \node (F1-4) at (3,0) {\large \LangLoopAlloc{}};
  11055. \node (F1-5) at (0,0) {\large \LangLoopAlloc{}};
  11056. \node (C3-2) at (3,-2) {\large \LangCLoop{}};
  11057. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  11058. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  11059. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  11060. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  11061. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  11062. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  11063. %% \path[->,bend left=15] (Rfun) edge [above] node
  11064. %% {\ttfamily\footnotesize type-check} (Rfun-2);
  11065. \path[->,bend left=15] (Rfun) edge [above] node
  11066. {\ttfamily\footnotesize shrink} (Rfun-2);
  11067. \path[->,bend left=15] (Rfun-2) edge [above] node
  11068. {\ttfamily\footnotesize uniquify} (Rfun-3);
  11069. \path[->,bend left=15] (Rfun-3) edge [above] node
  11070. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  11071. \path[->,bend left=15] (Rfun-4) edge [right] node
  11072. {\ttfamily\footnotesize convert-assignments} (F1-1);
  11073. \path[->,bend left=15] (F1-1) edge [below] node
  11074. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  11075. \path[->,bend right=15] (F1-2) edge [above] node
  11076. {\ttfamily\footnotesize limit-fun.} (F1-3);
  11077. \path[->,bend right=15] (F1-3) edge [above] node
  11078. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  11079. \path[->,bend right=15] (F1-4) edge [above] node
  11080. {\ttfamily\footnotesize remove-complex.} (F1-5);
  11081. \path[->,bend right=15] (F1-5) edge [right] node
  11082. {\ttfamily\footnotesize explicate-control} (C3-2);
  11083. \path[->,bend left=15] (C3-2) edge [left] node
  11084. {\ttfamily\footnotesize select-instr.} (x86-2);
  11085. \path[->,bend right=15] (x86-2) edge [left] node
  11086. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  11087. \path[->,bend right=15] (x86-2-1) edge [below] node
  11088. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  11089. \path[->,bend right=15] (x86-2-2) edge [left] node
  11090. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  11091. \path[->,bend left=15] (x86-3) edge [above] node
  11092. {\ttfamily\footnotesize patch-instr.} (x86-4);
  11093. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  11094. \end{tikzpicture}
  11095. \caption{Diagram of the passes for \LangLoop{} (loops and assignment).}
  11096. \label{fig:Rwhile-passes}
  11097. \end{figure}
  11098. Figure~\ref{fig:Rwhile-passes} provides an overview of all the passes needed
  11099. for the compilation of \LangLoop{}.
  11100. \section{Challenge: Arrays}
  11101. \label{sec:arrays}
  11102. In Chapter~\ref{ch:Rvec} we studied tuples, that is, sequences of
  11103. elements whose length is determined at compile-time and where each
  11104. element of a tuple may have a different type (they are
  11105. heterogeous). This challenge is also about sequences, but this time
  11106. the length is determined at run-time and all the elements have the same
  11107. type (they are homogeneous). We use the term ``array'' for this later
  11108. kind of sequence.
  11109. The Racket language does not distinguish between tuples and arrays,
  11110. they are both represented by vectors. However, Typed Racket
  11111. distinguishes between tuples and arrays: the \code{Vector} type is for
  11112. tuples and the \code{Vectorof} type is for arrays.
  11113. %
  11114. Figure~\ref{fig:Rvecof-concrete-syntax} defines the concrete syntax
  11115. for \LangArray{}, extending \LangLoop{} with the \code{Vectorof} type
  11116. and the \code{make-vector} primitive operator for creating an array,
  11117. whose arguments are the length of the array and an initial value for
  11118. all the elements in the array. The \code{vector-length},
  11119. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  11120. for tuples become overloaded for use with arrays.
  11121. %
  11122. We also include integer multiplication in \LangArray{}, as it is
  11123. useful in many examples involving arrays such as computing the
  11124. inner-product of two arrays (Figure~\ref{fig:inner-product}).
  11125. \begin{figure}[tp]
  11126. \centering
  11127. \fbox{
  11128. \begin{minipage}{0.96\textwidth}
  11129. \small
  11130. \[
  11131. \begin{array}{lcl}
  11132. \Type &::=& \ldots \mid \LP \key{Vectorof}~\Type \RP \\
  11133. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  11134. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \mid \CMUL{\Exp}{\Exp}\\
  11135. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  11136. &\mid& \gray{\key{\#t} \mid \key{\#f}
  11137. \mid \LP\key{and}\;\Exp\;\Exp\RP
  11138. \mid \LP\key{or}\;\Exp\;\Exp\RP
  11139. \mid \LP\key{not}\;\Exp\RP } \\
  11140. &\mid& \gray{ \LP\key{eq?}\;\Exp\;\Exp\RP \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  11141. &\mid& \gray{ \LP\key{vector}\;\Exp\ldots\RP \mid
  11142. \LP\key{vector-ref}\;\Exp\;\Int\RP} \\
  11143. &\mid& \gray{\LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP\mid \LP\key{void}\RP
  11144. \mid \LP\Exp \; \Exp\ldots\RP } \\
  11145. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP
  11146. \mid \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  11147. &\mid& \gray{ \CSETBANG{\Var}{\Exp}
  11148. \mid \CBEGIN{\Exp\ldots}{\Exp}
  11149. \mid \CWHILE{\Exp}{\Exp} } \\
  11150. &\mid& \CMAKEVEC{\Exp}{\Exp} \\
  11151. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  11152. \LangArray{} &::=& \gray{\Def\ldots \; \Exp}
  11153. \end{array}
  11154. \]
  11155. \end{minipage}
  11156. }
  11157. \caption{The concrete syntax of \LangArray{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  11158. \label{fig:Rvecof-concrete-syntax}
  11159. \end{figure}
  11160. \begin{figure}[tp]
  11161. \begin{lstlisting}
  11162. (define (inner-product [A : (Vectorof Integer)] [B : (Vectorof Integer)]
  11163. [n : Integer]) : Integer
  11164. (let ([i 0])
  11165. (let ([prod 0])
  11166. (begin
  11167. (while (< i n)
  11168. (begin
  11169. (set! prod (+ prod (* (vector-ref A i)
  11170. (vector-ref B i))))
  11171. (set! i (+ i 1))
  11172. ))
  11173. prod))))
  11174. (let ([A (make-vector 2 2)])
  11175. (let ([B (make-vector 2 3)])
  11176. (+ (inner-product A B 2)
  11177. 30)))
  11178. \end{lstlisting}
  11179. \caption{Example program that computes the inner-product.}
  11180. \label{fig:inner-product}
  11181. \end{figure}
  11182. The type checker for \LangArray{} is define in
  11183. Figure~\ref{fig:type-check-Rvecof}. The result type of
  11184. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  11185. of the intializing expression. The length expression is required to
  11186. have type \code{Integer}. The type checking of the operators
  11187. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  11188. updated to handle the situation where the vector has type
  11189. \code{Vectorof}. In these cases we translate the operators to their
  11190. \code{vectorof} form so that later passes can easily distinguish
  11191. between operations on tuples versus arrays. We override the
  11192. \code{operator-types} method to provide the type signature for
  11193. multiplication: it takes two integers and returns an integer. To
  11194. support injection and projection of arrays to the \code{Any} type
  11195. (Section~\ref{sec:Rany-lang}), we also override the \code{flat-ty?}
  11196. predicate.
  11197. \begin{figure}[tbp]
  11198. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11199. (define type-check-Rvecof-class
  11200. (class type-check-Rwhile-class
  11201. (super-new)
  11202. (inherit check-type-equal?)
  11203. (define/override (flat-ty? ty)
  11204. (match ty
  11205. ['(Vectorof Any) #t]
  11206. [else (super flat-ty? ty)]))
  11207. (define/override (operator-types)
  11208. (append '((* . ((Integer Integer) . Integer)))
  11209. (super operator-types)))
  11210. (define/override (type-check-exp env)
  11211. (lambda (e)
  11212. (define recur (type-check-exp env))
  11213. (match e
  11214. [(Prim 'make-vector (list e1 e2))
  11215. (define-values (e1^ t1) (recur e1))
  11216. (define-values (e2^ elt-type) (recur e2))
  11217. (define vec-type `(Vectorof ,elt-type))
  11218. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  11219. vec-type)]
  11220. [(Prim 'vector-ref (list e1 e2))
  11221. (define-values (e1^ t1) (recur e1))
  11222. (define-values (e2^ t2) (recur e2))
  11223. (match* (t1 t2)
  11224. [(`(Vectorof ,elt-type) 'Integer)
  11225. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  11226. [(other wise) ((super type-check-exp env) e)])]
  11227. [(Prim 'vector-set! (list e1 e2 e3) )
  11228. (define-values (e-vec t-vec) (recur e1))
  11229. (define-values (e2^ t2) (recur e2))
  11230. (define-values (e-arg^ t-arg) (recur e3))
  11231. (match t-vec
  11232. [`(Vectorof ,elt-type)
  11233. (check-type-equal? elt-type t-arg e)
  11234. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  11235. [else ((super type-check-exp env) e)])]
  11236. [(Prim 'vector-length (list e1))
  11237. (define-values (e1^ t1) (recur e1))
  11238. (match t1
  11239. [`(Vectorof ,t)
  11240. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  11241. [else ((super type-check-exp env) e)])]
  11242. [else ((super type-check-exp env) e)])))
  11243. ))
  11244. (define (type-check-Rvecof p)
  11245. (send (new type-check-Rvecof-class) type-check-program p))
  11246. \end{lstlisting}
  11247. \caption{Type checker for the \LangArray{} language.}
  11248. \label{fig:type-check-Rvecof}
  11249. \end{figure}
  11250. The interpreter for \LangArray{} is defined in
  11251. Figure~\ref{fig:interp-Rvecof}. The \code{make-vector} operator is
  11252. implemented with Racket's \code{make-vector} function and
  11253. multiplication is \code{fx*}, multiplication for \code{fixnum}
  11254. integers.
  11255. \begin{figure}[tbp]
  11256. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11257. (define interp-Rvecof-class
  11258. (class interp-Rwhile-class
  11259. (super-new)
  11260. (define/override (interp-op op)
  11261. (verbose "Rvecof/interp-op" op)
  11262. (match op
  11263. ['make-vector make-vector]
  11264. ['* fx*]
  11265. [else (super interp-op op)]))
  11266. ))
  11267. (define (interp-Rvecof p)
  11268. (send (new interp-Rvecof-class) interp-program p))
  11269. \end{lstlisting}
  11270. \caption{Interpreter for \LangArray{}.}
  11271. \label{fig:interp-Rvecof}
  11272. \end{figure}
  11273. \subsection{Data Representation}
  11274. \label{sec:array-rep}
  11275. Just like tuples, we store arrays on the heap which means that the
  11276. garbage collector will need to inspect arrays. An immediate thought is
  11277. to use the same representation for arrays that we use for tuples.
  11278. However, we limit tuples to a length of $50$ so that their length and
  11279. pointer mask can fit into the 64-bit tag at the beginning of each
  11280. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  11281. millions of elements, so we need more bits to store the length.
  11282. However, because arrays are homogeneous, we only need $1$ bit for the
  11283. pointer mask instead of one bit per array elements. Finally, the
  11284. garbage collector will need to be able to distinguish between tuples
  11285. and arrays, so we need to reserve $1$ bit for that purpose. So we
  11286. arrive at the following layout for the 64-bit tag at the beginning of
  11287. an array:
  11288. \begin{itemize}
  11289. \item The right-most bit is the forwarding bit, just like in a tuple.
  11290. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  11291. it is not.
  11292. \item The next bit to the left is the pointer mask. A $0$ indicates
  11293. that none of the elements are pointers to the heap and a $1$
  11294. indicates that all of the elements are pointers.
  11295. \item The next $61$ bits store the length of the array.
  11296. \item The left-most bit distinguishes between a tuple ($0$) versus an
  11297. array ($1$).
  11298. \end{itemize}
  11299. Recall that in Chapter~\ref{ch:Rdyn}, we use a $3$-bit tag to
  11300. differentiate the kinds of values that have been injected into the
  11301. \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  11302. to indicate that the value is an array.
  11303. In the following subsections we provide hints regarding how to update
  11304. the passes to handle arrays.
  11305. \subsection{Reveal Casts}
  11306. The array-access operators \code{vectorof-ref} and
  11307. \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  11308. \code{any-vector-set!} operators of Chapter~\ref{ch:Rdyn} in
  11309. that the type checker cannot tell whether the index will be in bounds,
  11310. so the bounds check must be performed at run time. Recall that the
  11311. \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  11312. an \code{If} arround a vector reference for update to check whether
  11313. the index is less than the length. You should do the same for
  11314. \code{vectorof-ref} and \code{vectorof-set!} .
  11315. In addition, the handling of the \code{any-vector} operators in
  11316. \code{reveal-casts} needs to be updated to account for arrays that are
  11317. injected to \code{Any}. For the \code{any-vector-length} operator, the
  11318. generated code should test whether the tag is for tuples (\code{010})
  11319. or arrays (\code{110}) and then dispatch to either
  11320. \code{any-vector-length} or \code{any-vectorof-length}. For the later
  11321. we add a case in \code{select-instructions} to generate the
  11322. appropriate instructions for accessing the array length from the
  11323. header of an array.
  11324. For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  11325. the generated code needs to check that the index is less than the
  11326. vector length, so like the code for \code{any-vector-length}, check
  11327. the tag to determine whether to use \code{any-vector-length} or
  11328. \code{any-vectorof-length} for this purpose. Once the bounds checking
  11329. is complete, the generated code can use \code{any-vector-ref} and
  11330. \code{any-vector-set!} for both tuples and arrays because the
  11331. instructions used for those operators do not look at the tag at the
  11332. front of the tuple or array.
  11333. \subsection{Expose Allocation}
  11334. This pass should translate the \code{make-vector} operator into
  11335. lower-level operations. In particular, the new AST node
  11336. $\LP\key{AllocateArray}~\Exp~\Type\RP$ allocates an array of the
  11337. length specified by the $\Exp$, but does not initialize the elements
  11338. of the array. (Analogous to the \code{Allocate} AST node for tuples.)
  11339. The $\Type$ argument must be $\LP\key{Vectorof}~T\RP$ where $T$ is the
  11340. element type for the array. Regarding the initialization of the array,
  11341. we recommend generated a \code{while} loop that uses
  11342. \code{vector-set!} to put the initializing value into every element of
  11343. the array.
  11344. \subsection{Remove Complex Operands}
  11345. Add cases in the \code{rco-atom} and \code{rco-exp} for
  11346. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  11347. complex and its subexpression must be atomic.
  11348. \subsection{Explicate Control}
  11349. Add cases for \code{AllocateArray} to \code{explicate-tail} and
  11350. \code{explicate-assign}.
  11351. \subsection{Select Instructions}
  11352. Generate instructions for \code{AllocateArray} similar to those for
  11353. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  11354. that the tag at the front of the array should instead use the
  11355. representation discussed in Section~\ref{sec:array-rep}.
  11356. Regarding \code{vectorof-length}, extract the length from the tag
  11357. according to the representation discussed in
  11358. Section~\ref{sec:array-rep}.
  11359. The instructions generated for \code{vectorof-ref} differ from those
  11360. for \code{vector-ref} (Section~\ref{sec:select-instructions-gc}) in
  11361. that the index is not a constant so the offset must be computed at
  11362. runtime, similar to the instructions generated for
  11363. \code{any-vector-of-ref} (Section~\ref{sec:select-Rany}). The same is
  11364. true for \code{vectorof-set!}. Also, the \code{vectorof-set!} may
  11365. appear in an assignment and as a stand-alone statement, so make sure
  11366. to handle both situations in this pass.
  11367. Finally, the instructions for \code{any-vectorof-length} should be
  11368. similar to those for \code{vectorof-length}, except that one must
  11369. first project the array by writing zeroes into the $3$-bit tag
  11370. \begin{exercise}\normalfont
  11371. Implement a compiler for the \LangArray{} language by extending your
  11372. compiler for \LangLoop{}. Test your compiler on a half dozen new
  11373. programs, including the one in Figure~\ref{fig:inner-product} and also
  11374. a program that multiplies two matrices. Note that matrices are
  11375. 2-dimensional arrays, but those can be encoded into 1-dimensional
  11376. arrays by laying out each row in the array, one after the next.
  11377. \end{exercise}
  11378. % Further Reading: dataflow analysis
  11379. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11380. \chapter{Gradual Typing}
  11381. \label{ch:Rgrad}
  11382. \index{gradual typing}
  11383. This chapter studies a language, \LangGrad{}, in which the programmer
  11384. can choose between static and dynamic type checking in different parts
  11385. of a program, thereby mixing the statically typed \LangLoop{} language
  11386. with the dynamically typed \LangDyn{}. There are several approaches to
  11387. mixing static and dynamic typing, including multi-language
  11388. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  11389. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  11390. we focus on \emph{gradual typing}\index{gradual typing}, in which the
  11391. programmer controls the amount of static versus dynamic checking by
  11392. adding or removing type annotations on parameters and
  11393. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  11394. %
  11395. The concrete syntax of \LangGrad{} is defined in
  11396. Figure~\ref{fig:Rgrad-concrete-syntax} and its abstract syntax is defined
  11397. in Figure~\ref{fig:Rgrad-syntax}. The main syntactic difference between
  11398. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  11399. non-terminals that make type annotations optional. The return types
  11400. are not optional in the abstract syntax; the parser fills in
  11401. \code{Any} when the return type is not specified in the concrete
  11402. syntax.
  11403. \begin{figure}[tp]
  11404. \centering
  11405. \fbox{
  11406. \begin{minipage}{0.96\textwidth}
  11407. \small
  11408. \[
  11409. \begin{array}{lcl}
  11410. \itm{param} &::=& \Var \mid \LS\Var \key{:} \Type\RS \\
  11411. \itm{ret} &::=& \epsilon \mid \key{:} \Type \\
  11412. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  11413. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  11414. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  11415. &\mid& \gray{\key{\#t} \mid \key{\#f}
  11416. \mid (\key{and}\;\Exp\;\Exp)
  11417. \mid (\key{or}\;\Exp\;\Exp)
  11418. \mid (\key{not}\;\Exp) } \\
  11419. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  11420. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  11421. (\key{vector-ref}\;\Exp\;\Int)} \\
  11422. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  11423. \mid (\Exp \; \Exp\ldots) } \\
  11424. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  11425. \mid \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  11426. &\mid& \gray{ \CSETBANG{\Var}{\Exp}
  11427. \mid \CBEGIN{\Exp\ldots}{\Exp}
  11428. \mid \CWHILE{\Exp}{\Exp} } \\
  11429. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  11430. \LangGrad{} &::=& \gray{\Def\ldots \; \Exp}
  11431. \end{array}
  11432. \]
  11433. \end{minipage}
  11434. }
  11435. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  11436. \label{fig:Rgrad-concrete-syntax}
  11437. \end{figure}
  11438. \begin{figure}[tp]
  11439. \centering
  11440. \fbox{
  11441. \begin{minipage}{0.96\textwidth}
  11442. \small
  11443. \[
  11444. \begin{array}{lcl}
  11445. \itm{param} &::=& \Var \mid \LS\Var \key{:} \Type\RS \\
  11446. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  11447. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  11448. &\mid& \gray{ \BOOL{\itm{bool}}
  11449. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  11450. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  11451. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  11452. &\mid& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  11453. &\mid& \gray{ \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  11454. &\mid& \gray{ \WHILE{\Exp}{\Exp} } \\
  11455. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  11456. \LangGrad{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11457. \end{array}
  11458. \]
  11459. \end{minipage}
  11460. }
  11461. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  11462. \label{fig:Rgrad-syntax}
  11463. \end{figure}
  11464. Both the type checker and the interpreter for \LangGrad{} require some
  11465. interesting changes to enable gradual typing, which we discuss in the
  11466. next two sections in the context of the \code{map-vec} example from
  11467. Chapter~\ref{ch:Rfun}. In Figure~\ref{fig:gradual-map-vec} we
  11468. revised the \code{map-vec} example, omitting the type annotations from
  11469. the \code{add1} function.
  11470. \begin{figure}[btp]
  11471. % gradual_test_9.rkt
  11472. \begin{lstlisting}
  11473. (define (map-vec [f : (Integer -> Integer)]
  11474. [v : (Vector Integer Integer)])
  11475. : (Vector Integer Integer)
  11476. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11477. (define (add1 x) (+ x 1))
  11478. (vector-ref (map-vec add1 (vector 0 41)) 1)
  11479. \end{lstlisting}
  11480. \caption{A partially-typed version of the \code{map-vec} example.}
  11481. \label{fig:gradual-map-vec}
  11482. \end{figure}
  11483. \section{Type Checking \LangGrad{}, Casts, and \LangCast{}}
  11484. \label{sec:gradual-type-check}
  11485. The type checker for \LangGrad{} uses the \code{Any} type for missing
  11486. parameter and return types. For example, the \code{x} parameter of
  11487. \code{add1} in Figure~\ref{fig:gradual-map-vec} is given the type
  11488. \code{Any} and the return type of \code{add1} is \code{Any}. Next
  11489. consider the \code{+} operator inside \code{add1}. It expects both
  11490. arguments to have type \code{Integer}, but its first argument \code{x}
  11491. has type \code{Any}. In a gradually typed language, such differences
  11492. are allowed so long as the types are \emph{consistent}, that is, they
  11493. are equal except in places where there is an \code{Any} type. The type
  11494. \code{Any} is consistent with every other type.
  11495. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  11496. \begin{figure}[tbp]
  11497. \begin{lstlisting}
  11498. (define/public (consistent? t1 t2)
  11499. (match* (t1 t2)
  11500. [('Integer 'Integer) #t]
  11501. [('Boolean 'Boolean) #t]
  11502. [('Void 'Void) #t]
  11503. [('Any t2) #t]
  11504. [(t1 'Any) #t]
  11505. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11506. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  11507. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11508. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  11509. (consistent? rt1 rt2))]
  11510. [(other wise) #f]))
  11511. \end{lstlisting}
  11512. \caption{The consistency predicate on types.}
  11513. \label{fig:consistent}
  11514. \end{figure}
  11515. Returning to the \code{map-vec} example of
  11516. Figure~\ref{fig:gradual-map-vec}, the \code{add1} function has type
  11517. \code{(Any -> Any)} but parameter \code{f} of \code{map-vec} has type
  11518. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  11519. because the two types are consistent. In particular, \code{->} is
  11520. equal to \code{->} and because \code{Any} is consistent with
  11521. \code{Integer}.
  11522. Next consider a program with an error, such as applying the
  11523. \code{map-vec} to a function that sometimes returns a Boolean, as
  11524. shown in Figure~\ref{fig:map-vec-maybe-add1}. The type checker for
  11525. \LangGrad{} accepts this program because the type of \code{maybe-add1} is
  11526. consistent with the type of parameter \code{f} of \code{map-vec}, that
  11527. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  11528. Integer)}. One might say that a gradual type checker is optimistic
  11529. in that it accepts programs that might execute without a runtime type
  11530. error.
  11531. %
  11532. Unfortunately, running this program with input \code{1} triggers an
  11533. error when the \code{maybe-add1} function returns \code{\#t}. \LangGrad{}
  11534. performs checking at runtime to ensure the integrity of the static
  11535. types, such as the \code{(Integer -> Integer)} annotation on parameter
  11536. \code{f} of \code{map-vec}. This runtime checking is carried out by a
  11537. new \code{Cast} form that is inserted by the type checker. Thus, the
  11538. output of the type checker is a program in the \LangCast{} language, which
  11539. adds \code{Cast} to \LangLoop{}, as shown in
  11540. Figure~\ref{fig:Rgrad-prime-syntax}.
  11541. \begin{figure}[tp]
  11542. \centering
  11543. \fbox{
  11544. \begin{minipage}{0.96\textwidth}
  11545. \small
  11546. \[
  11547. \begin{array}{lcl}
  11548. \Exp &::=& \ldots \mid \CAST{\Exp}{\Type}{\Type} \\
  11549. \LangCast{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11550. \end{array}
  11551. \]
  11552. \end{minipage}
  11553. }
  11554. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  11555. \label{fig:Rgrad-prime-syntax}
  11556. \end{figure}
  11557. \begin{figure}[tbp]
  11558. \begin{lstlisting}
  11559. (define (map-vec [f : (Integer -> Integer)]
  11560. [v : (Vector Integer Integer)])
  11561. : (Vector Integer Integer)
  11562. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11563. (define (add1 x) (+ x 1))
  11564. (define (true) #t)
  11565. (define (maybe-add1 x) (if (eq? 0 (read)) (add1 x) (true)))
  11566. (vector-ref (map-vec maybe-add1 (vector 0 41)) 0)
  11567. \end{lstlisting}
  11568. \caption{A variant of the \code{map-vec} example with an error.}
  11569. \label{fig:map-vec-maybe-add1}
  11570. \end{figure}
  11571. Figure~\ref{fig:map-vec-cast} shows the output of the type checker for
  11572. \code{map-vec} and \code{maybe-add1}. The idea is that \code{Cast} is
  11573. inserted every time the type checker sees two types that are
  11574. consistent but not equal. In the \code{add1} function, \code{x} is
  11575. cast to \code{Integer} and the result of the \code{+} is cast to
  11576. \code{Any}. In the call to \code{map-vec}, the \code{add1} argument
  11577. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  11578. \begin{figure}[btp]
  11579. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11580. (define (map-vec [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  11581. : (Vector Integer Integer)
  11582. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11583. (define (add1 [x : Any]) : Any
  11584. (cast (+ (cast x Any Integer) 1) Integer Any))
  11585. (define (true) : Any (cast #t Boolean Any))
  11586. (define (maybe-add1 [x : Any]) : Any
  11587. (if (eq? 0 (read)) (add1 x) (true)))
  11588. (vector-ref (map-vec (cast maybe-add1 (Any -> Any) (Integer -> Integer))
  11589. (vector 0 41)) 0)
  11590. \end{lstlisting}
  11591. \caption{Output of type checking \code{map-vec}
  11592. and \code{maybe-add1}.}
  11593. \label{fig:map-vec-cast}
  11594. \end{figure}
  11595. The type checker for \LangGrad{} is defined in
  11596. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  11597. and \ref{fig:type-check-Rgradual-3}.
  11598. \begin{figure}[tbp]
  11599. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11600. (define type-check-gradual-class
  11601. (class type-check-Rwhile-class
  11602. (super-new)
  11603. (inherit operator-types type-predicates)
  11604. (define/override (type-check-exp env)
  11605. (lambda (e)
  11606. (define recur (type-check-exp env))
  11607. (match e
  11608. [(Prim 'vector-length (list e1))
  11609. (define-values (e1^ t) (recur e1))
  11610. (match t
  11611. [`(Vector ,ts ...)
  11612. (values (Prim 'vector-length (list e1^)) 'Integer)]
  11613. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  11614. [(Prim 'vector-ref (list e1 e2))
  11615. (define-values (e1^ t1) (recur e1))
  11616. (define-values (e2^ t2) (recur e2))
  11617. (check-consistent? t2 'Integer e)
  11618. (match t1
  11619. [`(Vector ,ts ...)
  11620. (match e2^
  11621. [(Int i)
  11622. (unless (and (0 . <= . i) (i . < . (length ts)))
  11623. (error 'type-check "invalid index ~a in ~a" i e))
  11624. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  11625. [else (define e1^^ (make-cast e1^ t1 'Any))
  11626. (define e2^^ (make-cast e2^ t2 'Integer))
  11627. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  11628. ['Any
  11629. (define e2^^ (make-cast e2^ t2 'Integer))
  11630. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  11631. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  11632. [(Prim 'vector-set! (list e1 e2 e3) )
  11633. (define-values (e1^ t1) (recur e1))
  11634. (define-values (e2^ t2) (recur e2))
  11635. (define-values (e3^ t3) (recur e3))
  11636. (check-consistent? t2 'Integer e)
  11637. (match t1
  11638. [`(Vector ,ts ...)
  11639. (match e2^
  11640. [(Int i)
  11641. (unless (and (0 . <= . i) (i . < . (length ts)))
  11642. (error 'type-check "invalid index ~a in ~a" i e))
  11643. (check-consistent? (list-ref ts i) t3 e)
  11644. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  11645. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  11646. [else
  11647. (define e1^^ (make-cast e1^ t1 'Any))
  11648. (define e2^^ (make-cast e2^ t2 'Integer))
  11649. (define e3^^ (make-cast e3^ t3 'Any))
  11650. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  11651. ['Any
  11652. (define e2^^ (make-cast e2^ t2 'Integer))
  11653. (define e3^^ (make-cast e3^ t3 'Any))
  11654. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  11655. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  11656. \end{lstlisting}
  11657. \caption{Type checker for the \LangGrad{} language, part 1.}
  11658. \label{fig:type-check-Rgradual-1}
  11659. \end{figure}
  11660. \begin{figure}[tbp]
  11661. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11662. [(Prim 'eq? (list e1 e2))
  11663. (define-values (e1^ t1) (recur e1))
  11664. (define-values (e2^ t2) (recur e2))
  11665. (check-consistent? t1 t2 e)
  11666. (define T (meet t1 t2))
  11667. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  11668. 'Boolean)]
  11669. [(Prim 'not (list e1))
  11670. (define-values (e1^ t1) (recur e1))
  11671. (match t1
  11672. ['Any
  11673. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  11674. (Bool #t) (Bool #f)))]
  11675. [else
  11676. (define-values (t-ret new-es^)
  11677. (type-check-op 'not (list t1) (list e1^) e))
  11678. (values (Prim 'not new-es^) t-ret)])]
  11679. [(Prim 'and (list e1 e2))
  11680. (recur (If e1 e2 (Bool #f)))]
  11681. [(Prim 'or (list e1 e2))
  11682. (define tmp (gensym 'tmp))
  11683. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  11684. [(Prim op es)
  11685. #:when (not (set-member? explicit-prim-ops op))
  11686. (define-values (new-es ts)
  11687. (for/lists (exprs types) ([e es])
  11688. (recur e)))
  11689. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  11690. (values (Prim op new-es^) t-ret)]
  11691. [(If e1 e2 e3)
  11692. (define-values (e1^ T1) (recur e1))
  11693. (define-values (e2^ T2) (recur e2))
  11694. (define-values (e3^ T3) (recur e3))
  11695. (check-consistent? T2 T3 e)
  11696. (match T1
  11697. ['Boolean
  11698. (define Tif (join T2 T3))
  11699. (values (If e1^ (make-cast e2^ T2 Tif)
  11700. (make-cast e3^ T3 Tif)) Tif)]
  11701. ['Any
  11702. (define Tif (meet T2 T3))
  11703. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  11704. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  11705. Tif)]
  11706. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  11707. [(HasType e1 T)
  11708. (define-values (e1^ T1) (recur e1))
  11709. (check-consistent? T1 T)
  11710. (values (make-cast e1^ T1 T) T)]
  11711. [(SetBang x e1)
  11712. (define-values (e1^ T1) (recur e1))
  11713. (define varT (dict-ref env x))
  11714. (check-consistent? T1 varT e)
  11715. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  11716. [(WhileLoop e1 e2)
  11717. (define-values (e1^ T1) (recur e1))
  11718. (check-consistent? T1 'Boolean e)
  11719. (define-values (e2^ T2) ((type-check-exp env) e2))
  11720. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  11721. \end{lstlisting}
  11722. \caption{Type checker for the \LangGrad{} language, part 2.}
  11723. \label{fig:type-check-Rgradual-2}
  11724. \end{figure}
  11725. \begin{figure}[tbp]
  11726. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11727. [(Apply e1 e2s)
  11728. (define-values (e1^ T1) (recur e1))
  11729. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  11730. (match T1
  11731. [`(,T1ps ... -> ,T1rt)
  11732. (for ([T2 T2s] [Tp T1ps])
  11733. (check-consistent? T2 Tp e))
  11734. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  11735. (make-cast e2 src tgt)))
  11736. (values (Apply e1^ e2s^^) T1rt)]
  11737. [`Any
  11738. (define e1^^ (make-cast e1^ 'Any
  11739. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  11740. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  11741. (make-cast e2 src 'Any)))
  11742. (values (Apply e1^^ e2s^^) 'Any)]
  11743. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  11744. [(Lambda params Tr e1)
  11745. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  11746. (match p
  11747. [`[,x : ,T] (values x T)]
  11748. [(? symbol? x) (values x 'Any)])))
  11749. (define-values (e1^ T1)
  11750. ((type-check-exp (append (map cons xs Ts) env)) e1))
  11751. (check-consistent? Tr T1 e)
  11752. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  11753. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  11754. [else ((super type-check-exp env) e)]
  11755. )))
  11756. \end{lstlisting}
  11757. \caption{Type checker for the \LangGrad{} language, part 3.}
  11758. \label{fig:type-check-Rgradual-3}
  11759. \end{figure}
  11760. \begin{figure}[tbp]
  11761. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11762. (define/public (join t1 t2)
  11763. (match* (t1 t2)
  11764. [('Integer 'Integer) 'Integer]
  11765. [('Boolean 'Boolean) 'Boolean]
  11766. [('Void 'Void) 'Void]
  11767. [('Any t2) t2]
  11768. [(t1 'Any) t1]
  11769. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11770. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  11771. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11772. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  11773. -> ,(join rt1 rt2))]))
  11774. (define/public (meet t1 t2)
  11775. (match* (t1 t2)
  11776. [('Integer 'Integer) 'Integer]
  11777. [('Boolean 'Boolean) 'Boolean]
  11778. [('Void 'Void) 'Void]
  11779. [('Any t2) 'Any]
  11780. [(t1 'Any) 'Any]
  11781. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11782. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  11783. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11784. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  11785. -> ,(meet rt1 rt2))]))
  11786. (define/public (make-cast e src tgt)
  11787. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  11788. (define/public (check-consistent? t1 t2 e)
  11789. (unless (consistent? t1 t2)
  11790. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  11791. (define/override (type-check-op op arg-types args e)
  11792. (match (dict-ref (operator-types) op)
  11793. [`(,param-types . ,return-type)
  11794. (for ([at arg-types] [pt param-types])
  11795. (check-consistent? at pt e))
  11796. (values return-type
  11797. (for/list ([e args] [s arg-types] [t param-types])
  11798. (make-cast e s t)))]
  11799. [else (error 'type-check-op "unrecognized ~a" op)]))
  11800. (define explicit-prim-ops
  11801. (set-union
  11802. (type-predicates)
  11803. (set 'procedure-arity 'eq?
  11804. 'vector 'vector-length 'vector-ref 'vector-set!
  11805. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  11806. (define/override (fun-def-type d)
  11807. (match d
  11808. [(Def f params rt info body)
  11809. (define ps
  11810. (for/list ([p params])
  11811. (match p
  11812. [`[,x : ,T] T]
  11813. [(? symbol?) 'Any]
  11814. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  11815. `(,@ps -> ,rt)]
  11816. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  11817. \end{lstlisting}
  11818. \caption{Auxiliary functions for type checking \LangGrad{}.}
  11819. \label{fig:type-check-Rgradual-aux}
  11820. \end{figure}
  11821. \clearpage
  11822. \section{Interpreting \LangCast{}}
  11823. \label{sec:interp-casts}
  11824. The runtime behavior of first-order casts is straightforward, that is,
  11825. casts involving simple types such as \code{Integer} and
  11826. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  11827. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  11828. puts the integer into a tagged value
  11829. (Figure~\ref{fig:interp-Rany}). Similarly, a cast from \code{Any} to
  11830. \code{Integer} is accomplished with the \code{Project} operator, that
  11831. is, by checking the value's tag and either retrieving the underlying
  11832. integer or signaling an error if it the tag is not the one for
  11833. integers (Figure~\ref{fig:apply-project}).
  11834. %
  11835. Things get more interesting for higher-order casts, that is, casts
  11836. involving function or vector types.
  11837. Consider the cast of the function \code{maybe-add1} from \code{(Any ->
  11838. Any)} to \code{(Integer -> Integer)}. When a function flows through
  11839. this cast at runtime, we can't know in general whether the function
  11840. will always return an integer.\footnote{Predicting the return value of
  11841. a function is equivalent to the halting problem, which is
  11842. undecidable.} The \LangCast{} interpreter therefore delays the checking
  11843. of the cast until the function is applied. This is accomplished by
  11844. wrapping \code{maybe-add1} in a new function that casts its parameter
  11845. from \code{Integer} to \code{Any}, applies \code{maybe-add1}, and then
  11846. casts the return value from \code{Any} to \code{Integer}.
  11847. Turning our attention to casts involving vector types, we consider the
  11848. example in Figure~\ref{fig:map-vec-bang} that defines a
  11849. partially-typed version of \code{map-vec} whose parameter \code{v} has
  11850. type \code{(Vector Any Any)} and that updates \code{v} in place
  11851. instead of returning a new vector. So we name this function
  11852. \code{map-vec!}. We apply \code{map-vec!} to a vector of integers, so
  11853. the type checker inserts a cast from \code{(Vector Integer Integer)}
  11854. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  11855. cast between vector types would be a build a new vector whose elements
  11856. are the result of casting each of the original elements to the
  11857. appropriate target type. However, this approach is only valid for
  11858. immutable vectors; and our vectors are mutable. In the example of
  11859. Figure~\ref{fig:map-vec-bang}, if the cast created a new vector, then
  11860. the updates inside of \code{map-vec!} would happen to the new vector
  11861. and not the original one.
  11862. \begin{figure}[tbp]
  11863. % gradual_test_11.rkt
  11864. \begin{lstlisting}
  11865. (define (map-vec! [f : (Any -> Any)]
  11866. [v : (Vector Any Any)]) : Void
  11867. (begin
  11868. (vector-set! v 0 (f (vector-ref v 0)))
  11869. (vector-set! v 1 (f (vector-ref v 1)))))
  11870. (define (add1 x) (+ x 1))
  11871. (let ([v (vector 0 41)])
  11872. (begin (map-vec! add1 v) (vector-ref v 1)))
  11873. \end{lstlisting}
  11874. \caption{An example involving casts on vectors.}
  11875. \label{fig:map-vec-bang}
  11876. \end{figure}
  11877. Instead the interpreter needs to create a new kind of value, a
  11878. \emph{vector proxy}, that intercepts every vector operation. On a
  11879. read, the proxy reads from the underlying vector and then applies a
  11880. cast to the resulting value. On a write, the proxy casts the argument
  11881. value and then performs the write to the underlying vector. For the
  11882. first \code{(vector-ref v 0)} in \code{map-vec!}, the proxy casts
  11883. \code{0} from \code{Integer} to \code{Any}. For the first
  11884. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  11885. to \code{Integer}.
  11886. The final category of cast that we need to consider are casts between
  11887. the \code{Any} type and either a function or a vector
  11888. type. Figure~\ref{fig:map-vec-any} shows a variant of \code{map-vec!}
  11889. in which parameter \code{v} does not have a type annotation, so it is
  11890. given type \code{Any}. In the call to \code{map-vec!}, the vector has
  11891. type \code{(Vector Integer Integer)} so the type checker inserts a
  11892. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  11893. thought is to use \code{Inject}, but that doesn't work because
  11894. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  11895. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  11896. to \code{Any}.
  11897. \begin{figure}[tbp]
  11898. \begin{lstlisting}
  11899. (define (map-vec! [f : (Any -> Any)] v) : Void
  11900. (begin
  11901. (vector-set! v 0 (f (vector-ref v 0)))
  11902. (vector-set! v 1 (f (vector-ref v 1)))))
  11903. (define (add1 x) (+ x 1))
  11904. (let ([v (vector 0 41)])
  11905. (begin (map-vec! add1 v) (vector-ref v 1)))
  11906. \end{lstlisting}
  11907. \caption{Casting a vector to \code{Any}.}
  11908. \label{fig:map-vec-any}
  11909. \end{figure}
  11910. The \LangCast{} interpreter uses an auxiliary function named
  11911. \code{apply-cast} to cast a value from a source type to a target type,
  11912. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  11913. of the kinds of casts that we've discussed in this section.
  11914. \begin{figure}[tbp]
  11915. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11916. (define/public (apply-cast v s t)
  11917. (match* (s t)
  11918. [(t1 t2) #:when (equal? t1 t2) v]
  11919. [('Any t2)
  11920. (match t2
  11921. [`(,ts ... -> ,rt)
  11922. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  11923. (define v^ (apply-project v any->any))
  11924. (apply-cast v^ any->any `(,@ts -> ,rt))]
  11925. [`(Vector ,ts ...)
  11926. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  11927. (define v^ (apply-project v vec-any))
  11928. (apply-cast v^ vec-any `(Vector ,@ts))]
  11929. [else (apply-project v t2)])]
  11930. [(t1 'Any)
  11931. (match t1
  11932. [`(,ts ... -> ,rt)
  11933. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  11934. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  11935. (apply-inject v^ (any-tag any->any))]
  11936. [`(Vector ,ts ...)
  11937. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  11938. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  11939. (apply-inject v^ (any-tag vec-any))]
  11940. [else (apply-inject v (any-tag t1))])]
  11941. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11942. (define x (gensym 'x))
  11943. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  11944. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  11945. (define cast-writes
  11946. (for/list ([t1 ts1] [t2 ts2])
  11947. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  11948. `(vector-proxy ,(vector v (apply vector cast-reads)
  11949. (apply vector cast-writes)))]
  11950. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11951. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  11952. `(function ,xs ,(Cast
  11953. (Apply (Value v)
  11954. (for/list ([x xs][t1 ts1][t2 ts2])
  11955. (Cast (Var x) t2 t1)))
  11956. rt1 rt2) ())]
  11957. ))
  11958. \end{lstlisting}
  11959. \caption{The \code{apply-cast} auxiliary method.}
  11960. \label{fig:apply-cast}
  11961. \end{figure}
  11962. The interpreter for \LangCast{} is defined in
  11963. Figure~\ref{fig:interp-Rcast}, with the case for \code{Cast}
  11964. dispatching to \code{apply-cast}. To handle the addition of vector
  11965. proxies, we update the vector primitives in \code{interp-op} using the
  11966. functions in Figure~\ref{fig:guarded-vector}.
  11967. \begin{figure}[tbp]
  11968. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11969. (define interp-Rcast-class
  11970. (class interp-Rwhile-class
  11971. (super-new)
  11972. (inherit apply-fun apply-inject apply-project)
  11973. (define/override (interp-op op)
  11974. (match op
  11975. ['vector-length guarded-vector-length]
  11976. ['vector-ref guarded-vector-ref]
  11977. ['vector-set! guarded-vector-set!]
  11978. ['any-vector-ref (lambda (v i)
  11979. (match v [`(tagged ,v^ ,tg)
  11980. (guarded-vector-ref v^ i)]))]
  11981. ['any-vector-set! (lambda (v i a)
  11982. (match v [`(tagged ,v^ ,tg)
  11983. (guarded-vector-set! v^ i a)]))]
  11984. ['any-vector-length (lambda (v)
  11985. (match v [`(tagged ,v^ ,tg)
  11986. (guarded-vector-length v^)]))]
  11987. [else (super interp-op op)]
  11988. ))
  11989. (define/override ((interp-exp env) e)
  11990. (define (recur e) ((interp-exp env) e))
  11991. (match e
  11992. [(Value v) v]
  11993. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  11994. [else ((super interp-exp env) e)]))
  11995. ))
  11996. (define (interp-Rcast p)
  11997. (send (new interp-Rcast-class) interp-program p))
  11998. \end{lstlisting}
  11999. \caption{The interpreter for \LangCast{}.}
  12000. \label{fig:interp-Rcast}
  12001. \end{figure}
  12002. \begin{figure}[tbp]
  12003. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12004. (define (guarded-vector-ref vec i)
  12005. (match vec
  12006. [`(vector-proxy ,proxy)
  12007. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  12008. (define rd (vector-ref (vector-ref proxy 1) i))
  12009. (apply-fun rd (list val) 'guarded-vector-ref)]
  12010. [else (vector-ref vec i)]))
  12011. (define (guarded-vector-set! vec i arg)
  12012. (match vec
  12013. [`(vector-proxy ,proxy)
  12014. (define wr (vector-ref (vector-ref proxy 2) i))
  12015. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  12016. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  12017. [else (vector-set! vec i arg)]))
  12018. (define (guarded-vector-length vec)
  12019. (match vec
  12020. [`(vector-proxy ,proxy)
  12021. (guarded-vector-length (vector-ref proxy 0))]
  12022. [else (vector-length vec)]))
  12023. \end{lstlisting}
  12024. \caption{The guarded-vector auxiliary functions.}
  12025. \label{fig:guarded-vector}
  12026. \end{figure}
  12027. \section{Lower Casts}
  12028. \label{sec:lower-casts}
  12029. The next step in the journey towards x86 is the \code{lower-casts}
  12030. pass that translates the casts in \LangCast{} to the lower-level
  12031. \code{Inject} and \code{Project} operators and a new operator for
  12032. creating vector proxies, extending the \LangLoop{} language to create
  12033. \LangProxy{}. We recommend creating an auxiliary function named
  12034. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  12035. and a target type, and translates it to expression in \LangProxy{} that has
  12036. the same behavior as casting the expression from the source to the
  12037. target type in the interpreter.
  12038. The \code{lower-cast} function can follow a code structure similar to
  12039. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  12040. the interpreter for \LangCast{} because it must handle the same cases as
  12041. \code{apply-cast} and it needs to mimic the behavior of
  12042. \code{apply-cast}. The most interesting cases are those concerning the
  12043. casts between two vector types and between two function types.
  12044. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  12045. type to another vector type is accomplished by creating a proxy that
  12046. intercepts the operations on the underlying vector. Here we make the
  12047. creation of the proxy explicit with the \code{vector-proxy} primitive
  12048. operation. It takes three arguments, the first is an expression for
  12049. the vector, the second is a vector of functions for casting an element
  12050. that is being read from the vector, and the third is a vector of
  12051. functions for casting an element that is being written to the vector.
  12052. You can create the functions using \code{Lambda}. Also, as we shall
  12053. see in the next section, we need to differentiate these vectors from
  12054. the user-created ones, so we recommend using a new primitive operator
  12055. named \code{raw-vector} instead of \code{vector} to create these
  12056. vectors of functions. Figure~\ref{fig:map-vec-bang-lower-cast} shows
  12057. the output of \code{lower-casts} on the example in
  12058. Figure~\ref{fig:map-vec-bang} that involved casting a vector of
  12059. integers to a vector of \code{Any}.
  12060. \begin{figure}[tbp]
  12061. \begin{lstlisting}
  12062. (define (map-vec! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  12063. (begin
  12064. (vector-set! v 0 (f (vector-ref v 0)))
  12065. (vector-set! v 1 (f (vector-ref v 1)))))
  12066. (define (add1 [x : Any]) : Any
  12067. (inject (+ (project x Integer) 1) Integer))
  12068. (let ([v (vector 0 41)])
  12069. (begin
  12070. (map-vec! add1 (vector-proxy v
  12071. (raw-vector (lambda: ([x9 : Integer]) : Any
  12072. (inject x9 Integer))
  12073. (lambda: ([x9 : Integer]) : Any
  12074. (inject x9 Integer)))
  12075. (raw-vector (lambda: ([x9 : Any]) : Integer
  12076. (project x9 Integer))
  12077. (lambda: ([x9 : Any]) : Integer
  12078. (project x9 Integer)))))
  12079. (vector-ref v 1)))
  12080. \end{lstlisting}
  12081. \caption{Output of \code{lower-casts} on the example in
  12082. Figure~\ref{fig:map-vec-bang}.}
  12083. \label{fig:map-vec-bang-lower-cast}
  12084. \end{figure}
  12085. A cast from one function type to another function type is accomplished
  12086. by generating a \code{Lambda} whose parameter and return types match
  12087. the target function type. The body of the \code{Lambda} should cast
  12088. the parameters from the target type to the source type (yes,
  12089. backwards! functions are contravariant\index{contravariant} in the
  12090. parameters), then call the underlying function, and finally cast the
  12091. result from the source return type to the target return type.
  12092. Figure~\ref{fig:map-vec-lower-cast} shows the output of the
  12093. \code{lower-casts} pass on the \code{map-vec} example in
  12094. Figure~\ref{fig:gradual-map-vec}. Note that the \code{add1} argument
  12095. in the call to \code{map-vec} is wrapped in a \code{lambda}.
  12096. \begin{figure}[tbp]
  12097. \begin{lstlisting}
  12098. (define (map-vec [f : (Integer -> Integer)]
  12099. [v : (Vector Integer Integer)])
  12100. : (Vector Integer Integer)
  12101. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12102. (define (add1 [x : Any]) : Any
  12103. (inject (+ (project x Integer) 1) Integer))
  12104. (vector-ref (map-vec (lambda: ([x9 : Integer]) : Integer
  12105. (project (add1 (inject x9 Integer)) Integer))
  12106. (vector 0 41)) 1)
  12107. \end{lstlisting}
  12108. \caption{Output of \code{lower-casts} on the example in
  12109. Figure~\ref{fig:gradual-map-vec}.}
  12110. \label{fig:map-vec-lower-cast}
  12111. \end{figure}
  12112. \section{Differentiate Proxies}
  12113. \label{sec:differentiate-proxies}
  12114. So far the job of differentiating vectors and vector proxies has been
  12115. the job of the interpreter. For example, the interpreter for \LangCast{}
  12116. implements \code{vector-ref} using the \code{guarded-vector-ref}
  12117. function in Figure~\ref{fig:guarded-vector}. In the
  12118. \code{differentiate-proxies} pass we shift this responsibility to the
  12119. generated code.
  12120. We begin by designing the output language $R^p_8$. In
  12121. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  12122. proxies. In $R^p_8$ we return the \code{Vector} type to
  12123. its original meaning, as the type of real vectors, and we introduce a
  12124. new type, \code{PVector}, whose values can be either real vectors or
  12125. vector proxies. This new type comes with a suite of new primitive
  12126. operations for creating and using values of type \code{PVector}. We
  12127. don't need to introduce a new type to represent vector proxies. A
  12128. proxy is represented by a vector containing three things: 1) the
  12129. underlying vector, 2) a vector of functions for casting elements that
  12130. are read from the vector, and 3) a vector of functions for casting
  12131. values to be written to the vector. So we define the following
  12132. abbreviation for the type of a vector proxy:
  12133. \[
  12134. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  12135. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  12136. \to (\key{PVector}~ T' \ldots)
  12137. \]
  12138. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  12139. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  12140. %
  12141. Next we describe each of the new primitive operations.
  12142. \begin{description}
  12143. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  12144. (\key{PVector} $T \ldots$)]\ \\
  12145. %
  12146. This operation brands a vector as a value of the \code{PVector} type.
  12147. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  12148. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  12149. %
  12150. This operation brands a vector proxy as value of the \code{PVector} type.
  12151. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  12152. \code{Boolean}] \ \\
  12153. %
  12154. returns true if the value is a vector proxy and false if it is a
  12155. real vector.
  12156. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  12157. (\key{Vector} $T \ldots$)]\ \\
  12158. %
  12159. Assuming that the input is a vector (and not a proxy), this
  12160. operation returns the vector.
  12161. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  12162. $\to$ \code{Boolean}]\ \\
  12163. %
  12164. Given a vector proxy, this operation returns the length of the
  12165. underlying vector.
  12166. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  12167. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  12168. %
  12169. Given a vector proxy, this operation returns the $i$th element of
  12170. the underlying vector.
  12171. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  12172. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  12173. proxy, this operation writes a value to the $i$th element of the
  12174. underlying vector.
  12175. \end{description}
  12176. Now to discuss the translation that differentiates vectors from
  12177. proxies. First, every type annotation in the program must be
  12178. translated (recursively) to replace \code{Vector} with \code{PVector}.
  12179. Next, we must insert uses of \code{PVector} operations in the
  12180. appropriate places. For example, we wrap every vector creation with an
  12181. \code{inject-vector}.
  12182. \begin{lstlisting}
  12183. (vector |$e_1 \ldots e_n$|)
  12184. |$\Rightarrow$|
  12185. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  12186. \end{lstlisting}
  12187. The \code{raw-vector} operator that we introduced in the previous
  12188. section does not get injected.
  12189. \begin{lstlisting}
  12190. (raw-vector |$e_1 \ldots e_n$|)
  12191. |$\Rightarrow$|
  12192. (vector |$e'_1 \ldots e'_n$|)
  12193. \end{lstlisting}
  12194. The \code{vector-proxy} primitive translates as follows.
  12195. \begin{lstlisting}
  12196. (vector-proxy |$e_1~e_2~e_3$|)
  12197. |$\Rightarrow$|
  12198. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  12199. \end{lstlisting}
  12200. We translate the vector operations into conditional expressions that
  12201. check whether the value is a proxy and then dispatch to either the
  12202. appropriate proxy vector operation or the regular vector operation.
  12203. For example, the following is the translation for \code{vector-ref}.
  12204. \begin{lstlisting}
  12205. (vector-ref |$e_1$| |$i$|)
  12206. |$\Rightarrow$|
  12207. (let ([|$v~e_1$|])
  12208. (if (proxy? |$v$|)
  12209. (proxy-vector-ref |$v$| |$i$|)
  12210. (vector-ref (project-vector |$v$|) |$i$|)
  12211. \end{lstlisting}
  12212. Note in the case of a real vector, we must apply \code{project-vector}
  12213. before the \code{vector-ref}.
  12214. \section{Reveal Casts}
  12215. \label{sec:reveal-casts-gradual}
  12216. Recall that the \code{reveal-casts} pass
  12217. (Section~\ref{sec:reveal-casts-Rany}) is responsible for lowering
  12218. \code{Inject} and \code{Project} into lower-level operations. In
  12219. particular, \code{Project} turns into a conditional expression that
  12220. inspects the tag and retrieves the underlying value. Here we need to
  12221. augment the translation of \code{Project} to handle the situation when
  12222. the target type is \code{PVector}. Instead of using
  12223. \code{vector-length} we need to use \code{proxy-vector-length}.
  12224. \begin{lstlisting}
  12225. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  12226. |$\Rightarrow$|
  12227. (let |$\itm{tmp}$| |$e'$|
  12228. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  12229. (let |$\itm{vec}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  12230. (if (eq? (proxy-vector-length |$\itm{vec}$|) |$n$|) |$\itm{vec}$| (exit)))
  12231. (exit)))
  12232. \end{lstlisting}
  12233. \section{Closure Conversion}
  12234. \label{sec:closure-conversion-gradual}
  12235. The closure conversion pass only requires one minor adjustment. The
  12236. auxiliary function that translates type annotations needs to be
  12237. updated to handle the \code{PVector} type.
  12238. \section{Explicate Control}
  12239. \label{sec:explicate-control-gradual}
  12240. Update the \code{explicate-control} pass to handle the new primitive
  12241. operations on the \code{PVector} type.
  12242. \section{Select Instructions}
  12243. \label{sec:select-instructions-gradual}
  12244. Recall that the \code{select-instructions} pass is responsible for
  12245. lowering the primitive operations into x86 instructions. So we need
  12246. to translate the new \code{PVector} operations to x86. To do so, the
  12247. first question we need to answer is how will we differentiate the two
  12248. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  12249. We need just one bit to accomplish this, and use the bit in position
  12250. $57$ of the 64-bit tag at the front of every vector (see
  12251. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  12252. for \code{inject-vector} we leave it that way.
  12253. \begin{lstlisting}
  12254. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  12255. |$\Rightarrow$|
  12256. movq |$e'_1$|, |$\itm{lhs'}$|
  12257. \end{lstlisting}
  12258. On the other hand, \code{inject-proxy} sets bit $57$ to $1$.
  12259. \begin{lstlisting}
  12260. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  12261. |$\Rightarrow$|
  12262. movq |$e'_1$|, %r11
  12263. movq |$(1 << 57)$|, %rax
  12264. orq 0(%r11), %rax
  12265. movq %rax, 0(%r11)
  12266. movq %r11, |$\itm{lhs'}$|
  12267. \end{lstlisting}
  12268. The \code{proxy?} operation consumes the information so carefully
  12269. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  12270. isolates the $57$th bit to tell whether the value is a real vector or
  12271. a proxy.
  12272. \begin{lstlisting}
  12273. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  12274. |$\Rightarrow$|
  12275. movq |$e_1'$|, %r11
  12276. movq 0(%r11), %rax
  12277. sarq $57, %rax
  12278. andq $1, %rax
  12279. movq %rax, |$\itm{lhs'}$|
  12280. \end{lstlisting}
  12281. The \code{project-vector} operation is straightforward to translate,
  12282. so we leave it up to the reader.
  12283. Regarding the \code{proxy-vector} operations, the runtime provides
  12284. procedures that implement them (they are recursive functions!) so
  12285. here we simply need to translate these vector operations into the
  12286. appropriate function call. For example, here is the translation for
  12287. \code{proxy-vector-ref}.
  12288. \begin{lstlisting}
  12289. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  12290. |$\Rightarrow$|
  12291. movq |$e_1'$|, %rdi
  12292. movq |$e_2'$|, %rsi
  12293. callq proxy_vector_ref
  12294. movq %rax, |$\itm{lhs'}$|
  12295. \end{lstlisting}
  12296. We have another batch of vector operations to deal with, those for the
  12297. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  12298. \code{any-vector-ref} when there is a \code{vector-ref} on something
  12299. of type \code{Any}, and similarly for \code{any-vector-set!} and
  12300. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  12301. Section~\ref{sec:select-Rany} we selected instructions for these
  12302. operations based on the idea that the underlying value was a real
  12303. vector. But in the current setting, the underlying value is of type
  12304. \code{PVector}. So \code{any-vector-ref} can be translates to
  12305. pseudo-x86 as follows. We begin by projecting the underlying value out
  12306. of the tagged value and then call the \code{proxy\_vector\_ref}
  12307. procedure in the runtime.
  12308. \begin{lstlisting}
  12309. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  12310. movq |$\neg 111$|, %rdi
  12311. andq |$e_1'$|, %rdi
  12312. movq |$e_2'$|, %rsi
  12313. callq proxy_vector_ref
  12314. movq %rax, |$\itm{lhs'}$|
  12315. \end{lstlisting}
  12316. The \code{any-vector-set!} and \code{any-vector-length} operators can
  12317. be translated in a similar way.
  12318. \begin{exercise}\normalfont
  12319. Implement a compiler for the gradually-typed \LangGrad{} language by
  12320. extending and adapting your compiler for \LangLoop{}. Create 10 new
  12321. partially-typed test programs. In addition to testing with these
  12322. new programs, also test your compiler on all the tests for \LangLoop{}
  12323. and tests for \LangDyn{}. Sometimes you may get a type checking error
  12324. on the \LangDyn{} programs but you can adapt them by inserting
  12325. a cast to the \code{Any} type around each subexpression
  12326. causing a type error. While \LangDyn{} doesn't have explicit casts,
  12327. you can induce one by wrapping the subexpression \code{e}
  12328. with a call to an un-annotated identity function, like this:
  12329. \code{((lambda (x) x) e)}.
  12330. \end{exercise}
  12331. \begin{figure}[p]
  12332. \begin{tikzpicture}[baseline=(current bounding box.center)]
  12333. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  12334. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  12335. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  12336. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  12337. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  12338. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  12339. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  12340. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  12341. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  12342. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  12343. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  12344. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  12345. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  12346. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  12347. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  12348. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  12349. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  12350. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  12351. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  12352. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  12353. \path[->,bend right=15] (Rgradual) edge [above] node
  12354. {\ttfamily\footnotesize type-check} (Rgradualp);
  12355. \path[->,bend right=15] (Rgradualp) edge [above] node
  12356. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  12357. \path[->,bend right=15] (Rwhilepp) edge [right] node
  12358. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  12359. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  12360. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  12361. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  12362. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  12363. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  12364. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  12365. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  12366. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  12367. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  12368. {\ttfamily\footnotesize convert-assignments} (F1-1);
  12369. \path[->,bend left=15] (F1-1) edge [below] node
  12370. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  12371. \path[->,bend right=15] (F1-2) edge [above] node
  12372. {\ttfamily\footnotesize limit-fun.} (F1-3);
  12373. \path[->,bend right=15] (F1-3) edge [above] node
  12374. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  12375. \path[->,bend right=15] (F1-4) edge [above] node
  12376. {\ttfamily\footnotesize remove-complex.} (F1-5);
  12377. \path[->,bend right=15] (F1-5) edge [right] node
  12378. {\ttfamily\footnotesize explicate-control} (C3-2);
  12379. \path[->,bend left=15] (C3-2) edge [left] node
  12380. {\ttfamily\footnotesize select-instr.} (x86-2);
  12381. \path[->,bend right=15] (x86-2) edge [left] node
  12382. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  12383. \path[->,bend right=15] (x86-2-1) edge [below] node
  12384. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  12385. \path[->,bend right=15] (x86-2-2) edge [left] node
  12386. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  12387. \path[->,bend left=15] (x86-3) edge [above] node
  12388. {\ttfamily\footnotesize patch-instr.} (x86-4);
  12389. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  12390. \end{tikzpicture}
  12391. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  12392. \label{fig:Rgradual-passes}
  12393. \end{figure}
  12394. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  12395. for the compilation of \LangGrad{}.
  12396. \section{Further Reading}
  12397. This chapter just scratches the surface of gradual typing. The basic
  12398. approach described here is missing two key ingredients that one would
  12399. want in a implementation of gradual typing: blame
  12400. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  12401. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  12402. problem addressed by blame tracking is that when a cast on a
  12403. higher-order value fails, it often does so at a point in the program
  12404. that is far removed from the original cast. Blame tracking is a
  12405. technique for propagating extra information through casts and proxies
  12406. so that when a cast fails, the error message can point back to the
  12407. original location of the cast in the source program.
  12408. The problem addressed by space-efficient casts also relates to
  12409. higher-order casts. It turns out that in partially typed programs, a
  12410. function or vector can flow through very-many casts at runtime. With
  12411. the approach described in this chapter, each cast adds another
  12412. \code{lambda} wrapper or a vector proxy. Not only does this take up
  12413. considerable space, but it also makes the function calls and vector
  12414. operations slow. For example, a partially-typed version of quicksort
  12415. could, in the worst case, build a chain of proxies of length $O(n)$
  12416. around the vector, changing the overall time complexity of the
  12417. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  12418. solution to this problem by representing casts using the coercion
  12419. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  12420. long chains of proxies by compressing them into a concise normal
  12421. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  12422. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  12423. the Grift compiler.
  12424. \begin{center}
  12425. \url{https://github.com/Gradual-Typing/Grift}
  12426. \end{center}
  12427. There are also interesting interactions between gradual typing and
  12428. other language features, such as parametetric polymorphism,
  12429. information-flow types, and type inference, to name a few. We
  12430. recommend the reader to the online gradual typing bibliography:
  12431. \begin{center}
  12432. \url{http://samth.github.io/gradual-typing-bib/}
  12433. \end{center}
  12434. % TODO: challenge problem:
  12435. % type analysis and type specialization?
  12436. % coercions?
  12437. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12438. \chapter{Parametric Polymorphism}
  12439. \label{ch:Rpoly}
  12440. \index{parametric polymorphism}
  12441. \index{generics}
  12442. This chapter studies the compilation of parametric
  12443. polymorphism\index{parametric polymorphism}
  12444. (aka. generics\index{generics}) in the subset \LangPoly{} of Typed
  12445. Racket. Parametric polymorphism enables improved code reuse by
  12446. parameterizing functions and data structures with respect to the types
  12447. that they operate on. For example, Figure~\ref{fig:map-vec-poly}
  12448. revisits the \code{map-vec} example but this time gives it a more
  12449. fitting type. This \code{map-vec} function is parameterized with
  12450. respect to the element type of the vector. The type of \code{map-vec}
  12451. is the following polymorphic type as specified by the \code{All} and
  12452. the type parameter \code{a}.
  12453. \begin{lstlisting}
  12454. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  12455. \end{lstlisting}
  12456. The idea is that \code{map-vec} can be used at \emph{all} choices of a
  12457. type for parameter \code{a}. In Figure~\ref{fig:map-vec-poly} we apply
  12458. \code{map-vec} to a vector of integers, a choice of \code{Integer} for
  12459. \code{a}, but we could have just as well applied \code{map-vec} to a
  12460. vector of Booleans (and a function on Booleans).
  12461. \begin{figure}[tbp]
  12462. % poly_test_2.rkt
  12463. \begin{lstlisting}
  12464. (: map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  12465. (define (map-vec f v)
  12466. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12467. (define (add1 [x : Integer]) : Integer (+ x 1))
  12468. (vector-ref (map-vec add1 (vector 0 41)) 1)
  12469. \end{lstlisting}
  12470. \caption{The \code{map-vec} example using parametric polymorphism.}
  12471. \label{fig:map-vec-poly}
  12472. \end{figure}
  12473. Figure~\ref{fig:Rpoly-concrete-syntax} defines the concrete syntax of
  12474. \LangPoly{} and Figure~\ref{fig:Rpoly-syntax} defines the abstract
  12475. syntax. We add a second form for function definitions in which a type
  12476. declaration comes before the \code{define}. In the abstract syntax,
  12477. the return type in the \code{Def} is \code{Any}, but that should be
  12478. ignored in favor of the return type in the type declaration. (The
  12479. \code{Any} comes from using the same parser as in
  12480. Chapter~\ref{ch:Rdyn}.) The presence of a type declaration
  12481. enables the use of an \code{All} type for a function, thereby making
  12482. it polymorphic. The grammar for types is extended to include
  12483. polymorphic types and type variables.
  12484. \begin{figure}[tp]
  12485. \centering
  12486. \fbox{
  12487. \begin{minipage}{0.96\textwidth}
  12488. \small
  12489. \[
  12490. \begin{array}{lcl}
  12491. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  12492. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  12493. &\mid& \LP\key{:}~\Var~\Type\RP \\
  12494. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  12495. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  12496. \end{array}
  12497. \]
  12498. \end{minipage}
  12499. }
  12500. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  12501. (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  12502. \label{fig:Rpoly-concrete-syntax}
  12503. \end{figure}
  12504. \begin{figure}[tp]
  12505. \centering
  12506. \fbox{
  12507. \begin{minipage}{0.96\textwidth}
  12508. \small
  12509. \[
  12510. \begin{array}{lcl}
  12511. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  12512. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  12513. &\mid& \DECL{\Var}{\Type} \\
  12514. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  12515. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  12516. \end{array}
  12517. \]
  12518. \end{minipage}
  12519. }
  12520. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  12521. (Figure~\ref{fig:Rwhile-syntax}).}
  12522. \label{fig:Rpoly-syntax}
  12523. \end{figure}
  12524. By including polymorphic types in the $\Type$ non-terminal we choose
  12525. to make them first-class which has interesting repercussions on the
  12526. compiler. Many languages with polymorphism, such as
  12527. C++~\citep{stroustrup88:_param_types} and Standard
  12528. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  12529. it is useful to see an example of first-class polymorphism. In
  12530. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  12531. whose parameter is a polymorphic function. The occurrence of a
  12532. polymorphic type underneath a function type is enabled by the normal
  12533. recursive structure of the grammar for $\Type$ and the categorization
  12534. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  12535. applies the polymorphic function to a Boolean and to an integer.
  12536. \begin{figure}[tbp]
  12537. \begin{lstlisting}
  12538. (: apply-twice ((All (b) (b -> b)) -> Integer))
  12539. (define (apply-twice f)
  12540. (if (f #t) (f 42) (f 777)))
  12541. (: id (All (a) (a -> a)))
  12542. (define (id x) x)
  12543. (apply-twice id)
  12544. \end{lstlisting}
  12545. \caption{An example illustrating first-class polymorphism.}
  12546. \label{fig:apply-twice}
  12547. \end{figure}
  12548. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Rvar0} has
  12549. three new responsibilities (compared to \LangLoop{}). The type checking of
  12550. function application is extended to handle the case where the operator
  12551. expression is a polymorphic function. In that case the type arguments
  12552. are deduced by matching the type of the parameters with the types of
  12553. the arguments.
  12554. %
  12555. The \code{match-types} auxiliary function carries out this deduction
  12556. by recursively descending through a parameter type \code{pt} and the
  12557. corresponding argument type \code{at}, making sure that they are equal
  12558. except when there is a type parameter on the left (in the parameter
  12559. type). If it's the first time that the type parameter has been
  12560. encountered, then the algorithm deduces an association of the type
  12561. parameter to the corresponding type on the right (in the argument
  12562. type). If it's not the first time that the type parameter has been
  12563. encountered, the algorithm looks up its deduced type and makes sure
  12564. that it is equal to the type on the right.
  12565. %
  12566. Once the type arguments are deduced, the operator expression is
  12567. wrapped in an \code{Inst} AST node (for instantiate) that records the
  12568. type of the operator, but more importantly, records the deduced type
  12569. arguments. The return type of the application is the return type of
  12570. the polymorphic function, but with the type parameters replaced by the
  12571. deduced type arguments, using the \code{subst-type} function.
  12572. The second responsibility of the type checker is extending the
  12573. function \code{type-equal?} to handle the \code{All} type. This is
  12574. not quite a simple as equal on other types, such as function and
  12575. vector types, because two polymorphic types can be syntactically
  12576. different even though they are equivalent types. For example,
  12577. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  12578. Two polymorphic types should be considered equal if they differ only
  12579. in the choice of the names of the type parameters. The
  12580. \code{type-equal?} function in Figure~\ref{fig:type-check-Rvar0-aux}
  12581. renames the type parameters of the first type to match the type
  12582. parameters of the second type.
  12583. The third responsibility of the type checker is making sure that only
  12584. defined type variables appear in type annotations. The
  12585. \code{check-well-formed} function defined in
  12586. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  12587. sure that each type variable has been defined.
  12588. The output language of the type checker is \LangInst{}, defined in
  12589. Figure~\ref{fig:Rpoly-prime-syntax}. The type checker combines the type
  12590. declaration and polymorphic function into a single definition, using
  12591. the \code{Poly} form, to make polymorphic functions more convenient to
  12592. process in next pass of the compiler.
  12593. \begin{figure}[tp]
  12594. \centering
  12595. \fbox{
  12596. \begin{minipage}{0.96\textwidth}
  12597. \small
  12598. \[
  12599. \begin{array}{lcl}
  12600. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  12601. \Exp &::=& \ldots \mid \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  12602. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  12603. &\mid& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  12604. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  12605. \end{array}
  12606. \]
  12607. \end{minipage}
  12608. }
  12609. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  12610. (Figure~\ref{fig:Rwhile-syntax}).}
  12611. \label{fig:Rpoly-prime-syntax}
  12612. \end{figure}
  12613. The output of the type checker on the polymorphic \code{map-vec}
  12614. example is listed in Figure~\ref{fig:map-vec-type-check}.
  12615. \begin{figure}[tbp]
  12616. % poly_test_2.rkt
  12617. \begin{lstlisting}
  12618. (poly (a) (define (map-vec [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  12619. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  12620. (define (add1 [x : Integer]) : Integer (+ x 1))
  12621. (vector-ref ((inst map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  12622. (Integer))
  12623. add1 (vector 0 41)) 1)
  12624. \end{lstlisting}
  12625. \caption{Output of the type checker on the \code{map-vec} example.}
  12626. \label{fig:map-vec-type-check}
  12627. \end{figure}
  12628. \begin{figure}[tbp]
  12629. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12630. (define type-check-poly-class
  12631. (class type-check-Rwhile-class
  12632. (super-new)
  12633. (inherit check-type-equal?)
  12634. (define/override (type-check-apply env e1 es)
  12635. (define-values (e^ ty) ((type-check-exp env) e1))
  12636. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  12637. ((type-check-exp env) e)))
  12638. (match ty
  12639. [`(,ty^* ... -> ,rt)
  12640. (for ([arg-ty ty*] [param-ty ty^*])
  12641. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  12642. (values e^ es^ rt)]
  12643. [`(All ,xs (,tys ... -> ,rt))
  12644. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  12645. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  12646. (match-types env^^ param-ty arg-ty)))
  12647. (define targs
  12648. (for/list ([x xs])
  12649. (match (dict-ref env^^ x (lambda () #f))
  12650. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  12651. x (Apply e1 es))]
  12652. [ty ty])))
  12653. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  12654. [else (error 'type-check "expected a function, not ~a" ty)]))
  12655. (define/override ((type-check-exp env) e)
  12656. (match e
  12657. [(Lambda `([,xs : ,Ts] ...) rT body)
  12658. (for ([T Ts]) ((check-well-formed env) T))
  12659. ((check-well-formed env) rT)
  12660. ((super type-check-exp env) e)]
  12661. [(HasType e1 ty)
  12662. ((check-well-formed env) ty)
  12663. ((super type-check-exp env) e)]
  12664. [else ((super type-check-exp env) e)]))
  12665. (define/override ((type-check-def env) d)
  12666. (verbose 'type-check "poly/def" d)
  12667. (match d
  12668. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  12669. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  12670. (for ([p ps]) ((check-well-formed ts-env) p))
  12671. ((check-well-formed ts-env) rt)
  12672. (define new-env (append ts-env (map cons xs ps) env))
  12673. (define-values (body^ ty^) ((type-check-exp new-env) body))
  12674. (check-type-equal? ty^ rt body)
  12675. (Generic ts (Def f p:t* rt info body^))]
  12676. [else ((super type-check-def env) d)]))
  12677. (define/override (type-check-program p)
  12678. (match p
  12679. [(Program info body)
  12680. (type-check-program (ProgramDefsExp info '() body))]
  12681. [(ProgramDefsExp info ds body)
  12682. (define ds^ (combine-decls-defs ds))
  12683. (define new-env (for/list ([d ds^])
  12684. (cons (def-name d) (fun-def-type d))))
  12685. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  12686. (define-values (body^ ty) ((type-check-exp new-env) body))
  12687. (check-type-equal? ty 'Integer body)
  12688. (ProgramDefsExp info ds^^ body^)]))
  12689. ))
  12690. \end{lstlisting}
  12691. \caption{Type checker for the \LangPoly{} language.}
  12692. \label{fig:type-check-Rvar0}
  12693. \end{figure}
  12694. \begin{figure}[tbp]
  12695. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12696. (define/override (type-equal? t1 t2)
  12697. (match* (t1 t2)
  12698. [(`(All ,xs ,T1) `(All ,ys ,T2))
  12699. (define env (map cons xs ys))
  12700. (type-equal? (subst-type env T1) T2)]
  12701. [(other wise)
  12702. (super type-equal? t1 t2)]))
  12703. (define/public (match-types env pt at)
  12704. (match* (pt at)
  12705. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  12706. [('Void 'Void) env] [('Any 'Any) env]
  12707. [(`(Vector ,pts ...) `(Vector ,ats ...))
  12708. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  12709. (match-types env^ pt1 at1))]
  12710. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  12711. (define env^ (match-types env prt art))
  12712. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  12713. (match-types env^^ pt1 at1))]
  12714. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  12715. (define env^ (append (map cons pxs axs) env))
  12716. (match-types env^ pt1 at1)]
  12717. [((? symbol? x) at)
  12718. (match (dict-ref env x (lambda () #f))
  12719. [#f (error 'type-check "undefined type variable ~a" x)]
  12720. ['Type (cons (cons x at) env)]
  12721. [t^ (check-type-equal? at t^ 'matching) env])]
  12722. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  12723. (define/public (subst-type env pt)
  12724. (match pt
  12725. ['Integer 'Integer] ['Boolean 'Boolean]
  12726. ['Void 'Void] ['Any 'Any]
  12727. [`(Vector ,ts ...)
  12728. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  12729. [`(,ts ... -> ,rt)
  12730. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  12731. [`(All ,xs ,t)
  12732. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  12733. [(? symbol? x) (dict-ref env x)]
  12734. [else (error 'type-check "expected a type not ~a" pt)]))
  12735. (define/public (combine-decls-defs ds)
  12736. (match ds
  12737. ['() '()]
  12738. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  12739. (unless (equal? name f)
  12740. (error 'type-check "name mismatch, ~a != ~a" name f))
  12741. (match type
  12742. [`(All ,xs (,ps ... -> ,rt))
  12743. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  12744. (cons (Generic xs (Def name params^ rt info body))
  12745. (combine-decls-defs ds^))]
  12746. [`(,ps ... -> ,rt)
  12747. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  12748. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  12749. [else (error 'type-check "expected a function type, not ~a" type) ])]
  12750. [`(,(Def f params rt info body) . ,ds^)
  12751. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  12752. \end{lstlisting}
  12753. \caption{Auxiliary functions for type checking \LangPoly{}.}
  12754. \label{fig:type-check-Rvar0-aux}
  12755. \end{figure}
  12756. \begin{figure}[tbp]
  12757. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  12758. (define/public ((check-well-formed env) ty)
  12759. (match ty
  12760. ['Integer (void)]
  12761. ['Boolean (void)]
  12762. ['Void (void)]
  12763. [(? symbol? a)
  12764. (match (dict-ref env a (lambda () #f))
  12765. ['Type (void)]
  12766. [else (error 'type-check "undefined type variable ~a" a)])]
  12767. [`(Vector ,ts ...)
  12768. (for ([t ts]) ((check-well-formed env) t))]
  12769. [`(,ts ... -> ,t)
  12770. (for ([t ts]) ((check-well-formed env) t))
  12771. ((check-well-formed env) t)]
  12772. [`(All ,xs ,t)
  12773. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  12774. ((check-well-formed env^) t)]
  12775. [else (error 'type-check "unrecognized type ~a" ty)]))
  12776. \end{lstlisting}
  12777. \caption{Well-formed types.}
  12778. \label{fig:well-formed-types}
  12779. \end{figure}
  12780. % TODO: interpreter for R'_10
  12781. \section{Compiling Polymorphism}
  12782. \label{sec:compiling-poly}
  12783. Broadly speaking, there are four approaches to compiling parametric
  12784. polymorphism, which we describe below.
  12785. \begin{description}
  12786. \item[Monomorphization] generates a different version of a polymorphic
  12787. function for each set of type arguments that it is used with,
  12788. producing type-specialized code. This approach results in the most
  12789. efficient code but requires whole-program compilation (no separate
  12790. compilation) and increases code size. For our current purposes
  12791. monomorphization is a non-starter because, with first-class
  12792. polymorphism, it is sometimes not possible to determine which
  12793. generic functions are used with which type arguments during
  12794. compilation. (It can be done at runtime, with just-in-time
  12795. compilation.) This approach is used to compile C++
  12796. templates~\citep{stroustrup88:_param_types} and polymorphic
  12797. functions in NESL~\citep{Blelloch:1993aa} and
  12798. ML~\citep{Weeks:2006aa}.
  12799. \item[Uniform representation] generates one version of each
  12800. polymorphic function but requires all values have a common ``boxed''
  12801. format, such as the tagged values of type \code{Any} in
  12802. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  12803. similarly to code in a dynamically typed language (like \LangDyn{}),
  12804. in which primitive operators require their arguments to be projected
  12805. from \code{Any} and their results are injected into \code{Any}. (In
  12806. object-oriented languages, the projection is accomplished via
  12807. virtual method dispatch.) The uniform representation approach is
  12808. compatible with separate compilation and with first-class
  12809. polymorphism. However, it produces the least-efficient code because
  12810. it introduces overhead in the entire program, including
  12811. non-polymorphic code. This approach is used in implementations of
  12812. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  12813. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  12814. Java~\citep{Bracha:1998fk}.
  12815. \item[Mixed representation] generates one version of each polymorphic
  12816. function, using a boxed representation for type
  12817. variables. Monomorphic code is compiled as usual (as in \LangLoop{})
  12818. and conversions are performed at the boundaries between monomorphic
  12819. and polymorphic (e.g. when a polymorphic function is instantiated
  12820. and called). This approach is compatible with separate compilation
  12821. and first-class polymorphism and maintains the efficiency of
  12822. monomorphic code. The tradeoff is increased overhead at the boundary
  12823. between monomorphic and polymorphic code. This approach is used in
  12824. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  12825. Java 5 with the addition of autoboxing.
  12826. \item[Type passing] uses the unboxed representation in both
  12827. monomorphic and polymorphic code. Each polymorphic function is
  12828. compiled to a single function with extra parameters that describe
  12829. the type arguments. The type information is used by the generated
  12830. code to know how to access the unboxed values at runtime. This
  12831. approach is used in implementation of the Napier88
  12832. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. Type
  12833. passing is compatible with separate compilation and first-class
  12834. polymorphism and maintains the efficiency for monomorphic
  12835. code. There is runtime overhead in polymorphic code from dispatching
  12836. on type information.
  12837. \end{description}
  12838. In this chapter we use the mixed representation approach, partly
  12839. because of its favorable attributes, and partly because it is
  12840. straightforward to implement using the tools that we have already
  12841. built to support gradual typing. To compile polymorphic functions, we
  12842. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  12843. \LangCast{}.
  12844. \section{Erase Types}
  12845. \label{sec:erase-types}
  12846. We use the \code{Any} type from Chapter~\ref{ch:Rdyn} to
  12847. represent type variables. For example, Figure~\ref{fig:map-vec-erase}
  12848. shows the output of the \code{erase-types} pass on the polymorphic
  12849. \code{map-vec} (Figure~\ref{fig:map-vec-poly}). The occurrences of
  12850. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  12851. \code{All} types are removed from the type of \code{map-vec}.
  12852. \begin{figure}[tbp]
  12853. \begin{lstlisting}
  12854. (define (map-vec [f : (Any -> Any)] [v : (Vector Any Any)])
  12855. : (Vector Any Any)
  12856. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12857. (define (add1 [x : Integer]) : Integer (+ x 1))
  12858. (vector-ref ((cast map-vec
  12859. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  12860. ((Integer -> Integer) (Vector Integer Integer)
  12861. -> (Vector Integer Integer)))
  12862. add1 (vector 0 41)) 1)
  12863. \end{lstlisting}
  12864. \caption{The polymorphic \code{map-vec} example after type erasure.}
  12865. \label{fig:map-vec-erase}
  12866. \end{figure}
  12867. This process of type erasure creates a challenge at points of
  12868. instantiation. For example, consider the instantiation of
  12869. \code{map-vec} in Figure~\ref{fig:map-vec-type-check}.
  12870. The type of \code{map-vec} is
  12871. \begin{lstlisting}
  12872. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  12873. \end{lstlisting}
  12874. and it is instantiated to
  12875. \begin{lstlisting}
  12876. ((Integer -> Integer) (Vector Integer Integer)
  12877. -> (Vector Integer Integer))
  12878. \end{lstlisting}
  12879. After erasure, the type of \code{map-vec} is
  12880. \begin{lstlisting}
  12881. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  12882. \end{lstlisting}
  12883. but we need to convert it to the instantiated type. This is easy to
  12884. do in the target language \LangCast{} with a single \code{cast}. In
  12885. Figure~\ref{fig:map-vec-erase}, the instantiation of \code{map-vec}
  12886. has been compiled to a \code{cast} from the type of \code{map-vec} to
  12887. the instantiated type. The source and target type of a cast must be
  12888. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  12889. because both the source and target are obtained from the same
  12890. polymorphic type of \code{map-vec}, replacing the type parameters with
  12891. \code{Any} in the former and with the deduced type arguments in the
  12892. later. (Recall that the \code{Any} type is consistent with any type.)
  12893. To implement the \code{erase-types} pass, we recommend defining a
  12894. recursive auxiliary function named \code{erase-type} that applies the
  12895. following two transformations. It replaces type variables with
  12896. \code{Any}
  12897. \begin{lstlisting}
  12898. |$x$|
  12899. |$\Rightarrow$|
  12900. Any
  12901. \end{lstlisting}
  12902. and it removes the polymorphic \code{All} types.
  12903. \begin{lstlisting}
  12904. (All |$xs$| |$T_1$|)
  12905. |$\Rightarrow$|
  12906. |$T'_1$|
  12907. \end{lstlisting}
  12908. Apply the \code{erase-type} function to all of the type annotations in
  12909. the program.
  12910. Regarding the translation of expressions, the case for \code{Inst} is
  12911. the interesting one. We translate it into a \code{Cast}, as shown
  12912. below. The type of the subexpression $e$ is the polymorphic type
  12913. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  12914. $T$, the type $T'$. The target type $T''$ is the result of
  12915. substituting the arguments types $ts$ for the type parameters $xs$ in
  12916. $T$ followed by doing type erasure.
  12917. \begin{lstlisting}
  12918. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  12919. |$\Rightarrow$|
  12920. (Cast |$e'$| |$T'$| |$T''$|)
  12921. \end{lstlisting}
  12922. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  12923. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  12924. Finally, each polymorphic function is translated to a regular
  12925. functions in which type erasure has been applied to all the type
  12926. annotations and the body.
  12927. \begin{lstlisting}
  12928. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  12929. |$\Rightarrow$|
  12930. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  12931. \end{lstlisting}
  12932. \begin{exercise}\normalfont
  12933. Implement a compiler for the polymorphic language \LangPoly{} by
  12934. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  12935. programs that use polymorphic functions. Some of them should make
  12936. use of first-class polymorphism.
  12937. \end{exercise}
  12938. \begin{figure}[p]
  12939. \begin{tikzpicture}[baseline=(current bounding box.center)]
  12940. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  12941. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  12942. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  12943. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  12944. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  12945. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  12946. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  12947. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  12948. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  12949. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  12950. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  12951. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  12952. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  12953. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  12954. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  12955. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  12956. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  12957. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  12958. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  12959. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  12960. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  12961. \path[->,bend right=15] (Rpoly) edge [above] node
  12962. {\ttfamily\footnotesize type-check} (Rpolyp);
  12963. \path[->,bend right=15] (Rpolyp) edge [above] node
  12964. {\ttfamily\footnotesize erase-types} (Rgradualp);
  12965. \path[->,bend right=15] (Rgradualp) edge [above] node
  12966. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  12967. \path[->,bend right=15] (Rwhilepp) edge [right] node
  12968. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  12969. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  12970. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  12971. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  12972. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  12973. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  12974. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  12975. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  12976. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  12977. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  12978. {\ttfamily\footnotesize convert-assignments} (F1-1);
  12979. \path[->,bend left=15] (F1-1) edge [below] node
  12980. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  12981. \path[->,bend right=15] (F1-2) edge [above] node
  12982. {\ttfamily\footnotesize limit-fun.} (F1-3);
  12983. \path[->,bend right=15] (F1-3) edge [above] node
  12984. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  12985. \path[->,bend right=15] (F1-4) edge [above] node
  12986. {\ttfamily\footnotesize remove-complex.} (F1-5);
  12987. \path[->,bend right=15] (F1-5) edge [right] node
  12988. {\ttfamily\footnotesize explicate-control} (C3-2);
  12989. \path[->,bend left=15] (C3-2) edge [left] node
  12990. {\ttfamily\footnotesize select-instr.} (x86-2);
  12991. \path[->,bend right=15] (x86-2) edge [left] node
  12992. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  12993. \path[->,bend right=15] (x86-2-1) edge [below] node
  12994. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  12995. \path[->,bend right=15] (x86-2-2) edge [left] node
  12996. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  12997. \path[->,bend left=15] (x86-3) edge [above] node
  12998. {\ttfamily\footnotesize patch-instr.} (x86-4);
  12999. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  13000. \end{tikzpicture}
  13001. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  13002. \label{fig:Rpoly-passes}
  13003. \end{figure}
  13004. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  13005. for the compilation of \LangPoly{}.
  13006. % TODO: challenge problem: specialization of instantiations
  13007. % Further Reading
  13008. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13009. \chapter{Appendix}
  13010. \section{Interpreters}
  13011. \label{appendix:interp}
  13012. \index{interpreter}
  13013. We provide interpreters for each of the source languages \LangInt{},
  13014. \LangVar{}, $\ldots$ in the files \code{interp-Rint.rkt},
  13015. \code{interp-Rvar.rkt}, etc. The interpreters for the intermediate
  13016. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  13017. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  13018. and x86 are in the \key{interp.rkt} file.
  13019. \section{Utility Functions}
  13020. \label{appendix:utilities}
  13021. The utility functions described in this section are in the
  13022. \key{utilities.rkt} file of the support code.
  13023. \paragraph{\code{interp-tests}}
  13024. The \key{interp-tests} function runs the compiler passes and the
  13025. interpreters on each of the specified tests to check whether each pass
  13026. is correct. The \key{interp-tests} function has the following
  13027. parameters:
  13028. \begin{description}
  13029. \item[name (a string)] a name to identify the compiler,
  13030. \item[typechecker] a function of exactly one argument that either
  13031. raises an error using the \code{error} function when it encounters a
  13032. type error, or returns \code{\#f} when it encounters a type
  13033. error. If there is no type error, the type checker returns the
  13034. program.
  13035. \item[passes] a list with one entry per pass. An entry is a list with
  13036. four things:
  13037. \begin{enumerate}
  13038. \item a string giving the name of the pass,
  13039. \item the function that implements the pass (a translator from AST
  13040. to AST),
  13041. \item a function that implements the interpreter (a function from
  13042. AST to result value) for the output language,
  13043. \item and a type checker for the output language. Type checkers for
  13044. the $R$ and $C$ languages are provided in the support code. For
  13045. example, the type checkers for \LangVar{} and \LangCVar{} are in
  13046. \code{type-check-Rvar.rkt} and \code{type-check-Cvar.rkt}. The
  13047. type checker entry is optional. The support code does not provide
  13048. type checkers for the x86 languages.
  13049. \end{enumerate}
  13050. \item[source-interp] an interpreter for the source language. The
  13051. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  13052. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  13053. \item[tests] a list of test numbers that specifies which tests to
  13054. run. (see below)
  13055. \end{description}
  13056. %
  13057. The \key{interp-tests} function assumes that the subdirectory
  13058. \key{tests} has a collection of Racket programs whose names all start
  13059. with the family name, followed by an underscore and then the test
  13060. number, ending with the file extension \key{.rkt}. Also, for each test
  13061. program that calls \code{read} one or more times, there is a file with
  13062. the same name except that the file extension is \key{.in} that
  13063. provides the input for the Racket program. If the test program is
  13064. expected to fail type checking, then there should be an empty file of
  13065. the same name but with extension \key{.tyerr}.
  13066. \paragraph{\code{compiler-tests}}
  13067. runs the compiler passes to generate x86 (a \key{.s} file) and then
  13068. runs the GNU C compiler (gcc) to generate machine code. It runs the
  13069. machine code and checks that the output is $42$. The parameters to the
  13070. \code{compiler-tests} function are similar to those of the
  13071. \code{interp-tests} function, and consist of
  13072. \begin{itemize}
  13073. \item a compiler name (a string),
  13074. \item a type checker,
  13075. \item description of the passes,
  13076. \item name of a test-family, and
  13077. \item a list of test numbers.
  13078. \end{itemize}
  13079. \paragraph{\code{compile-file}}
  13080. takes a description of the compiler passes (see the comment for
  13081. \key{interp-tests}) and returns a function that, given a program file
  13082. name (a string ending in \key{.rkt}), applies all of the passes and
  13083. writes the output to a file whose name is the same as the program file
  13084. name but with \key{.rkt} replaced with \key{.s}.
  13085. \paragraph{\code{read-program}}
  13086. takes a file path and parses that file (it must be a Racket program)
  13087. into an abstract syntax tree.
  13088. \paragraph{\code{parse-program}}
  13089. takes an S-expression representation of an abstract syntax tree and converts it into
  13090. the struct-based representation.
  13091. \paragraph{\code{assert}}
  13092. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  13093. and displays the message \key{msg} if the Boolean \key{bool} is false.
  13094. \paragraph{\code{lookup}}
  13095. % remove discussion of lookup? -Jeremy
  13096. takes a key and an alist, and returns the first value that is
  13097. associated with the given key, if there is one. If not, an error is
  13098. triggered. The alist may contain both immutable pairs (built with
  13099. \key{cons}) and mutable pairs (built with \key{mcons}).
  13100. %The \key{map2} function ...
  13101. \section{x86 Instruction Set Quick-Reference}
  13102. \label{sec:x86-quick-reference}
  13103. \index{x86}
  13104. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  13105. do. We write $A \to B$ to mean that the value of $A$ is written into
  13106. location $B$. Address offsets are given in bytes. The instruction
  13107. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  13108. registers (such as \code{\%rax}), or memory references (such as
  13109. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  13110. reference per instruction. Other operands must be immediates or
  13111. registers.
  13112. \begin{table}[tbp]
  13113. \centering
  13114. \begin{tabular}{l|l}
  13115. \textbf{Instruction} & \textbf{Operation} \\ \hline
  13116. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  13117. \texttt{negq} $A$ & $- A \to A$ \\
  13118. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  13119. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  13120. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  13121. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  13122. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  13123. \texttt{retq} & Pops the return address and jumps to it \\
  13124. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  13125. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  13126. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  13127. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  13128. be an immediate) \\
  13129. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  13130. matches the condition code of the instruction, otherwise go to the
  13131. next instructions. The condition codes are \key{e} for ``equal'',
  13132. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  13133. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  13134. \texttt{jl} $L$ & \\
  13135. \texttt{jle} $L$ & \\
  13136. \texttt{jg} $L$ & \\
  13137. \texttt{jge} $L$ & \\
  13138. \texttt{jmp} $L$ & Jump to label $L$ \\
  13139. \texttt{movq} $A$, $B$ & $A \to B$ \\
  13140. \texttt{movzbq} $A$, $B$ &
  13141. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  13142. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  13143. and the extra bytes of $B$ are set to zero.} \\
  13144. & \\
  13145. & \\
  13146. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  13147. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  13148. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  13149. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  13150. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  13151. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  13152. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  13153. description of the condition codes. $A$ must be a single byte register
  13154. (e.g., \texttt{al} or \texttt{cl}).} \\
  13155. \texttt{setl} $A$ & \\
  13156. \texttt{setle} $A$ & \\
  13157. \texttt{setg} $A$ & \\
  13158. \texttt{setge} $A$ &
  13159. \end{tabular}
  13160. \vspace{5pt}
  13161. \caption{Quick-reference for the x86 instructions used in this book.}
  13162. \label{tab:x86-instr}
  13163. \end{table}
  13164. \cleardoublepage
  13165. \section{Concrete Syntax for Intermediate Languages}
  13166. The concrete syntax of \LangAny{} is defined in
  13167. Figure~\ref{fig:Rany-concrete-syntax}.
  13168. \begin{figure}[tp]
  13169. \centering
  13170. \fbox{
  13171. \begin{minipage}{0.97\textwidth}\small
  13172. \[
  13173. \begin{array}{lcl}
  13174. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  13175. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \key{Void}} \\
  13176. &\mid& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \mid \key{Any} \\
  13177. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void}
  13178. \mid \LP\key{Vector}\; \key{Any}\ldots\RP \\
  13179. &\mid& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  13180. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \mid \CPROJECT{\Exp}{\FType}\\
  13181. &\mid& \LP\key{any-vector-length}\;\Exp\RP
  13182. \mid \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  13183. &\mid& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  13184. &\mid& \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP
  13185. \mid \LP\key{void?}\;\Exp\RP \\
  13186. &\mid& \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \\
  13187. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  13188. \LangAny{} &::=& \gray{\Def\ldots \; \Exp}
  13189. \end{array}
  13190. \]
  13191. \end{minipage}
  13192. }
  13193. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  13194. (Figure~\ref{fig:Rlam-syntax}).}
  13195. \label{fig:Rany-concrete-syntax}
  13196. \end{figure}
  13197. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and \LangCFun{} is
  13198. defined in Figures~\ref{fig:c0-concrete-syntax},
  13199. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax},
  13200. and \ref{fig:c3-concrete-syntax}, respectively.
  13201. \begin{figure}[tbp]
  13202. \fbox{
  13203. \begin{minipage}{0.96\textwidth}
  13204. \[
  13205. \begin{array}{lcl}
  13206. \Atm &::=& \Int \mid \Var \\
  13207. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  13208. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  13209. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  13210. \LangCVar{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  13211. \end{array}
  13212. \]
  13213. \end{minipage}
  13214. }
  13215. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  13216. \label{fig:c0-concrete-syntax}
  13217. \end{figure}
  13218. \begin{figure}[tbp]
  13219. \fbox{
  13220. \begin{minipage}{0.96\textwidth}
  13221. \small
  13222. \[
  13223. \begin{array}{lcl}
  13224. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  13225. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  13226. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  13227. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  13228. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  13229. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  13230. \mid \key{goto}~\itm{label}\key{;}\\
  13231. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  13232. \LangCIf{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  13233. \end{array}
  13234. \]
  13235. \end{minipage}
  13236. }
  13237. \caption{The concrete syntax of the \LangCIf{} intermediate language.}
  13238. \label{fig:c1-concrete-syntax}
  13239. \end{figure}
  13240. \begin{figure}[tbp]
  13241. \fbox{
  13242. \begin{minipage}{0.96\textwidth}
  13243. \small
  13244. \[
  13245. \begin{array}{lcl}
  13246. \Atm &::=& \gray{ \Int \mid \Var \mid \itm{bool} } \\
  13247. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  13248. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  13249. &\mid& \gray{ \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP } \\
  13250. &\mid& \LP \key{allocate}~\Int~\Type \RP \\
  13251. &\mid& (\key{vector-ref}\;\Atm\;\Int) \mid (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  13252. &\mid& \LP \key{global-value}~\Var \RP \mid \LP \key{void} \RP \\
  13253. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \mid \LP\key{collect}~\Int \RP\\
  13254. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  13255. \mid \gray{ \key{goto}~\itm{label}\key{;} }\\
  13256. &\mid& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  13257. \LangCVec{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  13258. \end{array}
  13259. \]
  13260. \end{minipage}
  13261. }
  13262. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  13263. \label{fig:c2-concrete-syntax}
  13264. \end{figure}
  13265. \begin{figure}[tp]
  13266. \fbox{
  13267. \begin{minipage}{0.96\textwidth}
  13268. \small
  13269. \[
  13270. \begin{array}{lcl}
  13271. \Atm &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  13272. \\
  13273. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  13274. \Exp &::= & \gray{ \Atm \mid \LP\key{read}\RP \mid \LP\key{-}\;\Atm\RP \mid \LP\key{+} \; \Atm\;\Atm\RP
  13275. \mid \LP\key{not}\;\Atm\RP \mid \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  13276. &\mid& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  13277. \mid \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  13278. &\mid& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \mid \LP\key{global-value} \,\itm{name}\RP \mid \LP\key{void}\RP } \\
  13279. &\mid& \LP\key{fun-ref}~\itm{label}\RP \mid \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  13280. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  13281. \mid \LP\key{collect} \,\itm{int}\RP }\\
  13282. \Tail &::= & \gray{\RETURN{\Exp} \mid \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  13283. &\mid& \gray{\LP\key{goto}\,\itm{label}\RP
  13284. \mid \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  13285. &\mid& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  13286. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  13287. \LangCFun{} & ::= & \Def\ldots
  13288. \end{array}
  13289. \]
  13290. \end{minipage}
  13291. }
  13292. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  13293. \label{fig:c3-concrete-syntax}
  13294. \end{figure}
  13295. \cleardoublepage
  13296. \addcontentsline{toc}{chapter}{Index}
  13297. \printindex
  13298. \cleardoublepage
  13299. \bibliographystyle{plainnat}
  13300. \bibliography{all}
  13301. \addcontentsline{toc}{chapter}{Bibliography}
  13302. \end{document}
  13303. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  13304. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  13305. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  13306. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  13307. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator jane
  13308. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  13309. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  13310. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  13311. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs Tt
  13312. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  13313. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  13314. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  13315. %% LocalWords: boolean type-check notq cmpq sete movzbq jmp al xorq
  13316. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  13317. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  13318. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  13319. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  13320. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  13321. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  13322. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  13323. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  13324. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  13325. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  13326. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  13327. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  13328. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  13329. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  13330. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  13331. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  13332. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  13333. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  13334. % LocalWords: struct Friedman's MacOS Nystrom alist sam kate
  13335. % LocalWords: alists arity github unordered pqueue exprs ret param
  13336. % LocalWords: tyerr bytereg dh dl JmpIf HasType Osterlund Jacek TODO
  13337. % LocalWords: Gamari GlobalValue ProgramDefsExp prm ProgramDefs vn
  13338. % LocalWords: FunRef TailCall tailjmp IndirectCallq TailJmp Gilray
  13339. % LocalWords: dereference unbox Dataflow versa dataflow Kildall rhs
  13340. % LocalWords: Kleene enqueue dequeue AssignedFree FV cnvt SetBang tg
  13341. % LocalWords: ValueOf typechecker