book.tex 539 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931
  1. % Why direct style instead of continuation passing style?
  2. %% Student project ideas:
  3. %% * high-level optimizations like procedure inlining, etc.
  4. %% * closure optimization
  5. %% * adding letrec to the language
  6. %% (Thought: in the book and regular course, replace top-level defines
  7. %% with letrec.)
  8. %% * alternative back ends (ARM!, LLVM)
  9. %% * alternative calling convention (a la Dybvig)
  10. %% * lazy evaluation
  11. %% * continuations (frames in heap a la SML or segmented stack a la Dybvig)
  12. %% * exceptions
  13. %% * self hosting
  14. %% * I/O
  15. %% * foreign function interface
  16. %% * quasi-quote and unquote
  17. %% * macros (too difficult?)
  18. %% * alternative garbage collector
  19. %% * alternative register allocator
  20. %% * type classes
  21. %% * loop optimization (fusion, etc.)
  22. %% * deforestation
  23. %% * records with subtyping
  24. %% * object-oriented features
  25. %% - objects, object types, and structural subtyping (e.g. Abadi & Cardelli)
  26. %% - class-based objects and nominal subtyping (e.g. Featherweight Java)
  27. %% * multi-threading, fork join, futures, implicit parallelism
  28. %% * type analysis and specialization
  29. \documentclass[11pt]{book}
  30. \usepackage[T1]{fontenc}
  31. \usepackage[utf8]{inputenc}
  32. \usepackage{lmodern}
  33. \usepackage{hyperref}
  34. \usepackage{graphicx}
  35. \usepackage[english]{babel}
  36. \usepackage{listings}
  37. \usepackage{amsmath}
  38. \usepackage{amsthm}
  39. \usepackage{amssymb}
  40. \usepackage[numbers]{natbib}
  41. \usepackage{stmaryrd}
  42. \usepackage{xypic}
  43. \usepackage{semantic}
  44. \usepackage{wrapfig}
  45. \usepackage{tcolorbox}
  46. \usepackage{multirow}
  47. \usepackage{color}
  48. \usepackage{upquote}
  49. \usepackage{makeidx}
  50. \makeindex
  51. \definecolor{lightgray}{gray}{1}
  52. \newcommand{\black}[1]{{\color{black} #1}}
  53. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  54. \newcommand{\gray}[1]{{\color{gray} #1}}
  55. %% For pictures
  56. \usepackage{tikz}
  57. \usetikzlibrary{arrows.meta}
  58. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  59. % Computer Modern is already the default. -Jeremy
  60. %\renewcommand{\ttdefault}{cmtt}
  61. \definecolor{comment-red}{rgb}{0.8,0,0}
  62. \if01
  63. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  64. \newcommand{\margincomment}[1]{\marginpar{\color{comment-red}\tiny #1}}
  65. \else
  66. \newcommand{\rn}[1]{}
  67. \newcommand{\margincomment}[1]{}
  68. \fi
  69. \lstset{%
  70. language=Lisp,
  71. basicstyle=\ttfamily\small,
  72. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  73. deletekeywords={read,mapping,vector},
  74. escapechar=|,
  75. columns=flexible,
  76. moredelim=[is][\color{red}]{~}{~},
  77. showstringspaces=false
  78. }
  79. \newtheorem{theorem}{Theorem}
  80. \newtheorem{lemma}[theorem]{Lemma}
  81. \newtheorem{corollary}[theorem]{Corollary}
  82. \newtheorem{proposition}[theorem]{Proposition}
  83. \newtheorem{constraint}[theorem]{Constraint}
  84. \newtheorem{definition}[theorem]{Definition}
  85. \newtheorem{exercise}[theorem]{Exercise}
  86. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  87. % 'dedication' environment: To add a dedication paragraph at the start of book %
  88. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  89. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  90. \newenvironment{dedication}
  91. {
  92. \cleardoublepage
  93. \thispagestyle{empty}
  94. \vspace*{\stretch{1}}
  95. \hfill\begin{minipage}[t]{0.66\textwidth}
  96. \raggedright
  97. }
  98. {
  99. \end{minipage}
  100. \vspace*{\stretch{3}}
  101. \clearpage
  102. }
  103. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  104. % Chapter quote at the start of chapter %
  105. % Source: http://tex.stackexchange.com/a/53380 %
  106. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  107. \makeatletter
  108. \renewcommand{\@chapapp}{}% Not necessary...
  109. \newenvironment{chapquote}[2][2em]
  110. {\setlength{\@tempdima}{#1}%
  111. \def\chapquote@author{#2}%
  112. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  113. \itshape}
  114. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  115. \makeatother
  116. \input{defs}
  117. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  118. \title{\Huge \textbf{Essentials of Compilation} \\
  119. \huge The Incremental, Nano-Pass Approach}
  120. \author{\textsc{Jeremy G. Siek} \\
  121. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  122. Indiana University \\
  123. \\
  124. with contributions from: \\
  125. Carl Factora \\
  126. Andre Kuhlenschmidt \\
  127. Ryan R. Newton \\
  128. Ryan Scott \\
  129. Cameron Swords \\
  130. Michael M. Vitousek \\
  131. Michael Vollmer
  132. }
  133. \begin{document}
  134. \frontmatter
  135. \maketitle
  136. \begin{dedication}
  137. This book is dedicated to the programming language wonks at Indiana
  138. University.
  139. \end{dedication}
  140. \tableofcontents
  141. \listoffigures
  142. %\listoftables
  143. \mainmatter
  144. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  145. \chapter*{Preface}
  146. There is a magical moment when a programmer presses the ``run'' button
  147. and the software begins to execute. Somehow a program written in a
  148. high-level language is running on a computer that is only capable of
  149. shuffling bits. Here we reveal the wizardry that makes that moment
  150. possible. Beginning with the groundbreaking work of Backus and
  151. colleagues in the 1950s, computer scientists discovered techniques for
  152. constructing programs, called \emph{compilers}, that automatically
  153. translate high-level programs into machine code.
  154. We take you on a journey by constructing your own compiler for a small
  155. but powerful language. Along the way we explain the essential
  156. concepts, algorithms, and data structures that underlie compilers. We
  157. develop your understanding of how programs are mapped onto computer
  158. hardware, which is helpful when reasoning about properties at the
  159. junction between hardware and software such as execution time,
  160. software errors, and security vulnerabilities. For those interested
  161. in pursuing compiler construction, our goal is to provide a
  162. stepping-stone to advanced topics such as just-in-time compilation,
  163. program analysis, and program optimization. For those interested in
  164. designing and implementing programming languages, we connect
  165. language design choices to their impact on the compiler and the generated
  166. code.
  167. A compiler is typically organized as a sequence of stages that
  168. progressively translates a program to code that runs on hardware. We
  169. take this approach to the extreme by partitioning our compiler into a
  170. large number of \emph{nanopasses}, each of which performs a single
  171. task. This allows us to test the output of each pass in isolation, and
  172. furthermore, allows us to focus our attention making the compiler far
  173. easier to understand.
  174. %% [TODO: easier to understand/debug for those maintaining the compiler,
  175. %% proving correctness]
  176. The most familiar approach to describing compilers is with one pass
  177. per chapter. The problem with that is it obfuscates how language
  178. features motivate design choices in a compiler. We take an
  179. \emph{incremental} approach in which we build a complete compiler in
  180. each chapter, starting with arithmetic and variables and add new
  181. features in subsequent chapters.
  182. Our choice of language features is designed to elicit the fundamental
  183. concepts and algorithms used in compilers.
  184. \begin{itemize}
  185. \item We begin with integer arithmetic and local variables in
  186. Chapters~\ref{ch:trees-recur} and \ref{ch:Rvar}, where we introduce
  187. the fundamental tools of compiler construction: \emph{abstract
  188. syntax trees} and \emph{recursive functions}.
  189. \item In Chapter~\ref{ch:register-allocation-Rvar} we apply
  190. \emph{graph coloring} to assign variables to machine registers.
  191. \item Chapter~\ref{ch:Rif} adds \code{if} expressions, which motivates
  192. an elegant recursive algorithm for mapping expressions to
  193. \emph{control-flow graphs}.
  194. \item Chapter~\ref{ch:Rvec} adds heap-allocated tuples, motivating
  195. \emph{garbage collection}.
  196. \item Chapter~\ref{ch:Rfun} adds functions that are first-class values
  197. but lack lexical scoping, similar to the C programming
  198. language~\citep{Kernighan:1988nx} except that we generate efficient
  199. tail calls. The reader learns about the procedure call stack,
  200. \emph{calling conventions}, and their interaction with register
  201. allocation and garbage collection.
  202. \item Chapter~\ref{ch:Rlam} adds anonymous functions with lexical
  203. scoping, i.e., \emph{lambda abstraction}. The reader learns about
  204. \emph{closure conversion}, in which lambdas are translated into a
  205. combination of functions and tuples.
  206. \item Chapter~\ref{ch:Rdyn} adds \emph{dynamic typing}. Prior to this
  207. point the input languages are statically typed. The reader extends
  208. the statically typed language with an \code{Any} type which serves
  209. as a target for compiling the dynamically typed language.
  210. \item Chapter~\ref{ch:Rwhile} fleshes out support for imperative
  211. programming languages with the addition of loops and mutable
  212. variables. These additions elicit the need for \emph{dataflow
  213. analysis} in the register allocator.
  214. \item Chapter~\ref{ch:Rgrad} uses the \code{Any} type of
  215. Chapter~\ref{ch:Rdyn} to implement a \emph{gradually typed language}
  216. in which different regions of a program may be static or dynamically
  217. typed. The reader implements runtime support for \emph{proxies} that
  218. allow values to safely move between regions.
  219. \item Chapter~\ref{ch:Rpoly} adds \emph{generics} with autoboxing,
  220. leveraging the \code{Any} type and type casts developed in Chapters
  221. \ref{ch:Rdyn} and \ref{ch:Rgrad}.
  222. \end{itemize}
  223. There are many language features that we do not include. Our choices
  224. weigh the incidental complexity of a feature against the fundamental
  225. concepts that it exposes. For example, we include tuples and not
  226. records because they both elicit the study of heap allocation and
  227. garbage collection but records come with more incidental complexity.
  228. Since 2016 this book has served as the textbook for the compiler
  229. course at Indiana University, a 16-week course for upper-level
  230. undergraduates and first-year graduate students.
  231. %
  232. Prior to this course, students learn to program in both imperative and
  233. functional languages, study data structures and algorithms, and take
  234. discrete mathematics.
  235. %
  236. At the beginning of the course, students form groups of 2-4 people.
  237. The groups complete one chapter every two weeks, starting with
  238. Chapter~\ref{ch:Rvar} and finishing with Chapter~\ref{ch:Rdyn}. Many
  239. chapters include a challenge problem that we assign to the graduate
  240. students. The last two weeks of the course involve a final project in
  241. which students design and implement a compiler extension of their
  242. choosing. Chapters~\ref{ch:Rwhile}, \ref{ch:Rgrad}, and
  243. \ref{ch:Rpoly} can be used in support of these projects or they can
  244. replace some of the earlier chapters. For example, a course with an
  245. emphasis on statically-typed imperative languages would skip
  246. Chapter~\ref{ch:Rdyn} in favor of
  247. Chapter~\ref{ch:Rwhile}. Figure~\ref{fig:chapter-dependences} depicts
  248. the dependencies between chapters.
  249. This book has also been used in compiler courses at California
  250. Polytechnic State University, Rose–Hulman Institute of Technology, and
  251. University of Massachusetts Lowell.
  252. \begin{figure}[tp]
  253. \begin{tikzpicture}[baseline=(current bounding box.center)]
  254. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  255. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Rvar} Variables};
  256. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Rvar} Registers};
  257. \node (C4) at (0,0) {\small Ch.~\ref{ch:Rif} Control Flow};
  258. \node (C5) at (4,0) {\small Ch.~\ref{ch:Rvec} Tuples};
  259. \node (C6) at (8,0) {\small Ch.~\ref{ch:Rfun} Functions};
  260. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Rwhile} Loops};
  261. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Rdyn} Dynamic};
  262. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Rlam} Lambda};
  263. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Rgrad} Gradual};
  264. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Rpoly} Generics};
  265. \path[->] (C1) edge [above] node {} (C2);
  266. \path[->] (C2) edge [above] node {} (C3);
  267. \path[->] (C3) edge [above] node {} (C4);
  268. \path[->] (C4) edge [above] node {} (C5);
  269. \path[->] (C5) edge [above] node {} (C6);
  270. \path[->] (C6) edge [above] node {} (C7);
  271. \path[->] (C4) edge [above] node {} (C8);
  272. \path[->] (C4) edge [above] node {} (C9);
  273. \path[->] (C8) edge [above] node {} (C10);
  274. \path[->] (C10) edge [above] node {} (C11);
  275. \end{tikzpicture}
  276. \caption{Diagram of chapter dependencies.}
  277. \label{fig:chapter-dependences}
  278. \end{figure}
  279. We use the \href{https://racket-lang.org/}{Racket} language both for
  280. the implementation of the compiler and for the input language, so the
  281. reader should be proficient with Racket or Scheme. There are many
  282. excellent resources for learning Scheme and
  283. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. The
  284. support code for this book is in the \code{github} repository at the
  285. following URL:
  286. \begin{center}\small
  287. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  288. \end{center}
  289. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  290. is helpful but not necessary for the reader to have taken a computer
  291. systems course~\citep{Bryant:2010aa}. This book introduces the parts
  292. of x86-64 assembly language that are needed.
  293. %
  294. We follow the System V calling
  295. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  296. that we generate works with the runtime system (written in C) when it
  297. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  298. operating systems.
  299. %
  300. On the Windows operating system, \code{gcc} uses the Microsoft x64
  301. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  302. assembly code that we generate does \emph{not} work with the runtime
  303. system on Windows. One workaround is to use a virtual machine with
  304. Linux as the guest operating system.
  305. \section*{Acknowledgments}
  306. The tradition of compiler construction at Indiana University goes back
  307. to research and courses on programming languages by Daniel Friedman in
  308. the 1970's and 1980's. One of his students, Kent Dybvig, implemented
  309. Chez Scheme~\citep{Dybvig:2006aa}, a production-quality, efficient
  310. compiler for Scheme. Throughout the 1990's and 2000's, Dybvig taught
  311. the compiler course and continued the development of Chez Scheme.
  312. %
  313. The compiler course evolved to incorporate novel pedagogical ideas
  314. while also including elements of efficient real-world compilers. One
  315. of Friedman's ideas was to split the compiler into many small
  316. passes. Another idea, called ``the game'', was to test the code
  317. generated by each pass on interpreters.
  318. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  319. developed infrastructure to support this approach and evolved the
  320. course to use even smaller
  321. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  322. design decisions in this book are inspired by the assignment
  323. descriptions of \citet{Dybvig:2010aa}. In the mid 2000's a student of
  324. Dybvig's named Abdulaziz Ghuloum observed that the front-to-back
  325. organization of the course made it difficult for students to
  326. understand the rationale for the compiler design. Ghuloum proposed the
  327. incremental approach~\citep{Ghuloum:2006bh}.
  328. We thank Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph Near, Nate
  329. Nystrom, and Michael Wollowski for teaching courses based on early
  330. drafts.
  331. We thank Ronald Garcia for being Jeremy's partner when they took the
  332. compiler course in the early 2000's and especially for finding the bug
  333. that sent the garbage collector on a wild goose chase!
  334. \mbox{}\\
  335. \noindent Jeremy G. Siek \\
  336. Bloomington, Indiana
  337. %Oscar Waddell ??
  338. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  339. \chapter{Preliminaries}
  340. \label{ch:trees-recur}
  341. In this chapter we review the basic tools that are needed to implement
  342. a compiler. Programs are typically input by a programmer as text,
  343. i.e., a sequence of characters. The program-as-text representation is
  344. called \emph{concrete syntax}. We use concrete syntax to concisely
  345. write down and talk about programs. Inside the compiler, we use
  346. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  347. that efficiently supports the operations that the compiler needs to
  348. perform.\index{concrete syntax}\index{abstract syntax}\index{abstract
  349. syntax tree}\index{AST}\index{program}\index{parse} The translation
  350. from concrete syntax to abstract syntax is a process called
  351. \emph{parsing}~\citep{Aho:1986qf}. We do not cover the theory and
  352. implementation of parsing in this book. A parser is provided in the
  353. support code for translating from concrete to abstract syntax.
  354. ASTs can be represented in many different ways inside the compiler,
  355. depending on the programming language used to write the compiler.
  356. %
  357. We use Racket's
  358. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  359. feature to represent ASTs (Section~\ref{sec:ast}). We use grammars to
  360. define the abstract syntax of programming languages
  361. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  362. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  363. recursive functions to construct and deconstruct ASTs
  364. (Section~\ref{sec:recursion}). This chapter provides an brief
  365. introduction to these ideas. \index{struct}
  366. \section{Abstract Syntax Trees and Racket Structures}
  367. \label{sec:ast}
  368. Compilers use abstract syntax trees to represent programs because they
  369. often need to ask questions like: for a given part of a program, what
  370. kind of language feature is it? What are its sub-parts? Consider the
  371. program on the left and its AST on the right. This program is an
  372. addition operation and it has two sub-parts, a read operation and a
  373. negation. The negation has another sub-part, the integer constant
  374. \code{8}. By using a tree to represent the program, we can easily
  375. follow the links to go from one part of a program to its sub-parts.
  376. \begin{center}
  377. \begin{minipage}{0.4\textwidth}
  378. \begin{lstlisting}
  379. (+ (read) (- 8))
  380. \end{lstlisting}
  381. \end{minipage}
  382. \begin{minipage}{0.4\textwidth}
  383. \begin{equation}
  384. \begin{tikzpicture}
  385. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  386. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  387. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  388. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  389. \draw[->] (plus) to (read);
  390. \draw[->] (plus) to (minus);
  391. \draw[->] (minus) to (8);
  392. \end{tikzpicture}
  393. \label{eq:arith-prog}
  394. \end{equation}
  395. \end{minipage}
  396. \end{center}
  397. We use the standard terminology for trees to describe ASTs: each
  398. circle above is called a \emph{node}. The arrows connect a node to its
  399. \emph{children} (which are also nodes). The top-most node is the
  400. \emph{root}. Every node except for the root has a \emph{parent} (the
  401. node it is the child of). If a node has no children, it is a
  402. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  403. \index{node}
  404. \index{children}
  405. \index{root}
  406. \index{parent}
  407. \index{leaf}
  408. \index{internal node}
  409. %% Recall that an \emph{symbolic expression} (S-expression) is either
  410. %% \begin{enumerate}
  411. %% \item an atom, or
  412. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  413. %% where $e_1$ and $e_2$ are each an S-expression.
  414. %% \end{enumerate}
  415. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  416. %% null value \code{'()}, etc. We can create an S-expression in Racket
  417. %% simply by writing a backquote (called a quasi-quote in Racket)
  418. %% followed by the textual representation of the S-expression. It is
  419. %% quite common to use S-expressions to represent a list, such as $a, b
  420. %% ,c$ in the following way:
  421. %% \begin{lstlisting}
  422. %% `(a . (b . (c . ())))
  423. %% \end{lstlisting}
  424. %% Each element of the list is in the first slot of a pair, and the
  425. %% second slot is either the rest of the list or the null value, to mark
  426. %% the end of the list. Such lists are so common that Racket provides
  427. %% special notation for them that removes the need for the periods
  428. %% and so many parenthesis:
  429. %% \begin{lstlisting}
  430. %% `(a b c)
  431. %% \end{lstlisting}
  432. %% The following expression creates an S-expression that represents AST
  433. %% \eqref{eq:arith-prog}.
  434. %% \begin{lstlisting}
  435. %% `(+ (read) (- 8))
  436. %% \end{lstlisting}
  437. %% When using S-expressions to represent ASTs, the convention is to
  438. %% represent each AST node as a list and to put the operation symbol at
  439. %% the front of the list. The rest of the list contains the children. So
  440. %% in the above case, the root AST node has operation \code{`+} and its
  441. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  442. %% diagram \eqref{eq:arith-prog}.
  443. %% To build larger S-expressions one often needs to splice together
  444. %% several smaller S-expressions. Racket provides the comma operator to
  445. %% splice an S-expression into a larger one. For example, instead of
  446. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  447. %% we could have first created an S-expression for AST
  448. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  449. %% S-expression.
  450. %% \begin{lstlisting}
  451. %% (define ast1.4 `(- 8))
  452. %% (define ast1.1 `(+ (read) ,ast1.4))
  453. %% \end{lstlisting}
  454. %% In general, the Racket expression that follows the comma (splice)
  455. %% can be any expression that produces an S-expression.
  456. We define a Racket \code{struct} for each kind of node. For this
  457. chapter we require just two kinds of nodes: one for integer constants
  458. and one for primitive operations. The following is the \code{struct}
  459. definition for integer constants.
  460. \begin{lstlisting}
  461. (struct Int (value))
  462. \end{lstlisting}
  463. An integer node includes just one thing: the integer value.
  464. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  465. \begin{lstlisting}
  466. (define eight (Int 8))
  467. \end{lstlisting}
  468. We say that the value created by \code{(Int 8)} is an
  469. \emph{instance} of the \code{Int} structure.
  470. The following is the \code{struct} definition for primitives operations.
  471. \begin{lstlisting}
  472. (struct Prim (op args))
  473. \end{lstlisting}
  474. A primitive operation node includes an operator symbol \code{op}
  475. and a list of children \code{args}. For example, to create
  476. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  477. \begin{lstlisting}
  478. (define neg-eight (Prim '- (list eight)))
  479. \end{lstlisting}
  480. Primitive operations may have zero or more children. The \code{read}
  481. operator has zero children:
  482. \begin{lstlisting}
  483. (define rd (Prim 'read '()))
  484. \end{lstlisting}
  485. whereas the addition operator has two children:
  486. \begin{lstlisting}
  487. (define ast1.1 (Prim '+ (list rd neg-eight)))
  488. \end{lstlisting}
  489. We have made a design choice regarding the \code{Prim} structure.
  490. Instead of using one structure for many different operations
  491. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  492. structure for each operation, as follows.
  493. \begin{lstlisting}
  494. (struct Read ())
  495. (struct Add (left right))
  496. (struct Neg (value))
  497. \end{lstlisting}
  498. The reason we choose to use just one structure is that in many parts
  499. of the compiler the code for the different primitive operators is the
  500. same, so we might as well just write that code once, which is enabled
  501. by using a single structure.
  502. When compiling a program such as \eqref{eq:arith-prog}, we need to
  503. know that the operation associated with the root node is addition and
  504. we need to be able to access its two children. Racket provides pattern
  505. matching to support these kinds of queries, as we see in
  506. Section~\ref{sec:pattern-matching}.
  507. In this book, we often write down the concrete syntax of a program
  508. even when we really have in mind the AST because the concrete syntax
  509. is more concise. We recommend that, in your mind, you always think of
  510. programs as abstract syntax trees.
  511. \section{Grammars}
  512. \label{sec:grammar}
  513. \index{integer}
  514. \index{literal}
  515. \index{constant}
  516. A programming language can be thought of as a \emph{set} of programs.
  517. The set is typically infinite (one can always create larger and larger
  518. programs), so one cannot simply describe a language by listing all of
  519. the programs in the language. Instead we write down a set of rules, a
  520. \emph{grammar}, for building programs. Grammars are often used to
  521. define the concrete syntax of a language, but they can also be used to
  522. describe the abstract syntax. We write our rules in a variant of
  523. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  524. \index{Backus-Naur Form}\index{BNF}
  525. As an example, we describe a small language, named \LangInt{}, that consists of
  526. integers and arithmetic operations.
  527. \index{grammar}
  528. The first grammar rule for the abstract syntax of \LangInt{} says that an
  529. instance of the \code{Int} structure is an expression:
  530. \begin{equation}
  531. \Exp ::= \INT{\Int} \label{eq:arith-int}
  532. \end{equation}
  533. %
  534. Each rule has a left-hand-side and a right-hand-side. The way to read
  535. a rule is that if you have an AST node that matches the
  536. right-hand-side, then you can categorize it according to the
  537. left-hand-side.
  538. %
  539. A name such as $\Exp$ that is defined by the grammar rules is a
  540. \emph{non-terminal}. \index{non-terminal}
  541. %
  542. The name $\Int$ is a also a non-terminal, but instead of defining it
  543. with a grammar rule, we define it with the following explanation. We
  544. make the simplifying design decision that all of the languages in this
  545. book only handle machine-representable integers. On most modern
  546. machines this corresponds to integers represented with 64-bits, i.e.,
  547. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  548. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  549. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  550. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  551. that the sequence of decimals represent an integer in range $-2^{62}$
  552. to $2^{62}-1$.
  553. The second grammar rule is the \texttt{read} operation that receives
  554. an input integer from the user of the program.
  555. \begin{equation}
  556. \Exp ::= \READ{} \label{eq:arith-read}
  557. \end{equation}
  558. The third rule says that, given an $\Exp$ node, the negation of that
  559. node is also an $\Exp$.
  560. \begin{equation}
  561. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  562. \end{equation}
  563. Symbols in typewriter font such as \key{-} and \key{read} are
  564. \emph{terminal} symbols and must literally appear in the program for
  565. the rule to be applicable.
  566. \index{terminal}
  567. We can apply these rules to categorize the ASTs that are in the
  568. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  569. \texttt{(Int 8)} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  570. following AST is an $\Exp$.
  571. \begin{center}
  572. \begin{minipage}{0.4\textwidth}
  573. \begin{lstlisting}
  574. (Prim '- (list (Int 8)))
  575. \end{lstlisting}
  576. \end{minipage}
  577. \begin{minipage}{0.25\textwidth}
  578. \begin{equation}
  579. \begin{tikzpicture}
  580. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  581. \node[draw, circle] (8) at (0, -1.2) {$8$};
  582. \draw[->] (minus) to (8);
  583. \end{tikzpicture}
  584. \label{eq:arith-neg8}
  585. \end{equation}
  586. \end{minipage}
  587. \end{center}
  588. The next grammar rule is for addition expressions:
  589. \begin{equation}
  590. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  591. \end{equation}
  592. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  593. \LangInt{}. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  594. \eqref{eq:arith-read} and we have already categorized \code{(Prim '-
  595. (list (Int 8)))} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  596. to show that
  597. \begin{lstlisting}
  598. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  599. \end{lstlisting}
  600. is an $\Exp$ in the \LangInt{} language.
  601. If you have an AST for which the above rules do not apply, then the
  602. AST is not in \LangInt{}. For example, the program \code{(- (read) (+ 8))}
  603. is not in \LangInt{} because there are no rules for \code{+} with only one
  604. argument, nor for \key{-} with two arguments. Whenever we define a
  605. language with a grammar, the language only includes those programs
  606. that are justified by the rules.
  607. The last grammar rule for \LangInt{} states that there is a \code{Program}
  608. node to mark the top of the whole program:
  609. \[
  610. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  611. \]
  612. The \code{Program} structure is defined as follows
  613. \begin{lstlisting}
  614. (struct Program (info body))
  615. \end{lstlisting}
  616. where \code{body} is an expression. In later chapters, the \code{info}
  617. part will be used to store auxiliary information but for now it is
  618. just the empty list.
  619. It is common to have many grammar rules with the same left-hand side
  620. but different right-hand sides, such as the rules for $\Exp$ in the
  621. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  622. combine several right-hand-sides into a single rule.
  623. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  624. in Figure~\ref{fig:r0-syntax}. The concrete syntax for \LangInt{} is
  625. defined in Figure~\ref{fig:r0-concrete-syntax}.
  626. The \code{read-program} function provided in \code{utilities.rkt} of
  627. the support code reads a program in from a file (the sequence of
  628. characters in the concrete syntax of Racket) and parses it into an
  629. abstract syntax tree. See the description of \code{read-program} in
  630. Appendix~\ref{appendix:utilities} for more details.
  631. \begin{figure}[tp]
  632. \fbox{
  633. \begin{minipage}{0.96\textwidth}
  634. \[
  635. \begin{array}{rcl}
  636. \begin{array}{rcl}
  637. \Exp &::=& \Int \mid \LP\key{read}\RP \mid \LP\key{-}\;\Exp\RP \mid \LP\key{+} \; \Exp\;\Exp\RP\\
  638. \LangInt{} &::=& \Exp
  639. \end{array}
  640. \end{array}
  641. \]
  642. \end{minipage}
  643. }
  644. \caption{The concrete syntax of \LangInt{}.}
  645. \label{fig:r0-concrete-syntax}
  646. \end{figure}
  647. \begin{figure}[tp]
  648. \fbox{
  649. \begin{minipage}{0.96\textwidth}
  650. \[
  651. \begin{array}{rcl}
  652. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  653. &\mid& \ADD{\Exp}{\Exp} \\
  654. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  655. \end{array}
  656. \]
  657. \end{minipage}
  658. }
  659. \caption{The abstract syntax of \LangInt{}.}
  660. \label{fig:r0-syntax}
  661. \end{figure}
  662. \section{Pattern Matching}
  663. \label{sec:pattern-matching}
  664. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  665. the parts of an AST node. Racket provides the \texttt{match} form to
  666. access the parts of a structure. Consider the following example and
  667. the output on the right. \index{match} \index{pattern matching}
  668. \begin{center}
  669. \begin{minipage}{0.5\textwidth}
  670. \begin{lstlisting}
  671. (match ast1.1
  672. [(Prim op (list child1 child2))
  673. (print op)])
  674. \end{lstlisting}
  675. \end{minipage}
  676. \vrule
  677. \begin{minipage}{0.25\textwidth}
  678. \begin{lstlisting}
  679. '+
  680. \end{lstlisting}
  681. \end{minipage}
  682. \end{center}
  683. In the above example, the \texttt{match} form takes an AST
  684. \eqref{eq:arith-prog} and binds its parts to the three pattern
  685. variables \texttt{op}, \texttt{child1}, and \texttt{child2}, and then
  686. prints out the operator. In general, a match clause consists of a
  687. \emph{pattern} and a \emph{body}.\index{pattern} Patterns are
  688. recursively defined to be either a pattern variable, a structure name
  689. followed by a pattern for each of the structure's arguments, or an
  690. S-expression (symbols, lists, etc.). (See Chapter 12 of The Racket
  691. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  692. and Chapter 9 of The Racket
  693. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  694. for a complete description of \code{match}.)
  695. %
  696. The body of a match clause may contain arbitrary Racket code. The
  697. pattern variables can be used in the scope of the body, such as
  698. \code{op} in \code{(print op)}.
  699. A \code{match} form may contain several clauses, as in the following
  700. function \code{leaf?} that recognizes when an \LangInt{} node is a leaf in
  701. the AST. The \code{match} proceeds through the clauses in order,
  702. checking whether the pattern can match the input AST. The body of the
  703. first clause that matches is executed. The output of \code{leaf?} for
  704. several ASTs is shown on the right.
  705. \begin{center}
  706. \begin{minipage}{0.6\textwidth}
  707. \begin{lstlisting}
  708. (define (leaf? arith)
  709. (match arith
  710. [(Int n) #t]
  711. [(Prim 'read '()) #t]
  712. [(Prim '- (list e1)) #f]
  713. [(Prim '+ (list e1 e2)) #f]))
  714. (leaf? (Prim 'read '()))
  715. (leaf? (Prim '- (list (Int 8))))
  716. (leaf? (Int 8))
  717. \end{lstlisting}
  718. \end{minipage}
  719. \vrule
  720. \begin{minipage}{0.25\textwidth}
  721. \begin{lstlisting}
  722. #t
  723. #f
  724. #t
  725. \end{lstlisting}
  726. \end{minipage}
  727. \end{center}
  728. When writing a \code{match}, we refer to the grammar definition to
  729. identify which non-terminal we are expecting to match against, then we
  730. make sure that 1) we have one clause for each alternative of that
  731. non-terminal and 2) that the pattern in each clause corresponds to the
  732. corresponding right-hand side of a grammar rule. For the \code{match}
  733. in the \code{leaf?} function, we refer to the grammar for \LangInt{} in
  734. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  735. alternatives, so the \code{match} has 4 clauses. The pattern in each
  736. clause corresponds to the right-hand side of a grammar rule. For
  737. example, the pattern \code{(Prim '+ (list e1 e2))} corresponds to the
  738. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  739. patterns, replace non-terminals such as $\Exp$ with pattern variables
  740. of your choice (e.g. \code{e1} and \code{e2}).
  741. \section{Recursive Functions}
  742. \label{sec:recursion}
  743. \index{recursive function}
  744. Programs are inherently recursive. For example, an \LangInt{} expression is
  745. often made of smaller expressions. Thus, the natural way to process an
  746. entire program is with a recursive function. As a first example of
  747. such a recursive function, we define \texttt{exp?} below, which takes
  748. an arbitrary value and determines whether or not it is an \LangInt{}
  749. expression.
  750. %
  751. We say that a function is defined by \emph{structural recursion} when
  752. it is defined using a sequence of match clauses that correspond to a
  753. grammar, and the body of each clause makes a recursive call on each
  754. child node.\footnote{This principle of structuring code according to
  755. the data definition is advocated in the book \emph{How to Design
  756. Programs} \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}.
  757. Below we also define a second function, named \code{Rint?}, that
  758. determines whether an AST is an \LangInt{} program. In general we can
  759. expect to write one recursive function to handle each non-terminal in
  760. a grammar.\index{structural recursion}
  761. %
  762. \begin{center}
  763. \begin{minipage}{0.7\textwidth}
  764. \begin{lstlisting}
  765. (define (exp? ast)
  766. (match ast
  767. [(Int n) #t]
  768. [(Prim 'read '()) #t]
  769. [(Prim '- (list e)) (exp? e)]
  770. [(Prim '+ (list e1 e2))
  771. (and (exp? e1) (exp? e2))]
  772. [else #f]))
  773. (define (Rint? ast)
  774. (match ast
  775. [(Program '() e) (exp? e)]
  776. [else #f]))
  777. (Rint? (Program '() ast1.1)
  778. (Rint? (Program '()
  779. (Prim '- (list (Prim 'read '())
  780. (Prim '+ (list (Num 8)))))))
  781. \end{lstlisting}
  782. \end{minipage}
  783. \vrule
  784. \begin{minipage}{0.25\textwidth}
  785. \begin{lstlisting}
  786. #t
  787. #f
  788. \end{lstlisting}
  789. \end{minipage}
  790. \end{center}
  791. You may be tempted to merge the two functions into one, like this:
  792. \begin{center}
  793. \begin{minipage}{0.5\textwidth}
  794. \begin{lstlisting}
  795. (define (Rint? ast)
  796. (match ast
  797. [(Int n) #t]
  798. [(Prim 'read '()) #t]
  799. [(Prim '- (list e)) (Rint? e)]
  800. [(Prim '+ (list e1 e2)) (and (Rint? e1) (Rint? e2))]
  801. [(Program '() e) (Rint? e)]
  802. [else #f]))
  803. \end{lstlisting}
  804. \end{minipage}
  805. \end{center}
  806. %
  807. Sometimes such a trick will save a few lines of code, especially when
  808. it comes to the \code{Program} wrapper. Yet this style is generally
  809. \emph{not} recommended because it can get you into trouble.
  810. %
  811. For example, the above function is subtly wrong:
  812. \lstinline{(Rint? (Program '() (Program '() (Int 3))))}
  813. returns true when it should return false.
  814. \section{Interpreters}
  815. \label{sec:interp-Rint}
  816. \index{interpreter}
  817. In general, the intended behavior of a program is defined by the
  818. specification of the language. For example, the Scheme language is
  819. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  820. defined in its reference manual~\citep{plt-tr}. In this book we use
  821. interpreters to specify each language that we consider. An interpreter
  822. that is designated as the definition of a language is called a
  823. \emph{definitional interpreter}~\citep{reynolds72:_def_interp}.
  824. \index{definitional interpreter} We warm up by creating a definitional
  825. interpreter for the \LangInt{} language, which serves as a second example
  826. of structural recursion. The \texttt{interp-Rint} function is defined in
  827. Figure~\ref{fig:interp-Rint}. The body of the function is a match on the
  828. input program followed by a call to the \lstinline{interp-exp} helper
  829. function, which in turn has one match clause per grammar rule for
  830. \LangInt{} expressions.
  831. \begin{figure}[tp]
  832. \begin{lstlisting}
  833. (define (interp-exp e)
  834. (match e
  835. [(Int n) n]
  836. [(Prim 'read '())
  837. (define r (read))
  838. (cond [(fixnum? r) r]
  839. [else (error 'interp-exp "read expected an integer" r)])]
  840. [(Prim '- (list e))
  841. (define v (interp-exp e))
  842. (fx- 0 v)]
  843. [(Prim '+ (list e1 e2))
  844. (define v1 (interp-exp e1))
  845. (define v2 (interp-exp e2))
  846. (fx+ v1 v2)]))
  847. (define (interp-Rint p)
  848. (match p
  849. [(Program '() e) (interp-exp e)]))
  850. \end{lstlisting}
  851. \caption{Interpreter for the \LangInt{} language.}
  852. \label{fig:interp-Rint}
  853. \end{figure}
  854. Let us consider the result of interpreting a few \LangInt{} programs. The
  855. following program adds two integers.
  856. \begin{lstlisting}
  857. (+ 10 32)
  858. \end{lstlisting}
  859. The result is \key{42}, the answer to life, the universe, and
  860. everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to the
  861. Galaxy} by Douglas Adams.}.
  862. %
  863. We wrote the above program in concrete syntax whereas the parsed
  864. abstract syntax is:
  865. \begin{lstlisting}
  866. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  867. \end{lstlisting}
  868. The next example demonstrates that expressions may be nested within
  869. each other, in this case nesting several additions and negations.
  870. \begin{lstlisting}
  871. (+ 10 (- (+ 12 20)))
  872. \end{lstlisting}
  873. What is the result of the above program?
  874. As mentioned previously, the \LangInt{} language does not support
  875. arbitrarily-large integers, but only $63$-bit integers, so we
  876. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  877. in Racket.
  878. Suppose
  879. \[
  880. n = 999999999999999999
  881. \]
  882. which indeed fits in $63$-bits. What happens when we run the
  883. following program in our interpreter?
  884. \begin{lstlisting}
  885. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  886. \end{lstlisting}
  887. It produces an error:
  888. \begin{lstlisting}
  889. fx+: result is not a fixnum
  890. \end{lstlisting}
  891. We establish the convention that if running the definitional
  892. interpreter on a program produces an error then the meaning of that
  893. program is \emph{unspecified}\index{unspecified behavior}, unless the
  894. error is a \code{trapped-error}. A compiler for the language is under
  895. no obligations regarding programs with unspecified behavior; it does
  896. not have to produce an executable, and if it does, that executable can
  897. do anything. On the other hand, if the error is a
  898. \code{trapped-error}, then the compiler must produce an executable and
  899. it is required to report that an error occurred. To signal an error,
  900. exit with a return code of \code{255}. The interpreters in chapters
  901. \ref{ch:Rdyn} and \ref{ch:Rgrad} use
  902. \code{trapped-error}.
  903. %% This convention applies to the languages defined in this
  904. %% book, as a way to simplify the student's task of implementing them,
  905. %% but this convention is not applicable to all programming languages.
  906. %%
  907. Moving on to the last feature of the \LangInt{} language, the \key{read}
  908. operation prompts the user of the program for an integer. Recall that
  909. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  910. \code{8}. So if we run
  911. \begin{lstlisting}
  912. (interp-Rint (Program '() ast1.1))
  913. \end{lstlisting}
  914. and if the input is \code{50}, the result is \code{42}.
  915. We include the \key{read} operation in \LangInt{} so a clever student
  916. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  917. during compilation to obtain the output and then generates the trivial
  918. code to produce the output. (Yes, a clever student did this in the
  919. first instance of this course.)
  920. The job of a compiler is to translate a program in one language into a
  921. program in another language so that the output program behaves the
  922. same way as the input program does. This idea is depicted in the
  923. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  924. $\mathcal{L}_2$, and a definitional interpreter for each language.
  925. Given a compiler that translates from language $\mathcal{L}_1$ to
  926. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  927. compiler must translate it into some program $P_2$ such that
  928. interpreting $P_1$ and $P_2$ on their respective interpreters with
  929. same input $i$ yields the same output $o$.
  930. \begin{equation} \label{eq:compile-correct}
  931. \begin{tikzpicture}[baseline=(current bounding box.center)]
  932. \node (p1) at (0, 0) {$P_1$};
  933. \node (p2) at (3, 0) {$P_2$};
  934. \node (o) at (3, -2.5) {$o$};
  935. \path[->] (p1) edge [above] node {compile} (p2);
  936. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  937. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  938. \end{tikzpicture}
  939. \end{equation}
  940. In the next section we see our first example of a compiler.
  941. \section{Example Compiler: a Partial Evaluator}
  942. \label{sec:partial-evaluation}
  943. In this section we consider a compiler that translates \LangInt{} programs
  944. into \LangInt{} programs that may be more efficient, that is, this compiler
  945. is an optimizer. This optimizer eagerly computes the parts of the
  946. program that do not depend on any inputs, a process known as
  947. \emph{partial evaluation}~\citep{Jones:1993uq}.
  948. \index{partial evaluation}
  949. For example, given the following program
  950. \begin{lstlisting}
  951. (+ (read) (- (+ 5 3)))
  952. \end{lstlisting}
  953. our compiler will translate it into the program
  954. \begin{lstlisting}
  955. (+ (read) -8)
  956. \end{lstlisting}
  957. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  958. evaluator for the \LangInt{} language. The output of the partial evaluator
  959. is an \LangInt{} program. In Figure~\ref{fig:pe-arith}, the structural
  960. recursion over $\Exp$ is captured in the \code{pe-exp} function
  961. whereas the code for partially evaluating the negation and addition
  962. operations is factored into two separate helper functions:
  963. \code{pe-neg} and \code{pe-add}. The input to these helper
  964. functions is the output of partially evaluating the children.
  965. \begin{figure}[tp]
  966. \begin{lstlisting}
  967. (define (pe-neg r)
  968. (match r
  969. [(Int n) (Int (fx- 0 n))]
  970. [else (Prim '- (list r))]))
  971. (define (pe-add r1 r2)
  972. (match* (r1 r2)
  973. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  974. [(_ _) (Prim '+ (list r1 r2))]))
  975. (define (pe-exp e)
  976. (match e
  977. [(Int n) (Int n)]
  978. [(Prim 'read '()) (Prim 'read '())]
  979. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  980. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]))
  981. (define (pe-Rint p)
  982. (match p
  983. [(Program '() e) (Program '() (pe-exp e))]))
  984. \end{lstlisting}
  985. \caption{A partial evaluator for \LangInt{}.}
  986. \label{fig:pe-arith}
  987. \end{figure}
  988. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  989. arguments are integers and if they are, perform the appropriate
  990. arithmetic. Otherwise, they create an AST node for the arithmetic
  991. operation.
  992. To gain some confidence that the partial evaluator is correct, we can
  993. test whether it produces programs that get the same result as the
  994. input programs. That is, we can test whether it satisfies Diagram
  995. \ref{eq:compile-correct}. The following code runs the partial
  996. evaluator on several examples and tests the output program. The
  997. \texttt{parse-program} and \texttt{assert} functions are defined in
  998. Appendix~\ref{appendix:utilities}.\\
  999. \begin{minipage}{1.0\textwidth}
  1000. \begin{lstlisting}
  1001. (define (test-pe p)
  1002. (assert "testing pe-Rint"
  1003. (equal? (interp-Rint p) (interp-Rint (pe-Rint p)))))
  1004. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1005. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1006. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  1007. \end{lstlisting}
  1008. \end{minipage}
  1009. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1010. \chapter{Integers and Variables}
  1011. \label{ch:Rvar}
  1012. This chapter is about compiling a subset of Racket to x86-64 assembly
  1013. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1014. integer arithmetic and local variable binding. We often refer to
  1015. x86-64 simply as x86. The chapter begins with a description of the
  1016. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  1017. to of x86 assembly (Section~\ref{sec:x86}). The x86 assembly language
  1018. is large so we discuss only the instructions needed for compiling
  1019. \LangVar{}. We introduce more x86 instructions in later chapters.
  1020. After introducing \LangVar{} and x86, we reflect on their differences
  1021. and come up with a plan to break down the translation from \LangVar{}
  1022. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  1023. rest of the sections in this chapter give detailed hints regarding
  1024. each step (Sections~\ref{sec:uniquify-Rvar} through \ref{sec:patch-s0}).
  1025. We hope to give enough hints that the well-prepared reader, together
  1026. with a few friends, can implement a compiler from \LangVar{} to x86 in
  1027. a couple weeks. To give the reader a feeling for the scale of this
  1028. first compiler, the instructor solution for the \LangVar{} compiler is
  1029. approximately 500 lines of code.
  1030. \section{The \LangVar{} Language}
  1031. \label{sec:s0}
  1032. \index{variable}
  1033. The \LangVar{} language extends the \LangInt{} language with variable
  1034. definitions. The concrete syntax of the \LangVar{} language is defined by
  1035. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  1036. syntax is defined in Figure~\ref{fig:r1-syntax}. The non-terminal
  1037. \Var{} may be any Racket identifier. As in \LangInt{}, \key{read} is a
  1038. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  1039. operator. Similar to \LangInt{}, the abstract syntax of \LangVar{} includes the
  1040. \key{Program} struct to mark the top of the program.
  1041. %% The $\itm{info}$
  1042. %% field of the \key{Program} structure contains an \emph{association
  1043. %% list} (a list of key-value pairs) that is used to communicate
  1044. %% auxiliary data from one compiler pass the next.
  1045. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1046. exhibit several compilation techniques.
  1047. \begin{figure}[tp]
  1048. \centering
  1049. \fbox{
  1050. \begin{minipage}{0.96\textwidth}
  1051. \[
  1052. \begin{array}{rcl}
  1053. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp}\\
  1054. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  1055. \LangVar{} &::=& \Exp
  1056. \end{array}
  1057. \]
  1058. \end{minipage}
  1059. }
  1060. \caption{The concrete syntax of \LangVar{}.}
  1061. \label{fig:r1-concrete-syntax}
  1062. \end{figure}
  1063. \begin{figure}[tp]
  1064. \centering
  1065. \fbox{
  1066. \begin{minipage}{0.96\textwidth}
  1067. \[
  1068. \begin{array}{rcl}
  1069. \Exp &::=& \INT{\Int} \mid \READ{} \\
  1070. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  1071. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  1072. \LangVar{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1073. \end{array}
  1074. \]
  1075. \end{minipage}
  1076. }
  1077. \caption{The abstract syntax of \LangVar{}.}
  1078. \label{fig:r1-syntax}
  1079. \end{figure}
  1080. Let us dive further into the syntax and semantics of the \LangVar{}
  1081. language. The \key{let} feature defines a variable for use within its
  1082. body and initializes the variable with the value of an expression.
  1083. The abstract syntax for \key{let} is defined in
  1084. Figure~\ref{fig:r1-syntax}. The concrete syntax for \key{let} is
  1085. \begin{lstlisting}
  1086. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1087. \end{lstlisting}
  1088. For example, the following program initializes \code{x} to $32$ and then
  1089. evaluates the body \code{(+ 10 x)}, producing $42$.
  1090. \begin{lstlisting}
  1091. (let ([x (+ 12 20)]) (+ 10 x))
  1092. \end{lstlisting}
  1093. When there are multiple \key{let}'s for the same variable, the closest
  1094. enclosing \key{let} is used. That is, variable definitions overshadow
  1095. prior definitions. Consider the following program with two \key{let}'s
  1096. that define variables named \code{x}. Can you figure out the result?
  1097. \begin{lstlisting}
  1098. (let ([x 32]) (+ (let ([x 10]) x) x))
  1099. \end{lstlisting}
  1100. For the purposes of depicting which variable uses correspond to which
  1101. definitions, the following shows the \code{x}'s annotated with
  1102. subscripts to distinguish them. Double check that your answer for the
  1103. above is the same as your answer for this annotated version of the
  1104. program.
  1105. \begin{lstlisting}
  1106. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1107. \end{lstlisting}
  1108. The initializing expression is always evaluated before the body of the
  1109. \key{let}, so in the following, the \key{read} for \code{x} is
  1110. performed before the \key{read} for \code{y}. Given the input
  1111. $52$ then $10$, the following produces $42$ (not $-42$).
  1112. \begin{lstlisting}
  1113. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1114. \end{lstlisting}
  1115. \subsection{Extensible Interpreters via Method Overriding}
  1116. \label{sec:extensible-interp}
  1117. To prepare for discussing the interpreter for \LangVar{}, we need to
  1118. explain why we choose to implement the interpreter using
  1119. object-oriented programming, that is, as a collection of methods
  1120. inside of a class. Throughout this book we define many interpreters,
  1121. one for each of the languages that we study. Because each language
  1122. builds on the prior one, there is a lot of commonality between their
  1123. interpreters. We want to write down those common parts just once
  1124. instead of many times. A naive approach would be to have, for example,
  1125. the interpreter for \LangIf{} handle all of the new features in that
  1126. language and then have a default case that dispatches to the
  1127. interpreter for \LangVar{}. The following code sketches this idea.
  1128. \begin{center}
  1129. \begin{minipage}{0.45\textwidth}
  1130. \begin{lstlisting}
  1131. (define (interp-Rvar e)
  1132. (match e
  1133. [(Prim '- (list e))
  1134. (fx- 0 (interp-Rvar e))]
  1135. ...))
  1136. \end{lstlisting}
  1137. \end{minipage}
  1138. \begin{minipage}{0.45\textwidth}
  1139. \begin{lstlisting}
  1140. (define (interp-Rif e)
  1141. (match e
  1142. [(If cnd thn els)
  1143. (match (interp-Rif cnd)
  1144. [#t (interp-Rif thn)]
  1145. [#f (interp-Rif els)])]
  1146. ...
  1147. [else (interp-Rvar e)]))
  1148. \end{lstlisting}
  1149. \end{minipage}
  1150. \end{center}
  1151. The problem with this approach is that it does not handle situations
  1152. in which an \LangIf{} feature, like \code{If}, is nested inside an \LangVar{}
  1153. feature, like the \code{-} operator, as in the following program.
  1154. \begin{lstlisting}
  1155. (Prim '- (list (If (Bool #t) (Int 42) (Int 0))))
  1156. \end{lstlisting}
  1157. If we invoke \code{interp-Rif} on this program, it dispatches to
  1158. \code{interp-Rvar} to handle the \code{-} operator, but then it
  1159. recurisvely calls \code{interp-Rvar} again on the argument of \code{-},
  1160. which is an \code{If}. But there is no case for \code{If} in
  1161. \code{interp-Rvar}, so we get an error!
  1162. To make our interpreters extensible we need something called
  1163. \emph{open recursion}\index{open recursion}, where the tying of the
  1164. recursive knot is delayed to when the functions are
  1165. composed. Object-oriented languages provide open recursion with the
  1166. late-binding of overridden methods\index{method overriding}. The
  1167. following code sketches this idea for interpreting \LangVar{} and
  1168. \LangIf{} using the
  1169. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1170. \index{class} feature of Racket. We define one class for each
  1171. language and define a method for interpreting expressions inside each
  1172. class. The class for \LangIf{} inherits from the class for \LangVar{}
  1173. and the method \code{interp-exp} in \LangIf{} overrides the
  1174. \code{interp-exp} in \LangVar{}. Note that the default case of
  1175. \code{interp-exp} in \LangIf{} uses \code{super} to invoke
  1176. \code{interp-exp}, and because \LangIf{} inherits from \LangVar{},
  1177. that dispatches to the \code{interp-exp} in \LangVar{}.
  1178. \begin{center}
  1179. \begin{minipage}{0.45\textwidth}
  1180. \begin{lstlisting}
  1181. (define interp-Rvar-class
  1182. (class object%
  1183. (define/public (interp-exp e)
  1184. (match e
  1185. [(Prim '- (list e))
  1186. (fx- 0 (interp-exp e))]
  1187. ...))
  1188. ...))
  1189. \end{lstlisting}
  1190. \end{minipage}
  1191. \begin{minipage}{0.45\textwidth}
  1192. \begin{lstlisting}
  1193. (define interp-Rif-class
  1194. (class interp-Rvar-class
  1195. (define/override (interp-exp e)
  1196. (match e
  1197. [(If cnd thn els)
  1198. (match (interp-exp cnd)
  1199. [#t (interp-exp thn)]
  1200. [#f (interp-exp els)])]
  1201. ...
  1202. [else (super interp-exp e)]))
  1203. ...
  1204. ))
  1205. \end{lstlisting}
  1206. \end{minipage}
  1207. \end{center}
  1208. Getting back to the troublesome example, repeated here:
  1209. \begin{lstlisting}
  1210. (define e0 (Prim '- (list (If (Bool #t) (Int 42) (Int 0)))))
  1211. \end{lstlisting}
  1212. We can invoke the \code{interp-exp} method for \LangIf{} on this
  1213. expression by creating an object of the \LangIf{} class and sending it the
  1214. \code{interp-exp} method with the argument \code{e0}.
  1215. \begin{lstlisting}
  1216. (send (new interp-Rif-class) interp-exp e0)
  1217. \end{lstlisting}
  1218. The default case of \code{interp-exp} in \LangIf{} handles it by
  1219. dispatching to the \code{interp-exp} method in \LangVar{}, which
  1220. handles the \code{-} operator. But then for the recursive method call,
  1221. it dispatches back to \code{interp-exp} in \LangIf{}, where the
  1222. \code{If} is handled correctly. Thus, method overriding gives us the
  1223. open recursion that we need to implement our interpreters in an
  1224. extensible way.
  1225. \newpage
  1226. \subsection{Definitional Interpreter for \LangVar{}}
  1227. \begin{wrapfigure}[25]{r}[1.0in]{0.6\textwidth}
  1228. \small
  1229. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1230. An \emph{association list} (alist) is a list of key-value pairs.
  1231. For example, we can map people to their ages with an alist.
  1232. \index{alist}\index{association list}
  1233. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1234. (define ages
  1235. '((jane . 25) (sam . 24) (kate . 45)))
  1236. \end{lstlisting}
  1237. The \emph{dictionary} interface is for mapping keys to values.
  1238. Every alist implements this interface. \index{dictionary} The package
  1239. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1240. provides many functions for working with dictionaries. Here
  1241. are a few of them:
  1242. \begin{description}
  1243. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1244. returns the value associated with the given $\itm{key}$.
  1245. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1246. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1247. but otherwise is the same as $\itm{dict}$.
  1248. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1249. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1250. of keys and values in $\itm{dict}$. For example, the following
  1251. creates a new alist in which the ages are incremented.
  1252. \end{description}
  1253. \vspace{-10pt}
  1254. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1255. (for/list ([(k v) (in-dict ages)])
  1256. (cons k (add1 v)))
  1257. \end{lstlisting}
  1258. \end{tcolorbox}
  1259. \end{wrapfigure}
  1260. Having justified the use of classes and methods to implement
  1261. interpreters, we turn to the definitional interpreter for \LangVar{}
  1262. in Figure~\ref{fig:interp-Rvar}. It is similar to the interpreter for
  1263. \LangInt{} but adds two new \key{match} cases for variables and
  1264. \key{let}. For \key{let} we need a way to communicate the value bound
  1265. to a variable to all the uses of the variable. To accomplish this, we
  1266. maintain a mapping from variables to values. Throughout the compiler
  1267. we often need to map variables to information about them. We refer to
  1268. these mappings as
  1269. \emph{environments}\index{environment}.\footnote{Another common term
  1270. for environment in the compiler literature is \emph{symbol
  1271. table}\index{symbol table}.}
  1272. %
  1273. For simplicity, we use an association list (alist) to represent the
  1274. environment. The sidebar to the right gives a brief introduction to
  1275. alists and the \code{racket/dict} package. The \code{interp-exp}
  1276. function takes the current environment, \code{env}, as an extra
  1277. parameter. When the interpreter encounters a variable, it finds the
  1278. corresponding value using the \code{dict-ref} function. When the
  1279. interpreter encounters a \key{Let}, it evaluates the initializing
  1280. expression, extends the environment with the result value bound to the
  1281. variable, using \code{dict-set}, then evaluates the body of the
  1282. \key{Let}.
  1283. \begin{figure}[tp]
  1284. \begin{lstlisting}
  1285. (define interp-Rvar-class
  1286. (class object%
  1287. (super-new)
  1288. (define/public ((interp-exp env) e)
  1289. (match e
  1290. [(Int n) n]
  1291. [(Prim 'read '())
  1292. (define r (read))
  1293. (cond [(fixnum? r) r]
  1294. [else (error 'interp-exp "expected an integer" r)])]
  1295. [(Prim '- (list e)) (fx- 0 ((interp-exp env) e))]
  1296. [(Prim '+ (list e1 e2))
  1297. (fx+ ((interp-exp env) e1) ((interp-exp env) e2))]
  1298. [(Var x) (dict-ref env x)]
  1299. [(Let x e body)
  1300. (define new-env (dict-set env x ((interp-exp env) e)))
  1301. ((interp-exp new-env) body)]))
  1302. (define/public (interp-program p)
  1303. (match p
  1304. [(Program '() e) ((interp-exp '()) e)]))
  1305. ))
  1306. (define (interp-Rvar p)
  1307. (send (new interp-Rvar-class) interp-program p))
  1308. \end{lstlisting}
  1309. \caption{Interpreter for the \LangVar{} language.}
  1310. \label{fig:interp-Rvar}
  1311. \end{figure}
  1312. The goal for this chapter is to implement a compiler that translates
  1313. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  1314. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1315. computer as the $P_1$ program interpreted by \code{interp-Rvar}. That
  1316. is, they output the same integer $n$. We depict this correctness
  1317. criteria in the following diagram.
  1318. \[
  1319. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1320. \node (p1) at (0, 0) {$P_1$};
  1321. \node (p2) at (4, 0) {$P_2$};
  1322. \node (o) at (4, -2) {$n$};
  1323. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1324. \path[->] (p1) edge [left] node {\footnotesize\code{interp-Rvar}} (o);
  1325. \path[->] (p2) edge [right] node {\footnotesize\code{interp-x86int}} (o);
  1326. \end{tikzpicture}
  1327. \]
  1328. In the next section we introduce the \LangXInt{} subset of x86 that
  1329. suffices for compiling \LangVar{}.
  1330. \section{The \LangXInt{} Assembly Language}
  1331. \label{sec:x86}
  1332. \index{x86}
  1333. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  1334. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  1335. assembler.
  1336. %
  1337. A program begins with a \code{main} label followed by a sequence of
  1338. instructions. The \key{globl} directive says that the \key{main}
  1339. procedure is externally visible, which is necessary so that the
  1340. operating system can call it. In the grammar, ellipses such as
  1341. $\ldots$ are used to indicate a sequence of items, e.g., $\Instr
  1342. \ldots$ is a sequence of instructions.\index{instruction}
  1343. %
  1344. An x86 program is stored in the computer's memory. For our purposes,
  1345. the computer's memory is as a mapping of 64-bit addresses to 64-bit
  1346. values. The computer has a \emph{program counter} (PC)\index{program
  1347. counter}\index{PC} stored in the \code{rip} register that points to
  1348. the address of the next instruction to be executed. For most
  1349. instructions, the program counter is incremented after the instruction
  1350. is executed, so it points to the next instruction in memory. Most x86
  1351. instructions take two operands, where each operand is either an
  1352. integer constant (called \emph{immediate value}\index{immediate
  1353. value}), a \emph{register}\index{register}, or a memory location.
  1354. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1355. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1356. && \key{r8} \mid \key{r9} \mid \key{r10}
  1357. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1358. \mid \key{r14} \mid \key{r15}}
  1359. \begin{figure}[tp]
  1360. \fbox{
  1361. \begin{minipage}{0.96\textwidth}
  1362. \[
  1363. \begin{array}{lcl}
  1364. \Reg &::=& \allregisters{} \\
  1365. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1366. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1367. \key{subq} \; \Arg\key{,} \Arg \mid
  1368. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1369. && \key{callq} \; \mathit{label} \mid
  1370. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} \\
  1371. && \itm{label}\key{:}\; \Instr \\
  1372. \LangXInt{} &::= & \key{.globl main}\\
  1373. & & \key{main:} \; \Instr\ldots
  1374. \end{array}
  1375. \]
  1376. \end{minipage}
  1377. }
  1378. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  1379. \label{fig:x86-int-concrete}
  1380. \end{figure}
  1381. A register is a special kind of variable. Each one holds a 64-bit
  1382. value; there are 16 general-purpose registers in the computer and
  1383. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  1384. is written with a \key{\%} followed by the register name, such as
  1385. \key{\%rax}.
  1386. An immediate value is written using the notation \key{\$}$n$ where $n$
  1387. is an integer.
  1388. %
  1389. %
  1390. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1391. which obtains the address stored in register $r$ and then adds $n$
  1392. bytes to the address. The resulting address is used to load or store
  1393. to memory depending on whether it occurs as a source or destination
  1394. argument of an instruction.
  1395. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1396. source $s$ and destination $d$, applies the arithmetic operation, then
  1397. writes the result back to the destination $d$.
  1398. %
  1399. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1400. stores the result in $d$.
  1401. %
  1402. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  1403. specified by the label and $\key{retq}$ returns from a procedure to
  1404. its caller.
  1405. %
  1406. We discuss procedure calls in more detail later in this chapter and in
  1407. Chapter~\ref{ch:Rfun}. The instruction $\key{jmp}\,\itm{label}$
  1408. updates the program counter to the address of the instruction after
  1409. the specified label.
  1410. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  1411. all of the x86 instructions used in this book.
  1412. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent to
  1413. \code{(+ 10 32)}. The instruction \lstinline{movq $10, %rax}
  1414. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  1415. adds $32$ to the $10$ in \key{rax} and
  1416. puts the result, $42$, back into \key{rax}.
  1417. %
  1418. The last instruction, \key{retq}, finishes the \key{main} function by
  1419. returning the integer in \key{rax} to the operating system. The
  1420. operating system interprets this integer as the program's exit
  1421. code. By convention, an exit code of 0 indicates that a program
  1422. completed successfully, and all other exit codes indicate various
  1423. errors. Nevertheless, in this book we return the result of the program
  1424. as the exit code.
  1425. \begin{figure}[tbp]
  1426. \begin{lstlisting}
  1427. .globl main
  1428. main:
  1429. movq $10, %rax
  1430. addq $32, %rax
  1431. retq
  1432. \end{lstlisting}
  1433. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1434. \label{fig:p0-x86}
  1435. \end{figure}
  1436. The x86 assembly language varies in a couple ways depending on what
  1437. operating system it is assembled in. The code examples shown here are
  1438. correct on Linux and most Unix-like platforms, but when assembled on
  1439. Mac OS X, labels like \key{main} must be prefixed with an underscore,
  1440. as in \key{\_main}.
  1441. We exhibit the use of memory for storing intermediate results in the
  1442. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1443. equivalent to \code{(+ 52 (- 10))}. This program uses a region of
  1444. memory called the \emph{procedure call stack} (or \emph{stack} for
  1445. short). \index{stack}\index{procedure call stack} The stack consists
  1446. of a separate \emph{frame}\index{frame} for each procedure call. The
  1447. memory layout for an individual frame is shown in
  1448. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1449. \emph{stack pointer}\index{stack pointer} and points to the item at
  1450. the top of the stack. The stack grows downward in memory, so we
  1451. increase the size of the stack by subtracting from the stack pointer.
  1452. In the context of a procedure call, the \emph{return
  1453. address}\index{return address} is the instruction after the call
  1454. instruction on the caller side. The function call instruction,
  1455. \code{callq}, pushes the return address onto the stack prior to
  1456. jumping to the procedure. The register \key{rbp} is the \emph{base
  1457. pointer}\index{base pointer} and is used to access variables that
  1458. are stored in the frame of the current procedure call. The base
  1459. pointer of the caller is pushed onto the stack after the return
  1460. address and then the base pointer is set to the location of the old
  1461. base pointer. In Figure~\ref{fig:frame} we number the variables from
  1462. $1$ to $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$,
  1463. variable $2$ at $-16\key{(\%rbp)}$, etc.
  1464. \begin{figure}[tbp]
  1465. \begin{lstlisting}
  1466. start:
  1467. movq $10, -8(%rbp)
  1468. negq -8(%rbp)
  1469. movq -8(%rbp), %rax
  1470. addq $52, %rax
  1471. jmp conclusion
  1472. .globl main
  1473. main:
  1474. pushq %rbp
  1475. movq %rsp, %rbp
  1476. subq $16, %rsp
  1477. jmp start
  1478. conclusion:
  1479. addq $16, %rsp
  1480. popq %rbp
  1481. retq
  1482. \end{lstlisting}
  1483. \caption{An x86 program equivalent to \code{(+ 52 (- 10))}.}
  1484. \label{fig:p1-x86}
  1485. \end{figure}
  1486. \begin{figure}[tbp]
  1487. \centering
  1488. \begin{tabular}{|r|l|} \hline
  1489. Position & Contents \\ \hline
  1490. 8(\key{\%rbp}) & return address \\
  1491. 0(\key{\%rbp}) & old \key{rbp} \\
  1492. -8(\key{\%rbp}) & variable $1$ \\
  1493. -16(\key{\%rbp}) & variable $2$ \\
  1494. \ldots & \ldots \\
  1495. 0(\key{\%rsp}) & variable $n$\\ \hline
  1496. \end{tabular}
  1497. \caption{Memory layout of a frame.}
  1498. \label{fig:frame}
  1499. \end{figure}
  1500. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  1501. control is transferred from the operating system to the \code{main}
  1502. function. The operating system issues a \code{callq main} instruction
  1503. which pushes its return address on the stack and then jumps to
  1504. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  1505. by 16 bytes prior to the execution of any \code{callq} instruction, so
  1506. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  1507. alignment (because the \code{callq} pushed the return address). The
  1508. first three instructions are the typical \emph{prelude}\index{prelude}
  1509. for a procedure. The instruction \code{pushq \%rbp} saves the base
  1510. pointer for the caller onto the stack and subtracts $8$ from the stack
  1511. pointer. The second instruction \code{movq \%rsp, \%rbp} changes the
  1512. base pointer so that it points the location of the old base
  1513. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  1514. pointer down to make enough room for storing variables. This program
  1515. needs one variable ($8$ bytes) but we round up to 16 bytes so that
  1516. \code{rsp} is 16-byte aligned and we're ready to make calls to other
  1517. functions. The last instruction of the prelude is \code{jmp start},
  1518. which transfers control to the instructions that were generated from
  1519. the Racket expression \code{(+ 52 (- 10))}.
  1520. The first instruction under the \code{start} label is
  1521. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  1522. %
  1523. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  1524. %
  1525. The next instruction moves the $-10$ from variable $1$ into the
  1526. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  1527. the value in \code{rax}, updating its contents to $42$.
  1528. The three instructions under the label \code{conclusion} are the
  1529. typical \emph{conclusion}\index{conclusion} of a procedure. The first
  1530. two instructions restore the \code{rsp} and \code{rbp} registers to
  1531. the state they were in at the beginning of the procedure. The
  1532. instruction \key{addq \$16, \%rsp} moves the stack pointer back to
  1533. point at the old base pointer. Then \key{popq \%rbp} returns the old
  1534. base pointer to \key{rbp} and adds $8$ to the stack pointer. The last
  1535. instruction, \key{retq}, jumps back to the procedure that called this
  1536. one and adds $8$ to the stack pointer.
  1537. The compiler needs a convenient representation for manipulating x86
  1538. programs, so we define an abstract syntax for x86 in
  1539. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  1540. \LangXInt{}. The main difference compared to the concrete syntax of
  1541. \LangXInt{} (Figure~\ref{fig:x86-int-concrete}) is that labels are not
  1542. allowed in front of every instructions. Instead instructions are
  1543. grouped into \emph{blocks}\index{block}\index{basic block} with a
  1544. label associated with every block, which is why the \key{X86Program}
  1545. struct includes an alist mapping labels to blocks. The reason for this
  1546. organization becomes apparent in Chapter~\ref{ch:Rif} when we
  1547. introduce conditional branching. The \code{Block} structure includes
  1548. an $\itm{info}$ field that is not needed for this chapter, but becomes
  1549. useful in Chapter~\ref{ch:register-allocation-Rvar}. For now, the
  1550. $\itm{info}$ field should contain an empty list. Also, regarding the
  1551. abstract syntax for \code{callq}, the \code{Callq} struct includes an
  1552. integer for representing the arity of the function, i.e., the number
  1553. of arguments, which is helpful to know during register allocation
  1554. (Chapter~\ref{ch:register-allocation-Rvar}).
  1555. \begin{figure}[tp]
  1556. \fbox{
  1557. \begin{minipage}{0.98\textwidth}
  1558. \small
  1559. \[
  1560. \begin{array}{lcl}
  1561. \Reg &::=& \allregisters{} \\
  1562. \Arg &::=& \IMM{\Int} \mid \REG{\Reg}
  1563. \mid \DEREF{\Reg}{\Int} \\
  1564. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  1565. \mid \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  1566. &\mid& \BININSTR{\code{movq}}{\Arg}{\Arg}
  1567. \mid \UNIINSTR{\code{negq}}{\Arg}\\
  1568. &\mid& \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  1569. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  1570. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP} \\
  1571. \LangXInt{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  1572. \end{array}
  1573. \]
  1574. \end{minipage}
  1575. }
  1576. \caption{The abstract syntax of \LangXInt{} assembly.}
  1577. \label{fig:x86-int-ast}
  1578. \end{figure}
  1579. \section{Planning the trip to x86 via the \LangCVar{} language}
  1580. \label{sec:plan-s0-x86}
  1581. To compile one language to another it helps to focus on the
  1582. differences between the two languages because the compiler will need
  1583. to bridge those differences. What are the differences between \LangVar{}
  1584. and x86 assembly? Here are some of the most important ones:
  1585. \begin{enumerate}
  1586. \item[(a)] x86 arithmetic instructions typically have two arguments
  1587. and update the second argument in place. In contrast, \LangVar{}
  1588. arithmetic operations take two arguments and produce a new value.
  1589. An x86 instruction may have at most one memory-accessing argument.
  1590. Furthermore, some instructions place special restrictions on their
  1591. arguments.
  1592. \item[(b)] An argument of an \LangVar{} operator can be a deeply-nested
  1593. expression, whereas x86 instructions restrict their arguments to be
  1594. integers constants, registers, and memory locations.
  1595. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1596. sequence of instructions and jumps to labeled positions, whereas in
  1597. \LangVar{} the order of evaluation is a left-to-right depth-first
  1598. traversal of the abstract syntax tree.
  1599. \item[(d)] A program in \LangVar{} can have any number of variables
  1600. whereas x86 has 16 registers and the procedure calls stack.
  1601. \item[(e)] Variables in \LangVar{} can overshadow other variables with the
  1602. same name. In x86, registers have unique names and memory locations
  1603. have unique addresses.
  1604. \end{enumerate}
  1605. We ease the challenge of compiling from \LangVar{} to x86 by breaking down
  1606. the problem into several steps, dealing with the above differences one
  1607. at a time. Each of these steps is called a \emph{pass} of the
  1608. compiler.\index{pass}\index{compiler pass}
  1609. %
  1610. This terminology comes from the way each step passes over the AST of
  1611. the program.
  1612. %
  1613. We begin by sketching how we might implement each pass, and give them
  1614. names. We then figure out an ordering of the passes and the
  1615. input/output language for each pass. The very first pass has
  1616. \LangVar{} as its input language and the last pass has \LangXInt{} as
  1617. its output language. In between we can choose whichever language is
  1618. most convenient for expressing the output of each pass, whether that
  1619. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  1620. our own design. Finally, to implement each pass we write one
  1621. recursive function per non-terminal in the grammar of the input
  1622. language of the pass. \index{intermediate language}
  1623. \begin{description}
  1624. \item[\key{select-instructions}] handles the difference between
  1625. \LangVar{} operations and x86 instructions. This pass converts each
  1626. \LangVar{} operation to a short sequence of instructions that
  1627. accomplishes the same task.
  1628. \item[\key{remove-complex-opera*}] ensures that each subexpression of
  1629. a primitive operation is a variable or integer, that is, an
  1630. \emph{atomic} expression. We refer to non-atomic expressions as
  1631. \emph{complex}. This pass introduces temporary variables to hold
  1632. the results of complex subexpressions.\index{atomic
  1633. expression}\index{complex expression}%
  1634. \footnote{The subexpressions of an operation are often called
  1635. operators and operands which explains the presence of
  1636. \code{opera*} in the name of this pass.}
  1637. \item[\key{explicate-control}] makes the execution order of the
  1638. program explicit. It convert the abstract syntax tree representation
  1639. into a control-flow graph in which each node contains a sequence of
  1640. statements and the edges between nodes say which nodes contain jumps
  1641. to other nodes.
  1642. \item[\key{assign-homes}] replaces the variables in \LangVar{} with
  1643. registers or stack locations in x86.
  1644. \item[\key{uniquify}] deals with the shadowing of variables by
  1645. renaming every variable to a unique name.
  1646. \end{description}
  1647. The next question is: in what order should we apply these passes? This
  1648. question can be challenging because it is difficult to know ahead of
  1649. time which orderings will be better (easier to implement, produce more
  1650. efficient code, etc.) so oftentimes trial-and-error is
  1651. involved. Nevertheless, we can try to plan ahead and make educated
  1652. choices regarding the ordering.
  1653. What should be the ordering of \key{explicate-control} with respect to
  1654. \key{uniquify}? The \key{uniquify} pass should come first because
  1655. \key{explicate-control} changes all the \key{let}-bound variables to
  1656. become local variables whose scope is the entire program, which would
  1657. confuse variables with the same name.
  1658. %
  1659. We place \key{remove-complex-opera*} before \key{explicate-control}
  1660. because the later removes the \key{let} form, but it is convenient to
  1661. use \key{let} in the output of \key{remove-complex-opera*}.
  1662. %
  1663. The ordering of \key{uniquify} with respect to
  1664. \key{remove-complex-opera*} does not matter so we arbitrarily choose
  1665. \key{uniquify} to come first.
  1666. Last, we consider \key{select-instructions} and \key{assign-homes}.
  1667. These two passes are intertwined. In Chapter~\ref{ch:Rfun} we
  1668. learn that, in x86, registers are used for passing arguments to
  1669. functions and it is preferable to assign parameters to their
  1670. corresponding registers. On the other hand, by selecting instructions
  1671. first we may run into a dead end in \key{assign-homes}. Recall that
  1672. only one argument of an x86 instruction may be a memory access but
  1673. \key{assign-homes} might fail to assign even one of them to a
  1674. register.
  1675. %
  1676. A sophisticated approach is to iteratively repeat the two passes until
  1677. a solution is found. However, to reduce implementation complexity we
  1678. recommend a simpler approach in which \key{select-instructions} comes
  1679. first, followed by the \key{assign-homes}, then a third pass named
  1680. \key{patch-instructions} that uses a reserved register to fix
  1681. outstanding problems.
  1682. \begin{figure}[tbp]
  1683. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1684. \node (Rvar) at (0,2) {\large \LangVar{}};
  1685. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  1686. \node (Rvar-3) at (6,2) {\large \LangVarANF{}};
  1687. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  1688. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  1689. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  1690. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  1691. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  1692. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  1693. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  1694. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvar-3);
  1695. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate-control} (Cvar-2);
  1696. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1697. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1698. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1699. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1700. \end{tikzpicture}
  1701. \caption{Diagram of the passes for compiling \LangVar{}. }
  1702. \label{fig:Rvar-passes}
  1703. \end{figure}
  1704. Figure~\ref{fig:Rvar-passes} presents the ordering of the compiler
  1705. passes and identifies the input and output language of each pass. The
  1706. last pass, \key{print-x86}, converts from the abstract syntax of
  1707. \LangXInt{} to the concrete syntax. In the following two sections
  1708. we discuss the \LangCVar{} intermediate language and the \LangXVar{}
  1709. dialect of x86. The remainder of this chapter gives hints regarding
  1710. the implementation of each of the compiler passes in
  1711. Figure~\ref{fig:Rvar-passes}.
  1712. %% The output of \key{uniquify} and \key{remove-complex-opera*}
  1713. %% are programs that are still in the \LangVar{} language, though the
  1714. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  1715. %% (Section~\ref{sec:remove-complex-opera-Rvar}).
  1716. %% %
  1717. %% The output of \key{explicate-control} is in an intermediate language
  1718. %% \LangCVar{} designed to make the order of evaluation explicit in its
  1719. %% syntax, which we introduce in the next section. The
  1720. %% \key{select-instruction} pass translates from \LangCVar{} to
  1721. %% \LangXVar{}. The \key{assign-homes} and
  1722. %% \key{patch-instructions}
  1723. %% passes input and output variants of x86 assembly.
  1724. \subsection{The \LangCVar{} Intermediate Language}
  1725. The output of \key{explicate-control} is similar to the $C$
  1726. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1727. categories for expressions and statements, so we name it \LangCVar{}. The
  1728. abstract syntax for \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  1729. (The concrete syntax for \LangCVar{} is in the Appendix,
  1730. Figure~\ref{fig:c0-concrete-syntax}.)
  1731. %
  1732. The \LangCVar{} language supports the same operators as \LangVar{} but
  1733. the arguments of operators are restricted to atomic
  1734. expressions. Instead of \key{let} expressions, \LangCVar{} has
  1735. assignment statements which can be executed in sequence using the
  1736. \key{Seq} form. A sequence of statements always ends with
  1737. \key{Return}, a guarantee that is baked into the grammar rules for
  1738. \itm{tail}. The naming of this non-terminal comes from the term
  1739. \emph{tail position}\index{tail position}, which refers to an
  1740. expression that is the last one to execute within a function.
  1741. A \LangCVar{} program consists of a control-flow graph represented as
  1742. an alist mapping labels to tails. This is more general than necessary
  1743. for the present chapter, as we do not yet introduce \key{goto} for
  1744. jumping to labels, but it saves us from having to change the syntax in
  1745. Chapter~\ref{ch:Rif}. For now there will be just one label,
  1746. \key{start}, and the whole program is its tail.
  1747. %
  1748. The $\itm{info}$ field of the \key{CProgram} form, after the
  1749. \key{explicate-control} pass, contains a mapping from the symbol
  1750. \key{locals} to a list of variables, that is, a list of all the
  1751. variables used in the program. At the start of the program, these
  1752. variables are uninitialized; they become initialized on their first
  1753. assignment.
  1754. \begin{figure}[tbp]
  1755. \fbox{
  1756. \begin{minipage}{0.96\textwidth}
  1757. \[
  1758. \begin{array}{lcl}
  1759. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1760. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1761. &\mid& \ADD{\Atm}{\Atm}\\
  1762. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  1763. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1764. \LangCVar{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  1765. \end{array}
  1766. \]
  1767. \end{minipage}
  1768. }
  1769. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  1770. \label{fig:c0-syntax}
  1771. \end{figure}
  1772. The definitional interpreter for \LangCVar{} is in the support code,
  1773. in the file \code{interp-Cvar.rkt}.
  1774. \subsection{The \LangXVar{} dialect}
  1775. The \LangXVar{} language is the output of the pass
  1776. \key{select-instructions}. It extends \LangXInt{} with an unbounded
  1777. number of program-scope variables and removes the restrictions
  1778. regarding instruction arguments.
  1779. \section{Uniquify Variables}
  1780. \label{sec:uniquify-Rvar}
  1781. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  1782. programs in which every \key{let} binds a unique variable name. For
  1783. example, the \code{uniquify} pass should translate the program on the
  1784. left into the program on the right. \\
  1785. \begin{tabular}{lll}
  1786. \begin{minipage}{0.4\textwidth}
  1787. \begin{lstlisting}
  1788. (let ([x 32])
  1789. (+ (let ([x 10]) x) x))
  1790. \end{lstlisting}
  1791. \end{minipage}
  1792. &
  1793. $\Rightarrow$
  1794. &
  1795. \begin{minipage}{0.4\textwidth}
  1796. \begin{lstlisting}
  1797. (let ([x.1 32])
  1798. (+ (let ([x.2 10]) x.2) x.1))
  1799. \end{lstlisting}
  1800. \end{minipage}
  1801. \end{tabular} \\
  1802. %
  1803. The following is another example translation, this time of a program
  1804. with a \key{let} nested inside the initializing expression of another
  1805. \key{let}.\\
  1806. \begin{tabular}{lll}
  1807. \begin{minipage}{0.4\textwidth}
  1808. \begin{lstlisting}
  1809. (let ([x (let ([x 4])
  1810. (+ x 1))])
  1811. (+ x 2))
  1812. \end{lstlisting}
  1813. \end{minipage}
  1814. &
  1815. $\Rightarrow$
  1816. &
  1817. \begin{minipage}{0.4\textwidth}
  1818. \begin{lstlisting}
  1819. (let ([x.2 (let ([x.1 4])
  1820. (+ x.1 1))])
  1821. (+ x.2 2))
  1822. \end{lstlisting}
  1823. \end{minipage}
  1824. \end{tabular}
  1825. We recommend implementing \code{uniquify} by creating a structurally
  1826. recursive function named \code{uniquify-exp} that mostly just copies
  1827. an expression. However, when encountering a \key{let}, it should
  1828. generate a unique name for the variable and associate the old name
  1829. with the new name in an alist.\footnote{The Racket function
  1830. \code{gensym} is handy for generating unique variable names.} The
  1831. \code{uniquify-exp} function needs to access this alist when it gets
  1832. to a variable reference, so we add a parameter to \code{uniquify-exp}
  1833. for the alist.
  1834. The skeleton of the \code{uniquify-exp} function is shown in
  1835. Figure~\ref{fig:uniquify-Rvar}. The function is curried so that it is
  1836. convenient to partially apply it to an alist and then apply it to
  1837. different expressions, as in the last case for primitive operations in
  1838. Figure~\ref{fig:uniquify-Rvar}. The
  1839. %
  1840. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  1841. %
  1842. form of Racket is useful for transforming each element of a list to
  1843. produce a new list.\index{for/list}
  1844. \begin{exercise}
  1845. \normalfont % I don't like the italics for exercises. -Jeremy
  1846. Complete the \code{uniquify} pass by filling in the blanks in
  1847. Figure~\ref{fig:uniquify-Rvar}, that is, implement the cases for
  1848. variables and for the \key{let} form in the file \code{compiler.rkt}
  1849. in the support code.
  1850. \end{exercise}
  1851. \begin{figure}[tbp]
  1852. \begin{lstlisting}
  1853. (define (uniquify-exp env)
  1854. (lambda (e)
  1855. (match e
  1856. [(Var x) ___]
  1857. [(Int n) (Int n)]
  1858. [(Let x e body) ___]
  1859. [(Prim op es)
  1860. (Prim op (for/list ([e es]) ((uniquify-exp env) e)))])))
  1861. (define (uniquify p)
  1862. (match p
  1863. [(Program '() e) (Program '() ((uniquify-exp '()) e))]))
  1864. \end{lstlisting}
  1865. \caption{Skeleton for the \key{uniquify} pass.}
  1866. \label{fig:uniquify-Rvar}
  1867. \end{figure}
  1868. \begin{exercise}
  1869. \normalfont % I don't like the italics for exercises. -Jeremy
  1870. Create five \LangVar{} programs that exercise the most interesting
  1871. parts of the \key{uniquify} pass, that is, the programs should include
  1872. \key{let} forms, variables, and variables that overshadow each other.
  1873. The five programs should be placed in the subdirectory named
  1874. \key{tests} and the file names should start with \code{var\_test\_}
  1875. followed by a unique integer and end with the file extension
  1876. \key{.rkt}.
  1877. %
  1878. The \key{run-tests.rkt} script in the support code checks whether the
  1879. output programs produce the same result as the input programs. The
  1880. script uses the \key{interp-tests} function
  1881. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1882. your \key{uniquify} pass on the example programs. The \code{passes}
  1883. parameter of \key{interp-tests} is a list that should have one entry
  1884. for each pass in your compiler. For now, define \code{passes} to
  1885. contain just one entry for \code{uniquify} as follows.
  1886. \begin{lstlisting}
  1887. (define passes
  1888. (list (list "uniquify" uniquify interp-Rvar type-check-Rvar)))
  1889. \end{lstlisting}
  1890. Run the \key{run-tests.rkt} script in the support code to check
  1891. whether the output programs produce the same result as the input
  1892. programs.
  1893. \end{exercise}
  1894. \section{Remove Complex Operands}
  1895. \label{sec:remove-complex-opera-Rvar}
  1896. The \code{remove-complex-opera*} pass compiles \LangVar{} programs
  1897. into a restricted form in which the arguments of operations are atomic
  1898. expressions. Put another way, this pass removes complex
  1899. operands\index{complex operand}, such as the expression \code{(- 10)}
  1900. in the program below. This is accomplished by introducing a new
  1901. \key{let}-bound variable, binding the complex operand to the new
  1902. variable, and then using the new variable in place of the complex
  1903. operand, as shown in the output of \code{remove-complex-opera*} on the
  1904. right.\\
  1905. \begin{tabular}{lll}
  1906. \begin{minipage}{0.4\textwidth}
  1907. % var_test_19.rkt
  1908. \begin{lstlisting}
  1909. (+ 52 (- 10))
  1910. \end{lstlisting}
  1911. \end{minipage}
  1912. &
  1913. $\Rightarrow$
  1914. &
  1915. \begin{minipage}{0.4\textwidth}
  1916. \begin{lstlisting}
  1917. (let ([tmp.1 (- 10)])
  1918. (+ 52 tmp.1))
  1919. \end{lstlisting}
  1920. \end{minipage}
  1921. \end{tabular}
  1922. \begin{figure}[tp]
  1923. \centering
  1924. \fbox{
  1925. \begin{minipage}{0.96\textwidth}
  1926. \[
  1927. \begin{array}{rcl}
  1928. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1929. \Exp &::=& \Atm \mid \READ{} \\
  1930. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  1931. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  1932. R^{\dagger}_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1933. \end{array}
  1934. \]
  1935. \end{minipage}
  1936. }
  1937. \caption{\LangVarANF{} is \LangVar{} in administrative normal form (ANF).}
  1938. \label{fig:r1-anf-syntax}
  1939. \end{figure}
  1940. Figure~\ref{fig:r1-anf-syntax} presents the grammar for the output of
  1941. this pass, the language \LangVarANF{}. The only difference is that
  1942. operator arguments are restricted to be atomic expressions that are
  1943. defined by the \Atm{} non-terminal. In particular, integer constants
  1944. and variables are atomic. In the literature, restricting arguments to
  1945. be atomic expressions is called \emph{administrative normal form}, or
  1946. ANF for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  1947. \index{administrative normal form} \index{ANF}
  1948. We recommend implementing this pass with two mutually recursive
  1949. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1950. \code{rco-atom} to subexpressions that need to become atomic and to
  1951. apply \code{rco-exp} to subexpressions that do not. Both functions
  1952. take an \LangVar{} expression as input. The \code{rco-exp} function
  1953. returns an expression. The \code{rco-atom} function returns two
  1954. things: an atomic expression and alist mapping temporary variables to
  1955. complex subexpressions. You can return multiple things from a function
  1956. using Racket's \key{values} form and you can receive multiple things
  1957. from a function call using the \key{define-values} form. If you are
  1958. not familiar with these features, review the Racket documentation.
  1959. Also, the
  1960. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  1961. form is useful for applying a function to each element of a list, in
  1962. the case where the function returns multiple values.
  1963. \index{for/lists}
  1964. Returning to the example program \code{(+ 52 (- 10))}, the
  1965. subexpression \code{(- 10)} should be processed using the
  1966. \code{rco-atom} function because it is an argument of the \code{+} and
  1967. therefore needs to become atomic. The output of \code{rco-atom}
  1968. applied to \code{(- 10)} is as follows.
  1969. \begin{tabular}{lll}
  1970. \begin{minipage}{0.4\textwidth}
  1971. \begin{lstlisting}
  1972. (- 10)
  1973. \end{lstlisting}
  1974. \end{minipage}
  1975. &
  1976. $\Rightarrow$
  1977. &
  1978. \begin{minipage}{0.4\textwidth}
  1979. \begin{lstlisting}
  1980. tmp.1
  1981. ((tmp.1 . (- 10)))
  1982. \end{lstlisting}
  1983. \end{minipage}
  1984. \end{tabular}
  1985. Take special care of programs such as the following one that binds a
  1986. variable to an atomic expression. You should leave such variable
  1987. bindings unchanged, as shown in to the program on the right \\
  1988. \begin{tabular}{lll}
  1989. \begin{minipage}{0.4\textwidth}
  1990. % var_test_20.rkt
  1991. \begin{lstlisting}
  1992. (let ([a 42])
  1993. (let ([b a])
  1994. b))
  1995. \end{lstlisting}
  1996. \end{minipage}
  1997. &
  1998. $\Rightarrow$
  1999. &
  2000. \begin{minipage}{0.4\textwidth}
  2001. \begin{lstlisting}
  2002. (let ([a 42])
  2003. (let ([b a])
  2004. b))
  2005. \end{lstlisting}
  2006. \end{minipage}
  2007. \end{tabular} \\
  2008. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  2009. produce the following output with unnecessary temporary variables.\\
  2010. \begin{minipage}{0.4\textwidth}
  2011. \begin{lstlisting}
  2012. (let ([tmp.1 42])
  2013. (let ([a tmp.1])
  2014. (let ([tmp.2 a])
  2015. (let ([b tmp.2])
  2016. b))))
  2017. \end{lstlisting}
  2018. \end{minipage}
  2019. \begin{exercise}\normalfont
  2020. %
  2021. Implement the \code{remove-complex-opera*} function in
  2022. \code{compiler.rkt}.
  2023. %
  2024. Create three new \LangInt{} programs that exercise the interesting
  2025. code in the \code{remove-complex-opera*} pass (Following the same file
  2026. name guidelines as before.).
  2027. %
  2028. In the \code{run-tests.rkt} script, add the following entry to the
  2029. list of \code{passes} and then run the script to test your compiler.
  2030. \begin{lstlisting}
  2031. (list "remove-complex" remove-complex-opera* interp-Rvar type-check-Rvar)
  2032. \end{lstlisting}
  2033. While debugging your compiler, it is often useful to see the
  2034. intermediate programs that are output from each pass. To print the
  2035. intermeidate programs, place the following before the call to
  2036. \code{interp-tests} in \code{run-tests.rkt}.
  2037. \begin{lstlisting}
  2038. (debug-level 1)
  2039. \end{lstlisting}
  2040. \end{exercise}
  2041. \section{Explicate Control}
  2042. \label{sec:explicate-control-Rvar}
  2043. The \code{explicate-control} pass compiles \LangVar{} programs into \LangCVar{}
  2044. programs that make the order of execution explicit in their
  2045. syntax. For now this amounts to flattening \key{let} constructs into a
  2046. sequence of assignment statements. For example, consider the following
  2047. \LangVar{} program.\\
  2048. % var_test_11.rkt
  2049. \begin{minipage}{0.96\textwidth}
  2050. \begin{lstlisting}
  2051. (let ([y (let ([x 20])
  2052. (+ x (let ([x 22]) x)))])
  2053. y)
  2054. \end{lstlisting}
  2055. \end{minipage}\\
  2056. %
  2057. The output of the previous pass and of \code{explicate-control} is
  2058. shown below. Recall that the right-hand-side of a \key{let} executes
  2059. before its body, so the order of evaluation for this program is to
  2060. assign \code{20} to \code{x.1}, \code{22} to \code{x.2}, and
  2061. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  2062. output of \code{explicate-control} makes this ordering explicit.\\
  2063. \begin{tabular}{lll}
  2064. \begin{minipage}{0.4\textwidth}
  2065. \begin{lstlisting}
  2066. (let ([y (let ([x.1 20])
  2067. (let ([x.2 22])
  2068. (+ x.1 x.2)))])
  2069. y)
  2070. \end{lstlisting}
  2071. \end{minipage}
  2072. &
  2073. $\Rightarrow$
  2074. &
  2075. \begin{minipage}{0.4\textwidth}
  2076. \begin{lstlisting}[language=C]
  2077. start:
  2078. x.1 = 20;
  2079. x.2 = 22;
  2080. y = (+ x.1 x.2);
  2081. return y;
  2082. \end{lstlisting}
  2083. \end{minipage}
  2084. \end{tabular}
  2085. \begin{figure}[tbp]
  2086. \begin{lstlisting}
  2087. (define (explicate-tail e)
  2088. (match e
  2089. [(Var x) ___]
  2090. [(Int n) (Return (Int n))]
  2091. [(Let x rhs body) ___]
  2092. [(Prim op es) ___]
  2093. [else (error "explicate-tail unhandled case" e)]))
  2094. (define (explicate-assign e x cont)
  2095. (match e
  2096. [(Var x) ___]
  2097. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  2098. [(Let y rhs body) ___]
  2099. [(Prim op es) ___]
  2100. [else (error "explicate-assign unhandled case" e)]))
  2101. (define (explicate-control p)
  2102. (match p
  2103. [(Program info body) ___]))
  2104. \end{lstlisting}
  2105. \caption{Skeleton for the \key{explicate-control} pass.}
  2106. \label{fig:explicate-control-Rvar}
  2107. \end{figure}
  2108. The organization of this pass depends on the notion of tail position
  2109. that we have alluded to earlier. Formally, \emph{tail
  2110. position}\index{tail position} in the context of \LangVar{} is
  2111. defined recursively by the following two rules.
  2112. \begin{enumerate}
  2113. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  2114. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  2115. \end{enumerate}
  2116. We recommend implementing \code{explicate-control} using two mutually
  2117. recursive functions, \code{explicate-tail} and
  2118. \code{explicate-assign}, as suggested in the skeleton code in
  2119. Figure~\ref{fig:explicate-control-Rvar}. The \code{explicate-tail}
  2120. function should be applied to expressions in tail position whereas the
  2121. \code{explicate-assign} should be applied to expressions that occur on
  2122. the right-hand-side of a \key{let}.
  2123. %
  2124. The \code{explicate-tail} function takes an \Exp{} in \LangVar{} as
  2125. input and produces a \Tail{} in \LangCVar{} (see
  2126. Figure~\ref{fig:c0-syntax}).
  2127. %
  2128. The \code{explicate-assign} function takes an \Exp{} in \LangVar{},
  2129. the variable that it is to be assigned to, and a \Tail{} in
  2130. \LangCVar{} for the code that will come after the assignment. The
  2131. \code{explicate-assign} function returns a $\Tail$ in \LangCVar{}.
  2132. The \code{explicate-assign} function is in accumulator-passing style
  2133. in that the \code{cont} parameter is used for accumulating the
  2134. output. The reader might be tempted to instead organize
  2135. \code{explicate-assign} in a more direct fashion, without the
  2136. \code{cont} parameter and perhaps using \code{append} to combine
  2137. statements. We warn against that alternative because the
  2138. accumulator-passing style is key to how we generate high-quality code
  2139. for conditional expressions in Chapter~\ref{ch:Rif}.
  2140. \begin{exercise}\normalfont
  2141. %
  2142. Implement the \code{explicate-control} function in
  2143. \code{compiler.rkt}. Create three new \LangInt{} programs that
  2144. exercise the code in \code{explicate-control}.
  2145. %
  2146. In the \code{run-tests.rkt} script, add the following entry to the
  2147. list of \code{passes} and then run the script to test your compiler.
  2148. \begin{lstlisting}
  2149. (list "explicate control" explicate-control interp-Cvar type-check-Cvar)
  2150. \end{lstlisting}
  2151. \end{exercise}
  2152. \section{Select Instructions}
  2153. \label{sec:select-Rvar}
  2154. \index{instruction selection}
  2155. In the \code{select-instructions} pass we begin the work of
  2156. translating from \LangCVar{} to \LangXVar{}. The target language of
  2157. this pass is a variant of x86 that still uses variables, so we add an
  2158. AST node of the form $\VAR{\itm{var}}$ to the \Arg{} non-terminal of
  2159. the \LangXInt{} abstract syntax (Figure~\ref{fig:x86-int-ast}). We
  2160. recommend implementing the \code{select-instructions} with
  2161. three auxiliary functions, one for each of the non-terminals of
  2162. \LangCVar{}: $\Atm$, $\Stmt$, and $\Tail$.
  2163. The cases for $\Atm$ are straightforward, variables stay
  2164. the same and integer constants are changed to immediates:
  2165. $\INT{n}$ changes to $\IMM{n}$.
  2166. Next we consider the cases for $\Stmt$, starting with arithmetic
  2167. operations. For example, consider the addition operation. We can use
  2168. the \key{addq} instruction, but it performs an in-place update. So we
  2169. could move $\itm{arg}_1$ into the left-hand side \itm{var} and then
  2170. add $\itm{arg}_2$ to \itm{var}. \\
  2171. \begin{tabular}{lll}
  2172. \begin{minipage}{0.4\textwidth}
  2173. \begin{lstlisting}
  2174. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{arg}_2$|);
  2175. \end{lstlisting}
  2176. \end{minipage}
  2177. &
  2178. $\Rightarrow$
  2179. &
  2180. \begin{minipage}{0.4\textwidth}
  2181. \begin{lstlisting}
  2182. movq |$\itm{arg}_1$|, |$\itm{var}$|
  2183. addq |$\itm{arg}_2$|, |$\itm{var}$|
  2184. \end{lstlisting}
  2185. \end{minipage}
  2186. \end{tabular} \\
  2187. %
  2188. There are also cases that require special care to avoid generating
  2189. needlessly complicated code. For example, if one of the arguments of
  2190. the addition is the same variable as the left-hand side of the
  2191. assignment, then there is no need for the extra move instruction. The
  2192. assignment statement can be translated into a single \key{addq}
  2193. instruction as follows.\\
  2194. \begin{tabular}{lll}
  2195. \begin{minipage}{0.4\textwidth}
  2196. \begin{lstlisting}
  2197. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{var}$|);
  2198. \end{lstlisting}
  2199. \end{minipage}
  2200. &
  2201. $\Rightarrow$
  2202. &
  2203. \begin{minipage}{0.4\textwidth}
  2204. \begin{lstlisting}
  2205. addq |$\itm{arg}_1$|, |$\itm{var}$|
  2206. \end{lstlisting}
  2207. \end{minipage}
  2208. \end{tabular}
  2209. The \key{read} operation does not have a direct counterpart in x86
  2210. assembly, so we provide this functionality with the function
  2211. \code{read\_int} in the file \code{runtime.c}, written in
  2212. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  2213. functionality in this file as the \emph{runtime system}\index{runtime
  2214. system}, or simply the \emph{runtime} for short. When compiling your
  2215. generated x86 assembly code, you need to compile \code{runtime.c} to
  2216. \code{runtime.o} (an ``object file'', using \code{gcc} option
  2217. \code{-c}) and link it into the executable. For our purposes of code
  2218. generation, all you need to do is translate an assignment of
  2219. \key{read} into a call to the \code{read\_int} function followed by a
  2220. move from \code{rax} to the left-hand-side variable. (Recall that the
  2221. return value of a function goes into \code{rax}.) \\
  2222. \begin{tabular}{lll}
  2223. \begin{minipage}{0.3\textwidth}
  2224. \begin{lstlisting}
  2225. |$\itm{var}$| = (read);
  2226. \end{lstlisting}
  2227. \end{minipage}
  2228. &
  2229. $\Rightarrow$
  2230. &
  2231. \begin{minipage}{0.3\textwidth}
  2232. \begin{lstlisting}
  2233. callq read_int
  2234. movq %rax, |$\itm{var}$|
  2235. \end{lstlisting}
  2236. \end{minipage}
  2237. \end{tabular}
  2238. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  2239. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  2240. assignment to the \key{rax} register followed by a jump to the
  2241. conclusion of the program (so the conclusion needs to be labeled).
  2242. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  2243. recursively and then append the resulting instructions.
  2244. \begin{exercise}
  2245. \normalfont Implement the \key{select-instructions} pass in
  2246. \code{compiler.rkt}. Create three new example programs that are
  2247. designed to exercise all of the interesting cases in this pass.
  2248. %
  2249. In the \code{run-tests.rkt} script, add the following entry to the
  2250. list of \code{passes} and then run the script to test your compiler.
  2251. \begin{lstlisting}
  2252. (list "instruction selection" select-instructions interp-pseudo-x86-0)
  2253. \end{lstlisting}
  2254. \end{exercise}
  2255. \section{Assign Homes}
  2256. \label{sec:assign-Rvar}
  2257. The \key{assign-homes} pass compiles \LangXVar{} programs to
  2258. \LangXVar{} programs that no longer use program variables.
  2259. Thus, the \key{assign-homes} pass is responsible for placing all of
  2260. the program variables in registers or on the stack. For runtime
  2261. efficiency, it is better to place variables in registers, but as there
  2262. are only 16 registers, some programs must necessarily resort to
  2263. placing some variables on the stack. In this chapter we focus on the
  2264. mechanics of placing variables on the stack. We study an algorithm for
  2265. placing variables in registers in
  2266. Chapter~\ref{ch:register-allocation-Rvar}.
  2267. Consider again the following \LangVar{} program from
  2268. Section~\ref{sec:remove-complex-opera-Rvar}.
  2269. % var_test_20.rkt
  2270. \begin{lstlisting}
  2271. (let ([a 42])
  2272. (let ([b a])
  2273. b))
  2274. \end{lstlisting}
  2275. The output of \code{select-instructions} is shown on the left and the
  2276. output of \code{assign-homes} on the right. In this example, we
  2277. assign variable \code{a} to stack location \code{-8(\%rbp)} and
  2278. variable \code{b} to location \code{-16(\%rbp)}.\\
  2279. \begin{tabular}{l}
  2280. \begin{minipage}{0.4\textwidth}
  2281. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2282. locals-types:
  2283. a : Integer, b : Integer
  2284. start:
  2285. movq $42, a
  2286. movq a, b
  2287. movq b, %rax
  2288. jmp conclusion
  2289. \end{lstlisting}
  2290. \end{minipage}
  2291. {$\Rightarrow$}
  2292. \begin{minipage}{0.4\textwidth}
  2293. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2294. stack-space: 16
  2295. start:
  2296. movq $42, -8(%rbp)
  2297. movq -8(%rbp), -16(%rbp)
  2298. movq -16(%rbp), %rax
  2299. jmp conclusion
  2300. \end{lstlisting}
  2301. \end{minipage}
  2302. \end{tabular}
  2303. The \code{locals-types} entry in the $\itm{info}$ of the
  2304. \code{X86Program} node is an alist mapping all the variables in the
  2305. program to their types (for now just \code{Integer}). The
  2306. \code{assign-homes} pass should replace all uses of those variables
  2307. with stack locations. As an aside, the \code{locals-types} entry is
  2308. computed by \code{type-check-Cvar} in the support code, which installs
  2309. it in the $\itm{info}$ field of the \code{CProgram} node, which should
  2310. be propagated to the \code{X86Program} node.
  2311. In the process of assigning variables to stack locations, it is
  2312. convenient for you to compute and store the size of the frame (in
  2313. bytes) in the $\itm{info}$ field of the \key{X86Program} node, with
  2314. the key \code{stack-space}, which is needed later to generate the
  2315. conclusion of the \code{main} procedure. The x86-64 standard requires
  2316. the frame size to be a multiple of 16 bytes.\index{frame}
  2317. \begin{exercise}\normalfont
  2318. Implement the \key{assign-homes} pass in \code{compiler.rkt}, defining
  2319. auxiliary functions for the non-terminals \Arg{}, \Instr{}, and
  2320. \Block{}. We recommend that the auxiliary functions take an extra
  2321. parameter that is an alist mapping variable names to homes (stack
  2322. locations for now).
  2323. %
  2324. In the \code{run-tests.rkt} script, add the following entry to the
  2325. list of \code{passes} and then run the script to test your compiler.
  2326. \begin{lstlisting}
  2327. (list "assign homes" assign-homes interp-x86-0)
  2328. \end{lstlisting}
  2329. \end{exercise}
  2330. \section{Patch Instructions}
  2331. \label{sec:patch-s0}
  2332. The \code{patch-instructions} pass compiles from \LangXVar{} to
  2333. \LangXInt{} by making sure that each instruction adheres to the
  2334. restriction that at most one argument of an instruction may be a
  2335. memory reference.
  2336. We return to the following example.
  2337. % var_test_20.rkt
  2338. \begin{lstlisting}
  2339. (let ([a 42])
  2340. (let ([b a])
  2341. b))
  2342. \end{lstlisting}
  2343. The \key{assign-homes} pass produces the following output
  2344. for this program. \\
  2345. \begin{minipage}{0.5\textwidth}
  2346. \begin{lstlisting}
  2347. stack-space: 16
  2348. start:
  2349. movq $42, -8(%rbp)
  2350. movq -8(%rbp), -16(%rbp)
  2351. movq -16(%rbp), %rax
  2352. jmp conclusion
  2353. \end{lstlisting}
  2354. \end{minipage}\\
  2355. The second \key{movq} instruction is problematic because both
  2356. arguments are stack locations. We suggest fixing this problem by
  2357. moving from the source location to the register \key{rax} and then
  2358. from \key{rax} to the destination location, as follows.
  2359. \begin{lstlisting}
  2360. movq -8(%rbp), %rax
  2361. movq %rax, -16(%rbp)
  2362. \end{lstlisting}
  2363. \begin{exercise}
  2364. \normalfont Implement the \key{patch-instructions} pass in
  2365. \code{compiler.rkt}. Create three new example programs that are
  2366. designed to exercise all of the interesting cases in this pass.
  2367. %
  2368. In the \code{run-tests.rkt} script, add the following entry to the
  2369. list of \code{passes} and then run the script to test your compiler.
  2370. \begin{lstlisting}
  2371. (list "patch instructions" patch-instructions interp-x86-0)
  2372. \end{lstlisting}
  2373. \end{exercise}
  2374. \section{Print x86}
  2375. \label{sec:print-x86}
  2376. The last step of the compiler from \LangVar{} to x86 is to convert the
  2377. \LangXInt{} AST (defined in Figure~\ref{fig:x86-int-ast}) to the
  2378. string representation (defined in
  2379. Figure~\ref{fig:x86-int-concrete}). The Racket \key{format} and
  2380. \key{string-append} functions are useful in this regard. The main work
  2381. that this step needs to perform is to create the \key{main} function
  2382. and the standard instructions for its prelude and conclusion, as shown
  2383. in Figure~\ref{fig:p1-x86} of Section~\ref{sec:x86}. You will need to
  2384. know the amount of space needed for the stack frame, which you can
  2385. obtain from the \code{stack-space} entry in the $\itm{info}$ field of
  2386. the \key{X86Program} node.
  2387. When running on Mac OS X, you compiler should prefix an underscore to
  2388. labels like \key{main}. The Racket call \code{(system-type 'os)} is
  2389. useful for determining which operating system the compiler is running
  2390. on. It returns \code{'macosx}, \code{'unix}, or \code{'windows}.
  2391. \begin{exercise}\normalfont
  2392. %
  2393. Implement the \key{print-x86} pass in \code{compiler.rkt}.
  2394. %
  2395. In the \code{run-tests.rkt} script, add the following entry to the
  2396. list of \code{passes} and then run the script to test your compiler.
  2397. \begin{lstlisting}
  2398. (list "print x86" print-x86 #f)
  2399. \end{lstlisting}
  2400. %
  2401. Uncomment the call to the \key{compiler-tests} function
  2402. (Appendix~\ref{appendix:utilities}), which tests your complete
  2403. compiler by executing the generated x86 code. Compile the provided
  2404. \key{runtime.c} file to \key{runtime.o} using \key{gcc}. Run the
  2405. script to test your compiler.
  2406. \end{exercise}
  2407. \section{Challenge: Partial Evaluator for \LangVar{}}
  2408. \label{sec:pe-Rvar}
  2409. \index{partial evaluation}
  2410. This section describes optional challenge exercises that involve
  2411. adapting and improving the partial evaluator for \LangInt{} that was
  2412. introduced in Section~\ref{sec:partial-evaluation}.
  2413. \begin{exercise}\label{ex:pe-Rvar}
  2414. \normalfont
  2415. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2416. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  2417. instead of \LangInt{} programs. Recall that \LangVar{} adds \key{let} binding
  2418. and variables to the \LangInt{} language, so you will need to add cases for
  2419. them in the \code{pe-exp} function. Once complete, add the partial
  2420. evaluation pass to the front of your compiler and make sure that your
  2421. compiler still passes all of the tests.
  2422. \end{exercise}
  2423. The next exercise builds on Exercise~\ref{ex:pe-Rvar}.
  2424. \begin{exercise}
  2425. \normalfont
  2426. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2427. \code{pe-add} auxiliary functions with functions that know more about
  2428. arithmetic. For example, your partial evaluator should translate
  2429. \[
  2430. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  2431. \code{(+ 2 (read))}
  2432. \]
  2433. To accomplish this, the \code{pe-exp} function should produce output
  2434. in the form of the $\itm{residual}$ non-terminal of the following
  2435. grammar. The idea is that when processing an addition expression, we
  2436. can always produce either 1) an integer constant, 2) and addition
  2437. expression with an integer constant on the left-hand side but not the
  2438. right-hand side, or 3) or an addition expression in which neither
  2439. subexpression is a constant.
  2440. \[
  2441. \begin{array}{lcl}
  2442. \itm{inert} &::=& \Var \mid \LP\key{read}\RP \mid \LP\key{-} \;\Var\RP
  2443. \mid \LP\key{-} \;\LP\key{read}\RP\RP
  2444. \mid \LP\key{+} \; \itm{inert} \; \itm{inert}\RP\\
  2445. &\mid& \LP\key{let}~\LP\LS\Var~\itm{inert}\RS\RP~ \itm{inert} \RP \\
  2446. \itm{residual} &::=& \Int \mid \LP\key{+}\; \Int\; \itm{inert}\RP \mid \itm{inert}
  2447. \end{array}
  2448. \]
  2449. The \code{pe-add} and \code{pe-neg} functions may assume that their
  2450. inputs are $\itm{residual}$ expressions and they should return
  2451. $\itm{residual}$ expressions. Once the improvements are complete,
  2452. make sure that your compiler still passes all of the tests. After
  2453. all, fast code is useless if it produces incorrect results!
  2454. \end{exercise}
  2455. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2456. \chapter{Register Allocation}
  2457. \label{ch:register-allocation-Rvar}
  2458. \index{register allocation}
  2459. In Chapter~\ref{ch:Rvar} we learned how to store variables on the
  2460. stack. In this Chapter we learn how to improve the performance of the
  2461. generated code by placing some variables into registers. The CPU can
  2462. access a register in a single cycle, whereas accessing the stack can
  2463. take 10s to 100s of cycles. The program in Figure~\ref{fig:reg-eg}
  2464. serves as a running example. The source program is on the left and the
  2465. output of instruction selection is on the right. The program is almost
  2466. in the x86 assembly language but it still uses variables.
  2467. \begin{figure}
  2468. \begin{minipage}{0.45\textwidth}
  2469. Example \LangVar{} program:
  2470. % var_test_28.rkt
  2471. \begin{lstlisting}
  2472. (let ([v 1])
  2473. (let ([w 42])
  2474. (let ([x (+ v 7)])
  2475. (let ([y x])
  2476. (let ([z (+ x w)])
  2477. (+ z (- y)))))))
  2478. \end{lstlisting}
  2479. \end{minipage}
  2480. \begin{minipage}{0.45\textwidth}
  2481. After instruction selection:
  2482. \begin{lstlisting}
  2483. locals-types:
  2484. x : Integer, y : Integer,
  2485. z : Integer, t : Integer,
  2486. v : Integer, w : Integer
  2487. start:
  2488. movq $1, v
  2489. movq $42, w
  2490. movq v, x
  2491. addq $7, x
  2492. movq x, y
  2493. movq x, z
  2494. addq w, z
  2495. movq y, t
  2496. negq t
  2497. movq z, %rax
  2498. addq t, %rax
  2499. jmp conclusion
  2500. \end{lstlisting}
  2501. \end{minipage}
  2502. \caption{A running example for register allocation.}
  2503. \label{fig:reg-eg}
  2504. \end{figure}
  2505. The goal of register allocation is to fit as many variables into
  2506. registers as possible. Some programs have more variables than
  2507. registers so we cannot always map each variable to a different
  2508. register. Fortunately, it is common for different variables to be
  2509. needed during different periods of time during program execution, and
  2510. in such cases several variables can be mapped to the same register.
  2511. Consider variables \code{x} and \code{z} in Figure~\ref{fig:reg-eg}.
  2512. After the variable \code{x} is moved to \code{z} it is no longer
  2513. needed. Variable \code{z}, on the other hand, is used only after this
  2514. point, so \code{x} and \code{z} could share the same register. The
  2515. topic of Section~\ref{sec:liveness-analysis-Rvar} is how to compute
  2516. where a variable is needed. Once we have that information, we compute
  2517. which variables are needed at the same time, i.e., which ones
  2518. \emph{interfere} with each other, and represent this relation as an
  2519. undirected graph whose vertices are variables and edges indicate when
  2520. two variables interfere (Section~\ref{sec:build-interference}). We
  2521. then model register allocation as a graph coloring problem
  2522. (Section~\ref{sec:graph-coloring}).
  2523. If we run out of registers despite these efforts, we place the
  2524. remaining variables on the stack, similar to what we did in
  2525. Chapter~\ref{ch:Rvar}. It is common to use the verb \emph{spill}
  2526. for assigning a variable to a stack location. The decision to spill a
  2527. variable is handled as part of the graph coloring process
  2528. (Section~\ref{sec:graph-coloring}).
  2529. We make the simplifying assumption that each variable is assigned to
  2530. one location (a register or stack address). A more sophisticated
  2531. approach is to assign a variable to one or more locations in different
  2532. regions of the program. For example, if a variable is used many times
  2533. in short sequence and then only used again after many other
  2534. instructions, it could be more efficient to assign the variable to a
  2535. register during the initial sequence and then move it to the stack for
  2536. the rest of its lifetime. We refer the interested reader to
  2537. \citet{Cooper:2011aa} for more information about that approach.
  2538. % discuss prioritizing variables based on how much they are used.
  2539. \section{Registers and Calling Conventions}
  2540. \label{sec:calling-conventions}
  2541. \index{calling conventions}
  2542. As we perform register allocation, we need to be aware of the
  2543. \emph{calling conventions} \index{calling conventions} that govern how
  2544. functions calls are performed in x86.
  2545. %
  2546. Even though \LangVar{} does not include programmer-defined functions,
  2547. our generated code includes a \code{main} function that is called by
  2548. the operating system and our generated code contains calls to the
  2549. \code{read\_int} function.
  2550. Function calls require coordination between two pieces of code that
  2551. may be written by different programmers or generated by different
  2552. compilers. Here we follow the System V calling conventions that are
  2553. used by the GNU C compiler on Linux and
  2554. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  2555. %
  2556. The calling conventions include rules about how functions share the
  2557. use of registers. In particular, the caller is responsible for freeing
  2558. up some registers prior to the function call for use by the callee.
  2559. These are called the \emph{caller-saved registers}
  2560. \index{caller-saved registers}
  2561. and they are
  2562. \begin{lstlisting}
  2563. rax rcx rdx rsi rdi r8 r9 r10 r11
  2564. \end{lstlisting}
  2565. On the other hand, the callee is responsible for preserving the values
  2566. of the \emph{callee-saved registers}, \index{callee-saved registers}
  2567. which are
  2568. \begin{lstlisting}
  2569. rsp rbp rbx r12 r13 r14 r15
  2570. \end{lstlisting}
  2571. We can think about this caller/callee convention from two points of
  2572. view, the caller view and the callee view:
  2573. \begin{itemize}
  2574. \item The caller should assume that all the caller-saved registers get
  2575. overwritten with arbitrary values by the callee. On the other hand,
  2576. the caller can safely assume that all the callee-saved registers
  2577. contain the same values after the call that they did before the
  2578. call.
  2579. \item The callee can freely use any of the caller-saved registers.
  2580. However, if the callee wants to use a callee-saved register, the
  2581. callee must arrange to put the original value back in the register
  2582. prior to returning to the caller. This can be accomplished by saving
  2583. the value to the stack in the prelude of the function and restoring
  2584. the value in the conclusion of the function.
  2585. \end{itemize}
  2586. In x86, registers are also used for passing arguments to a function
  2587. and for the return value. In particular, the first six arguments to a
  2588. function are passed in the following six registers, in this order.
  2589. \begin{lstlisting}
  2590. rdi rsi rdx rcx r8 r9
  2591. \end{lstlisting}
  2592. If there are more than six arguments, then the convention is to use
  2593. space on the frame of the caller for the rest of the
  2594. arguments. However, in Chapter~\ref{ch:Rfun} we arrange never to
  2595. need more than six arguments. For now, the only function we care about
  2596. is \code{read\_int} and it takes zero arguments.
  2597. %
  2598. The register \code{rax} is used for the return value of a function.
  2599. The next question is how these calling conventions impact register
  2600. allocation. Consider the \LangVar{} program in
  2601. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  2602. example from the caller point of view and then from the callee point
  2603. of view.
  2604. The program makes two calls to the \code{read} function. Also, the
  2605. variable \code{x} is in use during the second call to \code{read}, so
  2606. we need to make sure that the value in \code{x} does not get
  2607. accidentally wiped out by the call to \code{read}. One obvious
  2608. approach is to save all the values in caller-saved registers to the
  2609. stack prior to each function call, and restore them after each
  2610. call. That way, if the register allocator chooses to assign \code{x}
  2611. to a caller-saved register, its value will be preserved across the
  2612. call to \code{read}. However, saving and restoring to the stack is
  2613. relatively slow. If \code{x} is not used many times, it may be better
  2614. to assign \code{x} to a stack location in the first place. Or better
  2615. yet, if we can arrange for \code{x} to be placed in a callee-saved
  2616. register, then it won't need to be saved and restored during function
  2617. calls.
  2618. The approach that we recommend for variables that are in use during a
  2619. function call is to either assign them to callee-saved registers or to
  2620. spill them to the stack. On the other hand, for variables that are not
  2621. in use during a function call, we try the following alternatives in
  2622. order 1) look for an available caller-saved register (to leave room
  2623. for other variables in the callee-saved register), 2) look for a
  2624. callee-saved register, and 3) spill the variable to the stack.
  2625. It is straightforward to implement this approach in a graph coloring
  2626. register allocator. First, we know which variables are in use during
  2627. every function call because we compute that information for every
  2628. instruction (Section~\ref{sec:liveness-analysis-Rvar}). Second, when we
  2629. build the interference graph (Section~\ref{sec:build-interference}),
  2630. we can place an edge between each of these variables and the
  2631. caller-saved registers in the interference graph. This will prevent
  2632. the graph coloring algorithm from assigning those variables to
  2633. caller-saved registers.
  2634. Returning to the example in
  2635. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  2636. generated x86 code on the right-hand side, focusing on the
  2637. \code{start} block. Notice that variable \code{x} is assigned to
  2638. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  2639. place during the second call to \code{read\_int}. Next, notice that
  2640. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  2641. because there are no function calls in the remainder of the block.
  2642. Next we analyze the example from the callee point of view, focusing on
  2643. the prelude and conclusion of the \code{main} function. As usual the
  2644. prelude begins with saving the \code{rbp} register to the stack and
  2645. setting the \code{rbp} to the current stack pointer. We now know why
  2646. it is necessary to save the \code{rbp}: it is a callee-saved register.
  2647. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  2648. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  2649. (\code{x}). The other callee-saved registers are not saved in the
  2650. prelude because they are not used. The prelude subtracts 8 bytes from
  2651. the \code{rsp} to make it 16-byte aligned and then jumps to the
  2652. \code{start} block. Shifting attention to the \code{conclusion}, we
  2653. see that \code{rbx} is restored from the stack with a \code{popq}
  2654. instruction. \index{prelude}\index{conclusion}
  2655. \begin{figure}[tp]
  2656. \begin{minipage}{0.45\textwidth}
  2657. Example \LangVar{} program:
  2658. %var_test_14.rkt
  2659. \begin{lstlisting}
  2660. (let ([x (read)])
  2661. (let ([y (read)])
  2662. (+ (+ x y) 42)))
  2663. \end{lstlisting}
  2664. \end{minipage}
  2665. \begin{minipage}{0.45\textwidth}
  2666. Generated x86 assembly:
  2667. \begin{lstlisting}
  2668. start:
  2669. callq read_int
  2670. movq %rax, %rbx
  2671. callq read_int
  2672. movq %rax, %rcx
  2673. addq %rcx, %rbx
  2674. movq %rbx, %rax
  2675. addq $42, %rax
  2676. jmp _conclusion
  2677. .globl main
  2678. main:
  2679. pushq %rbp
  2680. movq %rsp, %rbp
  2681. pushq %rbx
  2682. subq $8, %rsp
  2683. jmp start
  2684. conclusion:
  2685. addq $8, %rsp
  2686. popq %rbx
  2687. popq %rbp
  2688. retq
  2689. \end{lstlisting}
  2690. \end{minipage}
  2691. \caption{An example with function calls.}
  2692. \label{fig:example-calling-conventions}
  2693. \end{figure}
  2694. \clearpage
  2695. \section{Liveness Analysis}
  2696. \label{sec:liveness-analysis-Rvar}
  2697. \index{liveness analysis}
  2698. The \code{uncover-live} pass performs \emph{liveness analysis}, that
  2699. is, it discovers which variables are in-use in different regions of a
  2700. program.
  2701. %
  2702. A variable or register is \emph{live} at a program point if its
  2703. current value is used at some later point in the program. We
  2704. refer to variables and registers collectively as \emph{locations}.
  2705. %
  2706. Consider the following code fragment in which there are two writes to
  2707. \code{b}. Are \code{a} and \code{b} both live at the same time?
  2708. \begin{center}
  2709. \begin{minipage}{0.96\textwidth}
  2710. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2711. movq $5, a
  2712. movq $30, b
  2713. movq a, c
  2714. movq $10, b
  2715. addq b, c
  2716. \end{lstlisting}
  2717. \end{minipage}
  2718. \end{center}
  2719. The answer is no because \code{a} is live from line 1 to 3 and
  2720. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  2721. line 2 is never used because it is overwritten (line 4) before the
  2722. next read (line 5).
  2723. \begin{wrapfigure}[19]{l}[1.0in]{0.6\textwidth}
  2724. \small
  2725. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  2726. A \emph{set} is an unordered collection of elements without duplicates.
  2727. \index{set}
  2728. \begin{description}
  2729. \item[$\LP\code{set}\,v\,\ldots\RP$] constructs a set containing the specified elements.
  2730. \item[$\LP\code{set-union}\,set_1\,set_2\RP$] returns the union of the two sets.
  2731. \item[$\LP\code{set-subtract}\,set_1\,set_2\RP$] returns the difference of the two sets.
  2732. \item[$\LP\code{set-member?}\,set\,v\RP$] is element $v$ in $set$?
  2733. \item[$\LP\code{set-count}\,set\RP$] how many unique elements are in $set$?
  2734. \item[$\LP\code{set->list}\,set\RP$] converts the set to a list.
  2735. \end{description}
  2736. \end{tcolorbox}
  2737. \end{wrapfigure}
  2738. The live locations can be computed by traversing the instruction
  2739. sequence back to front (i.e., backwards in execution order). Let
  2740. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2741. $L_{\mathsf{after}}(k)$ for the set of live locations after
  2742. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2743. locations before instruction $I_k$. The live locations after an
  2744. instruction are always the same as the live locations before the next
  2745. instruction. \index{live-after} \index{live-before}
  2746. \begin{equation} \label{eq:live-after-before-next}
  2747. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2748. \end{equation}
  2749. To start things off, there are no live locations after the last
  2750. instruction, so
  2751. \begin{equation}\label{eq:live-last-empty}
  2752. L_{\mathsf{after}}(n) = \emptyset
  2753. \end{equation}
  2754. We then apply the following rule repeatedly, traversing the
  2755. instruction sequence back to front.
  2756. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2757. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2758. \end{equation}
  2759. where $W(k)$ are the locations written to by instruction $I_k$ and
  2760. $R(k)$ are the locations read by instruction $I_k$.
  2761. There is a special case for \code{jmp} instructions. The locations
  2762. that are live before a \code{jmp} should be the locations in
  2763. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  2764. maintaining an alist named \code{label->live} that maps each label to
  2765. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  2766. now the only \code{jmp} in a \LangXVar{} program is the one at the
  2767. end, to the conclusion. (For example, see Figure~\ref{fig:reg-eg}.)
  2768. The conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should
  2769. map \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  2770. Let us walk through the above example, applying these formulas
  2771. starting with the instruction on line 5. We collect the answers in
  2772. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  2773. \code{addq b, c} instruction is $\emptyset$ because it is the last
  2774. instruction (formula~\ref{eq:live-last-empty}). The
  2775. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  2776. because it reads from variables \code{b} and \code{c}
  2777. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  2778. \[
  2779. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  2780. \]
  2781. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2782. the live-before set from line 5 to be the live-after set for this
  2783. instruction (formula~\ref{eq:live-after-before-next}).
  2784. \[
  2785. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  2786. \]
  2787. This move instruction writes to \code{b} and does not read from any
  2788. variables, so we have the following live-before set
  2789. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2790. \[
  2791. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  2792. \]
  2793. The live-before for instruction \code{movq a, c}
  2794. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  2795. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2796. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  2797. variable that is not live and does not read from a variable.
  2798. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2799. because it writes to variable \code{a}.
  2800. \begin{figure}[tbp]
  2801. \begin{minipage}{0.45\textwidth}
  2802. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2803. movq $5, a
  2804. movq $30, b
  2805. movq a, c
  2806. movq $10, b
  2807. addq b, c
  2808. \end{lstlisting}
  2809. \end{minipage}
  2810. \vrule\hspace{10pt}
  2811. \begin{minipage}{0.45\textwidth}
  2812. \begin{align*}
  2813. L_{\mathsf{before}}(1)= \emptyset,
  2814. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  2815. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  2816. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  2817. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  2818. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  2819. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  2820. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  2821. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  2822. L_{\mathsf{after}}(5)= \emptyset
  2823. \end{align*}
  2824. \end{minipage}
  2825. \caption{Example output of liveness analysis on a short example.}
  2826. \label{fig:liveness-example-0}
  2827. \end{figure}
  2828. \begin{exercise}\normalfont
  2829. Perform liveness analysis on the running example in
  2830. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  2831. sets for each instruction. Compare your answers to the solution
  2832. shown in Figure~\ref{fig:live-eg}.
  2833. \end{exercise}
  2834. \begin{figure}[tp]
  2835. \hspace{20pt}
  2836. \begin{minipage}{0.45\textwidth}
  2837. \begin{lstlisting}
  2838. |$\{\ttm{rsp}\}$|
  2839. movq $1, v
  2840. |$\{\ttm{v},\ttm{rsp}\}$|
  2841. movq $42, w
  2842. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  2843. movq v, x
  2844. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  2845. addq $7, x
  2846. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  2847. movq x, y
  2848. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  2849. movq x, z
  2850. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  2851. addq w, z
  2852. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  2853. movq y, t
  2854. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  2855. negq t
  2856. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  2857. movq z, %rax
  2858. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  2859. addq t, %rax
  2860. |$\{\ttm{rax},\ttm{rsp}\}$|
  2861. jmp conclusion
  2862. \end{lstlisting}
  2863. \end{minipage}
  2864. \caption{The running example annotated with live-after sets.}
  2865. \label{fig:live-eg}
  2866. \end{figure}
  2867. \begin{exercise}\normalfont
  2868. Implement the \code{uncover-live} pass. Store the sequence of
  2869. live-after sets in the $\itm{info}$ field of the \code{Block}
  2870. structure.
  2871. %
  2872. We recommend creating an auxiliary function that takes a list of
  2873. instructions and an initial live-after set (typically empty) and
  2874. returns the list of live-after sets.
  2875. %
  2876. We also recommend creating auxiliary functions to 1) compute the set
  2877. of locations that appear in an \Arg{}, 2) compute the locations read
  2878. by an instruction (the $R$ function), and 3) the locations written by
  2879. an instruction (the $W$ function). The \code{callq} instruction should
  2880. include all of the caller-saved registers in its write-set $W$ because
  2881. the calling convention says that those registers may be written to
  2882. during the function call. Likewise, the \code{callq} instruction
  2883. should include the appropriate argument-passing registers in its
  2884. read-set $R$, depending on the arity of the function being
  2885. called. (This is why the abstract syntax for \code{callq} includes the
  2886. arity.)
  2887. \end{exercise}
  2888. \clearpage
  2889. \section{Build the Interference Graph}
  2890. \label{sec:build-interference}
  2891. \begin{wrapfigure}[25]{r}[1.0in]{0.6\textwidth}
  2892. \small
  2893. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  2894. A \emph{graph} is a collection of vertices and edges where each
  2895. edge connects two vertices. A graph is \emph{directed} if each
  2896. edge points from a source to a target. Otherwise the graph is
  2897. \emph{undirected}.
  2898. \index{graph}\index{directed graph}\index{undirected graph}
  2899. \begin{description}
  2900. %% We currently don't use directed graphs. We instead use
  2901. %% directed multi-graphs. -Jeremy
  2902. %% \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  2903. %% directed graph from a list of edges. Each edge is a list
  2904. %% containing the source and target vertex.
  2905. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  2906. undirected graph from a list of edges. Each edge is represented by
  2907. a list containing two vertices.
  2908. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  2909. inserts a vertex into the graph.
  2910. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  2911. inserts an edge between the two vertices into the graph.
  2912. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  2913. returns a sequence of all the neighbors of the given vertex.
  2914. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  2915. returns a sequence of all the vertices in the graph.
  2916. \end{description}
  2917. \end{tcolorbox}
  2918. \end{wrapfigure}
  2919. Based on the liveness analysis, we know where each location is live.
  2920. However, during register allocation, we need to answer questions of
  2921. the specific form: are locations $u$ and $v$ live at the same time?
  2922. (And therefore cannot be assigned to the same register.) To make this
  2923. question more efficient to answer, we create an explicit data
  2924. structure, an \emph{interference graph}\index{interference graph}. An
  2925. interference graph is an undirected graph that has an edge between two
  2926. locations if they are live at the same time, that is, if they
  2927. interfere with each other.
  2928. An obvious way to compute the interference graph is to look at the set
  2929. of live locations between each instruction and the next and add an edge to the graph
  2930. for every pair of variables in the same set. This approach is less
  2931. than ideal for two reasons. First, it can be expensive because it
  2932. takes $O(n^2)$ time to consider at every pair in a set of $n$ live
  2933. locations. Second, in the special case where two locations hold the
  2934. same value (because one was assigned to the other), they can be live
  2935. at the same time without interfering with each other.
  2936. A better way to compute the interference graph is to focus on
  2937. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  2938. must not overwrite something in a live location. So for each
  2939. instruction, we create an edge between the locations being written to
  2940. and the live locations. (Except that one should not create self
  2941. edges.) Note that for the \key{callq} instruction, we consider all of
  2942. the caller-saved registers as being written to, so an edge is added
  2943. between every live variable and every caller-saved register. For
  2944. \key{movq}, we deal with the above-mentioned special case by not
  2945. adding an edge between a live variable $v$ and the destination if $v$
  2946. matches the source. So we have the following two rules.
  2947. \begin{enumerate}
  2948. \item If instruction $I_k$ is a move such as \key{movq} $s$\key{,}
  2949. $d$, then add the edge $(d,v)$ for every $v \in
  2950. L_{\mathsf{after}}(k)$ unless $v = d$ or $v = s$.
  2951. \item For any other instruction $I_k$, for every $d \in W(k)$
  2952. add an edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  2953. %% \item If instruction $I_k$ is an arithmetic instruction such as
  2954. %% \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2955. %% L_{\mathsf{after}}(k)$ unless $v = d$.
  2956. %% \item If instruction $I_k$ is of the form \key{callq}
  2957. %% $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2958. %% register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2959. \end{enumerate}
  2960. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  2961. the above rules to each instruction. We highlight a few of the
  2962. instructions. The first instruction is \lstinline{movq $1, v} and the
  2963. live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies, so \code{v}
  2964. interferes with \code{rsp}.
  2965. %
  2966. The fourth instruction is \lstinline{addq $7, x} and the live-after
  2967. set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so $\ttm{x}$
  2968. interferes with \ttm{w} and \ttm{rsp}.
  2969. %
  2970. The next instruction is \lstinline{movq x, y} and the live-after set
  2971. is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1 applies, so \ttm{y}
  2972. interferes with \ttm{w} and \ttm{rsp} but not \ttm{x} because \ttm{x}
  2973. is the source of the move and therefore \ttm{x} and \ttm{y} hold the
  2974. same value. Figure~\ref{fig:interference-results} lists the
  2975. interference results for all of the instructions and the resulting
  2976. interference graph is shown in Figure~\ref{fig:interfere}.
  2977. \begin{figure}[tbp]
  2978. \begin{quote}
  2979. \begin{tabular}{ll}
  2980. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  2981. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  2982. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  2983. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  2984. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  2985. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  2986. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  2987. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  2988. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  2989. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  2990. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  2991. \lstinline!jmp conclusion!& no interference.
  2992. \end{tabular}
  2993. \end{quote}
  2994. \caption{Interference results for the running example.}
  2995. \label{fig:interference-results}
  2996. \end{figure}
  2997. \begin{figure}[tbp]
  2998. \large
  2999. \[
  3000. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3001. \node (rax) at (0,0) {$\ttm{rax}$};
  3002. \node (rsp) at (9,2) {$\ttm{rsp}$};
  3003. \node (t1) at (0,2) {$\ttm{t}$};
  3004. \node (z) at (3,2) {$\ttm{z}$};
  3005. \node (x) at (6,2) {$\ttm{x}$};
  3006. \node (y) at (3,0) {$\ttm{y}$};
  3007. \node (w) at (6,0) {$\ttm{w}$};
  3008. \node (v) at (9,0) {$\ttm{v}$};
  3009. \draw (t1) to (rax);
  3010. \draw (t1) to (z);
  3011. \draw (z) to (y);
  3012. \draw (z) to (w);
  3013. \draw (x) to (w);
  3014. \draw (y) to (w);
  3015. \draw (v) to (w);
  3016. \draw (v) to (rsp);
  3017. \draw (w) to (rsp);
  3018. \draw (x) to (rsp);
  3019. \draw (y) to (rsp);
  3020. \path[-.,bend left=15] (z) edge node {} (rsp);
  3021. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3022. \draw (rax) to (rsp);
  3023. \end{tikzpicture}
  3024. \]
  3025. \caption{The interference graph of the example program.}
  3026. \label{fig:interfere}
  3027. \end{figure}
  3028. %% Our next concern is to choose a data structure for representing the
  3029. %% interference graph. There are many choices for how to represent a
  3030. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  3031. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  3032. %% data structure is to study the algorithm that uses the data structure,
  3033. %% determine what operations need to be performed, and then choose the
  3034. %% data structure that provide the most efficient implementations of
  3035. %% those operations. Often times the choice of data structure can have an
  3036. %% effect on the time complexity of the algorithm, as it does here. If
  3037. %% you skim the next section, you will see that the register allocation
  3038. %% algorithm needs to ask the graph for all of its vertices and, given a
  3039. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  3040. %% correct choice of graph representation is that of an adjacency
  3041. %% list. There are helper functions in \code{utilities.rkt} for
  3042. %% representing graphs using the adjacency list representation:
  3043. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  3044. %% (Appendix~\ref{appendix:utilities}).
  3045. %% %
  3046. %% \margincomment{\footnotesize To do: change to use the
  3047. %% Racket graph library. \\ --Jeremy}
  3048. %% %
  3049. %% In particular, those functions use a hash table to map each vertex to
  3050. %% the set of adjacent vertices, and the sets are represented using
  3051. %% Racket's \key{set}, which is also a hash table.
  3052. \begin{exercise}\normalfont
  3053. Implement the compiler pass named \code{build-interference} according
  3054. to the algorithm suggested above. We recommend using the \code{graph}
  3055. package to create and inspect the interference graph. The output
  3056. graph of this pass should be stored in the $\itm{info}$ field of the
  3057. program, under the key \code{conflicts}.
  3058. \end{exercise}
  3059. \section{Graph Coloring via Sudoku}
  3060. \label{sec:graph-coloring}
  3061. \index{graph coloring}
  3062. \index{Sudoku}
  3063. \index{color}
  3064. We come to the main event, mapping variables to registers and stack
  3065. locations. Variables that interfere with each other must be mapped to
  3066. different locations. In terms of the interference graph, this means
  3067. that adjacent vertices must be mapped to different locations. If we
  3068. think of locations as colors, the register allocation problem becomes
  3069. the graph coloring problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  3070. The reader may be more familiar with the graph coloring problem than he
  3071. or she realizes; the popular game of Sudoku is an instance of the
  3072. graph coloring problem. The following describes how to build a graph
  3073. out of an initial Sudoku board.
  3074. \begin{itemize}
  3075. \item There is one vertex in the graph for each Sudoku square.
  3076. \item There is an edge between two vertices if the corresponding squares
  3077. are in the same row, in the same column, or if the squares are in
  3078. the same $3\times 3$ region.
  3079. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  3080. \item Based on the initial assignment of numbers to squares in the
  3081. Sudoku board, assign the corresponding colors to the corresponding
  3082. vertices in the graph.
  3083. \end{itemize}
  3084. If you can color the remaining vertices in the graph with the nine
  3085. colors, then you have also solved the corresponding game of Sudoku.
  3086. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  3087. the corresponding graph with colored vertices. We map the Sudoku
  3088. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  3089. sampling of the vertices (the colored ones) because showing edges for
  3090. all of the vertices would make the graph unreadable.
  3091. \begin{figure}[tbp]
  3092. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  3093. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  3094. \caption{A Sudoku game board and the corresponding colored graph.}
  3095. \label{fig:sudoku-graph}
  3096. \end{figure}
  3097. It turns out that some techniques for playing Sudoku correspond to
  3098. heuristics used in graph coloring algorithms. For example, one of the
  3099. basic techniques for Sudoku is called Pencil Marks. The idea is to use
  3100. a process of elimination to determine what numbers are no longer
  3101. available for a square and write down those numbers in the square
  3102. (writing very small). For example, if the number $1$ is assigned to a
  3103. square, then write the pencil mark $1$ in all the squares in the same
  3104. row, column, and region.
  3105. %
  3106. The Pencil Marks technique corresponds to the notion of
  3107. \emph{saturation}\index{saturation} due to \cite{Brelaz:1979eu}. The
  3108. saturation of a vertex, in Sudoku terms, is the set of numbers that
  3109. are no longer available. In graph terminology, we have the following
  3110. definition:
  3111. \begin{equation*}
  3112. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  3113. \text{ and } \mathrm{color}(v) = c \}
  3114. \end{equation*}
  3115. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  3116. edge with $u$.
  3117. Using the Pencil Marks technique leads to a simple strategy for
  3118. filling in numbers: if there is a square with only one possible number
  3119. left, then choose that number! But what if there are no squares with
  3120. only one possibility left? One brute-force approach is to try them
  3121. all: choose the first one and if it ultimately leads to a solution,
  3122. great. If not, backtrack and choose the next possibility. One good
  3123. thing about Pencil Marks is that it reduces the degree of branching in
  3124. the search tree. Nevertheless, backtracking can be horribly time
  3125. consuming. One way to reduce the amount of backtracking is to use the
  3126. most-constrained-first heuristic. That is, when choosing a square,
  3127. always choose one with the fewest possibilities left (the vertex with
  3128. the highest saturation). The idea is that choosing highly constrained
  3129. squares earlier rather than later is better because later on there may
  3130. not be any possibilities left in the highly saturated squares.
  3131. However, register allocation is easier than Sudoku because the
  3132. register allocator can map variables to stack locations when the
  3133. registers run out. Thus, it makes sense to replace backtracking with
  3134. greedy search: make the best choice at the time and keep going. We
  3135. still wish to minimize the number of colors needed, so we use the
  3136. most-constrained-first heuristic in the greedy search.
  3137. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  3138. algorithm for register allocation based on saturation and the
  3139. most-constrained-first heuristic. It is roughly equivalent to the
  3140. DSATUR
  3141. algorithm~\citep{Brelaz:1979eu,Gebremedhin:1999fk,Omari:2006uq}. Just
  3142. as in Sudoku, the algorithm represents colors with integers. The
  3143. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  3144. for register allocation. The integers $k$ and larger correspond to
  3145. stack locations. The registers that are not used for register
  3146. allocation, such as \code{rax}, are assigned to negative integers. In
  3147. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  3148. %% One might wonder why we include registers at all in the liveness
  3149. %% analysis and interference graph. For example, we never allocate a
  3150. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  3151. %% leave them out. As we see in Chapter~\ref{ch:Rvec}, when we begin
  3152. %% to use register for passing arguments to functions, it will be
  3153. %% necessary for those registers to appear in the interference graph
  3154. %% because those registers will also be assigned to variables, and we
  3155. %% don't want those two uses to encroach on each other. Regarding
  3156. %% registers such as \code{rax} and \code{rsp} that are not used for
  3157. %% variables, we could omit them from the interference graph but that
  3158. %% would require adding special cases to our algorithm, which would
  3159. %% complicate the logic for little gain.
  3160. \begin{figure}[btp]
  3161. \centering
  3162. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  3163. Algorithm: DSATUR
  3164. Input: a graph |$G$|
  3165. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  3166. |$W \gets \mathrm{vertices}(G)$|
  3167. while |$W \neq \emptyset$| do
  3168. pick a vertex |$u$| from |$W$| with the highest saturation,
  3169. breaking ties randomly
  3170. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  3171. |$\mathrm{color}[u] \gets c$|
  3172. |$W \gets W - \{u\}$|
  3173. \end{lstlisting}
  3174. \caption{The saturation-based greedy graph coloring algorithm.}
  3175. \label{fig:satur-algo}
  3176. \end{figure}
  3177. With the DSATUR algorithm in hand, let us return to the running
  3178. example and consider how to color the interference graph in
  3179. Figure~\ref{fig:interfere}.
  3180. %
  3181. We start by assigning the register nodes to their own color. For
  3182. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  3183. assigned $-2$. The variables are not yet colored, so they are
  3184. annotated with a dash. We then update the saturation for vertices that
  3185. are adjacent to a register, obtaining the following annotated
  3186. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  3187. it interferes with both \code{rax} and \code{rsp}.
  3188. \[
  3189. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3190. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  3191. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  3192. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  3193. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  3194. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3195. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3196. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3197. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3198. \draw (t1) to (rax);
  3199. \draw (t1) to (z);
  3200. \draw (z) to (y);
  3201. \draw (z) to (w);
  3202. \draw (x) to (w);
  3203. \draw (y) to (w);
  3204. \draw (v) to (w);
  3205. \draw (v) to (rsp);
  3206. \draw (w) to (rsp);
  3207. \draw (x) to (rsp);
  3208. \draw (y) to (rsp);
  3209. \path[-.,bend left=15] (z) edge node {} (rsp);
  3210. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3211. \draw (rax) to (rsp);
  3212. \end{tikzpicture}
  3213. \]
  3214. The algorithm says to select a maximally saturated vertex. So we pick
  3215. $\ttm{t}$ and color it with the first available integer, which is
  3216. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  3217. and \ttm{rsp} because they interfere with $\ttm{t}$.
  3218. \[
  3219. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3220. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3221. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  3222. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  3223. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  3224. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3225. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3226. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3227. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3228. \draw (t1) to (rax);
  3229. \draw (t1) to (z);
  3230. \draw (z) to (y);
  3231. \draw (z) to (w);
  3232. \draw (x) to (w);
  3233. \draw (y) to (w);
  3234. \draw (v) to (w);
  3235. \draw (v) to (rsp);
  3236. \draw (w) to (rsp);
  3237. \draw (x) to (rsp);
  3238. \draw (y) to (rsp);
  3239. \path[-.,bend left=15] (z) edge node {} (rsp);
  3240. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3241. \draw (rax) to (rsp);
  3242. \end{tikzpicture}
  3243. \]
  3244. We repeat the process, selecting the next maximally saturated vertex,
  3245. which is \code{z}, and color it with the first available number, which
  3246. is $1$. We add $1$ to the saturation for the neighboring vertices
  3247. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  3248. \[
  3249. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3250. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3251. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3252. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3253. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3254. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3255. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3256. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3257. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3258. \draw (t1) to (rax);
  3259. \draw (t1) to (z);
  3260. \draw (z) to (y);
  3261. \draw (z) to (w);
  3262. \draw (x) to (w);
  3263. \draw (y) to (w);
  3264. \draw (v) to (w);
  3265. \draw (v) to (rsp);
  3266. \draw (w) to (rsp);
  3267. \draw (x) to (rsp);
  3268. \draw (y) to (rsp);
  3269. \path[-.,bend left=15] (z) edge node {} (rsp);
  3270. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3271. \draw (rax) to (rsp);
  3272. \end{tikzpicture}
  3273. \]
  3274. The most saturated vertices are now \code{w} and \code{y}. We color
  3275. \code{w} with the first available color, which is $0$.
  3276. \[
  3277. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3278. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3279. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3280. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3281. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3282. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3283. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  3284. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  3285. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  3286. \draw (t1) to (rax);
  3287. \draw (t1) to (z);
  3288. \draw (z) to (y);
  3289. \draw (z) to (w);
  3290. \draw (x) to (w);
  3291. \draw (y) to (w);
  3292. \draw (v) to (w);
  3293. \draw (v) to (rsp);
  3294. \draw (w) to (rsp);
  3295. \draw (x) to (rsp);
  3296. \draw (y) to (rsp);
  3297. \path[-.,bend left=15] (z) edge node {} (rsp);
  3298. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3299. \draw (rax) to (rsp);
  3300. \end{tikzpicture}
  3301. \]
  3302. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  3303. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  3304. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  3305. and \code{z}, whose colors are $0$ and $1$ respectively.
  3306. \[
  3307. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3308. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3309. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3310. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3311. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3312. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3313. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3314. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3315. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  3316. \draw (t1) to (rax);
  3317. \draw (t1) to (z);
  3318. \draw (z) to (y);
  3319. \draw (z) to (w);
  3320. \draw (x) to (w);
  3321. \draw (y) to (w);
  3322. \draw (v) to (w);
  3323. \draw (v) to (rsp);
  3324. \draw (w) to (rsp);
  3325. \draw (x) to (rsp);
  3326. \draw (y) to (rsp);
  3327. \path[-.,bend left=15] (z) edge node {} (rsp);
  3328. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3329. \draw (rax) to (rsp);
  3330. \end{tikzpicture}
  3331. \]
  3332. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  3333. \[
  3334. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3335. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3336. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3337. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3338. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3339. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3340. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3341. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3342. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3343. \draw (t1) to (rax);
  3344. \draw (t1) to (z);
  3345. \draw (z) to (y);
  3346. \draw (z) to (w);
  3347. \draw (x) to (w);
  3348. \draw (y) to (w);
  3349. \draw (v) to (w);
  3350. \draw (v) to (rsp);
  3351. \draw (w) to (rsp);
  3352. \draw (x) to (rsp);
  3353. \draw (y) to (rsp);
  3354. \path[-.,bend left=15] (z) edge node {} (rsp);
  3355. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3356. \draw (rax) to (rsp);
  3357. \end{tikzpicture}
  3358. \]
  3359. In the last step of the algorithm, we color \code{x} with $1$.
  3360. \[
  3361. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3362. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3363. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3364. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3365. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3366. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  3367. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3368. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3369. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3370. \draw (t1) to (rax);
  3371. \draw (t1) to (z);
  3372. \draw (z) to (y);
  3373. \draw (z) to (w);
  3374. \draw (x) to (w);
  3375. \draw (y) to (w);
  3376. \draw (v) to (w);
  3377. \draw (v) to (rsp);
  3378. \draw (w) to (rsp);
  3379. \draw (x) to (rsp);
  3380. \draw (y) to (rsp);
  3381. \path[-.,bend left=15] (z) edge node {} (rsp);
  3382. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3383. \draw (rax) to (rsp);
  3384. \end{tikzpicture}
  3385. \]
  3386. \begin{wrapfigure}[25]{r}[1.0in]{0.6\textwidth}
  3387. \small
  3388. \begin{tcolorbox}[title=Priority Queue]
  3389. A \emph{priority queue} is a collection of items in which the
  3390. removal of items is governed by priority. In a ``min'' queue,
  3391. lower priority items are removed first. An implementation is in
  3392. \code{priority\_queue.rkt} of the support code. \index{priority
  3393. queue} \index{minimum priority queue}
  3394. \begin{description}
  3395. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  3396. priority queue that uses the $\itm{cmp}$ predicate to determine
  3397. whether its first argument has lower or equal priority to its
  3398. second argument.
  3399. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  3400. items in the queue.
  3401. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  3402. the item into the queue and returns a handle for the item in the
  3403. queue.
  3404. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  3405. the lowest priority.
  3406. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  3407. notifies the queue that the priority has decreased for the item
  3408. associated with the given handle.
  3409. \end{description}
  3410. \end{tcolorbox}
  3411. \end{wrapfigure}
  3412. We recommend creating an auxiliary function named \code{color-graph}
  3413. that takes an interference graph and a list of all the variables in
  3414. the program. This function should return a mapping of variables to
  3415. their colors (represented as natural numbers). By creating this helper
  3416. function, you will be able to reuse it in Chapter~\ref{ch:Rfun}
  3417. when we add support for functions.
  3418. To prioritize the processing of highly saturated nodes inside the
  3419. \code{color-graph} function, we recommend using the priority queue
  3420. data structure (see the side bar on the right). In addition, you will
  3421. need to maintain a mapping from variables to their ``handles'' in the
  3422. priority queue so that you can notify the priority queue when their
  3423. saturation changes.
  3424. With the coloring complete, we finalize the assignment of variables to
  3425. registers and stack locations. We map the first $k$ colors to the $k$
  3426. registers and the rest of the colors to stack locations. Suppose for
  3427. the moment that we have just one register to use for register
  3428. allocation, \key{rcx}. Then we have the following map from colors to
  3429. locations.
  3430. \[
  3431. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  3432. \]
  3433. Composing this mapping with the coloring, we arrive at the following
  3434. assignment of variables to locations.
  3435. \begin{gather*}
  3436. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  3437. \ttm{w} \mapsto \key{\%rcx}, \,
  3438. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  3439. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  3440. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  3441. \ttm{t} \mapsto \key{\%rcx} \}
  3442. \end{gather*}
  3443. Adapt the code from the \code{assign-homes} pass
  3444. (Section~\ref{sec:assign-Rvar}) to replace the variables with their
  3445. assigned location. Applying the above assignment to our running
  3446. example, on the left, yields the program on the right.
  3447. % why frame size of 32? -JGS
  3448. \begin{center}
  3449. \begin{minipage}{0.3\textwidth}
  3450. \begin{lstlisting}
  3451. movq $1, v
  3452. movq $42, w
  3453. movq v, x
  3454. addq $7, x
  3455. movq x, y
  3456. movq x, z
  3457. addq w, z
  3458. movq y, t
  3459. negq t
  3460. movq z, %rax
  3461. addq t, %rax
  3462. jmp conclusion
  3463. \end{lstlisting}
  3464. \end{minipage}
  3465. $\Rightarrow\qquad$
  3466. \begin{minipage}{0.45\textwidth}
  3467. \begin{lstlisting}
  3468. movq $1, -8(%rbp)
  3469. movq $42, %rcx
  3470. movq -8(%rbp), -8(%rbp)
  3471. addq $7, -8(%rbp)
  3472. movq -8(%rbp), -16(%rbp)
  3473. movq -8(%rbp), -8(%rbp)
  3474. addq %rcx, -8(%rbp)
  3475. movq -16(%rbp), %rcx
  3476. negq %rcx
  3477. movq -8(%rbp), %rax
  3478. addq %rcx, %rax
  3479. jmp conclusion
  3480. \end{lstlisting}
  3481. \end{minipage}
  3482. \end{center}
  3483. \begin{exercise}\normalfont
  3484. %
  3485. Implement the compiler pass \code{allocate-registers}.
  3486. %
  3487. Create five programs that exercise all of the register allocation
  3488. algorithm, including spilling variables to the stack.
  3489. %
  3490. Replace \code{assign-homes} in the list of \code{passes} in the
  3491. \code{run-tests.rkt} script with the three new passes:
  3492. \code{uncover-live}, \code{build-interference}, and
  3493. \code{allocate-registers}.
  3494. %
  3495. Temporarily remove the \code{print-x86} pass from the list of passes
  3496. and the call to \code{compiler-tests}.
  3497. %
  3498. Run the script to test the register allocator.
  3499. \end{exercise}
  3500. \section{Patch Instructions}
  3501. \label{sec:patch-instructions}
  3502. The remaining step in the compilation to x86 is to ensure that the
  3503. instructions have at most one argument that is a memory access.
  3504. In the running example, the instruction \code{movq -8(\%rbp), -16(\%rbp)}
  3505. is problematic. The fix is to first move \code{-8(\%rbp)}
  3506. into \code{rax} and then move \code{rax} into \code{-16(\%rbp)}.
  3507. %
  3508. The two moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  3509. problematic, but they can be fixed by simply deleting them. In
  3510. general, we recommend deleting all the trivial moves whose source and
  3511. destination are the same location.
  3512. %
  3513. The following is the output of \code{patch-instructions} on the
  3514. running example.
  3515. \begin{center}
  3516. \begin{minipage}{0.4\textwidth}
  3517. \begin{lstlisting}
  3518. movq $1, -8(%rbp)
  3519. movq $42, %rcx
  3520. movq -8(%rbp), -8(%rbp)
  3521. addq $7, -8(%rbp)
  3522. movq -8(%rbp), -16(%rbp)
  3523. movq -8(%rbp), -8(%rbp)
  3524. addq %rcx, -8(%rbp)
  3525. movq -16(%rbp), %rcx
  3526. negq %rcx
  3527. movq -8(%rbp), %rax
  3528. addq %rcx, %rax
  3529. jmp conclusion
  3530. \end{lstlisting}
  3531. \end{minipage}
  3532. $\Rightarrow\qquad$
  3533. \begin{minipage}{0.45\textwidth}
  3534. \begin{lstlisting}
  3535. movq $1, -8(%rbp)
  3536. movq $42, %rcx
  3537. addq $7, -8(%rbp)
  3538. movq -8(%rbp), %rax
  3539. movq %rax, -16(%rbp)
  3540. addq %rcx, -8(%rbp)
  3541. movq -16(%rbp), %rcx
  3542. negq %rcx
  3543. movq -8(%rbp), %rax
  3544. addq %rcx, %rax
  3545. jmp conclusion
  3546. \end{lstlisting}
  3547. \end{minipage}
  3548. \end{center}
  3549. \begin{exercise}\normalfont
  3550. %
  3551. Implement the \code{patch-instructions} compiler pass.
  3552. %
  3553. Insert it after \code{allocate-registers} in the list of \code{passes}
  3554. in the \code{run-tests.rkt} script.
  3555. %
  3556. Run the script to test the \code{patch-instructions} pass.
  3557. \end{exercise}
  3558. \section{Print x86}
  3559. \label{sec:print-x86-reg-alloc}
  3560. \index{calling conventions}
  3561. \index{prelude}\index{conclusion}
  3562. Recall that the \code{print-x86} pass generates the prelude and
  3563. conclusion instructions to satisfy the x86 calling conventions
  3564. (Section~\ref{sec:calling-conventions}). With the addition of the
  3565. register allocator, the callee-saved registers used by the register
  3566. allocator must be saved in the prelude and restored in the conclusion.
  3567. In the \code{allocate-registers} pass, add an entry to the \itm{info}
  3568. of \code{X86Program} named \code{used-callee} that stores the set of
  3569. callee-saved registers that were assigned to variables. The
  3570. \code{print-x86} pass can then access this information to decide which
  3571. callee-saved registers need to be saved and restored.
  3572. %
  3573. When calculating the size of the frame to adjust the \code{rsp} in the
  3574. prelude, make sure to take into account the space used for saving the
  3575. callee-saved registers. Also, don't forget that the frame needs to be
  3576. a multiple of 16 bytes!
  3577. An overview of all of the passes involved in register allocation is
  3578. shown in Figure~\ref{fig:reg-alloc-passes}.
  3579. \begin{figure}[tbp]
  3580. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3581. \node (Rvar) at (0,2) {\large \LangVar{}};
  3582. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  3583. \node (Rvar-3) at (6,2) {\large \LangVar{}};
  3584. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  3585. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  3586. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  3587. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  3588. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  3589. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  3590. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  3591. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  3592. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvar-3);
  3593. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate-control} (Cvar-1);
  3594. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  3595. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  3596. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  3597. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  3598. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  3599. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  3600. \end{tikzpicture}
  3601. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  3602. \label{fig:reg-alloc-passes}
  3603. \end{figure}
  3604. \begin{exercise}\normalfont
  3605. Update the \code{print-x86} pass as described in this section.
  3606. %
  3607. In the \code{run-tests.rkt} script, reinstate \code{print-x86} in the
  3608. list of passes and the call to \code{compiler-tests}.
  3609. %
  3610. Run the script to test the complete compiler for \LangVar{} that
  3611. performs register allocation.
  3612. \end{exercise}
  3613. \section{Challenge: Move Biasing}
  3614. \label{sec:move-biasing}
  3615. \index{move biasing}
  3616. This section describes an enhancement to the register allocator for
  3617. students looking for an extra challenge or who have a deeper interest
  3618. in register allocation.
  3619. To motivate the need for move biasing we return to the running example
  3620. but this time use all of the general purpose registers. So we have
  3621. the following mapping of color numbers to registers.
  3622. \[
  3623. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi} \}
  3624. \]
  3625. Using the same assignment of variables to color numbers that was
  3626. produced by the register allocator described in the last section, we
  3627. get the following program.
  3628. \begin{center}
  3629. \begin{minipage}{0.3\textwidth}
  3630. \begin{lstlisting}
  3631. movq $1, v
  3632. movq $42, w
  3633. movq v, x
  3634. addq $7, x
  3635. movq x, y
  3636. movq x, z
  3637. addq w, z
  3638. movq y, t
  3639. negq t
  3640. movq z, %rax
  3641. addq t, %rax
  3642. jmp conclusion
  3643. \end{lstlisting}
  3644. \end{minipage}
  3645. $\Rightarrow\qquad$
  3646. \begin{minipage}{0.45\textwidth}
  3647. \begin{lstlisting}
  3648. movq $1, %rdx
  3649. movq $42, %rcx
  3650. movq %rdx, %rdx
  3651. addq $7, %rdx
  3652. movq %rdx, %rsi
  3653. movq %rdx, %rdx
  3654. addq %rcx, %rdx
  3655. movq %rsi, %rcx
  3656. negq %rcx
  3657. movq %rdx, %rax
  3658. addq %rcx, %rax
  3659. jmp conclusion
  3660. \end{lstlisting}
  3661. \end{minipage}
  3662. \end{center}
  3663. In the above output code there are two \key{movq} instructions that
  3664. can be removed because their source and target are the same. However,
  3665. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  3666. register, we could instead remove three \key{movq} instructions. We
  3667. can accomplish this by taking into account which variables appear in
  3668. \key{movq} instructions with which other variables.
  3669. We say that two variables $p$ and $q$ are \emph{move
  3670. related}\index{move related} if they participate together in a
  3671. \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  3672. \key{movq} $q$\key{,} $p$. When the register allocator chooses a color
  3673. for a variable, it should prefer a color that has already been used
  3674. for a move-related variable (assuming that they do not interfere). Of
  3675. course, this preference should not override the preference for
  3676. registers over stack locations. This preference should be used as a
  3677. tie breaker when choosing between registers or when choosing between
  3678. stack locations.
  3679. We recommend representing the move relationships in a graph, similar
  3680. to how we represented interference. The following is the \emph{move
  3681. graph} for our running example.
  3682. \[
  3683. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3684. \node (rax) at (0,0) {$\ttm{rax}$};
  3685. \node (rsp) at (9,2) {$\ttm{rsp}$};
  3686. \node (t) at (0,2) {$\ttm{t}$};
  3687. \node (z) at (3,2) {$\ttm{z}$};
  3688. \node (x) at (6,2) {$\ttm{x}$};
  3689. \node (y) at (3,0) {$\ttm{y}$};
  3690. \node (w) at (6,0) {$\ttm{w}$};
  3691. \node (v) at (9,0) {$\ttm{v}$};
  3692. \draw (v) to (x);
  3693. \draw (x) to (y);
  3694. \draw (x) to (z);
  3695. \draw (y) to (t);
  3696. \end{tikzpicture}
  3697. \]
  3698. Now we replay the graph coloring, pausing to see the coloring of
  3699. \code{y}. Recall the following configuration. The most saturated vertices
  3700. were \code{w} and \code{y}.
  3701. \[
  3702. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3703. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3704. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3705. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3706. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3707. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3708. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3709. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3710. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  3711. \draw (t1) to (rax);
  3712. \draw (t1) to (z);
  3713. \draw (z) to (y);
  3714. \draw (z) to (w);
  3715. \draw (x) to (w);
  3716. \draw (y) to (w);
  3717. \draw (v) to (w);
  3718. \draw (v) to (rsp);
  3719. \draw (w) to (rsp);
  3720. \draw (x) to (rsp);
  3721. \draw (y) to (rsp);
  3722. \path[-.,bend left=15] (z) edge node {} (rsp);
  3723. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3724. \draw (rax) to (rsp);
  3725. \end{tikzpicture}
  3726. \]
  3727. %
  3728. Last time we chose to color \code{w} with $0$. But this time we see
  3729. that \code{w} is not move related to any vertex, but \code{y} is move
  3730. related to \code{t}. So we choose to color \code{y} the same color as
  3731. \code{t}, $0$.
  3732. \[
  3733. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3734. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3735. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3736. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3737. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3738. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3739. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  3740. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  3741. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  3742. \draw (t1) to (rax);
  3743. \draw (t1) to (z);
  3744. \draw (z) to (y);
  3745. \draw (z) to (w);
  3746. \draw (x) to (w);
  3747. \draw (y) to (w);
  3748. \draw (v) to (w);
  3749. \draw (v) to (rsp);
  3750. \draw (w) to (rsp);
  3751. \draw (x) to (rsp);
  3752. \draw (y) to (rsp);
  3753. \path[-.,bend left=15] (z) edge node {} (rsp);
  3754. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3755. \draw (rax) to (rsp);
  3756. \end{tikzpicture}
  3757. \]
  3758. Now \code{w} is the most saturated, so we color it $2$.
  3759. \[
  3760. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3761. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3762. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3763. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3764. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3765. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  3766. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  3767. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  3768. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  3769. \draw (t1) to (rax);
  3770. \draw (t1) to (z);
  3771. \draw (z) to (y);
  3772. \draw (z) to (w);
  3773. \draw (x) to (w);
  3774. \draw (y) to (w);
  3775. \draw (v) to (w);
  3776. \draw (v) to (rsp);
  3777. \draw (w) to (rsp);
  3778. \draw (x) to (rsp);
  3779. \draw (y) to (rsp);
  3780. \path[-.,bend left=15] (z) edge node {} (rsp);
  3781. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3782. \draw (rax) to (rsp);
  3783. \end{tikzpicture}
  3784. \]
  3785. At this point, vertices \code{x} and \code{v} are most saturated, but
  3786. \code{x} is move related to \code{y} and \code{z}, so we color
  3787. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  3788. \[
  3789. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3790. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3791. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3792. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3793. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3794. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  3795. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  3796. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  3797. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  3798. \draw (t1) to (rax);
  3799. \draw (t) to (z);
  3800. \draw (z) to (y);
  3801. \draw (z) to (w);
  3802. \draw (x) to (w);
  3803. \draw (y) to (w);
  3804. \draw (v) to (w);
  3805. \draw (v) to (rsp);
  3806. \draw (w) to (rsp);
  3807. \draw (x) to (rsp);
  3808. \draw (y) to (rsp);
  3809. \path[-.,bend left=15] (z) edge node {} (rsp);
  3810. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3811. \draw (rax) to (rsp);
  3812. \end{tikzpicture}
  3813. \]
  3814. So we have the following assignment of variables to registers.
  3815. \begin{gather*}
  3816. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  3817. \ttm{w} \mapsto \key{\%rsi}, \,
  3818. \ttm{x} \mapsto \key{\%rcx}, \,
  3819. \ttm{y} \mapsto \key{\%rcx}, \,
  3820. \ttm{z} \mapsto \key{\%rdx}, \,
  3821. \ttm{t} \mapsto \key{\%rcx} \}
  3822. \end{gather*}
  3823. We apply this register assignment to the running example, on the left,
  3824. to obtain the code in the middle. The \code{patch-instructions} then
  3825. removes the three trivial moves to obtain the code on the right.
  3826. \begin{minipage}{0.25\textwidth}
  3827. \begin{lstlisting}
  3828. movq $1, v
  3829. movq $42, w
  3830. movq v, x
  3831. addq $7, x
  3832. movq x, y
  3833. movq x, z
  3834. addq w, z
  3835. movq y, t
  3836. negq t
  3837. movq z, %rax
  3838. addq t, %rax
  3839. jmp conclusion
  3840. \end{lstlisting}
  3841. \end{minipage}
  3842. $\Rightarrow\qquad$
  3843. \begin{minipage}{0.25\textwidth}
  3844. \begin{lstlisting}
  3845. movq $1, %rcx
  3846. movq $42, %rsi
  3847. movq %rcx, %rcx
  3848. addq $7, %rcx
  3849. movq %rcx, %rcx
  3850. movq %rcx, %rdx
  3851. addq %rsi, %rdx
  3852. movq %rcx, %rcx
  3853. negq %rcx
  3854. movq %rdx, %rax
  3855. addq %rcx, %rax
  3856. jmp conclusion
  3857. \end{lstlisting}
  3858. \end{minipage}
  3859. $\Rightarrow\qquad$
  3860. \begin{minipage}{0.25\textwidth}
  3861. \begin{lstlisting}
  3862. movq $1, %rcx
  3863. movq $42, %rsi
  3864. addq $7, %rcx
  3865. movq %rcx, %rdx
  3866. addq %rsi, %rdx
  3867. negq %rcx
  3868. movq %rdx, %rax
  3869. addq %rcx, %rax
  3870. jmp conclusion
  3871. \end{lstlisting}
  3872. \end{minipage}
  3873. \begin{exercise}\normalfont
  3874. Change your implementation of \code{allocate-registers} to take move
  3875. biasing into account. Create two new tests that include at least one
  3876. opportunity for move biasing and visually inspect the output x86
  3877. programs to make sure that your move biasing is working properly. Make
  3878. sure that your compiler still passes all of the tests.
  3879. \end{exercise}
  3880. \margincomment{\footnotesize To do: another neat challenge would be to do
  3881. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3882. %% \subsection{Output of the Running Example}
  3883. %% \label{sec:reg-alloc-output}
  3884. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  3885. the running example (Figure~\ref{fig:reg-eg}) with register allocation
  3886. and move biasing. To demonstrate both the use of registers and the
  3887. stack, we have limited the register allocator to use just two
  3888. registers: \code{rbx} and \code{rcx}. In the prelude\index{prelude}
  3889. of the \code{main} function, we push \code{rbx} onto the stack because
  3890. it is a callee-saved register and it was assigned to variable by the
  3891. register allocator. We subtract \code{8} from the \code{rsp} at the
  3892. end of the prelude to reserve space for the one spilled variable.
  3893. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  3894. Moving on the the \code{start} block, we see how the registers were
  3895. allocated. Variables \code{v}, \code{x}, and \code{y} were assigned to
  3896. \code{rbx} and variable \code{z} was assigned to \code{rcx}. Variable
  3897. \code{w} was spilled to the stack location \code{-16(\%rbp)}. Recall
  3898. that the prelude saved the callee-save register \code{rbx} onto the
  3899. stack. The spilled variables must be placed lower on the stack than
  3900. the saved callee-save registers, so in this case \code{w} is placed at
  3901. \code{-16(\%rbp)}.
  3902. In the \code{conclusion}\index{conclusion}, we undo the work that was
  3903. done in the prelude. We move the stack pointer up by \code{8} bytes
  3904. (the room for spilled variables), then we pop the old values of
  3905. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  3906. \code{retq} to return control to the operating system.
  3907. \begin{figure}[tbp]
  3908. % var_test_28.rkt
  3909. % (use-minimal-set-of-registers! #t)
  3910. % and only rbx rcx
  3911. % tmp 0 rbx
  3912. % z 1 rcx
  3913. % y 0 rbx
  3914. % w 2 16(%rbp)
  3915. % v 0 rbx
  3916. % x 0 rbx
  3917. \begin{lstlisting}
  3918. start:
  3919. movq $1, %rbx
  3920. movq $42, -16(%rbp)
  3921. addq $7, %rbx
  3922. movq %rbx, %rcx
  3923. addq -16(%rbp), %rcx
  3924. negq %rbx
  3925. movq %rcx, %rax
  3926. addq %rbx, %rax
  3927. jmp conclusion
  3928. .globl main
  3929. main:
  3930. pushq %rbp
  3931. movq %rsp, %rbp
  3932. pushq %rbx
  3933. subq $8, %rsp
  3934. jmp start
  3935. conclusion:
  3936. addq $8, %rsp
  3937. popq %rbx
  3938. popq %rbp
  3939. retq
  3940. \end{lstlisting}
  3941. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  3942. \label{fig:running-example-x86}
  3943. \end{figure}
  3944. % challenge: prioritize variables based on execution frequencies
  3945. % and the number of uses of a variable
  3946. % challenge: enhance the coloring algorithm using Chaitin's
  3947. % approach of prioritizing high-degree variables
  3948. % by removing low-degree variables (coloring them later)
  3949. % from the interference graph
  3950. \section{Further Reading}
  3951. \label{sec:register-allocation-further-reading}
  3952. Early register allocation algorithms were developed for Fortran
  3953. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  3954. of graph coloring began in the late 1970s and early 1980s with the
  3955. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  3956. algorithm is based on the following observation of
  3957. \citet{Kempe:1879aa} from the 1870s. If a graph $G$ has a vertex $v$
  3958. with degree lower than $k$, then $G$ is $k$ colorable if the subgraph
  3959. of $G$ with $v$ removed is also $k$ colorable. Suppose that the
  3960. subgraph is $k$ colorable. At worst the neighbors of $v$ are assigned
  3961. different colors, but since there are less than $k$ of them, there
  3962. will be one or more colors left over to use for coloring $v$ in $G$.
  3963. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  3964. less than $k$ from the graph and recursively colors the rest of the
  3965. graph. Upon returning from the recursion, it colors $v$ with one of
  3966. the available colors and returns. \citet{Chaitin:1982vn} augments
  3967. this algorithm to handle spilling as follows. If there are no vertices
  3968. of degree lower than $k$ then pick a vertex at random, spill it,
  3969. remove it from the graph, and proceed recursively to color the rest of
  3970. the graph.
  3971. Prior to coloring, \citet{Chaitin:1981vl} merge variables that are
  3972. move-related and that don't interfere with each other, a process
  3973. called \emph{coalescing}. While coalescing decreases the number of
  3974. moves, it can make the graph more difficult to
  3975. color. \citet{Briggs:1994kx} propose \emph{conservative coalescing} in
  3976. which two variables are merged only if they have fewer than $k$
  3977. neighbors of high degree. \citet{George:1996aa} observe that
  3978. conservative coalescing is sometimes too conservative and make it more
  3979. aggressive by iterating the coalescing with the removal of low-degree
  3980. vertices.
  3981. %
  3982. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  3983. also propose \emph{biased coloring} in which a variable is assigned to
  3984. the same color as another move-related variable if possible, as
  3985. discussed in Section~\ref{sec:move-biasing}.
  3986. %
  3987. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  3988. performs coalescing, graph coloring, and spill code insertion until
  3989. all variables have been assigned a location.
  3990. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  3991. spills variables that don't have to be: a high-degree variable can be
  3992. colorable if many of its neighbors are assigned the same color.
  3993. \citet{Briggs:1994kx} propose \emph{optimistic coloring}, in which a
  3994. high-degree vertex is not immediately spilled. Instead the decision is
  3995. deferred until after the recursive call, at which point it is apparent
  3996. whether there is actually an available color or not. We observe that
  3997. this algorithm is equivalent to the smallest-last ordering
  3998. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  3999. be registers and the rest to be stack locations.
  4000. %% biased coloring
  4001. Earlier editions of the compiler course at Indiana University
  4002. \citep{Dybvig:2010aa} were based on the algorithm of
  4003. \citet{Briggs:1994kx}.
  4004. The smallest-last ordering algorithm is one of many \emph{greedy}
  4005. coloring algorithms. A greedy coloring algorithm visits all the
  4006. vertices in a particular order and assigns each one the first
  4007. available color. An \emph{offline} greedy algorithm chooses the
  4008. ordering up-front, prior to assigning colors. The algorithm of
  4009. \citet{Chaitin:1981vl} should be considered offline because the vertex
  4010. ordering does not depend on the colors assigned, so the algorithm
  4011. could be split into two phases. Other orderings are possible. For
  4012. example, \citet{Chow:1984ys} order variables according an estimate of
  4013. runtime cost.
  4014. An \emph{online} greedy coloring algorithm uses information about the
  4015. current assignment of colors to influence the order in which the
  4016. remaining vertices are colored. The saturation-based algorithm
  4017. described in this chapter is one such algorithm. We choose to use
  4018. saturation-based coloring is because it is fun to introduce graph
  4019. coloring via Sudoku.
  4020. A register allocator may choose to map each variable to just one
  4021. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  4022. variable to one or more locations. The later can be achieved by
  4023. \emph{live range splitting}, where a variable is replaced by several
  4024. variables that each handle part of its live
  4025. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  4026. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  4027. %% replacement algorithm, bottom-up local
  4028. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  4029. %% Cooper: top-down (priority bassed), bottom-up
  4030. %% top-down
  4031. %% order variables by priority (estimated cost)
  4032. %% caveat: split variables into two groups:
  4033. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  4034. %% color the constrained ones first
  4035. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  4036. %% cite J. Cocke for an algorithm that colors variables
  4037. %% in a high-degree first ordering
  4038. %Register Allocation via Usage Counts, Freiburghouse CACM
  4039. \citet{Palsberg:2007si} observe that many of the interference graphs
  4040. that arise from Java programs in the JoeQ compiler are \emph{chordal},
  4041. that is, every cycle with four or more edges has an edge which is not
  4042. part of the cycle but which connects two vertices on the cycle. Such
  4043. graphs can be optimally colored by the greedy algorithm with a vertex
  4044. ordering determined by maximum cardinality search.
  4045. In situations where compile time is of utmost importance, such as in
  4046. just-in-time compilers, graph coloring algorithms can be too expensive
  4047. and the linear scan of \citet{Poletto:1999uq} may be more appropriate.
  4048. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4049. \chapter{Booleans and Control Flow}
  4050. \label{ch:Rif}
  4051. \index{Boolean}
  4052. \index{control flow}
  4053. \index{conditional expression}
  4054. The \LangInt{} and \LangVar{} languages only have a single kind of
  4055. value, integers. In this chapter we add a second kind of value, the
  4056. Booleans, to create the \LangIf{} language. The Boolean values
  4057. \emph{true} and \emph{false} are written \key{\#t} and \key{\#f}
  4058. respectively in Racket. The \LangIf{} language includes several
  4059. operations that involve Booleans (\key{and}, \key{not}, \key{eq?},
  4060. \key{<}, etc.) and the conditional \key{if} expression. With the
  4061. addition of \key{if}, programs can have non-trivial control flow which
  4062. impacts \code{explicate-control} and liveness analysis. Also, because
  4063. we now have two kinds of values, we need to handle programs that apply
  4064. an operation to the wrong kind of value, such as \code{(not 1)}.
  4065. There are two language design options for such situations. One option
  4066. is to signal an error and the other is to provide a wider
  4067. interpretation of the operation. The Racket language uses a mixture of
  4068. these two options, depending on the operation and the kind of
  4069. value. For example, the result of \code{(not 1)} in Racket is
  4070. \code{\#f} because Racket treats non-zero integers as if they were
  4071. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  4072. error in Racket because \code{car} expects a pair.
  4073. Typed Racket makes similar design choices as Racket, except much of
  4074. the error detection happens at compile time instead of run time. Typed
  4075. Racket accepts and runs \code{(not 1)}, producing \code{\#f}. But in
  4076. the case of \code{(car 1)}, Typed Racket reports a compile-time error
  4077. because Typed Racket expects the type of the argument to be of the
  4078. form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  4079. The \LangIf{} language performs type checking during compilation like
  4080. Typed Racket. In Chapter~\ref{ch:type-dynamic} we study the
  4081. alternative choice, that is, a dynamically typed language like Racket.
  4082. The \LangIf{} language is a subset of Typed Racket; for some
  4083. operations we are more restrictive, for example, rejecting
  4084. \code{(not 1)}.
  4085. This chapter is organized as follows. We begin by defining the syntax
  4086. and interpreter for the \LangIf{} language
  4087. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  4088. checking and build a type checker for \LangIf{}
  4089. (Section~\ref{sec:type-check-Rif}). To compile \LangIf{} we need to
  4090. enlarge the intermediate language \LangCVar{} into \LangCIf{}
  4091. (Section~\ref{sec:Cif}) and \LangXInt{} into \LangXIf{}
  4092. (Section~\ref{sec:x86-if}). The remaining sections of this chapter
  4093. discuss how our compiler passes change to accommodate Booleans and
  4094. conditional control flow. There is one new pass, named \code{shrink},
  4095. that translates some operators into others, thereby reducing the
  4096. number of operators that need to be handled in later passes. The
  4097. largest changes occur in \code{explicate-control}, to translate
  4098. \code{if} expressions into control-flow graphs
  4099. (Section~\ref{sec:explicate-control-Rif}). Regarding register
  4100. allocation, the liveness analysis now has multiple basic blocks to
  4101. process and there is the interesting question of how to handle
  4102. conditional jumps.
  4103. \section{The \LangIf{} Language}
  4104. \label{sec:lang-if}
  4105. The concrete syntax of the \LangIf{} language is defined in
  4106. Figure~\ref{fig:Rif-concrete-syntax} and the abstract syntax is defined
  4107. in Figure~\ref{fig:Rif-syntax}. The \LangIf{} language includes all of
  4108. \LangVar{} (shown in gray), the Boolean literals \code{\#t} and
  4109. \code{\#f}, and the conditional \code{if} expression. We expand the
  4110. operators to include
  4111. \begin{enumerate}
  4112. \item subtraction on integers,
  4113. \item the logical operators \key{and}, \key{or} and \key{not},
  4114. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  4115. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  4116. comparing integers.
  4117. \end{enumerate}
  4118. We reorganize the abstract syntax for the primitive operations in
  4119. Figure~\ref{fig:Rif-syntax}, using only one grammar rule for all of
  4120. them. This means that the grammar no longer checks whether the arity
  4121. of an operators matches the number of arguments. That responsibility
  4122. is moved to the type checker for \LangIf{}, which we introduce in
  4123. Section~\ref{sec:type-check-Rif}.
  4124. \begin{figure}[tp]
  4125. \centering
  4126. \fbox{
  4127. \begin{minipage}{0.96\textwidth}
  4128. \[
  4129. \begin{array}{lcl}
  4130. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  4131. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  4132. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} } \mid \CSUB{\Exp}{\Exp} \\
  4133. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} } \\
  4134. &\mid& \itm{bool}
  4135. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  4136. \mid (\key{not}\;\Exp) \\
  4137. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} \\
  4138. \LangIf{} &::=& \Exp
  4139. \end{array}
  4140. \]
  4141. \end{minipage}
  4142. }
  4143. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  4144. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  4145. \label{fig:Rif-concrete-syntax}
  4146. \end{figure}
  4147. \begin{figure}[tp]
  4148. \centering
  4149. \fbox{
  4150. \begin{minipage}{0.96\textwidth}
  4151. \[
  4152. \begin{array}{lcl}
  4153. \itm{bool} &::=& \code{\#t} \mid \code{\#f} \\
  4154. \itm{cmp} &::= & \code{eq?} \mid \code{<} \mid \code{<=} \mid \code{>} \mid \code{>=} \\
  4155. \itm{op} &::= & \itm{cmp} \mid \code{read} \mid \code{+} \mid \code{-}
  4156. \mid \code{and} \mid \code{or} \mid \code{not} \\
  4157. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  4158. &\mid& \PRIM{\itm{op}}{\Exp\ldots}\\
  4159. &\mid& \BOOL{\itm{bool}} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4160. \LangIf{} &::=& \PROGRAM{\code{'()}}{\Exp}
  4161. \end{array}
  4162. \]
  4163. \end{minipage}
  4164. }
  4165. \caption{The abstract syntax of \LangIf{}.}
  4166. \label{fig:Rif-syntax}
  4167. \end{figure}
  4168. Figure~\ref{fig:interp-Rif} defines the interpreter for \LangIf{},
  4169. which inherits from the interpreter for \LangVar{}
  4170. (Figure~\ref{fig:interp-Rvar}). The literals \code{\#t} and \code{\#f}
  4171. evaluate to the corresponding Boolean values. The conditional
  4172. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  4173. \itm{cnd} and then either evaluates \itm{thn} or \itm{els} depending
  4174. on whether \itm{cnd} produced \code{\#t} or \code{\#f}. The logical
  4175. operations \code{not} and \code{and} behave as you might expect, but
  4176. note that the \code{and} operation is short-circuiting. That is, given
  4177. the expression $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not
  4178. evaluated if $e_1$ evaluates to \code{\#f}.
  4179. With the increase in the number of primitive operations, the
  4180. interpreter would become repetitive without some care. We refactor
  4181. the case for \code{Prim}, moving the code that differs with each
  4182. operation into the \code{interp-op} method shown in in
  4183. Figure~\ref{fig:interp-op-Rif}. We handle the \code{and} operation
  4184. separately because of its short-circuiting behavior.
  4185. \begin{figure}[tbp]
  4186. \begin{lstlisting}
  4187. (define interp-Rif-class
  4188. (class interp-Rvar-class
  4189. (super-new)
  4190. (define/public (interp-op op) ...)
  4191. (define/override ((interp-exp env) e)
  4192. (define recur (interp-exp env))
  4193. (match e
  4194. [(Bool b) b]
  4195. [(If cnd thn els)
  4196. (match (recur cnd)
  4197. [#t (recur thn)]
  4198. [#f (recur els)])]
  4199. [(Prim 'and (list e1 e2))
  4200. (match (recur e1)
  4201. [#t (match (recur e2) [#t #t] [#f #f])]
  4202. [#f #f])]
  4203. [(Prim op args)
  4204. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  4205. [else ((super interp-exp env) e)]))
  4206. ))
  4207. (define (interp-Rif p)
  4208. (send (new interp-Rif-class) interp-program p))
  4209. \end{lstlisting}
  4210. \caption{Interpreter for the \LangIf{} language. (See
  4211. Figure~\ref{fig:interp-op-Rif} for \code{interp-op}.)}
  4212. \label{fig:interp-Rif}
  4213. \end{figure}
  4214. \begin{figure}[tbp]
  4215. \begin{lstlisting}
  4216. (define/public (interp-op op)
  4217. (match op
  4218. ['+ fx+]
  4219. ['- fx-]
  4220. ['read read-fixnum]
  4221. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  4222. ['or (lambda (v1 v2)
  4223. (cond [(and (boolean? v1) (boolean? v2))
  4224. (or v1 v2)]))]
  4225. ['eq? (lambda (v1 v2)
  4226. (cond [(or (and (fixnum? v1) (fixnum? v2))
  4227. (and (boolean? v1) (boolean? v2))
  4228. (and (vector? v1) (vector? v2)))
  4229. (eq? v1 v2)]))]
  4230. ['< (lambda (v1 v2)
  4231. (cond [(and (fixnum? v1) (fixnum? v2))
  4232. (< v1 v2)]))]
  4233. ['<= (lambda (v1 v2)
  4234. (cond [(and (fixnum? v1) (fixnum? v2))
  4235. (<= v1 v2)]))]
  4236. ['> (lambda (v1 v2)
  4237. (cond [(and (fixnum? v1) (fixnum? v2))
  4238. (> v1 v2)]))]
  4239. ['>= (lambda (v1 v2)
  4240. (cond [(and (fixnum? v1) (fixnum? v2))
  4241. (>= v1 v2)]))]
  4242. [else (error 'interp-op "unknown operator")]))
  4243. \end{lstlisting}
  4244. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  4245. \label{fig:interp-op-Rif}
  4246. \end{figure}
  4247. \section{Type Checking \LangIf{} Programs}
  4248. \label{sec:type-check-Rif}
  4249. \index{type checking}
  4250. \index{semantic analysis}
  4251. It is helpful to think about type checking in two complementary
  4252. ways. A type checker predicts the type of value that will be produced
  4253. by each expression in the program. For \LangIf{}, we have just two types,
  4254. \key{Integer} and \key{Boolean}. So a type checker should predict that
  4255. \begin{lstlisting}
  4256. (+ 10 (- (+ 12 20)))
  4257. \end{lstlisting}
  4258. produces an \key{Integer} while
  4259. \begin{lstlisting}
  4260. (and (not #f) #t)
  4261. \end{lstlisting}
  4262. produces a \key{Boolean}.
  4263. Another way to think about type checking is that it enforces a set of
  4264. rules about which operators can be applied to which kinds of
  4265. values. For example, our type checker for \LangIf{} signals an error
  4266. for the below expression
  4267. \begin{lstlisting}
  4268. (not (+ 10 (- (+ 12 20))))
  4269. \end{lstlisting}
  4270. The subexpression \code{(+ 10 (- (+ 12 20)))} has type \key{Integer}
  4271. but the type checker enforces the rule that the argument of \code{not}
  4272. must be a \key{Boolean}.
  4273. We implement type checking using classes and methods because they
  4274. provide the open recursion needed to reuse code as we extend the type
  4275. checker in later chapters, analogous to the use of classes and methods
  4276. for the interpreters (Section~\ref{sec:extensible-interp}).
  4277. We separate the type checker for the \LangVar{} fragment into its own
  4278. class, shown in Figure~\ref{fig:type-check-Rvar}. The type checker for
  4279. \LangIf{} is shown in Figure~\ref{fig:type-check-Rif} and it inherits
  4280. from the type checker for \LangVar{}. These type checkers are in the
  4281. files \code{type-check-Rvar.rkt} and \code{type-check-Rif.rkt} of the
  4282. support code.
  4283. %
  4284. Each type checker is a structurally recursive function over the AST.
  4285. Given an input expression \code{e}, the type checker either signals an
  4286. error or returns an expression and its type (\key{Integer} or
  4287. \key{Boolean}). It returns an expression because there are situations
  4288. in which we want to change or update the expression.
  4289. Next we discuss the \code{match} cases in \code{type-check-exp} of
  4290. Figure~\ref{fig:type-check-Rvar}. The type of an integer constant is
  4291. \code{Integer}. To handle variables, the type checker uses the
  4292. environment \code{env} to map variables to types. Consider the case
  4293. for \key{let}. We type check the initializing expression to obtain
  4294. its type \key{T} and then associate type \code{T} with the variable
  4295. \code{x} in the environment used to type check the body of the
  4296. \key{let}. Thus, when the type checker encounters a use of variable
  4297. \code{x}, it can find its type in the environment. Regarding
  4298. primitive operators, we recursively analyze the arguments and then
  4299. invoke \code{type-check-op} to check whether the argument types are
  4300. allowed.
  4301. Several auxiliary methods are used in the type checker. The method
  4302. \code{operator-types} defines a dictionary that maps the operator
  4303. names to their parameter and return types. The \code{type-equal?}
  4304. method determines whether two types are equal, which for now simply
  4305. dispatches to \code{equal?} (deep equality). The
  4306. \code{check-type-equal?} method triggers an error if the two types are
  4307. not equal. The \code{type-check-op} method looks up the operator in
  4308. the \code{operator-types} dictionary and then checks whether the
  4309. argument types are equal to the parameter types. The result is the
  4310. return type of the operator.
  4311. \begin{figure}[tbp]
  4312. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4313. (define type-check-Rvar-class
  4314. (class object%
  4315. (super-new)
  4316. (define/public (operator-types)
  4317. '((+ . ((Integer Integer) . Integer))
  4318. (- . ((Integer) . Integer))
  4319. (read . (() . Integer))))
  4320. (define/public (type-equal? t1 t2) (equal? t1 t2))
  4321. (define/public (check-type-equal? t1 t2 e)
  4322. (unless (type-equal? t1 t2)
  4323. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  4324. (define/public (type-check-op op arg-types e)
  4325. (match (dict-ref (operator-types) op)
  4326. [`(,param-types . ,return-type)
  4327. (for ([at arg-types] [pt param-types])
  4328. (check-type-equal? at pt e))
  4329. return-type]
  4330. [else (error 'type-check-op "unrecognized ~a" op)]))
  4331. (define/public (type-check-exp env)
  4332. (lambda (e)
  4333. (match e
  4334. [(Int n) (values (Int n) 'Integer)]
  4335. [(Var x) (values (Var x) (dict-ref env x))]
  4336. [(Let x e body)
  4337. (define-values (e^ Te) ((type-check-exp env) e))
  4338. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  4339. (values (Let x e^ b) Tb)]
  4340. [(Prim op es)
  4341. (define-values (new-es ts)
  4342. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  4343. (values (Prim op new-es) (type-check-op op ts e))]
  4344. [else (error 'type-check-exp "couldn't match" e)])))
  4345. (define/public (type-check-program e)
  4346. (match e
  4347. [(Program info body)
  4348. (define-values (body^ Tb) ((type-check-exp '()) body))
  4349. (check-type-equal? Tb 'Integer body)
  4350. (Program info body^)]
  4351. [else (error 'type-check-Rvar "couldn't match ~a" e)]))
  4352. ))
  4353. (define (type-check-Rvar p)
  4354. (send (new type-check-Rvar-class) type-check-program p))
  4355. \end{lstlisting}
  4356. \caption{Type checker for the \LangVar{} language.}
  4357. \label{fig:type-check-Rvar}
  4358. \end{figure}
  4359. \begin{figure}[tbp]
  4360. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4361. (define type-check-Rif-class
  4362. (class type-check-Rvar-class
  4363. (super-new)
  4364. (inherit check-type-equal?)
  4365. (define/override (operator-types)
  4366. (append '((- . ((Integer Integer) . Integer))
  4367. (and . ((Boolean Boolean) . Boolean))
  4368. (or . ((Boolean Boolean) . Boolean))
  4369. (< . ((Integer Integer) . Boolean))
  4370. (<= . ((Integer Integer) . Boolean))
  4371. (> . ((Integer Integer) . Boolean))
  4372. (>= . ((Integer Integer) . Boolean))
  4373. (not . ((Boolean) . Boolean))
  4374. )
  4375. (super operator-types)))
  4376. (define/override (type-check-exp env)
  4377. (lambda (e)
  4378. (match e
  4379. [(Prim 'eq? (list e1 e2))
  4380. (define-values (e1^ T1) ((type-check-exp env) e1))
  4381. (define-values (e2^ T2) ((type-check-exp env) e2))
  4382. (check-type-equal? T1 T2 e)
  4383. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  4384. [(Bool b) (values (Bool b) 'Boolean)]
  4385. [(If cnd thn els)
  4386. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  4387. (define-values (thn^ Tt) ((type-check-exp env) thn))
  4388. (define-values (els^ Te) ((type-check-exp env) els))
  4389. (check-type-equal? Tc 'Boolean e)
  4390. (check-type-equal? Tt Te e)
  4391. (values (If cnd^ thn^ els^) Te)]
  4392. [else ((super type-check-exp env) e)])))
  4393. ))
  4394. (define (type-check-Rif p)
  4395. (send (new type-check-Rif-class) type-check-program p))
  4396. \end{lstlisting}
  4397. \caption{Type checker for the \LangIf{} language.}
  4398. \label{fig:type-check-Rif}
  4399. \end{figure}
  4400. Next we discuss the type checker for \LangIf{} in
  4401. Figure~\ref{fig:type-check-Rif}. The operator \code{eq?} requires the
  4402. two arguments to have the same type. The type of a Boolean constant is
  4403. \code{Boolean}. The condition of an \code{if} must be of
  4404. \code{Boolean} type and the two branches must have the same type. The
  4405. \code{operator-types} function adds dictionary entries for the other
  4406. new operators.
  4407. \begin{exercise}\normalfont
  4408. Create 10 new test programs in \LangIf{}. Half of the programs should
  4409. have a type error. For those programs, create an empty file with the
  4410. same base name but with file extension \code{.tyerr}. For example, if
  4411. the test \code{cond\_test\_14.rkt} is expected to error, then create
  4412. an empty file named \code{cond\_test\_14.tyerr}. This indicates to
  4413. \code{interp-tests} and \code{compiler-tests} that a type error is
  4414. expected. The other half of the test programs should not have type
  4415. errors.
  4416. In the \code{run-tests.rkt} script, change the second argument of
  4417. \code{interp-tests} and \code{compiler-tests} to
  4418. \code{type-check-Rif}, which causes the type checker to run prior to
  4419. the compiler passes. Temporarily change the \code{passes} to an empty
  4420. list and run the script, thereby checking that the new test programs
  4421. either type check or not as intended.
  4422. \end{exercise}
  4423. \section{The \LangCIf{} Intermediate Language}
  4424. \label{sec:Cif}
  4425. Figure~\ref{fig:c1-syntax} defines the abstract syntax of the
  4426. \LangCIf{} intermediate language. (The concrete syntax is in the
  4427. Appendix, Figure~\ref{fig:c1-concrete-syntax}.) Compared to
  4428. \LangCVar{}, the \LangCIf{} language adds logical and comparison
  4429. operators to the \Exp{} non-terminal and the literals \key{\#t} and
  4430. \key{\#f} to the \Arg{} non-terminal.
  4431. Regarding control flow, \LangCIf{} adds \key{goto} and \code{if}
  4432. statements to the \Tail{} non-terminal. The condition of an \code{if}
  4433. statement is a comparison operation and the branches are \code{goto}
  4434. statements, making it straightforward to compile \code{if} statements
  4435. to x86.
  4436. \begin{figure}[tp]
  4437. \fbox{
  4438. \begin{minipage}{0.96\textwidth}
  4439. \small
  4440. \[
  4441. \begin{array}{lcl}
  4442. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  4443. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  4444. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  4445. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4446. &\mid& \UNIOP{\key{'not}}{\Atm}
  4447. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  4448. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  4449. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  4450. \mid \GOTO{\itm{label}} \\
  4451. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  4452. \LangCIf{} & ::= & \gray{\CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}}
  4453. \end{array}
  4454. \]
  4455. \end{minipage}
  4456. }
  4457. \caption{The abstract syntax of \LangCIf{}, an extension of \LangCVar{}
  4458. (Figure~\ref{fig:c0-syntax}).}
  4459. \label{fig:c1-syntax}
  4460. \end{figure}
  4461. \section{The \LangXIf{} Language}
  4462. \label{sec:x86-if}
  4463. \index{x86} To implement the new logical operations, the comparison
  4464. operations, and the \key{if} expression, we need to delve further into
  4465. the x86 language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1}
  4466. define the concrete and abstract syntax for the \LangXIf{} subset
  4467. of x86, which includes instructions for logical operations,
  4468. comparisons, and conditional jumps.
  4469. One challenge is that x86 does not provide an instruction that
  4470. directly implements logical negation (\code{not} in \LangIf{} and
  4471. \LangCIf{}). However, the \code{xorq} instruction can be used to
  4472. encode \code{not}. The \key{xorq} instruction takes two arguments,
  4473. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  4474. bit of its arguments, and writes the results into its second argument.
  4475. Recall the truth table for exclusive-or:
  4476. \begin{center}
  4477. \begin{tabular}{l|cc}
  4478. & 0 & 1 \\ \hline
  4479. 0 & 0 & 1 \\
  4480. 1 & 1 & 0
  4481. \end{tabular}
  4482. \end{center}
  4483. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  4484. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  4485. for the bit $1$, the result is the opposite of the second bit. Thus,
  4486. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  4487. the first argument:
  4488. \[
  4489. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  4490. \qquad\Rightarrow\qquad
  4491. \begin{array}{l}
  4492. \key{movq}~ \Arg\key{,} \Var\\
  4493. \key{xorq}~ \key{\$1,} \Var
  4494. \end{array}
  4495. \]
  4496. \begin{figure}[tp]
  4497. \fbox{
  4498. \begin{minipage}{0.96\textwidth}
  4499. \[
  4500. \begin{array}{lcl}
  4501. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  4502. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4503. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} } \mid \key{\%}\itm{bytereg}\\
  4504. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4505. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \mid
  4506. \key{subq} \; \Arg\key{,} \Arg \mid
  4507. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid } \\
  4508. && \gray{ \key{callq} \; \itm{label} \mid
  4509. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} } \\
  4510. && \gray{ \itm{label}\key{:}\; \Instr }
  4511. \mid \key{xorq}~\Arg\key{,}~\Arg
  4512. \mid \key{cmpq}~\Arg\key{,}~\Arg \mid \\
  4513. && \key{set}cc~\Arg
  4514. \mid \key{movzbq}~\Arg\key{,}~\Arg
  4515. \mid \key{j}cc~\itm{label}
  4516. \\
  4517. \LangXIf{} &::= & \gray{ \key{.globl main} }\\
  4518. & & \gray{ \key{main:} \; \Instr\ldots }
  4519. \end{array}
  4520. \]
  4521. \end{minipage}
  4522. }
  4523. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  4524. \label{fig:x86-1-concrete}
  4525. \end{figure}
  4526. \begin{figure}[tp]
  4527. \fbox{
  4528. \begin{minipage}{0.98\textwidth}
  4529. \small
  4530. \[
  4531. \begin{array}{lcl}
  4532. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  4533. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4534. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}}
  4535. \mid \BYTEREG{\itm{bytereg}} \\
  4536. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4537. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  4538. \mid \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  4539. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  4540. \mid \UNIINSTR{\code{negq}}{\Arg} } \\
  4541. &\mid& \gray{ \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  4542. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  4543. &\mid& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  4544. \mid \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  4545. &\mid& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  4546. \mid \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  4547. &\mid& \JMPIF{\itm{cc}}{\itm{label}} \\
  4548. \Block &::= & \gray{\BLOCK{\itm{info}}{\LP\Instr\ldots\RP}} \\
  4549. \LangXIf{} &::= & \gray{\XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}}
  4550. \end{array}
  4551. \]
  4552. \end{minipage}
  4553. }
  4554. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  4555. \label{fig:x86-1}
  4556. \end{figure}
  4557. Next we consider the x86 instructions that are relevant for compiling
  4558. the comparison operations. The \key{cmpq} instruction compares its two
  4559. arguments to determine whether one argument is less than, equal, or
  4560. greater than the other argument. The \key{cmpq} instruction is unusual
  4561. regarding the order of its arguments and where the result is
  4562. placed. The argument order is backwards: if you want to test whether
  4563. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  4564. \key{cmpq} is placed in the special EFLAGS register. This register
  4565. cannot be accessed directly but it can be queried by a number of
  4566. instructions, including the \key{set} instruction. The instruction
  4567. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  4568. depending on whether the comparison comes out according to the
  4569. condition code \itm{cc} (\key{e} for equal, \key{l} for less, \key{le}
  4570. for less-or-equal, \key{g} for greater, \key{ge} for
  4571. greater-or-equal). The \key{set} instruction has an annoying quirk in
  4572. that its destination argument must be single byte register, such as
  4573. \code{al} (L for lower bits) or \code{ah} (H for higher bits), which
  4574. are part of the \code{rax} register. Thankfully, the \key{movzbq}
  4575. instruction can be used to move from a single byte register to a
  4576. normal 64-bit register. The abstract syntax for the \code{set}
  4577. instruction differs from the concrete syntax in that it separates the
  4578. instruction name from the condition code.
  4579. The x86 instruction for conditional jump is relevant to the
  4580. compilation of \key{if} expressions. The instruction
  4581. $\key{j}\itm{cc}~\itm{label}$ updates the program counter to point to
  4582. the instruction after \itm{label} depending on whether the result in
  4583. the EFLAGS register matches the condition code \itm{cc}, otherwise the
  4584. jump instruction falls through to the next instruction. Like the
  4585. abstract syntax for \code{set}, the abstract syntax for conditional
  4586. jump separates the instruction name from the condition code. For
  4587. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  4588. the conditional jump instruction relies on the EFLAGS register, it is
  4589. common for it to be immediately preceded by a \key{cmpq} instruction
  4590. to set the EFLAGS register.
  4591. \section{Shrink the \LangIf{} Language}
  4592. \label{sec:shrink-Rif}
  4593. The \LangIf{} language includes several operators that are easily
  4594. expressible with other operators. For example, subtraction is
  4595. expressible using addition and negation.
  4596. \[
  4597. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  4598. \]
  4599. Several of the comparison operations are expressible using less-than
  4600. and logical negation.
  4601. \[
  4602. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  4603. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  4604. \]
  4605. The \key{let} is needed in the above translation to ensure that
  4606. expression $e_1$ is evaluated before $e_2$.
  4607. By performing these translations in the front-end of the compiler, the
  4608. later passes of the compiler do not need to deal with these operators,
  4609. making the passes shorter.
  4610. %% On the other hand, sometimes
  4611. %% these translations make it more difficult to generate the most
  4612. %% efficient code with respect to the number of instructions. However,
  4613. %% these differences typically do not affect the number of accesses to
  4614. %% memory, which is the primary factor that determines execution time on
  4615. %% modern computer architectures.
  4616. \begin{exercise}\normalfont
  4617. Implement the pass \code{shrink} to remove subtraction, \key{and},
  4618. \key{or}, \key{<=}, \key{>}, and \key{>=} from the language by
  4619. translating them to other constructs in \LangIf{}.
  4620. %
  4621. Create six test programs that involve these operators.
  4622. %
  4623. In the \code{run-tests.rkt} script, add the following entry for
  4624. \code{shrink} to the list of passes (it should be the only pass at
  4625. this point).
  4626. \begin{lstlisting}
  4627. (list "shrink" shrink interp-Rif type-check-Rif)
  4628. \end{lstlisting}
  4629. This instructs \code{interp-tests} to run the intepreter
  4630. \code{interp-Rif} and the type checker \code{type-check-Rif} on the
  4631. output of \code{shrink}.
  4632. %
  4633. Run the script to test your compiler on all the test programs.
  4634. \end{exercise}
  4635. \section{Uniquify Variables}
  4636. \label{sec:uniquify-Rif}
  4637. Add cases to \code{uniquify-exp} to handle Boolean constants and
  4638. \code{if} expressions.
  4639. \begin{exercise}\normalfont
  4640. Update the \code{uniquify-exp} for \LangIf{} and add the following
  4641. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  4642. \begin{lstlisting}
  4643. (list "uniquify" uniquify interp-Rif type-check-Rif)
  4644. \end{lstlisting}
  4645. Run the script to test your compiler.
  4646. \end{exercise}
  4647. \section{Remove Complex Operands}
  4648. \label{sec:remove-complex-opera-Rif}
  4649. The output language for this pass is \LangIfANF{}
  4650. (Figure~\ref{fig:Rif-anf-syntax}), the administrative normal form of
  4651. \LangIf{}. The \code{Bool} form is an atomic expressions but
  4652. \code{If} is not. All three sub-expressions of an \code{If} are
  4653. allowed to be complex expressions but the operands of \code{not} and
  4654. the comparisons must be atoms.
  4655. Add cases for \code{Bool} and \code{If} to the \code{rco-exp} and
  4656. \code{rco-atom} functions according to whether the output needs to be
  4657. \Exp{} or \Atm{} as specified in the grammar for \LangIfANF{}.
  4658. Regarding \code{If}, it is particularly important to \textbf{not}
  4659. replace its condition with a temporary variable because that would
  4660. interfere with the generation of high-quality output in the
  4661. \code{explicate-control} pass.
  4662. \begin{figure}[tp]
  4663. \centering
  4664. \fbox{
  4665. \begin{minipage}{0.96\textwidth}
  4666. \[
  4667. \begin{array}{rcl}
  4668. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} } \mid \BOOL{\itm{bool}}\\
  4669. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  4670. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4671. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  4672. &\mid& \UNIOP{\key{not}}{\Atm} \\
  4673. &\mid& \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4674. R^{\dagger}_2 &::=& \PROGRAM{\code{()}}{\Exp}
  4675. \end{array}
  4676. \]
  4677. \end{minipage}
  4678. }
  4679. \caption{\LangIfANF{} is \LangIf{} in administrative normal form (ANF).}
  4680. \label{fig:Rif-anf-syntax}
  4681. \end{figure}
  4682. \begin{exercise}\normalfont
  4683. %
  4684. Add cases for Boolean constants and \code{if} to the \code{rco-atom}
  4685. and \code{rco-exp} functions in \code{compiler.rkt}.
  4686. %
  4687. Create three new \LangInt{} programs that exercise the interesting
  4688. code in this pass.
  4689. %
  4690. In the \code{run-tests.rkt} script, add the following entry to the
  4691. list of \code{passes} and then run the script to test your compiler.
  4692. \begin{lstlisting}
  4693. (list "remove-complex" remove-complex-opera* interp-Rif type-check-Rif)
  4694. \end{lstlisting}
  4695. \end{exercise}
  4696. \section{Explicate Control}
  4697. \label{sec:explicate-control-Rif}
  4698. Recall that the purpose of \code{explicate-control} is to make the
  4699. order of evaluation explicit in the syntax of the program. With the
  4700. addition of \key{if} this get more interesting.
  4701. As a motivating example, consider the following program that has an
  4702. \key{if} expression nested in the predicate of another \key{if}.
  4703. % cond_test_41.rkt
  4704. \begin{center}
  4705. \begin{minipage}{0.96\textwidth}
  4706. \begin{lstlisting}
  4707. (let ([x (read)])
  4708. (let ([y (read)])
  4709. (if (if (< x 1) (eq? x 0) (eq? x 2))
  4710. (+ y 2)
  4711. (+ y 10))))
  4712. \end{lstlisting}
  4713. \end{minipage}
  4714. \end{center}
  4715. %
  4716. The naive way to compile \key{if} and the comparison would be to
  4717. handle each of them in isolation, regardless of their context. Each
  4718. comparison would be translated into a \key{cmpq} instruction followed
  4719. by a couple instructions to move the result from the EFLAGS register
  4720. into a general purpose register or stack location. Each \key{if} would
  4721. be translated into a \key{cmpq} instruction followed by a conditional
  4722. jump. The generated code for the inner \key{if} in the above example
  4723. would be as follows.
  4724. \begin{center}
  4725. \begin{minipage}{0.96\textwidth}
  4726. \begin{lstlisting}
  4727. ...
  4728. cmpq $1, x ;; (< x 1)
  4729. setl %al
  4730. movzbq %al, tmp
  4731. cmpq $1, tmp ;; (if ...)
  4732. je then_branch_1
  4733. jmp else_branch_1
  4734. ...
  4735. \end{lstlisting}
  4736. \end{minipage}
  4737. \end{center}
  4738. However, if we take context into account we can do better and reduce
  4739. the use of \key{cmpq} instructions for accessing the EFLAG register.
  4740. Our goal will be compile \key{if} expressions so that the relevant
  4741. comparison instruction appears directly before the conditional jump.
  4742. For example, we want to generate the following code for the inner
  4743. \code{if}.
  4744. \begin{center}
  4745. \begin{minipage}{0.96\textwidth}
  4746. \begin{lstlisting}
  4747. ...
  4748. cmpq $1, x
  4749. je then_branch_1
  4750. jmp else_branch_1
  4751. ...
  4752. \end{lstlisting}
  4753. \end{minipage}
  4754. \end{center}
  4755. One way to achieve this is to reorganize the code at the level of
  4756. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  4757. the following code.
  4758. \begin{center}
  4759. \begin{minipage}{0.96\textwidth}
  4760. \begin{lstlisting}
  4761. (let ([x (read)])
  4762. (let ([y (read)])
  4763. (if (< x 1)
  4764. (if (eq? x 0)
  4765. (+ y 2)
  4766. (+ y 10))
  4767. (if (eq? x 2)
  4768. (+ y 2)
  4769. (+ y 10)))))
  4770. \end{lstlisting}
  4771. \end{minipage}
  4772. \end{center}
  4773. Unfortunately, this approach duplicates the two branches from the
  4774. outer \code{if} and a compiler must never duplicate code!
  4775. We need a way to perform the above transformation but without
  4776. duplicating code. That is, we need a way for different parts of a
  4777. program to refer to the same piece of code. At the level of x86
  4778. assembly this is straightforward because we can label the code for
  4779. each branch and insert jumps in all the places that need to execute
  4780. the branch. In our intermediate language, we need to move away from
  4781. abstract syntax \emph{trees} and instead use \emph{graphs}. In
  4782. particular, we use a standard program representation called a
  4783. \emph{control flow graph} (CFG), due to Frances Elizabeth
  4784. \citet{Allen:1970uq}. \index{control-flow graph} Each vertex is a
  4785. labeled sequence of code, called a \emph{basic block}, and each edge
  4786. represents a jump to another block. The \key{CProgram} construct of
  4787. \LangCVar{} and \LangCIf{} contains a control flow graph represented
  4788. as an alist mapping labels to basic blocks. Each basic block is
  4789. represented by the $\Tail$ non-terminal.
  4790. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  4791. \code{remove-complex-opera*} pass and then the
  4792. \code{explicate-control} pass on the example program. We walk through
  4793. the output program and then discuss the algorithm.
  4794. %
  4795. Following the order of evaluation in the output of
  4796. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  4797. and then the comparison \lstinline{(< x 1)} in the predicate of the
  4798. inner \key{if}. In the output of \code{explicate-control}, in the
  4799. block labeled \code{start}, is two assignment statements followed by a
  4800. \code{if} statement that branches to \code{block40} or
  4801. \code{block41}. The blocks associated with those labels contain the
  4802. translations of the code \lstinline{(eq? x 0)} and \lstinline{(eq? x 2)},
  4803. respectively. In particular, we start \code{block40} with the
  4804. comparison \lstinline{(eq? x 0)} and then branch to \code{block38} or
  4805. \code{block39}, the two branches of the outer \key{if}, i.e.,
  4806. \lstinline{(+ y 2)} and \lstinline{(+ y 10)}. The story for
  4807. \code{block41} is similar.
  4808. \begin{figure}[tbp]
  4809. \begin{tabular}{lll}
  4810. \begin{minipage}{0.4\textwidth}
  4811. % cond_test_41.rkt
  4812. \begin{lstlisting}
  4813. (let ([x (read)])
  4814. (let ([y (read)])
  4815. (if (if (< x 1)
  4816. (eq? x 0)
  4817. (eq? x 2))
  4818. (+ y 2)
  4819. (+ y 10))))
  4820. \end{lstlisting}
  4821. \hspace{40pt}$\Downarrow$
  4822. \begin{lstlisting}
  4823. (let ([x (read)])
  4824. (let ([y (read)])
  4825. (if (if (< x 1)
  4826. (eq? x 0)
  4827. (eq? x 2))
  4828. (+ y 2)
  4829. (+ y 10))))
  4830. \end{lstlisting}
  4831. \end{minipage}
  4832. &
  4833. $\Rightarrow$
  4834. &
  4835. \begin{minipage}{0.55\textwidth}
  4836. \begin{lstlisting}
  4837. start:
  4838. x = (read);
  4839. y = (read);
  4840. if (< x 1) goto block40;
  4841. else goto block41;
  4842. block40:
  4843. if (eq? x 0) goto block38;
  4844. else goto block39;
  4845. block41:
  4846. if (eq? x 2) goto block38;
  4847. else goto block39;
  4848. block38:
  4849. return (+ y 2);
  4850. block39:
  4851. return (+ y 10);
  4852. \end{lstlisting}
  4853. \end{minipage}
  4854. \end{tabular}
  4855. \caption{Translation from \LangIf{} to \LangCIf{}
  4856. via the \code{explicate-control}.}
  4857. \label{fig:explicate-control-s1-38}
  4858. \end{figure}
  4859. %% The nice thing about the output of \code{explicate-control} is that
  4860. %% there are no unnecessary comparisons and every comparison is part of a
  4861. %% conditional jump.
  4862. %% The down-side of this output is that it includes
  4863. %% trivial blocks, such as the blocks labeled \code{block92} through
  4864. %% \code{block95}, that only jump to another block. We discuss a solution
  4865. %% to this problem in Section~\ref{sec:opt-jumps}.
  4866. Recall that in Section~\ref{sec:explicate-control-Rvar} we implement
  4867. \code{explicate-control} for \LangVar{} using two mutually recursive
  4868. functions, \code{explicate-tail} and \code{explicate-assign}. The
  4869. former function translates expressions in tail position whereas the
  4870. later function translates expressions on the right-hand-side of a
  4871. \key{let}. With the addition of \key{if} expression in \LangIf{} we
  4872. have a new kind of position to deal with: the predicate position of
  4873. the \key{if}. We need another function, \code{explicate-pred}, that
  4874. takes an \LangIf{} expression and two blocks for the then-branch and
  4875. else-branch. The output of \code{explicate-pred} is a block.
  4876. %
  4877. In the following paragraphs we discuss specific cases in the
  4878. \code{explicate-pred} function as well as additions to the
  4879. \code{explicate-tail} and \code{explicate-assign} functions.
  4880. \begin{figure}[tbp]
  4881. \begin{lstlisting}
  4882. (define (explicate-pred cnd thn els)
  4883. (match cnd
  4884. [(Var x) ___]
  4885. [(Let x rhs body) ___]
  4886. [(Prim 'not (list e)) ___]
  4887. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  4888. (IfStmt (Prim op arg*) (force (block->goto thn))
  4889. (force (block->goto els)))]
  4890. [(Bool b) (if b thn els)]
  4891. [(If cnd^ thn^ els^) ___]
  4892. [else (error "explicate-pred unhandled case" cnd)]))
  4893. \end{lstlisting}
  4894. \caption{Skeleton for the \key{explicate-pred} auxiliary function.}
  4895. \label{fig:explicate-pred}
  4896. \end{figure}
  4897. The skeleton for the \code{explicate-pred} function is given in
  4898. Figure~\ref{fig:explicate-pred}. It has a case for every expression
  4899. that can have type \code{Boolean}. We detail a few cases here and
  4900. leave the rest for the reader. The input to this function is an
  4901. expression and two blocks, \code{thn} and \code{els}, for the two
  4902. branches of the enclosing \key{if}.
  4903. %
  4904. Consider the case for Boolean constants in
  4905. Figure~\ref{fig:explicate-pred}. We perform a kind of partial
  4906. evaluation\index{partial evaluation} and output either the \code{thn}
  4907. or \code{els} branch depending on whether the constant is true or
  4908. false. This case demonstrates that we sometimes discard the \code{thn}
  4909. or \code{els} blocks that are input to \code{explicate-pred}.
  4910. The case for \key{if} in \code{explicate-pred} is particularly
  4911. illuminating because it deals with the challenges we discussed above
  4912. regarding nested \key{if} expressions
  4913. (Figure~\ref{fig:explicate-control-s1-38}). The \lstinline{thn^} and
  4914. \lstinline{els^} branches of the \key{if} inherit their context from
  4915. the current one, that is, predicate context. So you should recursively
  4916. apply \code{explicate-pred} to the \lstinline{thn^} and
  4917. \lstinline{els^} branches. For both of those recursive calls, pass
  4918. \code{thn} and \code{els} as the extra parameters. Thus, \code{thn}
  4919. and \code{els} may get used twice, once inside each recursive call. As
  4920. discussed above, to avoid duplicating code, we need to add them to the
  4921. control-flow graph so that we can instead refer to them by name and
  4922. execute them with a \key{goto}. However, as we saw in the cases above
  4923. for Boolean constants, the blocks \code{thn} and \code{els} may not
  4924. get used at all and we don't want to prematurely add them to the
  4925. control-flow graph if they end up being discarded.
  4926. The solution to this conundrum is to use \emph{lazy
  4927. evaluation}\index{lazy evaluation}\citep{Friedman:1976aa} to delay
  4928. adding the blocks to the control-flow graph until the points where we
  4929. know they will be used. Racket provides support for lazy evaluation
  4930. with the
  4931. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  4932. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  4933. \index{delay} creates a \emph{promise}\index{promise} in which the
  4934. evaluation of the expressions is postponed. When \key{(force}
  4935. $p$\key{)}\index{force} is applied to a promise $p$ for the first
  4936. time, the expressions $e_1 \ldots e_n$ are evaluated and the result of
  4937. $e_n$ is cached in the promise and returned. If \code{force} is
  4938. applied again to the same promise, then the cached result is returned.
  4939. If \code{force} is applied to an argument that is not a promise,
  4940. \code{force} simply returns the argument.
  4941. We use lazy evaluation for the input and output blocks of the
  4942. functions \code{explicate-pred} and \code{explicate-assign} and for
  4943. the output block of \code{explicate-tail}. So instead of taking and
  4944. returning blocks, they take and return promises. Furthermore, when we
  4945. come to a situation in which we a block might be used more than once,
  4946. as in the case for \code{if} in \code{explicate-pred}, we transform
  4947. the promise into a new promise that will add the block to the
  4948. control-flow graph and return a \code{goto}. The following auxiliary
  4949. function named \code{block->goto} accomplishes this task. It begins
  4950. with \code{delay} to create a promise. When forced, this promise will
  4951. force the original promise. If that returns a \code{goto} (because the
  4952. block was already added to the control-flow graph), then we return the
  4953. \code{goto}. Otherwise we add the block to the control-flow graph with
  4954. another auxiliary function named \code{add-node}. That function
  4955. returns the label for the new block, which we use to create a
  4956. \code{goto}.
  4957. \begin{lstlisting}
  4958. (define (block->goto block)
  4959. (delay
  4960. (define b (force block))
  4961. (match b
  4962. [(Goto label) (Goto label)]
  4963. [else (Goto (add-node b))])))
  4964. \end{lstlisting}
  4965. Returning to the discussion of \code{explicate-pred}
  4966. (Figure~\ref{fig:explicate-pred}), consider the case for comparison
  4967. operators. This is one of the base cases of the recursive function so
  4968. we translate the comparison to an \code{if} statement. We apply
  4969. \code{block->goto} to \code{thn} and \code{els} to obtain two promises
  4970. that will add then to the control-flow graph, which we can immediately
  4971. \code{force} to obtain the two goto's that form the branches of the
  4972. \code{if} statement.
  4973. %% Getting back to the case for \code{if} in \code{explicate-pred}, we
  4974. %% make the recursive calls to \code{explicate-pred} on the ``then'' and
  4975. %% ``else'' branches with the arguments \code{(block->goto} $B_1$\code{)}
  4976. %% and \code{(block->goto} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  4977. %% results from the two recursive calls. We complete the case for
  4978. %% \code{if} by recursively apply \code{explicate-pred} to the condition
  4979. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  4980. %% the result $B_5$.
  4981. %% \[
  4982. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  4983. %% \quad\Rightarrow\quad
  4984. %% B_5
  4985. %% \]
  4986. The \code{explicate-tail} and \code{explicate-assign} functions need
  4987. additional cases for Boolean constants and \key{if}.
  4988. %
  4989. In the cases for \code{if}, the two branches inherit the current
  4990. context, so in \code{explicate-tail} they are in tail position and in
  4991. \code{explicate-assign} they are in assignment position. The
  4992. \code{cont} parameter of \code{explicate-assign} is used in both
  4993. recursive calls, so make sure to use \code{block->goto} on it.
  4994. %% In the case for \code{if} in \code{explicate-tail}, the two branches
  4995. %% inherit the current context, so they are in tail position. Thus, the
  4996. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  4997. %% \code{explicate-tail}.
  4998. %% %
  4999. %% We need to pass $B_0$ as the accumulator argument for both of these
  5000. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  5001. %% Thus, we first apply \code{block->goto} to $B_0$ so that it gets added
  5002. %% to the control-flow graph and obtain a promised goto $G_0$.
  5003. %% %
  5004. %% Let $B_1$ be the result of \code{explicate-tail} on the ``then''
  5005. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate-tail}
  5006. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  5007. %% \code{explicate-pred} to the condition of the \key{if}, $B_1$, and
  5008. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  5009. %% \[
  5010. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  5011. %% \]
  5012. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  5013. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  5014. %% should not be confused with the labels for the blocks that appear in
  5015. %% the generated code. We initially construct unlabeled blocks; we only
  5016. %% attach labels to blocks when we add them to the control-flow graph, as
  5017. %% we see in the next case.
  5018. %% Next consider the case for \key{if} in the \code{explicate-assign}
  5019. %% function. The context of the \key{if} is an assignment to some
  5020. %% variable $x$ and then the control continues to some promised block
  5021. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  5022. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  5023. %% apply \code{block->goto} to it and obtain a promised goto $G_1$. The
  5024. %% branches of the \key{if} inherit the current context, so they are in
  5025. %% assignment positions. Let $B_2$ be the result of applying
  5026. %% \code{explicate-assign} to the ``then'' branch, variable $x$, and
  5027. %% $G_1$. Let $B_3$ be the result of applying \code{explicate-assign} to
  5028. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  5029. %% the result of applying \code{explicate-pred} to the predicate
  5030. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  5031. %% translates to the promise $B_4$.
  5032. %% \[
  5033. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  5034. %% \]
  5035. %% This completes the description of \code{explicate-control} for \LangIf{}.
  5036. The way in which the \code{shrink} pass transforms logical operations
  5037. such as \code{and} and \code{or} can impact the quality of code
  5038. generated by \code{explicate-control}. For example, consider the
  5039. following program.
  5040. % cond_test_21.rkt
  5041. \begin{lstlisting}
  5042. (if (and (eq? (read) 0) (eq? (read) 1))
  5043. 0
  5044. 42)
  5045. \end{lstlisting}
  5046. The \code{and} operation should transform into something that the
  5047. \code{explicate-pred} function can still analyze and descend through to
  5048. reach the underlying \code{eq?} conditions. Ideally, your
  5049. \code{explicate-control} pass should generate code similar to the
  5050. following for the above program.
  5051. \begin{center}
  5052. \begin{lstlisting}
  5053. start:
  5054. tmp1 = (read);
  5055. if (eq? tmp1 0) goto block40;
  5056. else goto block39;
  5057. block40:
  5058. tmp2 = (read);
  5059. if (eq? tmp2 1) goto block38;
  5060. else goto block39;
  5061. block38:
  5062. return 0;
  5063. block39:
  5064. return 42;
  5065. \end{lstlisting}
  5066. \end{center}
  5067. \begin{exercise}\normalfont
  5068. Implement the pass \code{explicate-control} by adding the cases for
  5069. Boolean constants and \key{if} to the \code{explicate-tail} and
  5070. \code{explicate-assign}. Implement the auxiliary function
  5071. \code{explicate-pred} for predicate contexts.
  5072. %
  5073. Create test cases that exercise all of the new cases in the code for
  5074. this pass.
  5075. %
  5076. Add the following entry to the list of \code{passes} in
  5077. \code{run-tests.rkt} and then run this script to test your compiler.
  5078. \begin{lstlisting}
  5079. (list "explicate-control" explicate-control interp-Cif type-check-Cif)
  5080. \end{lstlisting}
  5081. \end{exercise}
  5082. \section{Select Instructions}
  5083. \label{sec:select-Rif}
  5084. \index{instruction selection}
  5085. The \code{select-instructions} pass translate \LangCIf{} to
  5086. \LangXIfVar{}. Recall that we implement this pass using three
  5087. auxiliary functions, one for each of the non-terminals $\Atm$,
  5088. $\Stmt$, and $\Tail$.
  5089. For $\Atm$, we have new cases for the Booleans. We take the usual
  5090. approach of encoding them as integers, with true as 1 and false as 0.
  5091. \[
  5092. \key{\#t} \Rightarrow \key{1}
  5093. \qquad
  5094. \key{\#f} \Rightarrow \key{0}
  5095. \]
  5096. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  5097. be implemented in terms of \code{xorq} as we discussed at the
  5098. beginning of this section. Given an assignment
  5099. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  5100. if the left-hand side $\itm{var}$ is
  5101. the same as $\Atm$, then just the \code{xorq} suffices.
  5102. \[
  5103. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  5104. \quad\Rightarrow\quad
  5105. \key{xorq}~\key{\$}1\key{,}~\Var
  5106. \]
  5107. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  5108. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  5109. x86. Then we have
  5110. \[
  5111. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  5112. \quad\Rightarrow\quad
  5113. \begin{array}{l}
  5114. \key{movq}~\Arg\key{,}~\Var\\
  5115. \key{xorq}~\key{\$}1\key{,}~\Var
  5116. \end{array}
  5117. \]
  5118. Next consider the cases for \code{eq?} and less-than comparison.
  5119. Translating these operations to x86 is slightly involved due to the
  5120. unusual nature of the \key{cmpq} instruction discussed above. We
  5121. recommend translating an assignment from \code{eq?} into the following
  5122. sequence of three instructions. \\
  5123. \begin{tabular}{lll}
  5124. \begin{minipage}{0.4\textwidth}
  5125. \begin{lstlisting}
  5126. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  5127. \end{lstlisting}
  5128. \end{minipage}
  5129. &
  5130. $\Rightarrow$
  5131. &
  5132. \begin{minipage}{0.4\textwidth}
  5133. \begin{lstlisting}
  5134. cmpq |$\Arg_2$|, |$\Arg_1$|
  5135. sete %al
  5136. movzbq %al, |$\Var$|
  5137. \end{lstlisting}
  5138. \end{minipage}
  5139. \end{tabular} \\
  5140. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  5141. and \key{if} statements. Both are straightforward to translate to
  5142. x86. A \key{goto} becomes a jump instruction.
  5143. \[
  5144. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  5145. \]
  5146. An \key{if} statement becomes a compare instruction followed by a
  5147. conditional jump (for the ``then'' branch) and the fall-through is to
  5148. a regular jump (for the ``else'' branch).\\
  5149. \begin{tabular}{lll}
  5150. \begin{minipage}{0.4\textwidth}
  5151. \begin{lstlisting}
  5152. if (eq? |$\Atm_1$| |$\Atm_2$|) goto |$\ell_1$|;
  5153. else goto |$\ell_2$|;
  5154. \end{lstlisting}
  5155. \end{minipage}
  5156. &
  5157. $\Rightarrow$
  5158. &
  5159. \begin{minipage}{0.4\textwidth}
  5160. \begin{lstlisting}
  5161. cmpq |$\Arg_2$|, |$\Arg_1$|
  5162. je |$\ell_1$|
  5163. jmp |$\ell_2$|
  5164. \end{lstlisting}
  5165. \end{minipage}
  5166. \end{tabular} \\
  5167. \begin{exercise}\normalfont
  5168. Expand your \code{select-instructions} pass to handle the new features
  5169. of the \LangIf{} language.
  5170. %
  5171. Add the following entry to the list of \code{passes} in
  5172. \code{run-tests.rkt}
  5173. \begin{lstlisting}
  5174. (list "select-instructions" select-instructions interp-pseudo-x86-1)
  5175. \end{lstlisting}
  5176. %
  5177. Run the script to test your compiler on all the test programs.
  5178. \end{exercise}
  5179. \section{Register Allocation}
  5180. \label{sec:register-allocation-Rif}
  5181. \index{register allocation}
  5182. The changes required for \LangIf{} affect liveness analysis, building the
  5183. interference graph, and assigning homes, but the graph coloring
  5184. algorithm itself does not change.
  5185. \subsection{Liveness Analysis}
  5186. \label{sec:liveness-analysis-Rif}
  5187. \index{liveness analysis}
  5188. Recall that for \LangVar{} we implemented liveness analysis for a single
  5189. basic block (Section~\ref{sec:liveness-analysis-Rvar}). With the
  5190. addition of \key{if} expressions to \LangIf{}, \code{explicate-control}
  5191. produces many basic blocks arranged in a control-flow graph. We
  5192. recommend that you create a new auxiliary function named
  5193. \code{uncover-live-CFG} that applies liveness analysis to a
  5194. control-flow graph.
  5195. The first question we is: what order should we process the basic
  5196. blocks in the control-flow graph? Recall that to perform liveness
  5197. analysis on a basic block we need to know its live-after set. If a
  5198. basic block has no successors (i.e. no out-edges in the control flow
  5199. graph), then it has an empty live-after set and we can immediately
  5200. apply liveness analysis to it. If a basic block has some successors,
  5201. then we need to complete liveness analysis on those blocks first. In
  5202. graph theory, a sequence of nodes is in \emph{topological
  5203. order}\index{topological order} if each vertex comes before its
  5204. successors. We need the opposite, so we can transpose the graph
  5205. before computing a topological order.
  5206. %
  5207. Use the \code{tsort} and \code{transpose} functions of the Racket
  5208. \code{graph} package to accomplish this.
  5209. %
  5210. As an aside, a topological ordering is only guaranteed to exist if the
  5211. graph does not contain any cycles. That is indeed the case for the
  5212. control-flow graphs that we generate from \LangIf{} programs.
  5213. However, in Chapter~\ref{ch:Rwhile} we add loops to \LangLoop{} and
  5214. learn how to handle cycles in the control-flow graph.
  5215. You'll need to construct a directed graph to represent the
  5216. control-flow graph. Do not use the \code{directed-graph} of the
  5217. \code{graph} package because that only allows at most one edge between
  5218. each pair of vertices, but a control-flow graph may have multiple
  5219. edges between a pair of vertices. The \code{multigraph.rkt} file in
  5220. the support code implements a graph representation that allows
  5221. multiple edges between a pair of vertices.
  5222. The next question is how to analyze jump instructions. Recall that in
  5223. Section~\ref{sec:liveness-analysis-Rvar} we maintain an alist named
  5224. \code{label->live} that maps each label to the set of live locations
  5225. at the beginning of its block. We use \code{label->live} to determine
  5226. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  5227. that we have many basic blocks, \code{label->live} needs to be updated
  5228. as we process the blocks. In particular, after performing liveness
  5229. analysis on a block, we take the live-before set of its first
  5230. instruction and associate that with the block's label in the
  5231. \code{label->live}.
  5232. In \LangXIfVar{} we also have the conditional jump
  5233. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  5234. this instruction is particularly interesting because during
  5235. compilation we do not know which way a conditional jump will go. So
  5236. we do not know whether to use the live-before set for the following
  5237. instruction or the live-before set for the $\itm{label}$. However,
  5238. there is no harm to the correctness of the compiler if we classify
  5239. more locations as live than the ones that are truly live during a
  5240. particular execution of the instruction. Thus, we can take the union
  5241. of the live-before sets from the following instruction and from the
  5242. mapping for $\itm{label}$ in \code{label->live}.
  5243. The auxiliary functions for computing the variables in an
  5244. instruction's argument and for computing the variables read-from ($R$)
  5245. or written-to ($W$) by an instruction need to be updated to handle the
  5246. new kinds of arguments and instructions in \LangXIfVar{}.
  5247. \begin{exercise}\normalfont
  5248. Update the \code{uncover-live} pass and implement the
  5249. \code{uncover-live-CFG} auxiliary function to apply liveness analysis
  5250. to the control-flow graph. Add the following entry to the list of
  5251. \code{passes} in the \code{run-tests.rkt} script.
  5252. \begin{lstlisting}
  5253. (list "uncover-live" uncover-live interp-pseudo-x86-1)
  5254. \end{lstlisting}
  5255. \end{exercise}
  5256. \subsection{Build the Interference Graph}
  5257. \label{sec:build-interference-Rif}
  5258. Many of the new instructions in \LangXIfVar{} can be handled in the
  5259. same way as the instructions in \LangXVar{}. Thus, if your code was
  5260. already quite general, it will not need to be changed to handle the
  5261. new instructions. If you code is not general enough, we recommend that
  5262. you change your code to be more general. For example, you can factor
  5263. out the computing of the the read and write sets for each kind of
  5264. instruction into two auxiliary functions.
  5265. Note that the \key{movzbq} instruction requires some special care,
  5266. similar to the \key{movq} instruction. See rule number 1 in
  5267. Section~\ref{sec:build-interference}.
  5268. \begin{exercise}\normalfont
  5269. Update the \code{build-interference} pass for \LangXIfVar{} and add the
  5270. following entries to the list of \code{passes} in the
  5271. \code{run-tests.rkt} script.
  5272. \begin{lstlisting}
  5273. (list "build-interference" build-interference interp-pseudo-x86-1)
  5274. (list "allocate-registers" allocate-registers interp-x86-1)
  5275. \end{lstlisting}
  5276. Run the script to test your compiler on all the \LangIf{} test
  5277. programs.
  5278. \end{exercise}
  5279. \section{Patch Instructions}
  5280. The second argument of the \key{cmpq} instruction must not be an
  5281. immediate value (such as an integer). So if you are comparing two
  5282. immediates, we recommend inserting a \key{movq} instruction to put the
  5283. second argument in \key{rax}. Also, recall that instructions may have
  5284. at most one memory reference.
  5285. %
  5286. The second argument of the \key{movzbq} must be a register.
  5287. %
  5288. There are no special restrictions on the jump instructions.
  5289. \begin{exercise}\normalfont
  5290. %
  5291. Update \code{patch-instructions} pass for \LangXIfVar{}.
  5292. %
  5293. Add the following entry to the list of \code{passes} in
  5294. \code{run-tests.rkt} and then run this script to test your compiler.
  5295. \begin{lstlisting}
  5296. (list "patch-instructions" patch-instructions interp-x86-1)
  5297. \end{lstlisting}
  5298. \end{exercise}
  5299. \begin{figure}[tbp]
  5300. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5301. \node (Rif) at (0,2) {\large \LangIf{}};
  5302. \node (Rif-2) at (3,2) {\large \LangIf{}};
  5303. \node (Rif-3) at (6,2) {\large \LangIf{}};
  5304. \node (Rif-4) at (9,2) {\large \LangIf{}};
  5305. \node (Rif-5) at (12,2) {\large \LangIf{}};
  5306. \node (C1-1) at (3,0) {\large \LangCIf{}};
  5307. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  5308. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  5309. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  5310. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  5311. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  5312. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  5313. \path[->,bend left=15] (Rif) edge [above] node {\ttfamily\footnotesize type-check} (Rif-2);
  5314. \path[->,bend left=15] (Rif-2) edge [above] node {\ttfamily\footnotesize shrink} (Rif-3);
  5315. \path[->,bend left=15] (Rif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Rif-4);
  5316. \path[->,bend left=15] (Rif-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rif-5);
  5317. \path[->,bend left=15] (Rif-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C1-1);
  5318. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select-instructions} (x86-2);
  5319. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  5320. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  5321. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  5322. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  5323. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86 } (x86-5);
  5324. \end{tikzpicture}
  5325. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  5326. \label{fig:Rif-passes}
  5327. \end{figure}
  5328. Figure~\ref{fig:Rif-passes} lists all the passes needed for the
  5329. compilation of \LangIf{}.
  5330. \section{An Example Translation}
  5331. Figure~\ref{fig:if-example-x86} shows a simple example program in
  5332. \LangIf{} translated to x86, showing the results of
  5333. \code{explicate-control}, \code{select-instructions}, and the final
  5334. x86 assembly code.
  5335. \begin{figure}[tbp]
  5336. \begin{tabular}{lll}
  5337. \begin{minipage}{0.4\textwidth}
  5338. % cond_test_20.rkt
  5339. \begin{lstlisting}
  5340. (if (eq? (read) 1) 42 0)
  5341. \end{lstlisting}
  5342. $\Downarrow$
  5343. \begin{lstlisting}
  5344. start:
  5345. tmp7951 = (read);
  5346. if (eq? tmp7951 1)
  5347. goto block7952;
  5348. else
  5349. goto block7953;
  5350. block7952:
  5351. return 42;
  5352. block7953:
  5353. return 0;
  5354. \end{lstlisting}
  5355. $\Downarrow$
  5356. \begin{lstlisting}
  5357. start:
  5358. callq read_int
  5359. movq %rax, tmp7951
  5360. cmpq $1, tmp7951
  5361. je block7952
  5362. jmp block7953
  5363. block7953:
  5364. movq $0, %rax
  5365. jmp conclusion
  5366. block7952:
  5367. movq $42, %rax
  5368. jmp conclusion
  5369. \end{lstlisting}
  5370. \end{minipage}
  5371. &
  5372. $\Rightarrow\qquad$
  5373. \begin{minipage}{0.4\textwidth}
  5374. \begin{lstlisting}
  5375. start:
  5376. callq read_int
  5377. movq %rax, %rcx
  5378. cmpq $1, %rcx
  5379. je block7952
  5380. jmp block7953
  5381. block7953:
  5382. movq $0, %rax
  5383. jmp conclusion
  5384. block7952:
  5385. movq $42, %rax
  5386. jmp conclusion
  5387. .globl main
  5388. main:
  5389. pushq %rbp
  5390. movq %rsp, %rbp
  5391. pushq %r13
  5392. pushq %r12
  5393. pushq %rbx
  5394. pushq %r14
  5395. subq $0, %rsp
  5396. jmp start
  5397. conclusion:
  5398. addq $0, %rsp
  5399. popq %r14
  5400. popq %rbx
  5401. popq %r12
  5402. popq %r13
  5403. popq %rbp
  5404. retq
  5405. \end{lstlisting}
  5406. \end{minipage}
  5407. \end{tabular}
  5408. \caption{Example compilation of an \key{if} expression to x86.}
  5409. \label{fig:if-example-x86}
  5410. \end{figure}
  5411. \section{Challenge: Remove Jumps}
  5412. \label{sec:opt-jumps}
  5413. %% Recall that in the example output of \code{explicate-control} in
  5414. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  5415. %% \code{block60} are trivial blocks, they do nothing but jump to another
  5416. %% block. The first goal of this challenge assignment is to remove those
  5417. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  5418. %% \code{explicate-control} on the left and shows the result of bypassing
  5419. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  5420. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  5421. %% \code{block55}. The optimized code on the right of
  5422. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  5423. %% \code{then} branch jumping directly to \code{block55}. The story is
  5424. %% similar for the \code{else} branch, as well as for the two branches in
  5425. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  5426. %% have been optimized in this way, there are no longer any jumps to
  5427. %% blocks \code{block57} through \code{block60}, so they can be removed.
  5428. %% \begin{figure}[tbp]
  5429. %% \begin{tabular}{lll}
  5430. %% \begin{minipage}{0.4\textwidth}
  5431. %% \begin{lstlisting}
  5432. %% block62:
  5433. %% tmp54 = (read);
  5434. %% if (eq? tmp54 2) then
  5435. %% goto block59;
  5436. %% else
  5437. %% goto block60;
  5438. %% block61:
  5439. %% tmp53 = (read);
  5440. %% if (eq? tmp53 0) then
  5441. %% goto block57;
  5442. %% else
  5443. %% goto block58;
  5444. %% block60:
  5445. %% goto block56;
  5446. %% block59:
  5447. %% goto block55;
  5448. %% block58:
  5449. %% goto block56;
  5450. %% block57:
  5451. %% goto block55;
  5452. %% block56:
  5453. %% return (+ 700 77);
  5454. %% block55:
  5455. %% return (+ 10 32);
  5456. %% start:
  5457. %% tmp52 = (read);
  5458. %% if (eq? tmp52 1) then
  5459. %% goto block61;
  5460. %% else
  5461. %% goto block62;
  5462. %% \end{lstlisting}
  5463. %% \end{minipage}
  5464. %% &
  5465. %% $\Rightarrow$
  5466. %% &
  5467. %% \begin{minipage}{0.55\textwidth}
  5468. %% \begin{lstlisting}
  5469. %% block62:
  5470. %% tmp54 = (read);
  5471. %% if (eq? tmp54 2) then
  5472. %% goto block55;
  5473. %% else
  5474. %% goto block56;
  5475. %% block61:
  5476. %% tmp53 = (read);
  5477. %% if (eq? tmp53 0) then
  5478. %% goto block55;
  5479. %% else
  5480. %% goto block56;
  5481. %% block56:
  5482. %% return (+ 700 77);
  5483. %% block55:
  5484. %% return (+ 10 32);
  5485. %% start:
  5486. %% tmp52 = (read);
  5487. %% if (eq? tmp52 1) then
  5488. %% goto block61;
  5489. %% else
  5490. %% goto block62;
  5491. %% \end{lstlisting}
  5492. %% \end{minipage}
  5493. %% \end{tabular}
  5494. %% \caption{Optimize jumps by removing trivial blocks.}
  5495. %% \label{fig:optimize-jumps}
  5496. %% \end{figure}
  5497. %% The name of this pass is \code{optimize-jumps}. We recommend
  5498. %% implementing this pass in two phases. The first phrase builds a hash
  5499. %% table that maps labels to possibly improved labels. The second phase
  5500. %% changes the target of each \code{goto} to use the improved label. If
  5501. %% the label is for a trivial block, then the hash table should map the
  5502. %% label to the first non-trivial block that can be reached from this
  5503. %% label by jumping through trivial blocks. If the label is for a
  5504. %% non-trivial block, then the hash table should map the label to itself;
  5505. %% we do not want to change jumps to non-trivial blocks.
  5506. %% The first phase can be accomplished by constructing an empty hash
  5507. %% table, call it \code{short-cut}, and then iterating over the control
  5508. %% flow graph. Each time you encouter a block that is just a \code{goto},
  5509. %% then update the hash table, mapping the block's source to the target
  5510. %% of the \code{goto}. Also, the hash table may already have mapped some
  5511. %% labels to the block's source, to you must iterate through the hash
  5512. %% table and update all of those so that they instead map to the target
  5513. %% of the \code{goto}.
  5514. %% For the second phase, we recommend iterating through the $\Tail$ of
  5515. %% each block in the program, updating the target of every \code{goto}
  5516. %% according to the mapping in \code{short-cut}.
  5517. %% \begin{exercise}\normalfont
  5518. %% Implement the \code{optimize-jumps} pass as a transformation from
  5519. %% \LangCIf{} to \LangCIf{}, coming after the \code{explicate-control} pass.
  5520. %% Check that \code{optimize-jumps} removes trivial blocks in a few
  5521. %% example programs. Then check that your compiler still passes all of
  5522. %% your tests.
  5523. %% \end{exercise}
  5524. There is an opportunity for optimizing jumps that is apparent in the
  5525. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  5526. ends with a jump to \code{block7953} and there are no other jumps to
  5527. \code{block7953} in the rest of the program. In this situation we can
  5528. avoid the runtime overhead of this jump by merging \code{block7953}
  5529. into the preceding block, in this case the \code{start} block.
  5530. Figure~\ref{fig:remove-jumps} shows the output of
  5531. \code{select-instructions} on the left and the result of this
  5532. optimization on the right.
  5533. \begin{figure}[tbp]
  5534. \begin{tabular}{lll}
  5535. \begin{minipage}{0.5\textwidth}
  5536. % cond_test_20.rkt
  5537. \begin{lstlisting}
  5538. start:
  5539. callq read_int
  5540. movq %rax, tmp7951
  5541. cmpq $1, tmp7951
  5542. je block7952
  5543. jmp block7953
  5544. block7953:
  5545. movq $0, %rax
  5546. jmp conclusion
  5547. block7952:
  5548. movq $42, %rax
  5549. jmp conclusion
  5550. \end{lstlisting}
  5551. \end{minipage}
  5552. &
  5553. $\Rightarrow\qquad$
  5554. \begin{minipage}{0.4\textwidth}
  5555. \begin{lstlisting}
  5556. start:
  5557. callq read_int
  5558. movq %rax, tmp7951
  5559. cmpq $1, tmp7951
  5560. je block7952
  5561. movq $0, %rax
  5562. jmp conclusion
  5563. block7952:
  5564. movq $42, %rax
  5565. jmp conclusion
  5566. \end{lstlisting}
  5567. \end{minipage}
  5568. \end{tabular}
  5569. \caption{Merging basic blocks by removing unnecessary jumps.}
  5570. \label{fig:remove-jumps}
  5571. \end{figure}
  5572. \begin{exercise}\normalfont
  5573. %
  5574. Implement a pass named \code{remove-jumps} that merges basic blocks
  5575. into their preceding basic block, when there is only one preceding
  5576. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  5577. %
  5578. In the \code{run-tests.rkt} script, add the following entry to the
  5579. list of \code{passes} between \code{allocate-registers}
  5580. and \code{patch-instructions}.
  5581. \begin{lstlisting}
  5582. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  5583. \end{lstlisting}
  5584. Run this script to test your compiler.
  5585. %
  5586. Check that \code{remove-jumps} accomplishes the goal of merging basic
  5587. blocks on several test programs.
  5588. \end{exercise}
  5589. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5590. \chapter{Tuples and Garbage Collection}
  5591. \label{ch:Rvec}
  5592. \index{tuple}
  5593. \index{vector}
  5594. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  5595. all the IR grammars are spelled out! \\ --Jeremy}
  5596. \margincomment{\scriptsize Be more explicit about how to deal with
  5597. the root stack. \\ --Jeremy}
  5598. In this chapter we study the implementation of mutable tuples, called
  5599. vectors in Racket. This language feature is the first to use the
  5600. computer's \emph{heap}\index{heap} because the lifetime of a Racket
  5601. tuple is indefinite, that is, a tuple lives forever from the
  5602. programmer's viewpoint. Of course, from an implementer's viewpoint, it
  5603. is important to reclaim the space associated with a tuple when it is
  5604. no longer needed, which is why we also study \emph{garbage collection}
  5605. \emph{garbage collection} techniques in this chapter.
  5606. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  5607. interpreter and type checker. The \LangVec{} language extends the \LangIf{}
  5608. language of Chapter~\ref{ch:Rif} with vectors and Racket's
  5609. \code{void} value. The reason for including the later is that the
  5610. \code{vector-set!} operation returns a value of type
  5611. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  5612. called the \code{Unit} type in the programming languages
  5613. literature. Racket's \code{Void} type is inhabited by a single value
  5614. \code{void} which corresponds to \code{unit} or \code{()} in the
  5615. literature~\citep{Pierce:2002hj}.}.
  5616. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  5617. copying live objects back and forth between two halves of the
  5618. heap. The garbage collector requires coordination with the compiler so
  5619. that it can see all of the \emph{root} pointers, that is, pointers in
  5620. registers or on the procedure call stack.
  5621. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  5622. discuss all the necessary changes and additions to the compiler
  5623. passes, including a new compiler pass named \code{expose-allocation}.
  5624. \section{The \LangVec{} Language}
  5625. \label{sec:r3}
  5626. Figure~\ref{fig:Rvec-concrete-syntax} defines the concrete syntax for
  5627. \LangVec{} and Figure~\ref{fig:Rvec-syntax} defines the abstract syntax. The
  5628. \LangVec{} language includes three new forms: \code{vector} for creating a
  5629. tuple, \code{vector-ref} for reading an element of a tuple, and
  5630. \code{vector-set!} for writing to an element of a tuple. The program
  5631. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  5632. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  5633. the 3-tuple, demonstrating that tuples are first-class values. The
  5634. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  5635. of the \key{if} is taken. The element at index $0$ of \code{t} is
  5636. \code{40}, to which we add \code{2}, the element at index $0$ of the
  5637. 1-tuple. So the result of the program is \code{42}.
  5638. \begin{figure}[tbp]
  5639. \centering
  5640. \fbox{
  5641. \begin{minipage}{0.96\textwidth}
  5642. \[
  5643. \begin{array}{lcl}
  5644. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  5645. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \key{Void}\\
  5646. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  5647. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  5648. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5649. \mid \LP\key{and}\;\Exp\;\Exp\RP
  5650. \mid \LP\key{or}\;\Exp\;\Exp\RP
  5651. \mid \LP\key{not}\;\Exp\RP } \\
  5652. &\mid& \gray{ \LP\itm{cmp}\;\Exp\;\Exp\RP
  5653. \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  5654. &\mid& \LP\key{vector}\;\Exp\ldots\RP
  5655. \mid \LP\key{vector-length}\;\Exp\RP \\
  5656. &\mid& \LP\key{vector-ref}\;\Exp\;\Int\RP
  5657. \mid \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP \\
  5658. &\mid& \LP\key{void}\RP \mid \LP\key{has-type}~\Exp~\Type\RP\\
  5659. \LangVec{} &::=& \Exp
  5660. \end{array}
  5661. \]
  5662. \end{minipage}
  5663. }
  5664. \caption{The concrete syntax of \LangVec{}, extending \LangIf{}
  5665. (Figure~\ref{fig:Rif-concrete-syntax}).}
  5666. \label{fig:Rvec-concrete-syntax}
  5667. \end{figure}
  5668. \begin{figure}[tbp]
  5669. \begin{lstlisting}
  5670. (let ([t (vector 40 #t (vector 2))])
  5671. (if (vector-ref t 1)
  5672. (+ (vector-ref t 0)
  5673. (vector-ref (vector-ref t 2) 0))
  5674. 44))
  5675. \end{lstlisting}
  5676. \caption{Example program that creates tuples and reads from them.}
  5677. \label{fig:vector-eg}
  5678. \end{figure}
  5679. \begin{figure}[tp]
  5680. \centering
  5681. \fbox{
  5682. \begin{minipage}{0.96\textwidth}
  5683. \[
  5684. \begin{array}{lcl}
  5685. \itm{op} &::=& \ldots \mid \code{vector} \mid \code{vector-length} \\
  5686. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  5687. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots}
  5688. \mid \BOOL{\itm{bool}}
  5689. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  5690. &\mid& \VECREF{\Exp}{\INT{\Int}}\\
  5691. &\mid& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  5692. &\mid& \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP \\
  5693. \LangVec{} &::=& \PROGRAM{\key{'()}}{\Exp}
  5694. \end{array}
  5695. \]
  5696. \end{minipage}
  5697. }
  5698. \caption{The abstract syntax of \LangVec{}.}
  5699. \label{fig:Rvec-syntax}
  5700. \end{figure}
  5701. \index{allocate}
  5702. \index{heap allocate}
  5703. Tuples are our first encounter with heap-allocated data, which raises
  5704. several interesting issues. First, variable binding performs a
  5705. shallow-copy when dealing with tuples, which means that different
  5706. variables can refer to the same tuple, that is, different variables
  5707. can be \emph{aliases} for the same entity. Consider the following
  5708. example in which both \code{t1} and \code{t2} refer to the same tuple.
  5709. Thus, the mutation through \code{t2} is visible when referencing the
  5710. tuple from \code{t1}, so the result of this program is \code{42}.
  5711. \index{alias}\index{mutation}
  5712. \begin{center}
  5713. \begin{minipage}{0.96\textwidth}
  5714. \begin{lstlisting}
  5715. (let ([t1 (vector 3 7)])
  5716. (let ([t2 t1])
  5717. (let ([_ (vector-set! t2 0 42)])
  5718. (vector-ref t1 0))))
  5719. \end{lstlisting}
  5720. \end{minipage}
  5721. \end{center}
  5722. The next issue concerns the lifetime of tuples. Of course, they are
  5723. created by the \code{vector} form, but when does their lifetime end?
  5724. Notice that \LangVec{} does not include an operation for deleting
  5725. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  5726. of static scoping. For example, the following program returns
  5727. \code{42} even though the variable \code{w} goes out of scope prior to
  5728. the \code{vector-ref} that reads from the vector it was bound to.
  5729. \begin{center}
  5730. \begin{minipage}{0.96\textwidth}
  5731. \begin{lstlisting}
  5732. (let ([v (vector (vector 44))])
  5733. (let ([x (let ([w (vector 42)])
  5734. (let ([_ (vector-set! v 0 w)])
  5735. 0))])
  5736. (+ x (vector-ref (vector-ref v 0) 0))))
  5737. \end{lstlisting}
  5738. \end{minipage}
  5739. \end{center}
  5740. From the perspective of programmer-observable behavior, tuples live
  5741. forever. Of course, if they really lived forever, then many programs
  5742. would run out of memory.\footnote{The \LangVec{} language does not have
  5743. looping or recursive functions, so it is nigh impossible to write a
  5744. program in \LangVec{} that will run out of memory. However, we add
  5745. recursive functions in the next Chapter!} A Racket implementation
  5746. must therefore perform automatic garbage collection.
  5747. Figure~\ref{fig:interp-Rvec} shows the definitional interpreter for the
  5748. \LangVec{} language. We define the \code{vector}, \code{vector-length},
  5749. \code{vector-ref}, and \code{vector-set!} operations for \LangVec{} in
  5750. terms of the corresponding operations in Racket. One subtle point is
  5751. that the \code{vector-set!} operation returns the \code{\#<void>}
  5752. value. The \code{\#<void>} value can be passed around just like other
  5753. values inside an \LangVec{} program and a \code{\#<void>} value can be
  5754. compared for equality with another \code{\#<void>} value. However,
  5755. there are no other operations specific to the the \code{\#<void>}
  5756. value in \LangVec{}. In contrast, Racket defines the \code{void?} predicate
  5757. that returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  5758. otherwise.
  5759. \begin{figure}[tbp]
  5760. \begin{lstlisting}
  5761. (define interp-Rvec-class
  5762. (class interp-Rif-class
  5763. (super-new)
  5764. (define/override (interp-op op)
  5765. (match op
  5766. ['eq? (lambda (v1 v2)
  5767. (cond [(or (and (fixnum? v1) (fixnum? v2))
  5768. (and (boolean? v1) (boolean? v2))
  5769. (and (vector? v1) (vector? v2))
  5770. (and (void? v1) (void? v2)))
  5771. (eq? v1 v2)]))]
  5772. ['vector vector]
  5773. ['vector-length vector-length]
  5774. ['vector-ref vector-ref]
  5775. ['vector-set! vector-set!]
  5776. [else (super interp-op op)]
  5777. ))
  5778. (define/override ((interp-exp env) e)
  5779. (define recur (interp-exp env))
  5780. (match e
  5781. [(HasType e t) (recur e)]
  5782. [(Void) (void)]
  5783. [else ((super interp-exp env) e)]
  5784. ))
  5785. ))
  5786. (define (interp-Rvec p)
  5787. (send (new interp-Rvec-class) interp-program p))
  5788. \end{lstlisting}
  5789. \caption{Interpreter for the \LangVec{} language.}
  5790. \label{fig:interp-Rvec}
  5791. \end{figure}
  5792. Figure~\ref{fig:type-check-Rvec} shows the type checker for \LangVec{}, which
  5793. deserves some explanation. When allocating a vector, we need to know
  5794. which elements of the vector are pointers (i.e. are also vectors). We
  5795. can obtain this information during type checking. The type checker in
  5796. Figure~\ref{fig:type-check-Rvec} not only computes the type of an
  5797. expression, it also wraps every \key{vector} creation with the form
  5798. $(\key{HasType}~e~T)$, where $T$ is the vector's type.
  5799. %
  5800. To create the s-expression for the \code{Vector} type in
  5801. Figure~\ref{fig:type-check-Rvec}, we use the
  5802. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  5803. operator} \code{,@} to insert the list \code{t*} without its usual
  5804. start and end parentheses. \index{unquote-slicing}
  5805. \begin{figure}[tp]
  5806. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5807. (define type-check-Rvec-class
  5808. (class type-check-Rif-class
  5809. (super-new)
  5810. (inherit check-type-equal?)
  5811. (define/override (type-check-exp env)
  5812. (lambda (e)
  5813. (define recur (type-check-exp env))
  5814. (match e
  5815. [(Void) (values (Void) 'Void)]
  5816. [(Prim 'vector es)
  5817. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  5818. (define t `(Vector ,@t*))
  5819. (values (HasType (Prim 'vector e*) t) t)]
  5820. [(Prim 'vector-ref (list e1 (Int i)))
  5821. (define-values (e1^ t) (recur e1))
  5822. (match t
  5823. [`(Vector ,ts ...)
  5824. (unless (and (0 . <= . i) (i . < . (length ts)))
  5825. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  5826. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  5827. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  5828. [(Prim 'vector-set! (list e1 (Int i) arg) )
  5829. (define-values (e-vec t-vec) (recur e1))
  5830. (define-values (e-arg^ t-arg) (recur arg))
  5831. (match t-vec
  5832. [`(Vector ,ts ...)
  5833. (unless (and (0 . <= . i) (i . < . (length ts)))
  5834. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  5835. (check-type-equal? (list-ref ts i) t-arg e)
  5836. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  5837. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  5838. [(Prim 'vector-length (list e))
  5839. (define-values (e^ t) (recur e))
  5840. (match t
  5841. [`(Vector ,ts ...)
  5842. (values (Prim 'vector-length (list e^)) 'Integer)]
  5843. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  5844. [(Prim 'eq? (list arg1 arg2))
  5845. (define-values (e1 t1) (recur arg1))
  5846. (define-values (e2 t2) (recur arg2))
  5847. (match* (t1 t2)
  5848. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  5849. [(other wise) (check-type-equal? t1 t2 e)])
  5850. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  5851. [(HasType (Prim 'vector es) t)
  5852. ((type-check-exp env) (Prim 'vector es))]
  5853. [(HasType e1 t)
  5854. (define-values (e1^ t^) (recur e1))
  5855. (check-type-equal? t t^ e)
  5856. (values (HasType e1^ t) t)]
  5857. [else ((super type-check-exp env) e)]
  5858. )))
  5859. ))
  5860. (define (type-check-Rvec p)
  5861. (send (new type-check-Rvec-class) type-check-program p))
  5862. \end{lstlisting}
  5863. \caption{Type checker for the \LangVec{} language.}
  5864. \label{fig:type-check-Rvec}
  5865. \end{figure}
  5866. \section{Garbage Collection}
  5867. \label{sec:GC}
  5868. Here we study a relatively simple algorithm for garbage collection
  5869. that is the basis of state-of-the-art garbage
  5870. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  5871. particular, we describe a two-space copying
  5872. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  5873. perform the
  5874. copy~\citep{Cheney:1970aa}.
  5875. \index{copying collector}
  5876. \index{two-space copying collector}
  5877. Figure~\ref{fig:copying-collector} gives a
  5878. coarse-grained depiction of what happens in a two-space collector,
  5879. showing two time steps, prior to garbage collection (on the top) and
  5880. after garbage collection (on the bottom). In a two-space collector,
  5881. the heap is divided into two parts named the FromSpace and the
  5882. ToSpace. Initially, all allocations go to the FromSpace until there is
  5883. not enough room for the next allocation request. At that point, the
  5884. garbage collector goes to work to make more room.
  5885. \index{ToSpace}
  5886. \index{FromSpace}
  5887. The garbage collector must be careful not to reclaim tuples that will
  5888. be used by the program in the future. Of course, it is impossible in
  5889. general to predict what a program will do, but we can over approximate
  5890. the will-be-used tuples by preserving all tuples that could be
  5891. accessed by \emph{any} program given the current computer state. A
  5892. program could access any tuple whose address is in a register or on
  5893. the procedure call stack. These addresses are called the \emph{root
  5894. set}\index{root set}. In addition, a program could access any tuple that is
  5895. transitively reachable from the root set. Thus, it is safe for the
  5896. garbage collector to reclaim the tuples that are not reachable in this
  5897. way.
  5898. So the goal of the garbage collector is twofold:
  5899. \begin{enumerate}
  5900. \item preserve all tuple that are reachable from the root set via a
  5901. path of pointers, that is, the \emph{live} tuples, and
  5902. \item reclaim the memory of everything else, that is, the
  5903. \emph{garbage}.
  5904. \end{enumerate}
  5905. A copying collector accomplishes this by copying all of the live
  5906. objects from the FromSpace into the ToSpace and then performs a sleight
  5907. of hand, treating the ToSpace as the new FromSpace and the old
  5908. FromSpace as the new ToSpace. In the example of
  5909. Figure~\ref{fig:copying-collector}, there are three pointers in the
  5910. root set, one in a register and two on the stack. All of the live
  5911. objects have been copied to the ToSpace (the right-hand side of
  5912. Figure~\ref{fig:copying-collector}) in a way that preserves the
  5913. pointer relationships. For example, the pointer in the register still
  5914. points to a 2-tuple whose first element is a 3-tuple and whose second
  5915. element is a 2-tuple. There are four tuples that are not reachable
  5916. from the root set and therefore do not get copied into the ToSpace.
  5917. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  5918. created by a well-typed program in \LangVec{} because it contains a
  5919. cycle. However, creating cycles will be possible once we get to \LangAny{}.
  5920. We design the garbage collector to deal with cycles to begin with so
  5921. we will not need to revisit this issue.
  5922. \begin{figure}[tbp]
  5923. \centering
  5924. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  5925. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  5926. \caption{A copying collector in action.}
  5927. \label{fig:copying-collector}
  5928. \end{figure}
  5929. There are many alternatives to copying collectors (and their bigger
  5930. siblings, the generational collectors) when its comes to garbage
  5931. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  5932. reference counting~\citep{Collins:1960aa}. The strengths of copying
  5933. collectors are that allocation is fast (just a comparison and pointer
  5934. increment), there is no fragmentation, cyclic garbage is collected,
  5935. and the time complexity of collection only depends on the amount of
  5936. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  5937. main disadvantages of a two-space copying collector is that it uses a
  5938. lot of space and takes a long time to perform the copy, though these
  5939. problems are ameliorated in generational collectors. Racket and
  5940. Scheme programs tend to allocate many small objects and generate a lot
  5941. of garbage, so copying and generational collectors are a good fit.
  5942. Garbage collection is an active research topic, especially concurrent
  5943. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  5944. developing new techniques and revisiting old
  5945. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  5946. meet every year at the International Symposium on Memory Management to
  5947. present these findings.
  5948. \subsection{Graph Copying via Cheney's Algorithm}
  5949. \label{sec:cheney}
  5950. \index{Cheney's algorithm}
  5951. Let us take a closer look at the copying of the live objects. The
  5952. allocated objects and pointers can be viewed as a graph and we need to
  5953. copy the part of the graph that is reachable from the root set. To
  5954. make sure we copy all of the reachable vertices in the graph, we need
  5955. an exhaustive graph traversal algorithm, such as depth-first search or
  5956. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  5957. such algorithms take into account the possibility of cycles by marking
  5958. which vertices have already been visited, so as to ensure termination
  5959. of the algorithm. These search algorithms also use a data structure
  5960. such as a stack or queue as a to-do list to keep track of the vertices
  5961. that need to be visited. We use breadth-first search and a trick
  5962. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  5963. and copying tuples into the ToSpace.
  5964. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  5965. copy progresses. The queue is represented by a chunk of contiguous
  5966. memory at the beginning of the ToSpace, using two pointers to track
  5967. the front and the back of the queue. The algorithm starts by copying
  5968. all tuples that are immediately reachable from the root set into the
  5969. ToSpace to form the initial queue. When we copy a tuple, we mark the
  5970. old tuple to indicate that it has been visited. We discuss how this
  5971. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  5972. pointers inside the copied tuples in the queue still point back to the
  5973. FromSpace. Once the initial queue has been created, the algorithm
  5974. enters a loop in which it repeatedly processes the tuple at the front
  5975. of the queue and pops it off the queue. To process a tuple, the
  5976. algorithm copies all the tuple that are directly reachable from it to
  5977. the ToSpace, placing them at the back of the queue. The algorithm then
  5978. updates the pointers in the popped tuple so they point to the newly
  5979. copied tuples.
  5980. \begin{figure}[tbp]
  5981. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  5982. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  5983. \label{fig:cheney}
  5984. \end{figure}
  5985. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  5986. tuple whose second element is $42$ to the back of the queue. The other
  5987. pointer goes to a tuple that has already been copied, so we do not
  5988. need to copy it again, but we do need to update the pointer to the new
  5989. location. This can be accomplished by storing a \emph{forwarding
  5990. pointer} to the new location in the old tuple, back when we initially
  5991. copied the tuple into the ToSpace. This completes one step of the
  5992. algorithm. The algorithm continues in this way until the front of the
  5993. queue is empty, that is, until the front catches up with the back.
  5994. \subsection{Data Representation}
  5995. \label{sec:data-rep-gc}
  5996. The garbage collector places some requirements on the data
  5997. representations used by our compiler. First, the garbage collector
  5998. needs to distinguish between pointers and other kinds of data. There
  5999. are several ways to accomplish this.
  6000. \begin{enumerate}
  6001. \item Attached a tag to each object that identifies what type of
  6002. object it is~\citep{McCarthy:1960dz}.
  6003. \item Store different types of objects in different
  6004. regions~\citep{Steele:1977ab}.
  6005. \item Use type information from the program to either generate
  6006. type-specific code for collecting or to generate tables that can
  6007. guide the
  6008. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  6009. \end{enumerate}
  6010. Dynamically typed languages, such as Lisp, need to tag objects
  6011. anyways, so option 1 is a natural choice for those languages.
  6012. However, \LangVec{} is a statically typed language, so it would be
  6013. unfortunate to require tags on every object, especially small and
  6014. pervasive objects like integers and Booleans. Option 3 is the
  6015. best-performing choice for statically typed languages, but comes with
  6016. a relatively high implementation complexity. To keep this chapter
  6017. within a 2-week time budget, we recommend a combination of options 1
  6018. and 2, using separate strategies for the stack and the heap.
  6019. Regarding the stack, we recommend using a separate stack for pointers,
  6020. which we call a \emph{root stack}\index{root stack} (a.k.a. ``shadow
  6021. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  6022. is, when a local variable needs to be spilled and is of type
  6023. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  6024. stack instead of the normal procedure call stack. Furthermore, we
  6025. always spill vector-typed variables if they are live during a call to
  6026. the collector, thereby ensuring that no pointers are in registers
  6027. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  6028. example from Figure~\ref{fig:copying-collector} and contrasts it with
  6029. the data layout using a root stack. The root stack contains the two
  6030. pointers from the regular stack and also the pointer in the second
  6031. register.
  6032. \begin{figure}[tbp]
  6033. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  6034. \caption{Maintaining a root stack to facilitate garbage collection.}
  6035. \label{fig:shadow-stack}
  6036. \end{figure}
  6037. The problem of distinguishing between pointers and other kinds of data
  6038. also arises inside of each tuple on the heap. We solve this problem by
  6039. attaching a tag, an extra 64-bits, to each
  6040. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  6041. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  6042. that we have drawn the bits in a big-endian way, from right-to-left,
  6043. with bit location 0 (the least significant bit) on the far right,
  6044. which corresponds to the direction of the x86 shifting instructions
  6045. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  6046. is dedicated to specifying which elements of the tuple are pointers,
  6047. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  6048. indicates there is a pointer and a 0 bit indicates some other kind of
  6049. data. The pointer mask starts at bit location 7. We have limited
  6050. tuples to a maximum size of 50 elements, so we just need 50 bits for
  6051. the pointer mask. The tag also contains two other pieces of
  6052. information. The length of the tuple (number of elements) is stored in
  6053. bits location 1 through 6. Finally, the bit at location 0 indicates
  6054. whether the tuple has yet to be copied to the ToSpace. If the bit has
  6055. value 1, then this tuple has not yet been copied. If the bit has
  6056. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  6057. of a pointer are always zero anyways because our tuples are 8-byte
  6058. aligned.)
  6059. \begin{figure}[tbp]
  6060. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  6061. \caption{Representation of tuples in the heap.}
  6062. \label{fig:tuple-rep}
  6063. \end{figure}
  6064. \subsection{Implementation of the Garbage Collector}
  6065. \label{sec:organize-gz}
  6066. \index{prelude}
  6067. An implementation of the copying collector is provided in the
  6068. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  6069. interface to the garbage collector that is used by the compiler. The
  6070. \code{initialize} function creates the FromSpace, ToSpace, and root
  6071. stack and should be called in the prelude of the \code{main}
  6072. function. The arguments of \code{initialize} are the root stack size
  6073. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  6074. good choice for both. The \code{initialize} function puts the address
  6075. of the beginning of the FromSpace into the global variable
  6076. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  6077. the address that is 1-past the last element of the FromSpace. (We use
  6078. half-open intervals to represent chunks of
  6079. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  6080. points to the first element of the root stack.
  6081. As long as there is room left in the FromSpace, your generated code
  6082. can allocate tuples simply by moving the \code{free\_ptr} forward.
  6083. %
  6084. The amount of room left in FromSpace is the difference between the
  6085. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  6086. function should be called when there is not enough room left in the
  6087. FromSpace for the next allocation. The \code{collect} function takes
  6088. a pointer to the current top of the root stack (one past the last item
  6089. that was pushed) and the number of bytes that need to be
  6090. allocated. The \code{collect} function performs the copying collection
  6091. and leaves the heap in a state such that the next allocation will
  6092. succeed.
  6093. \begin{figure}[tbp]
  6094. \begin{lstlisting}
  6095. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  6096. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  6097. int64_t* free_ptr;
  6098. int64_t* fromspace_begin;
  6099. int64_t* fromspace_end;
  6100. int64_t** rootstack_begin;
  6101. \end{lstlisting}
  6102. \caption{The compiler's interface to the garbage collector.}
  6103. \label{fig:gc-header}
  6104. \end{figure}
  6105. %% \begin{exercise}
  6106. %% In the file \code{runtime.c} you will find the implementation of
  6107. %% \code{initialize} and a partial implementation of \code{collect}.
  6108. %% The \code{collect} function calls another function, \code{cheney},
  6109. %% to perform the actual copy, and that function is left to the reader
  6110. %% to implement. The following is the prototype for \code{cheney}.
  6111. %% \begin{lstlisting}
  6112. %% static void cheney(int64_t** rootstack_ptr);
  6113. %% \end{lstlisting}
  6114. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  6115. %% rootstack (which is an array of pointers). The \code{cheney} function
  6116. %% also communicates with \code{collect} through the global
  6117. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  6118. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  6119. %% the ToSpace:
  6120. %% \begin{lstlisting}
  6121. %% static int64_t* tospace_begin;
  6122. %% static int64_t* tospace_end;
  6123. %% \end{lstlisting}
  6124. %% The job of the \code{cheney} function is to copy all the live
  6125. %% objects (reachable from the root stack) into the ToSpace, update
  6126. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  6127. %% update the root stack so that it points to the objects in the
  6128. %% ToSpace, and finally to swap the global pointers for the FromSpace
  6129. %% and ToSpace.
  6130. %% \end{exercise}
  6131. %% \section{Compiler Passes}
  6132. %% \label{sec:code-generation-gc}
  6133. The introduction of garbage collection has a non-trivial impact on our
  6134. compiler passes. We introduce a new compiler pass named
  6135. \code{expose-allocation}. We make
  6136. significant changes to \code{select-instructions},
  6137. \code{build-interference}, \code{allocate-registers}, and
  6138. \code{print-x86} and make minor changes in several more passes. The
  6139. following program will serve as our running example. It creates two
  6140. tuples, one nested inside the other. Both tuples have length one. The
  6141. program accesses the element in the inner tuple tuple via two vector
  6142. references.
  6143. % tests/s2_17.rkt
  6144. \begin{lstlisting}
  6145. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  6146. \end{lstlisting}
  6147. \section{Shrink}
  6148. \label{sec:shrink-Rvec}
  6149. Recall that the \code{shrink} pass translates the primitives operators
  6150. into a smaller set of primitives. Because this pass comes after type
  6151. checking, but before the passes that require the type information in
  6152. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  6153. to wrap \code{HasType} around each AST node that it generates.
  6154. \section{Expose Allocation}
  6155. \label{sec:expose-allocation}
  6156. The pass \code{expose-allocation} lowers the \code{vector} creation
  6157. form into a conditional call to the collector followed by the
  6158. allocation. We choose to place the \code{expose-allocation} pass
  6159. before \code{remove-complex-opera*} because the code generated by
  6160. \code{expose-allocation} contains complex operands. We also place
  6161. \code{expose-allocation} before \code{explicate-control} because
  6162. \code{expose-allocation} introduces new variables using \code{let},
  6163. but \code{let} is gone after \code{explicate-control}.
  6164. The output of \code{expose-allocation} is a language \LangAlloc{} that
  6165. extends \LangVec{} with the three new forms that we use in the translation
  6166. of the \code{vector} form.
  6167. \[
  6168. \begin{array}{lcl}
  6169. \Exp &::=& \cdots
  6170. \mid (\key{collect} \,\itm{int})
  6171. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  6172. \mid (\key{global-value} \,\itm{name})
  6173. \end{array}
  6174. \]
  6175. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  6176. $n$ bytes. It will become a call to the \code{collect} function in
  6177. \code{runtime.c} in \code{select-instructions}. The
  6178. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  6179. \index{allocate}
  6180. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  6181. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  6182. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  6183. a global variable, such as \code{free\_ptr}.
  6184. In the following, we show the transformation for the \code{vector}
  6185. form into 1) a sequence of let-bindings for the initializing
  6186. expressions, 2) a conditional call to \code{collect}, 3) a call to
  6187. \code{allocate}, and 4) the initialization of the vector. In the
  6188. following, \itm{len} refers to the length of the vector and
  6189. \itm{bytes} is how many total bytes need to be allocated for the
  6190. vector, which is 8 for the tag plus \itm{len} times 8.
  6191. \begin{lstlisting}
  6192. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  6193. |$\Longrightarrow$|
  6194. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  6195. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  6196. (global-value fromspace_end))
  6197. (void)
  6198. (collect |\itm{bytes}|))])
  6199. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  6200. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  6201. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  6202. |$v$|) ... )))) ...)
  6203. \end{lstlisting}
  6204. In the above, we suppressed all of the \code{has-type} forms in the
  6205. output for the sake of readability. The placement of the initializing
  6206. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  6207. sequence of \code{vector-set!} is important, as those expressions may
  6208. trigger garbage collection and we cannot have an allocated but
  6209. uninitialized tuple on the heap during a collection.
  6210. Figure~\ref{fig:expose-alloc-output} shows the output of the
  6211. \code{expose-allocation} pass on our running example.
  6212. \begin{figure}[tbp]
  6213. % tests/s2_17.rkt
  6214. \begin{lstlisting}
  6215. (vector-ref
  6216. (vector-ref
  6217. (let ([vecinit7976
  6218. (let ([vecinit7972 42])
  6219. (let ([collectret7974
  6220. (if (< (+ (global-value free_ptr) 16)
  6221. (global-value fromspace_end))
  6222. (void)
  6223. (collect 16)
  6224. )])
  6225. (let ([alloc7971 (allocate 1 (Vector Integer))])
  6226. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  6227. alloc7971)
  6228. )
  6229. )
  6230. )
  6231. ])
  6232. (let ([collectret7978
  6233. (if (< (+ (global-value free_ptr) 16)
  6234. (global-value fromspace_end))
  6235. (void)
  6236. (collect 16)
  6237. )])
  6238. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  6239. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  6240. alloc7975)
  6241. )
  6242. )
  6243. )
  6244. 0)
  6245. 0)
  6246. \end{lstlisting}
  6247. \caption{Output of the \code{expose-allocation} pass, minus
  6248. all of the \code{has-type} forms.}
  6249. \label{fig:expose-alloc-output}
  6250. \end{figure}
  6251. \section{Remove Complex Operands}
  6252. \label{sec:remove-complex-opera-Rvec}
  6253. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  6254. should all be treated as complex operands.
  6255. %% A new case for
  6256. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  6257. %% handled carefully to prevent the \code{Prim} node from being separated
  6258. %% from its enclosing \code{HasType}.
  6259. Figure~\ref{fig:Rvec-anf-syntax}
  6260. shows the grammar for the output language \LangVecANF{} of this
  6261. pass, which is \LangVec{} in administrative normal form.
  6262. \begin{figure}[tp]
  6263. \centering
  6264. \fbox{
  6265. \begin{minipage}{0.96\textwidth}
  6266. \small
  6267. \[
  6268. \begin{array}{rcl}
  6269. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }
  6270. \mid \VOID{} \\
  6271. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  6272. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  6273. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  6274. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  6275. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  6276. &\mid& \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  6277. \mid \LP\key{GlobalValue}~\Var\RP\\
  6278. % &\mid& \LP\key{HasType}~\Exp~\Type\RP \\
  6279. R^{\dagger}_3 &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  6280. \end{array}
  6281. \]
  6282. \end{minipage}
  6283. }
  6284. \caption{\LangVecANF{} is \LangVec{} in administrative normal form (ANF).}
  6285. \label{fig:Rvec-anf-syntax}
  6286. \end{figure}
  6287. \section{Explicate Control and the \LangCVec{} language}
  6288. \label{sec:explicate-control-r3}
  6289. \begin{figure}[tp]
  6290. \fbox{
  6291. \begin{minipage}{0.96\textwidth}
  6292. \small
  6293. \[
  6294. \begin{array}{lcl}
  6295. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  6296. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  6297. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  6298. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  6299. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  6300. &\mid& \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  6301. &\mid& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  6302. &\mid& \LP\key{Prim}~\key{'vector-set!}\,\LP\Atm\,\INT{\Int}\,\Atm\RP\RP\\
  6303. &\mid& \LP\key{GlobalValue} \,\Var\RP \mid \LP\key{Void}\RP\\
  6304. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  6305. \mid \LP\key{Collect} \,\itm{int}\RP \\
  6306. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  6307. \mid \GOTO{\itm{label}} } \\
  6308. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  6309. \LangCVec{} & ::= & \gray{ \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }
  6310. \end{array}
  6311. \]
  6312. \end{minipage}
  6313. }
  6314. \caption{The abstract syntax of \LangCVec{}, extending \LangCIf{}
  6315. (Figure~\ref{fig:c1-syntax}).}
  6316. \label{fig:c2-syntax}
  6317. \end{figure}
  6318. The output of \code{explicate-control} is a program in the
  6319. intermediate language \LangCVec{}, whose abstract syntax is defined in
  6320. Figure~\ref{fig:c2-syntax}. (The concrete syntax is defined in
  6321. Figure~\ref{fig:c2-concrete-syntax} of the Appendix.) The new forms
  6322. of \LangCVec{} include the \key{allocate}, \key{vector-ref}, and
  6323. \key{vector-set!}, and \key{global-value} expressions and the
  6324. \code{collect} statement. The \code{explicate-control} pass can treat
  6325. these new forms much like the other expression forms that we've
  6326. already encoutered.
  6327. \section{Select Instructions and the \LangXGlobal{} Language}
  6328. \label{sec:select-instructions-gc}
  6329. \index{instruction selection}
  6330. %% void (rep as zero)
  6331. %% allocate
  6332. %% collect (callq collect)
  6333. %% vector-ref
  6334. %% vector-set!
  6335. %% global (postpone)
  6336. In this pass we generate x86 code for most of the new operations that
  6337. were needed to compile tuples, including \code{Allocate},
  6338. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  6339. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  6340. the later has a different concrete syntax (see
  6341. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  6342. \index{x86}
  6343. The \code{vector-ref} and \code{vector-set!} forms translate into
  6344. \code{movq} instructions. (The plus one in the offset is to get past
  6345. the tag at the beginning of the tuple representation.)
  6346. \begin{lstlisting}
  6347. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  6348. |$\Longrightarrow$|
  6349. movq |$\itm{vec}'$|, %r11
  6350. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  6351. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  6352. |$\Longrightarrow$|
  6353. movq |$\itm{vec}'$|, %r11
  6354. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  6355. movq $0, |$\itm{lhs'}$|
  6356. \end{lstlisting}
  6357. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  6358. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  6359. register \code{r11} ensures that offset expression
  6360. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  6361. removing \code{r11} from consideration by the register allocating.
  6362. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  6363. \code{rax}. Then the generated code for \code{vector-set!} would be
  6364. \begin{lstlisting}
  6365. movq |$\itm{vec}'$|, %rax
  6366. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  6367. movq $0, |$\itm{lhs}'$|
  6368. \end{lstlisting}
  6369. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  6370. \code{patch-instructions} would insert a move through \code{rax}
  6371. as follows.
  6372. \begin{lstlisting}
  6373. movq |$\itm{vec}'$|, %rax
  6374. movq |$\itm{arg}'$|, %rax
  6375. movq %rax, |$8(n+1)$|(%rax)
  6376. movq $0, |$\itm{lhs}'$|
  6377. \end{lstlisting}
  6378. But the above sequence of instructions does not work because we're
  6379. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  6380. $\itm{arg}'$) at the same time!
  6381. We compile the \code{allocate} form to operations on the
  6382. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  6383. is the next free address in the FromSpace, so we copy it into
  6384. \code{r11} and then move it forward by enough space for the tuple
  6385. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  6386. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  6387. initialize the \itm{tag} and finally copy the address in \code{r11} to
  6388. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  6389. tag is organized. We recommend using the Racket operations
  6390. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  6391. during compilation. The type annotation in the \code{vector} form is
  6392. used to determine the pointer mask region of the tag.
  6393. \begin{lstlisting}
  6394. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  6395. |$\Longrightarrow$|
  6396. movq free_ptr(%rip), %r11
  6397. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  6398. movq $|$\itm{tag}$|, 0(%r11)
  6399. movq %r11, |$\itm{lhs}'$|
  6400. \end{lstlisting}
  6401. The \code{collect} form is compiled to a call to the \code{collect}
  6402. function in the runtime. The arguments to \code{collect} are 1) the
  6403. top of the root stack and 2) the number of bytes that need to be
  6404. allocated. We use another dedicated register, \code{r15}, to
  6405. store the pointer to the top of the root stack. So \code{r15} is not
  6406. available for use by the register allocator.
  6407. \begin{lstlisting}
  6408. (collect |$\itm{bytes}$|)
  6409. |$\Longrightarrow$|
  6410. movq %r15, %rdi
  6411. movq $|\itm{bytes}|, %rsi
  6412. callq collect
  6413. \end{lstlisting}
  6414. \begin{figure}[tp]
  6415. \fbox{
  6416. \begin{minipage}{0.96\textwidth}
  6417. \[
  6418. \begin{array}{lcl}
  6419. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)} \\
  6420. \LangXGlobal{} &::= & \gray{ \key{.globl main} }\\
  6421. & & \gray{ \key{main:} \; \Instr\ldots }
  6422. \end{array}
  6423. \]
  6424. \end{minipage}
  6425. }
  6426. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  6427. \label{fig:x86-2-concrete}
  6428. \end{figure}
  6429. \begin{figure}[tp]
  6430. \fbox{
  6431. \begin{minipage}{0.96\textwidth}
  6432. \small
  6433. \[
  6434. \begin{array}{lcl}
  6435. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  6436. \mid \BYTEREG{\Reg}} \\
  6437. &\mid& (\key{Global}~\Var) \\
  6438. \LangXGlobal{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  6439. \end{array}
  6440. \]
  6441. \end{minipage}
  6442. }
  6443. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  6444. \label{fig:x86-2}
  6445. \end{figure}
  6446. The concrete and abstract syntax of the \LangXGlobal{} language is
  6447. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  6448. differs from \LangXIf{} just in the addition of the form for global
  6449. variables.
  6450. %
  6451. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  6452. \code{select-instructions} pass on the running example.
  6453. \begin{figure}[tbp]
  6454. \centering
  6455. % tests/s2_17.rkt
  6456. \begin{minipage}[t]{0.5\textwidth}
  6457. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6458. block35:
  6459. movq free_ptr(%rip), alloc9024
  6460. addq $16, free_ptr(%rip)
  6461. movq alloc9024, %r11
  6462. movq $131, 0(%r11)
  6463. movq alloc9024, %r11
  6464. movq vecinit9025, 8(%r11)
  6465. movq $0, initret9026
  6466. movq alloc9024, %r11
  6467. movq 8(%r11), tmp9034
  6468. movq tmp9034, %r11
  6469. movq 8(%r11), %rax
  6470. jmp conclusion
  6471. block36:
  6472. movq $0, collectret9027
  6473. jmp block35
  6474. block38:
  6475. movq free_ptr(%rip), alloc9020
  6476. addq $16, free_ptr(%rip)
  6477. movq alloc9020, %r11
  6478. movq $3, 0(%r11)
  6479. movq alloc9020, %r11
  6480. movq vecinit9021, 8(%r11)
  6481. movq $0, initret9022
  6482. movq alloc9020, vecinit9025
  6483. movq free_ptr(%rip), tmp9031
  6484. movq tmp9031, tmp9032
  6485. addq $16, tmp9032
  6486. movq fromspace_end(%rip), tmp9033
  6487. cmpq tmp9033, tmp9032
  6488. jl block36
  6489. jmp block37
  6490. block37:
  6491. movq %r15, %rdi
  6492. movq $16, %rsi
  6493. callq 'collect
  6494. jmp block35
  6495. block39:
  6496. movq $0, collectret9023
  6497. jmp block38
  6498. \end{lstlisting}
  6499. \end{minipage}
  6500. \begin{minipage}[t]{0.45\textwidth}
  6501. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6502. start:
  6503. movq $42, vecinit9021
  6504. movq free_ptr(%rip), tmp9028
  6505. movq tmp9028, tmp9029
  6506. addq $16, tmp9029
  6507. movq fromspace_end(%rip), tmp9030
  6508. cmpq tmp9030, tmp9029
  6509. jl block39
  6510. jmp block40
  6511. block40:
  6512. movq %r15, %rdi
  6513. movq $16, %rsi
  6514. callq 'collect
  6515. jmp block38
  6516. \end{lstlisting}
  6517. \end{minipage}
  6518. \caption{Output of the \code{select-instructions} pass.}
  6519. \label{fig:select-instr-output-gc}
  6520. \end{figure}
  6521. \clearpage
  6522. \section{Register Allocation}
  6523. \label{sec:reg-alloc-gc}
  6524. \index{register allocation}
  6525. As discussed earlier in this chapter, the garbage collector needs to
  6526. access all the pointers in the root set, that is, all variables that
  6527. are vectors. It will be the responsibility of the register allocator
  6528. to make sure that:
  6529. \begin{enumerate}
  6530. \item the root stack is used for spilling vector-typed variables, and
  6531. \item if a vector-typed variable is live during a call to the
  6532. collector, it must be spilled to ensure it is visible to the
  6533. collector.
  6534. \end{enumerate}
  6535. The later responsibility can be handled during construction of the
  6536. interference graph, by adding interference edges between the call-live
  6537. vector-typed variables and all the callee-saved registers. (They
  6538. already interfere with the caller-saved registers.) The type
  6539. information for variables is in the \code{Program} form, so we
  6540. recommend adding another parameter to the \code{build-interference}
  6541. function to communicate this alist.
  6542. The spilling of vector-typed variables to the root stack can be
  6543. handled after graph coloring, when choosing how to assign the colors
  6544. (integers) to registers and stack locations. The \code{Program} output
  6545. of this pass changes to also record the number of spills to the root
  6546. stack.
  6547. % build-interference
  6548. %
  6549. % callq
  6550. % extra parameter for var->type assoc. list
  6551. % update 'program' and 'if'
  6552. % allocate-registers
  6553. % allocate spilled vectors to the rootstack
  6554. % don't change color-graph
  6555. \section{Print x86}
  6556. \label{sec:print-x86-gc}
  6557. \index{prelude}\index{conclusion}
  6558. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  6559. \code{print-x86} pass on the running example. In the prelude and
  6560. conclusion of the \code{main} function, we treat the root stack very
  6561. much like the regular stack in that we move the root stack pointer
  6562. (\code{r15}) to make room for the spills to the root stack, except
  6563. that the root stack grows up instead of down. For the running
  6564. example, there was just one spill so we increment \code{r15} by 8
  6565. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  6566. One issue that deserves special care is that there may be a call to
  6567. \code{collect} prior to the initializing assignments for all the
  6568. variables in the root stack. We do not want the garbage collector to
  6569. accidentally think that some uninitialized variable is a pointer that
  6570. needs to be followed. Thus, we zero-out all locations on the root
  6571. stack in the prelude of \code{main}. In
  6572. Figure~\ref{fig:print-x86-output-gc}, the instruction
  6573. %
  6574. \lstinline{movq $0, (%r15)}
  6575. %
  6576. accomplishes this task. The garbage collector tests each root to see
  6577. if it is null prior to dereferencing it.
  6578. \begin{figure}[htbp]
  6579. \begin{minipage}[t]{0.5\textwidth}
  6580. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6581. block35:
  6582. movq free_ptr(%rip), %rcx
  6583. addq $16, free_ptr(%rip)
  6584. movq %rcx, %r11
  6585. movq $131, 0(%r11)
  6586. movq %rcx, %r11
  6587. movq -8(%r15), %rax
  6588. movq %rax, 8(%r11)
  6589. movq $0, %rdx
  6590. movq %rcx, %r11
  6591. movq 8(%r11), %rcx
  6592. movq %rcx, %r11
  6593. movq 8(%r11), %rax
  6594. jmp conclusion
  6595. block36:
  6596. movq $0, %rcx
  6597. jmp block35
  6598. block38:
  6599. movq free_ptr(%rip), %rcx
  6600. addq $16, free_ptr(%rip)
  6601. movq %rcx, %r11
  6602. movq $3, 0(%r11)
  6603. movq %rcx, %r11
  6604. movq %rbx, 8(%r11)
  6605. movq $0, %rdx
  6606. movq %rcx, -8(%r15)
  6607. movq free_ptr(%rip), %rcx
  6608. addq $16, %rcx
  6609. movq fromspace_end(%rip), %rdx
  6610. cmpq %rdx, %rcx
  6611. jl block36
  6612. movq %r15, %rdi
  6613. movq $16, %rsi
  6614. callq collect
  6615. jmp block35
  6616. block39:
  6617. movq $0, %rcx
  6618. jmp block38
  6619. \end{lstlisting}
  6620. \end{minipage}
  6621. \begin{minipage}[t]{0.45\textwidth}
  6622. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6623. start:
  6624. movq $42, %rbx
  6625. movq free_ptr(%rip), %rdx
  6626. addq $16, %rdx
  6627. movq fromspace_end(%rip), %rcx
  6628. cmpq %rcx, %rdx
  6629. jl block39
  6630. movq %r15, %rdi
  6631. movq $16, %rsi
  6632. callq collect
  6633. jmp block38
  6634. .globl main
  6635. main:
  6636. pushq %rbp
  6637. movq %rsp, %rbp
  6638. pushq %r13
  6639. pushq %r12
  6640. pushq %rbx
  6641. pushq %r14
  6642. subq $0, %rsp
  6643. movq $16384, %rdi
  6644. movq $16384, %rsi
  6645. callq initialize
  6646. movq rootstack_begin(%rip), %r15
  6647. movq $0, (%r15)
  6648. addq $8, %r15
  6649. jmp start
  6650. conclusion:
  6651. subq $8, %r15
  6652. addq $0, %rsp
  6653. popq %r14
  6654. popq %rbx
  6655. popq %r12
  6656. popq %r13
  6657. popq %rbp
  6658. retq
  6659. \end{lstlisting}
  6660. \end{minipage}
  6661. \caption{Output of the \code{print-x86} pass.}
  6662. \label{fig:print-x86-output-gc}
  6663. \end{figure}
  6664. \begin{figure}[p]
  6665. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6666. \node (Rvec) at (0,2) {\large \LangVec{}};
  6667. \node (Rvec-2) at (3,2) {\large \LangVec{}};
  6668. \node (Rvec-3) at (6,2) {\large \LangVec{}};
  6669. \node (Rvec-4) at (9,2) {\large \LangVec{}};
  6670. \node (Rvec-5) at (12,2) {\large \LangAlloc{}};
  6671. \node (C2-4) at (3,0) {\large \LangCVec{}};
  6672. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  6673. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  6674. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  6675. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  6676. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  6677. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  6678. %\path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize type-check} (Rvec-2);
  6679. \path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize shrink} (Rvec-2);
  6680. \path[->,bend left=15] (Rvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Rvec-3);
  6681. \path[->,bend left=15] (Rvec-3) edge [above] node {\ttfamily\footnotesize expose-alloc.} (Rvec-4);
  6682. \path[->,bend left=15] (Rvec-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvec-5);
  6683. \path[->,bend left=20] (Rvec-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-4);
  6684. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select-instr.} (x86-2);
  6685. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6686. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  6687. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6688. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  6689. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  6690. \end{tikzpicture}
  6691. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  6692. \label{fig:Rvec-passes}
  6693. \end{figure}
  6694. Figure~\ref{fig:Rvec-passes} gives an overview of all the passes needed
  6695. for the compilation of \LangVec{}.
  6696. \section{Challenge: Simple Structures}
  6697. \label{sec:simple-structures}
  6698. \index{struct}
  6699. \index{structure}
  6700. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  6701. \LangStruct{}, which extends \LangVec{} with support for simple structures.
  6702. Recall that a \code{struct} in Typed Racket is a user-defined data
  6703. type that contains named fields and that is heap allocated, similar to
  6704. a vector. The following is an example of a structure definition, in
  6705. this case the definition of a \code{point} type.
  6706. \begin{lstlisting}
  6707. (struct point ([x : Integer] [y : Integer]) #:mutable)
  6708. \end{lstlisting}
  6709. \begin{figure}[tbp]
  6710. \centering
  6711. \fbox{
  6712. \begin{minipage}{0.96\textwidth}
  6713. \[
  6714. \begin{array}{lcl}
  6715. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6716. \mid (\key{Vector}\;\Type \ldots) \mid \key{Void} } \mid \Var \\
  6717. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6718. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  6719. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  6720. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6721. \mid (\key{and}\;\Exp\;\Exp)
  6722. \mid (\key{or}\;\Exp\;\Exp)
  6723. \mid (\key{not}\;\Exp) } \\
  6724. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  6725. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  6726. &\mid& \gray{ (\key{vector}\;\Exp \ldots)
  6727. \mid (\key{vector-ref}\;\Exp\;\Int) } \\
  6728. &\mid& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  6729. &\mid& \gray{ (\key{void}) } \mid (\Var\;\Exp \ldots)\\
  6730. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  6731. \LangStruct{} &::=& \Def \ldots \; \Exp
  6732. \end{array}
  6733. \]
  6734. \end{minipage}
  6735. }
  6736. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  6737. (Figure~\ref{fig:Rvec-concrete-syntax}).}
  6738. \label{fig:r3s-concrete-syntax}
  6739. \end{figure}
  6740. An instance of a structure is created using function call syntax, with
  6741. the name of the structure in the function position:
  6742. \begin{lstlisting}
  6743. (point 7 12)
  6744. \end{lstlisting}
  6745. Function-call syntax is also used to read the value in a field of a
  6746. structure. The function name is formed by the structure name, a dash,
  6747. and the field name. The following example uses \code{point-x} and
  6748. \code{point-y} to access the \code{x} and \code{y} fields of two point
  6749. instances.
  6750. \begin{center}
  6751. \begin{lstlisting}
  6752. (let ([pt1 (point 7 12)])
  6753. (let ([pt2 (point 4 3)])
  6754. (+ (- (point-x pt1) (point-x pt2))
  6755. (- (point-y pt1) (point-y pt2)))))
  6756. \end{lstlisting}
  6757. \end{center}
  6758. Similarly, to write to a field of a structure, use its set function,
  6759. whose name starts with \code{set-}, followed by the structure name,
  6760. then a dash, then the field name, and concluded with an exclamation
  6761. mark. The following example uses \code{set-point-x!} to change the
  6762. \code{x} field from \code{7} to \code{42}.
  6763. \begin{center}
  6764. \begin{lstlisting}
  6765. (let ([pt (point 7 12)])
  6766. (let ([_ (set-point-x! pt 42)])
  6767. (point-x pt)))
  6768. \end{lstlisting}
  6769. \end{center}
  6770. \begin{exercise}\normalfont
  6771. Extend your compiler with support for simple structures, compiling
  6772. \LangStruct{} to x86 assembly code. Create five new test cases that use
  6773. structures and test your compiler.
  6774. \end{exercise}
  6775. \section{Challenge: Generational Collection}
  6776. The copying collector described in Section~\ref{sec:GC} can incur
  6777. significant runtime overhead because the call to \code{collect} takes
  6778. time proportional to all of the live data. One way to reduce this
  6779. overhead is to reduce how much data is inspected in each call to
  6780. \code{collect}. In particular, researchers have observed that recently
  6781. allocated data is more likely to become garbage then data that has
  6782. survived one or more previous calls to \code{collect}. This insight
  6783. motivated the creation of \emph{generational garbage collectors}
  6784. \index{generational garbage collector} that
  6785. 1) segregates data according to its age into two or more generations,
  6786. 2) allocates less space for younger generations, so collecting them is
  6787. faster, and more space for the older generations, and 3) performs
  6788. collection on the younger generations more frequently then for older
  6789. generations~\citep{Wilson:1992fk}.
  6790. For this challenge assignment, the goal is to adapt the copying
  6791. collector implemented in \code{runtime.c} to use two generations, one
  6792. for young data and one for old data. Each generation consists of a
  6793. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  6794. \code{collect} function to use the two generations.
  6795. \begin{enumerate}
  6796. \item Copy the young generation's FromSpace to its ToSpace then switch
  6797. the role of the ToSpace and FromSpace
  6798. \item If there is enough space for the requested number of bytes in
  6799. the young FromSpace, then return from \code{collect}.
  6800. \item If there is not enough space in the young FromSpace for the
  6801. requested bytes, then move the data from the young generation to the
  6802. old one with the following steps:
  6803. \begin{enumerate}
  6804. \item If there is enough room in the old FromSpace, copy the young
  6805. FromSpace to the old FromSpace and then return.
  6806. \item If there is not enough room in the old FromSpace, then collect
  6807. the old generation by copying the old FromSpace to the old ToSpace
  6808. and swap the roles of the old FromSpace and ToSpace.
  6809. \item If there is enough room now, copy the young FromSpace to the
  6810. old FromSpace and return. Otherwise, allocate a larger FromSpace
  6811. and ToSpace for the old generation. Copy the young FromSpace and
  6812. the old FromSpace into the larger FromSpace for the old
  6813. generation and then return.
  6814. \end{enumerate}
  6815. \end{enumerate}
  6816. We recommend that you generalize the \code{cheney} function so that it
  6817. can be used for all the copies mentioned above: between the young
  6818. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  6819. between the young FromSpace and old FromSpace. This can be
  6820. accomplished by adding parameters to \code{cheney} that replace its
  6821. use of the global variables \code{fromspace\_begin},
  6822. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  6823. Note that the collection of the young generation does not traverse the
  6824. old generation. This introduces a potential problem: there may be
  6825. young data that is only reachable through pointers in the old
  6826. generation. If these pointers are not taken into account, the
  6827. collector could throw away young data that is live! One solution,
  6828. called \emph{pointer recording}, is to maintain a set of all the
  6829. pointers from the old generation into the new generation and consider
  6830. this set as part of the root set. To maintain this set, the compiler
  6831. must insert extra instructions around every \code{vector-set!}. If the
  6832. vector being modified is in the old generation, and if the value being
  6833. written is a pointer into the new generation, than that pointer must
  6834. be added to the set. Also, if the value being overwritten was a
  6835. pointer into the new generation, then that pointer should be removed
  6836. from the set.
  6837. \begin{exercise}\normalfont
  6838. Adapt the \code{collect} function in \code{runtime.c} to implement
  6839. generational garbage collection, as outlined in this section.
  6840. Update the code generation for \code{vector-set!} to implement
  6841. pointer recording. Make sure that your new compiler and runtime
  6842. passes your test suite.
  6843. \end{exercise}
  6844. % Further Reading
  6845. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6846. \chapter{Functions}
  6847. \label{ch:Rfun}
  6848. \index{function}
  6849. This chapter studies the compilation of functions similar to those
  6850. found in the C language. This corresponds to a subset of Typed Racket
  6851. in which only top-level function definitions are allowed. This kind of
  6852. function is an important stepping stone to implementing
  6853. lexically-scoped functions, that is, \key{lambda} abstractions, which
  6854. is the topic of Chapter~\ref{ch:Rlam}.
  6855. \section{The \LangFun{} Language}
  6856. The concrete and abstract syntax for function definitions and function
  6857. application is shown in Figures~\ref{fig:Rfun-concrete-syntax} and
  6858. \ref{fig:Rfun-syntax}, where we define the \LangFun{} language. Programs in
  6859. \LangFun{} begin with zero or more function definitions. The function
  6860. names from these definitions are in-scope for the entire program,
  6861. including all other function definitions (so the ordering of function
  6862. definitions does not matter). The concrete syntax for function
  6863. application\index{function application} is $(\Exp \; \Exp \ldots)$
  6864. where the first expression must
  6865. evaluate to a function and the rest are the arguments.
  6866. The abstract syntax for function application is
  6867. $\APPLY{\Exp}{\Exp\ldots}$.
  6868. %% The syntax for function application does not include an explicit
  6869. %% keyword, which is error prone when using \code{match}. To alleviate
  6870. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  6871. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  6872. Functions are first-class in the sense that a function pointer
  6873. \index{function pointer} is data and can be stored in memory or passed
  6874. as a parameter to another function. Thus, we introduce a function
  6875. type, written
  6876. \begin{lstlisting}
  6877. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  6878. \end{lstlisting}
  6879. for a function whose $n$ parameters have the types $\Type_1$ through
  6880. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  6881. these functions (with respect to Racket functions) is that they are
  6882. not lexically scoped. That is, the only external entities that can be
  6883. referenced from inside a function body are other globally-defined
  6884. functions. The syntax of \LangFun{} prevents functions from being nested
  6885. inside each other.
  6886. \begin{figure}[tp]
  6887. \centering
  6888. \fbox{
  6889. \begin{minipage}{0.96\textwidth}
  6890. \small
  6891. \[
  6892. \begin{array}{lcl}
  6893. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  6894. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void} } \mid (\Type \ldots \; \key{->}\; \Type) \\
  6895. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6896. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  6897. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  6898. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6899. \mid (\key{and}\;\Exp\;\Exp)
  6900. \mid (\key{or}\;\Exp\;\Exp)
  6901. \mid (\key{not}\;\Exp)} \\
  6902. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  6903. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  6904. (\key{vector-ref}\;\Exp\;\Int)} \\
  6905. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  6906. \mid \LP\key{has-type}~\Exp~\Type\RP } \\
  6907. &\mid& \LP\Exp \; \Exp \ldots\RP \\
  6908. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  6909. \LangFun{} &::=& \Def \ldots \; \Exp
  6910. \end{array}
  6911. \]
  6912. \end{minipage}
  6913. }
  6914. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-concrete-syntax}).}
  6915. \label{fig:Rfun-concrete-syntax}
  6916. \end{figure}
  6917. \begin{figure}[tp]
  6918. \centering
  6919. \fbox{
  6920. \begin{minipage}{0.96\textwidth}
  6921. \small
  6922. \[
  6923. \begin{array}{lcl}
  6924. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6925. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  6926. &\mid& \gray{ \BOOL{\itm{bool}}
  6927. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6928. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP }
  6929. \mid \APPLY{\Exp}{\Exp\ldots}\\
  6930. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}\\
  6931. \LangFun{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  6932. \end{array}
  6933. \]
  6934. \end{minipage}
  6935. }
  6936. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-syntax}).}
  6937. \label{fig:Rfun-syntax}
  6938. \end{figure}
  6939. The program in Figure~\ref{fig:Rfun-function-example} is a
  6940. representative example of defining and using functions in \LangFun{}. We
  6941. define a function \code{map-vec} that applies some other function
  6942. \code{f} to both elements of a vector and returns a new
  6943. vector containing the results. We also define a function \code{add1}.
  6944. The program applies
  6945. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  6946. \code{(vector 1 42)}, from which we return the \code{42}.
  6947. \begin{figure}[tbp]
  6948. \begin{lstlisting}
  6949. (define (map-vec [f : (Integer -> Integer)]
  6950. [v : (Vector Integer Integer)])
  6951. : (Vector Integer Integer)
  6952. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  6953. (define (add1 [x : Integer]) : Integer
  6954. (+ x 1))
  6955. (vector-ref (map-vec add1 (vector 0 41)) 1)
  6956. \end{lstlisting}
  6957. \caption{Example of using functions in \LangFun{}.}
  6958. \label{fig:Rfun-function-example}
  6959. \end{figure}
  6960. The definitional interpreter for \LangFun{} is in
  6961. Figure~\ref{fig:interp-Rfun}. The case for the \code{ProgramDefsExp} form is
  6962. responsible for setting up the mutual recursion between the top-level
  6963. function definitions. We use the classic back-patching \index{back-patching}
  6964. approach that uses mutable variables and makes two passes over the function
  6965. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  6966. top-level environment using a mutable cons cell for each function
  6967. definition. Note that the \code{lambda} value for each function is
  6968. incomplete; it does not yet include the environment. Once the
  6969. top-level environment is constructed, we then iterate over it and
  6970. update the \code{lambda} values to use the top-level environment.
  6971. \begin{figure}[tp]
  6972. \begin{lstlisting}
  6973. (define interp-Rfun-class
  6974. (class interp-Rvec-class
  6975. (super-new)
  6976. (define/override ((interp-exp env) e)
  6977. (define recur (interp-exp env))
  6978. (match e
  6979. [(Var x) (unbox (dict-ref env x))]
  6980. [(Let x e body)
  6981. (define new-env (dict-set env x (box (recur e))))
  6982. ((interp-exp new-env) body)]
  6983. [(Apply fun args)
  6984. (define fun-val (recur fun))
  6985. (define arg-vals (for/list ([e args]) (recur e)))
  6986. (match fun-val
  6987. [`(function (,xs ...) ,body ,fun-env)
  6988. (define params-args (for/list ([x xs] [arg arg-vals])
  6989. (cons x (box arg))))
  6990. (define new-env (append params-args fun-env))
  6991. ((interp-exp new-env) body)]
  6992. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  6993. [else ((super interp-exp env) e)]
  6994. ))
  6995. (define/public (interp-def d)
  6996. (match d
  6997. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  6998. (cons f (box `(function ,xs ,body ())))]))
  6999. (define/override (interp-program p)
  7000. (match p
  7001. [(ProgramDefsExp info ds body)
  7002. (let ([top-level (for/list ([d ds]) (interp-def d))])
  7003. (for/list ([f (in-dict-values top-level)])
  7004. (set-box! f (match (unbox f)
  7005. [`(function ,xs ,body ())
  7006. `(function ,xs ,body ,top-level)])))
  7007. ((interp-exp top-level) body))]))
  7008. ))
  7009. (define (interp-Rfun p)
  7010. (send (new interp-Rfun-class) interp-program p))
  7011. \end{lstlisting}
  7012. \caption{Interpreter for the \LangFun{} language.}
  7013. \label{fig:interp-Rfun}
  7014. \end{figure}
  7015. \margincomment{TODO: explain type checker}
  7016. The type checker for \LangFun{} is is in Figure~\ref{fig:type-check-Rfun}.
  7017. \begin{figure}[tp]
  7018. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7019. (define type-check-Rfun-class
  7020. (class type-check-Rvec-class
  7021. (super-new)
  7022. (inherit check-type-equal?)
  7023. (define/public (type-check-apply env e es)
  7024. (define-values (e^ ty) ((type-check-exp env) e))
  7025. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  7026. ((type-check-exp env) e)))
  7027. (match ty
  7028. [`(,ty^* ... -> ,rt)
  7029. (for ([arg-ty ty*] [param-ty ty^*])
  7030. (check-type-equal? arg-ty param-ty (Apply e es)))
  7031. (values e^ e* rt)]))
  7032. (define/override (type-check-exp env)
  7033. (lambda (e)
  7034. (match e
  7035. [(FunRef f)
  7036. (values (FunRef f) (dict-ref env f))]
  7037. [(Apply e es)
  7038. (define-values (e^ es^ rt) (type-check-apply env e es))
  7039. (values (Apply e^ es^) rt)]
  7040. [(Call e es)
  7041. (define-values (e^ es^ rt) (type-check-apply env e es))
  7042. (values (Call e^ es^) rt)]
  7043. [else ((super type-check-exp env) e)])))
  7044. (define/public (type-check-def env)
  7045. (lambda (e)
  7046. (match e
  7047. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  7048. (define new-env (append (map cons xs ps) env))
  7049. (define-values (body^ ty^) ((type-check-exp new-env) body))
  7050. (check-type-equal? ty^ rt body)
  7051. (Def f p:t* rt info body^)])))
  7052. (define/public (fun-def-type d)
  7053. (match d
  7054. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  7055. (define/override (type-check-program e)
  7056. (match e
  7057. [(ProgramDefsExp info ds body)
  7058. (define new-env (for/list ([d ds])
  7059. (cons (Def-name d) (fun-def-type d))))
  7060. (define ds^ (for/list ([d ds]) ((type-check-def new-env) d)))
  7061. (define-values (body^ ty) ((type-check-exp new-env) body))
  7062. (check-type-equal? ty 'Integer body)
  7063. (ProgramDefsExp info ds^ body^)]))))
  7064. (define (type-check-Rfun p)
  7065. (send (new type-check-Rfun-class) type-check-program p))
  7066. \end{lstlisting}
  7067. \caption{Type checker for the \LangFun{} language.}
  7068. \label{fig:type-check-Rfun}
  7069. \end{figure}
  7070. \section{Functions in x86}
  7071. \label{sec:fun-x86}
  7072. \margincomment{\tiny Make sure callee-saved registers are discussed
  7073. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  7074. \margincomment{\tiny Talk about the return address on the
  7075. stack and what callq and retq does.\\ --Jeremy }
  7076. The x86 architecture provides a few features to support the
  7077. implementation of functions. We have already seen that x86 provides
  7078. labels so that one can refer to the location of an instruction, as is
  7079. needed for jump instructions. Labels can also be used to mark the
  7080. beginning of the instructions for a function. Going further, we can
  7081. obtain the address of a label by using the \key{leaq} instruction and
  7082. PC-relative addressing. For example, the following puts the
  7083. address of the \code{add1} label into the \code{rbx} register.
  7084. \begin{lstlisting}
  7085. leaq add1(%rip), %rbx
  7086. \end{lstlisting}
  7087. The instruction pointer register \key{rip} (aka. the program counter
  7088. \index{program counter}) always points to the next instruction to be
  7089. executed. When combined with an label, as in \code{add1(\%rip)}, the
  7090. linker computes the distance $d$ between the address of \code{add1}
  7091. and where the \code{rip} would be at that moment and then changes
  7092. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  7093. the address of \code{add1}.
  7094. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  7095. jump to a function whose location is given by a label. To support
  7096. function calls in this chapter we instead will be jumping to a
  7097. function whose location is given by an address in a register, that is,
  7098. we need to make an \emph{indirect function call}. The x86 syntax for
  7099. this is a \code{callq} instruction but with an asterisk before the
  7100. register name.\index{indirect function call}
  7101. \begin{lstlisting}
  7102. callq *%rbx
  7103. \end{lstlisting}
  7104. \subsection{Calling Conventions}
  7105. \index{calling conventions}
  7106. The \code{callq} instruction provides partial support for implementing
  7107. functions: it pushes the return address on the stack and it jumps to
  7108. the target. However, \code{callq} does not handle
  7109. \begin{enumerate}
  7110. \item parameter passing,
  7111. \item pushing frames on the procedure call stack and popping them off,
  7112. or
  7113. \item determining how registers are shared by different functions.
  7114. \end{enumerate}
  7115. Regarding (1) parameter passing, recall that the following six
  7116. registers are used to pass arguments to a function, in this order.
  7117. \begin{lstlisting}
  7118. rdi rsi rdx rcx r8 r9
  7119. \end{lstlisting}
  7120. If there are
  7121. more than six arguments, then the convention is to use space on the
  7122. frame of the caller for the rest of the arguments. However, to ease
  7123. the implementation of efficient tail calls
  7124. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  7125. arguments.
  7126. %
  7127. Also recall that the register \code{rax} is for the return value of
  7128. the function.
  7129. \index{prelude}\index{conclusion}
  7130. Regarding (2) frames \index{frame} and the procedure call stack,
  7131. \index{procedure call stack} recall from Section~\ref{sec:x86} that
  7132. the stack grows down, with each function call using a chunk of space
  7133. called a frame. The caller sets the stack pointer, register
  7134. \code{rsp}, to the last data item in its frame. The callee must not
  7135. change anything in the caller's frame, that is, anything that is at or
  7136. above the stack pointer. The callee is free to use locations that are
  7137. below the stack pointer.
  7138. Recall that we are storing variables of vector type on the root stack.
  7139. So the prelude needs to move the root stack pointer \code{r15} up and
  7140. the conclusion needs to move the root stack pointer back down. Also,
  7141. the prelude must initialize to \code{0} this frame's slots in the root
  7142. stack to signal to the garbage collector that those slots do not yet
  7143. contain a pointer to a vector. Otherwise the garbage collector will
  7144. interpret the garbage bits in those slots as memory addresses and try
  7145. to traverse them, causing serious mayhem!
  7146. Regarding (3) the sharing of registers between different functions,
  7147. recall from Section~\ref{sec:calling-conventions} that the registers
  7148. are divided into two groups, the caller-saved registers and the
  7149. callee-saved registers. The caller should assume that all the
  7150. caller-saved registers get overwritten with arbitrary values by the
  7151. callee. That is why we recommend in
  7152. Section~\ref{sec:calling-conventions} that variables that are live
  7153. during a function call should not be assigned to caller-saved
  7154. registers.
  7155. On the flip side, if the callee wants to use a callee-saved register,
  7156. the callee must save the contents of those registers on their stack
  7157. frame and then put them back prior to returning to the caller. That
  7158. is why we recommended in Section~\ref{sec:calling-conventions} that if
  7159. the register allocator assigns a variable to a callee-saved register,
  7160. then the prelude of the \code{main} function must save that register
  7161. to the stack and the conclusion of \code{main} must restore it. This
  7162. recommendation now generalizes to all functions.
  7163. Also recall that the base pointer, register \code{rbp}, is used as a
  7164. point-of-reference within a frame, so that each local variable can be
  7165. accessed at a fixed offset from the base pointer
  7166. (Section~\ref{sec:x86}).
  7167. %
  7168. Figure~\ref{fig:call-frames} shows the general layout of the caller
  7169. and callee frames.
  7170. \begin{figure}[tbp]
  7171. \centering
  7172. \begin{tabular}{r|r|l|l} \hline
  7173. Caller View & Callee View & Contents & Frame \\ \hline
  7174. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  7175. 0(\key{\%rbp}) & & old \key{rbp} \\
  7176. -8(\key{\%rbp}) & & callee-saved $1$ \\
  7177. \ldots & & \ldots \\
  7178. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  7179. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  7180. \ldots & & \ldots \\
  7181. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  7182. %% & & \\
  7183. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  7184. %% & \ldots & \ldots \\
  7185. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  7186. \hline
  7187. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  7188. & 0(\key{\%rbp}) & old \key{rbp} \\
  7189. & -8(\key{\%rbp}) & callee-saved $1$ \\
  7190. & \ldots & \ldots \\
  7191. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  7192. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  7193. & \ldots & \ldots \\
  7194. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  7195. \end{tabular}
  7196. \caption{Memory layout of caller and callee frames.}
  7197. \label{fig:call-frames}
  7198. \end{figure}
  7199. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  7200. %% local variables and for storing the values of callee-saved registers
  7201. %% (we shall refer to all of these collectively as ``locals''), and that
  7202. %% at the beginning of a function we move the stack pointer \code{rsp}
  7203. %% down to make room for them.
  7204. %% We recommend storing the local variables
  7205. %% first and then the callee-saved registers, so that the local variables
  7206. %% can be accessed using \code{rbp} the same as before the addition of
  7207. %% functions.
  7208. %% To make additional room for passing arguments, we shall
  7209. %% move the stack pointer even further down. We count how many stack
  7210. %% arguments are needed for each function call that occurs inside the
  7211. %% body of the function and find their maximum. Adding this number to the
  7212. %% number of locals gives us how much the \code{rsp} should be moved at
  7213. %% the beginning of the function. In preparation for a function call, we
  7214. %% offset from \code{rsp} to set up the stack arguments. We put the first
  7215. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  7216. %% so on.
  7217. %% Upon calling the function, the stack arguments are retrieved by the
  7218. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  7219. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  7220. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  7221. %% the layout of the caller and callee frames. Notice how important it is
  7222. %% that we correctly compute the maximum number of arguments needed for
  7223. %% function calls; if that number is too small then the arguments and
  7224. %% local variables will smash into each other!
  7225. \subsection{Efficient Tail Calls}
  7226. \label{sec:tail-call}
  7227. In general, the amount of stack space used by a program is determined
  7228. by the longest chain of nested function calls. That is, if function
  7229. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  7230. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  7231. $n$ can grow quite large in the case of recursive or mutually
  7232. recursive functions. However, in some cases we can arrange to use only
  7233. constant space, i.e. $O(1)$, instead of $O(n)$.
  7234. If a function call is the last action in a function body, then that
  7235. call is said to be a \emph{tail call}\index{tail call}.
  7236. For example, in the following
  7237. program, the recursive call to \code{tail-sum} is a tail call.
  7238. \begin{center}
  7239. \begin{lstlisting}
  7240. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  7241. (if (eq? n 0)
  7242. r
  7243. (tail-sum (- n 1) (+ n r))))
  7244. (+ (tail-sum 5 0) 27)
  7245. \end{lstlisting}
  7246. \end{center}
  7247. At a tail call, the frame of the caller is no longer needed, so we
  7248. can pop the caller's frame before making the tail call. With this
  7249. approach, a recursive function that only makes tail calls will only
  7250. use $O(1)$ stack space. Functional languages like Racket typically
  7251. rely heavily on recursive functions, so they typically guarantee that
  7252. all tail calls will be optimized in this way.
  7253. \index{frame}
  7254. However, some care is needed with regards to argument passing in tail
  7255. calls. As mentioned above, for arguments beyond the sixth, the
  7256. convention is to use space in the caller's frame for passing
  7257. arguments. But for a tail call we pop the caller's frame and can no
  7258. longer use it. Another alternative is to use space in the callee's
  7259. frame for passing arguments. However, this option is also problematic
  7260. because the caller and callee's frame overlap in memory. As we begin
  7261. to copy the arguments from their sources in the caller's frame, the
  7262. target locations in the callee's frame might overlap with the sources
  7263. for later arguments! We solve this problem by not using the stack for
  7264. passing more than six arguments but instead using the heap, as we
  7265. describe in the Section~\ref{sec:limit-functions-r4}.
  7266. As mentioned above, for a tail call we pop the caller's frame prior to
  7267. making the tail call. The instructions for popping a frame are the
  7268. instructions that we usually place in the conclusion of a
  7269. function. Thus, we also need to place such code immediately before
  7270. each tail call. These instructions include restoring the callee-saved
  7271. registers, so it is good that the argument passing registers are all
  7272. caller-saved registers.
  7273. One last note regarding which instruction to use to make the tail
  7274. call. When the callee is finished, it should not return to the current
  7275. function, but it should return to the function that called the current
  7276. one. Thus, the return address that is already on the stack is the
  7277. right one, and we should not use \key{callq} to make the tail call, as
  7278. that would unnecessarily overwrite the return address. Instead we can
  7279. simply use the \key{jmp} instruction. Like the indirect function call,
  7280. we write an \emph{indirect jump}\index{indirect jump} with a register
  7281. prefixed with an asterisk. We recommend using \code{rax} to hold the
  7282. jump target because the preceding conclusion overwrites just about
  7283. everything else.
  7284. \begin{lstlisting}
  7285. jmp *%rax
  7286. \end{lstlisting}
  7287. \section{Shrink \LangFun{}}
  7288. \label{sec:shrink-r4}
  7289. The \code{shrink} pass performs a minor modification to ease the
  7290. later passes. This pass introduces an explicit \code{main} function
  7291. and changes the top \code{ProgramDefsExp} form to
  7292. \code{ProgramDefs} as follows.
  7293. \begin{lstlisting}
  7294. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  7295. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  7296. \end{lstlisting}
  7297. where $\itm{mainDef}$ is
  7298. \begin{lstlisting}
  7299. (Def 'main '() 'Integer '() |$\Exp'$|)
  7300. \end{lstlisting}
  7301. \section{Reveal Functions and the \LangFunRef{} language}
  7302. \label{sec:reveal-functions-r4}
  7303. The syntax of \LangFun{} is inconvenient for purposes of compilation in one
  7304. respect: it conflates the use of function names and local
  7305. variables. This is a problem because we need to compile the use of a
  7306. function name differently than the use of a local variable; we need to
  7307. use \code{leaq} to convert the function name (a label in x86) to an
  7308. address in a register. Thus, it is a good idea to create a new pass
  7309. that changes function references from just a symbol $f$ to
  7310. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  7311. output language, \LangFunRef{}, is defined in Figure~\ref{fig:f1-syntax}.
  7312. The concrete syntax for a function reference is $\CFUNREF{f}$.
  7313. \begin{figure}[tp]
  7314. \centering
  7315. \fbox{
  7316. \begin{minipage}{0.96\textwidth}
  7317. \[
  7318. \begin{array}{lcl}
  7319. \Exp &::=& \ldots \mid \FUNREF{\Var}\\
  7320. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7321. \LangFunRef{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  7322. \end{array}
  7323. \]
  7324. \end{minipage}
  7325. }
  7326. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  7327. (Figure~\ref{fig:Rfun-syntax}).}
  7328. \label{fig:f1-syntax}
  7329. \end{figure}
  7330. %% Distinguishing between calls in tail position and non-tail position
  7331. %% requires the pass to have some notion of context. We recommend using
  7332. %% two mutually recursive functions, one for processing expressions in
  7333. %% tail position and another for the rest.
  7334. Placing this pass after \code{uniquify} will make sure that there are
  7335. no local variables and functions that share the same name. On the
  7336. other hand, \code{reveal-functions} needs to come before the
  7337. \code{explicate-control} pass because that pass helps us compile
  7338. \code{FunRef} forms into assignment statements.
  7339. \section{Limit Functions}
  7340. \label{sec:limit-functions-r4}
  7341. Recall that we wish to limit the number of function parameters to six
  7342. so that we do not need to use the stack for argument passing, which
  7343. makes it easier to implement efficient tail calls. However, because
  7344. the input language \LangFun{} supports arbitrary numbers of function
  7345. arguments, we have some work to do!
  7346. This pass transforms functions and function calls that involve more
  7347. than six arguments to pass the first five arguments as usual, but it
  7348. packs the rest of the arguments into a vector and passes it as the
  7349. sixth argument.
  7350. Each function definition with too many parameters is transformed as
  7351. follows.
  7352. \begin{lstlisting}
  7353. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  7354. |$\Rightarrow$|
  7355. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  7356. \end{lstlisting}
  7357. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  7358. the occurrences of the later parameters with vector references.
  7359. \begin{lstlisting}
  7360. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  7361. \end{lstlisting}
  7362. For function calls with too many arguments, the \code{limit-functions}
  7363. pass transforms them in the following way.
  7364. \begin{tabular}{lll}
  7365. \begin{minipage}{0.2\textwidth}
  7366. \begin{lstlisting}
  7367. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  7368. \end{lstlisting}
  7369. \end{minipage}
  7370. &
  7371. $\Rightarrow$
  7372. &
  7373. \begin{minipage}{0.4\textwidth}
  7374. \begin{lstlisting}
  7375. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  7376. \end{lstlisting}
  7377. \end{minipage}
  7378. \end{tabular}
  7379. \section{Remove Complex Operands}
  7380. \label{sec:rco-r4}
  7381. The primary decisions to make for this pass is whether to classify
  7382. \code{FunRef} and \code{Apply} as either atomic or complex
  7383. expressions. Recall that a simple expression will eventually end up as
  7384. just an immediate argument of an x86 instruction. Function
  7385. application will be translated to a sequence of instructions, so
  7386. \code{Apply} must be classified as complex expression.
  7387. On the other hand, the arguments of \code{Apply} should be
  7388. atomic expressions.
  7389. %
  7390. Regarding \code{FunRef}, as discussed above, the function label needs
  7391. to be converted to an address using the \code{leaq} instruction. Thus,
  7392. even though \code{FunRef} seems rather simple, it needs to be
  7393. classified as a complex expression so that we generate an assignment
  7394. statement with a left-hand side that can serve as the target of the
  7395. \code{leaq}. Figure~\ref{fig:Rfun-anf-syntax} defines the
  7396. output language \LangFunANF{} of this pass.
  7397. \begin{figure}[tp]
  7398. \centering
  7399. \fbox{
  7400. \begin{minipage}{0.96\textwidth}
  7401. \small
  7402. \[
  7403. \begin{array}{rcl}
  7404. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  7405. \mid \VOID{} } \\
  7406. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  7407. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  7408. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  7409. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  7410. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  7411. &\mid& \gray{ \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  7412. \mid \LP\key{GlobalValue}~\Var\RP }\\
  7413. &\mid& \FUNREF{\Var} \mid \APPLY{\Atm}{\Atm\ldots}\\
  7414. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7415. R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  7416. \end{array}
  7417. \]
  7418. \end{minipage}
  7419. }
  7420. \caption{\LangFunANF{} is \LangFun{} in administrative normal form (ANF).}
  7421. \label{fig:Rfun-anf-syntax}
  7422. \end{figure}
  7423. \section{Explicate Control and the \LangCFun{} language}
  7424. \label{sec:explicate-control-r4}
  7425. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  7426. output of \key{explicate-control}. (The concrete syntax is given in
  7427. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.) The auxiliary
  7428. functions for assignment and tail contexts should be updated with
  7429. cases for \code{Apply} and \code{FunRef} and the function for
  7430. predicate context should be updated for \code{Apply} but not
  7431. \code{FunRef}. (A \code{FunRef} can't be a Boolean.) In assignment
  7432. and predicate contexts, \code{Apply} becomes \code{Call}, whereas in
  7433. tail position \code{Apply} becomes \code{TailCall}. We recommend
  7434. defining a new auxiliary function for processing function definitions.
  7435. This code is similar to the case for \code{Program} in \LangVec{}. The
  7436. top-level \code{explicate-control} function that handles the
  7437. \code{ProgramDefs} form of \LangFun{} can then apply this new function to
  7438. all the function definitions.
  7439. \begin{figure}[tp]
  7440. \fbox{
  7441. \begin{minipage}{0.96\textwidth}
  7442. \small
  7443. \[
  7444. \begin{array}{lcl}
  7445. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  7446. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  7447. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  7448. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  7449. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  7450. &\mid& \gray{ \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP } \\
  7451. &\mid& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  7452. &\mid& \gray{ \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP }\\
  7453. &\mid& \gray{ \LP\key{GlobalValue} \,\Var\RP \mid \LP\key{Void}\RP }\\
  7454. &\mid& \FUNREF{\itm{label}} \mid \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  7455. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  7456. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  7457. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  7458. \mid \GOTO{\itm{label}} } \\
  7459. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  7460. &\mid& \TAILCALL{\Atm}{\Atm\ldots} \\
  7461. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  7462. \LangCFun{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  7463. \end{array}
  7464. \]
  7465. \end{minipage}
  7466. }
  7467. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  7468. \label{fig:c3-syntax}
  7469. \end{figure}
  7470. \section{Select Instructions and the \LangXIndCall{} Language}
  7471. \label{sec:select-r4}
  7472. \index{instruction selection}
  7473. The output of select instructions is a program in the \LangXIndCall{}
  7474. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  7475. \index{x86}
  7476. \begin{figure}[tp]
  7477. \fbox{
  7478. \begin{minipage}{0.96\textwidth}
  7479. \small
  7480. \[
  7481. \begin{array}{lcl}
  7482. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)}
  7483. \mid \LP\key{fun-ref}\; \itm{label}\RP\\
  7484. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  7485. \Instr &::=& \ldots
  7486. \mid \key{callq}\;\key{*}\Arg \mid \key{tailjmp}\;\Arg
  7487. \mid \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  7488. \Block &::= & \Instr\ldots \\
  7489. \Def &::= & \LP\key{define} \; \LP\itm{label}\RP \;\LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\RP\\
  7490. \LangXIndCall{} &::= & \Def\ldots
  7491. \end{array}
  7492. \]
  7493. \end{minipage}
  7494. }
  7495. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  7496. \label{fig:x86-3-concrete}
  7497. \end{figure}
  7498. \begin{figure}[tp]
  7499. \fbox{
  7500. \begin{minipage}{0.96\textwidth}
  7501. \small
  7502. \[
  7503. \begin{array}{lcl}
  7504. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  7505. \mid \BYTEREG{\Reg} } \\
  7506. &\mid& \gray{ (\key{Global}~\Var) } \mid \FUNREF{\itm{label}} \\
  7507. \Instr &::=& \ldots \mid \INDCALLQ{\Arg}{\itm{int}}
  7508. \mid \TAILJMP{\Arg}{\itm{int}}\\
  7509. &\mid& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  7510. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  7511. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  7512. \LangXIndCall{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  7513. \end{array}
  7514. \]
  7515. \end{minipage}
  7516. }
  7517. \caption{The abstract syntax of \LangXIndCall{} (extends
  7518. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  7519. \label{fig:x86-3}
  7520. \end{figure}
  7521. An assignment of a function reference to a variable becomes a
  7522. load-effective-address instruction as follows: \\
  7523. \begin{tabular}{lcl}
  7524. \begin{minipage}{0.35\textwidth}
  7525. \begin{lstlisting}
  7526. |$\itm{lhs}$| = (fun-ref |$f$|);
  7527. \end{lstlisting}
  7528. \end{minipage}
  7529. &
  7530. $\Rightarrow$\qquad\qquad
  7531. &
  7532. \begin{minipage}{0.3\textwidth}
  7533. \begin{lstlisting}
  7534. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  7535. \end{lstlisting}
  7536. \end{minipage}
  7537. \end{tabular} \\
  7538. Regarding function definitions, we need to remove the parameters and
  7539. instead perform parameter passing using the conventions discussed in
  7540. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  7541. registers. We recommend turning the parameters into local variables
  7542. and generating instructions at the beginning of the function to move
  7543. from the argument passing registers to these local variables.
  7544. \begin{lstlisting}
  7545. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  7546. |$\Rightarrow$|
  7547. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  7548. \end{lstlisting}
  7549. The $G'$ control-flow graph is the same as $G$ except that the
  7550. \code{start} block is modified to add the instructions for moving from
  7551. the argument registers to the parameter variables. So the \code{start}
  7552. block of $G$ shown on the left is changed to the code on the right.
  7553. \begin{center}
  7554. \begin{minipage}{0.3\textwidth}
  7555. \begin{lstlisting}
  7556. start:
  7557. |$\itm{instr}_1$|
  7558. |$\vdots$|
  7559. |$\itm{instr}_n$|
  7560. \end{lstlisting}
  7561. \end{minipage}
  7562. $\Rightarrow$
  7563. \begin{minipage}{0.3\textwidth}
  7564. \begin{lstlisting}
  7565. start:
  7566. movq %rdi, |$x_1$|
  7567. movq %rsi, |$x_2$|
  7568. |$\vdots$|
  7569. |$\itm{instr}_1$|
  7570. |$\vdots$|
  7571. |$\itm{instr}_n$|
  7572. \end{lstlisting}
  7573. \end{minipage}
  7574. \end{center}
  7575. By changing the parameters to local variables, we are giving the
  7576. register allocator control over which registers or stack locations to
  7577. use for them. If you implemented the move-biasing challenge
  7578. (Section~\ref{sec:move-biasing}), the register allocator will try to
  7579. assign the parameter variables to the corresponding argument register,
  7580. in which case the \code{patch-instructions} pass will remove the
  7581. \code{movq} instruction. This happens in the example translation in
  7582. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  7583. the \code{add} function.
  7584. %
  7585. Also, note that the register allocator will perform liveness analysis
  7586. on this sequence of move instructions and build the interference
  7587. graph. So, for example, $x_1$ will be marked as interfering with
  7588. \code{rsi} and that will prevent the assignment of $x_1$ to
  7589. \code{rsi}, which is good, because that would overwrite the argument
  7590. that needs to move into $x_2$.
  7591. Next, consider the compilation of function calls. In the mirror image
  7592. of handling the parameters of function definitions, the arguments need
  7593. to be moved to the argument passing registers. The function call
  7594. itself is performed with an indirect function call. The return value
  7595. from the function is stored in \code{rax}, so it needs to be moved
  7596. into the \itm{lhs}.
  7597. \begin{lstlisting}
  7598. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  7599. |$\Rightarrow$|
  7600. movq |$\itm{arg}_1$|, %rdi
  7601. movq |$\itm{arg}_2$|, %rsi
  7602. |$\vdots$|
  7603. callq *|\itm{fun}|
  7604. movq %rax, |\itm{lhs}|
  7605. \end{lstlisting}
  7606. The \code{IndirectCallq} AST node includes an integer for the arity of
  7607. the function, i.e., the number of parameters. That information is
  7608. useful in the \code{uncover-live} pass for determining which
  7609. argument-passing registers are potentially read during the call.
  7610. For tail calls, the parameter passing is the same as non-tail calls:
  7611. generate instructions to move the arguments into to the argument
  7612. passing registers. After that we need to pop the frame from the
  7613. procedure call stack. However, we do not yet know how big the frame
  7614. is; that gets determined during register allocation. So instead of
  7615. generating those instructions here, we invent a new instruction that
  7616. means ``pop the frame and then do an indirect jump'', which we name
  7617. \code{TailJmp}. The abstract syntax for this instruction includes an
  7618. argument that specifies where to jump and an integer that represents
  7619. the arity of the function being called.
  7620. Recall that in Section~\ref{sec:explicate-control-Rvar} we recommended
  7621. using the label \code{start} for the initial block of a program, and
  7622. in Section~\ref{sec:select-Rvar} we recommended labeling the conclusion
  7623. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  7624. can be compiled to an assignment to \code{rax} followed by a jump to
  7625. \code{conclusion}. With the addition of function definitions, we will
  7626. have a starting block and conclusion for each function, but their
  7627. labels need to be unique. We recommend prepending the function's name
  7628. to \code{start} and \code{conclusion}, respectively, to obtain unique
  7629. labels. (Alternatively, one could \code{gensym} labels for the start
  7630. and conclusion and store them in the $\itm{info}$ field of the
  7631. function definition.)
  7632. \section{Register Allocation}
  7633. \label{sec:register-allocation-r4}
  7634. \subsection{Liveness Analysis}
  7635. \label{sec:liveness-analysis-r4}
  7636. \index{liveness analysis}
  7637. %% The rest of the passes need only minor modifications to handle the new
  7638. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  7639. %% \code{leaq}.
  7640. The \code{IndirectCallq} instruction should be treated like
  7641. \code{Callq} regarding its written locations $W$, in that they should
  7642. include all the caller-saved registers. Recall that the reason for
  7643. that is to force call-live variables to be assigned to callee-saved
  7644. registers or to be spilled to the stack.
  7645. Regarding the set of read locations $R$ the arity field of
  7646. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  7647. argument-passing registers should be considered as read by those
  7648. instructions.
  7649. \subsection{Build Interference Graph}
  7650. \label{sec:build-interference-r4}
  7651. With the addition of function definitions, we compute an interference
  7652. graph for each function (not just one for the whole program).
  7653. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  7654. spill vector-typed variables that are live during a call to the
  7655. \code{collect}. With the addition of functions to our language, we
  7656. need to revisit this issue. Many functions perform allocation and
  7657. therefore have calls to the collector inside of them. Thus, we should
  7658. not only spill a vector-typed variable when it is live during a call
  7659. to \code{collect}, but we should spill the variable if it is live
  7660. during any function call. Thus, in the \code{build-interference} pass,
  7661. we recommend adding interference edges between call-live vector-typed
  7662. variables and the callee-saved registers (in addition to the usual
  7663. addition of edges between call-live variables and the caller-saved
  7664. registers).
  7665. \subsection{Allocate Registers}
  7666. The primary change to the \code{allocate-registers} pass is adding an
  7667. auxiliary function for handling definitions (the \Def{} non-terminal
  7668. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  7669. logic is the same as described in
  7670. Chapter~\ref{ch:register-allocation-Rvar}, except now register
  7671. allocation is performed many times, once for each function definition,
  7672. instead of just once for the whole program.
  7673. \section{Patch Instructions}
  7674. In \code{patch-instructions}, you should deal with the x86
  7675. idiosyncrasy that the destination argument of \code{leaq} must be a
  7676. register. Additionally, you should ensure that the argument of
  7677. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  7678. code generation more convenient, because we trample many registers
  7679. before the tail call (as explained in the next section).
  7680. \section{Print x86}
  7681. For the \code{print-x86} pass, the cases for \code{FunRef} and
  7682. \code{IndirectCallq} are straightforward: output their concrete
  7683. syntax.
  7684. \begin{lstlisting}
  7685. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  7686. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  7687. \end{lstlisting}
  7688. The \code{TailJmp} node requires a bit work. A straightforward
  7689. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  7690. before the jump we need to pop the current frame. This sequence of
  7691. instructions is the same as the code for the conclusion of a function,
  7692. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  7693. Regarding function definitions, you will need to generate a prelude
  7694. and conclusion for each one. This code is similar to the prelude and
  7695. conclusion that you generated for the \code{main} function in
  7696. Chapter~\ref{ch:Rvec}. To review, the prelude of every function
  7697. should carry out the following steps.
  7698. \begin{enumerate}
  7699. \item Start with \code{.global} and \code{.align} directives followed
  7700. by the label for the function. (See Figure~\ref{fig:add-fun} for an
  7701. example.)
  7702. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  7703. pointer.
  7704. \item Push to the stack all of the callee-saved registers that were
  7705. used for register allocation.
  7706. \item Move the stack pointer \code{rsp} down by the size of the stack
  7707. frame for this function, which depends on the number of regular
  7708. spills. (Aligned to 16 bytes.)
  7709. \item Move the root stack pointer \code{r15} up by the size of the
  7710. root-stack frame for this function, which depends on the number of
  7711. spilled vectors. \label{root-stack-init}
  7712. \item Initialize to zero all of the entries in the root-stack frame.
  7713. \item Jump to the start block.
  7714. \end{enumerate}
  7715. The prelude of the \code{main} function has one additional task: call
  7716. the \code{initialize} function to set up the garbage collector and
  7717. move the value of the global \code{rootstack\_begin} in
  7718. \code{r15}. This should happen before step \ref{root-stack-init}
  7719. above, which depends on \code{r15}.
  7720. The conclusion of every function should do the following.
  7721. \begin{enumerate}
  7722. \item Move the stack pointer back up by the size of the stack frame
  7723. for this function.
  7724. \item Restore the callee-saved registers by popping them from the
  7725. stack.
  7726. \item Move the root stack pointer back down by the size of the
  7727. root-stack frame for this function.
  7728. \item Restore \code{rbp} by popping it from the stack.
  7729. \item Return to the caller with the \code{retq} instruction.
  7730. \end{enumerate}
  7731. \begin{exercise}\normalfont
  7732. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  7733. Create 5 new programs that use functions, including examples that pass
  7734. functions and return functions from other functions, recursive
  7735. functions, functions that create vectors, and functions that make tail
  7736. calls. Test your compiler on these new programs and all of your
  7737. previously created test programs.
  7738. \end{exercise}
  7739. \begin{figure}[tbp]
  7740. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7741. \node (Rfun) at (0,2) {\large \LangFun{}};
  7742. \node (Rfun-1) at (3,2) {\large \LangFun{}};
  7743. \node (Rfun-2) at (6,2) {\large \LangFun{}};
  7744. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  7745. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  7746. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  7747. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  7748. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  7749. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  7750. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  7751. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  7752. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  7753. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  7754. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  7755. \path[->,bend left=15] (Rfun) edge [above] node
  7756. {\ttfamily\footnotesize shrink} (Rfun-1);
  7757. \path[->,bend left=15] (Rfun-1) edge [above] node
  7758. {\ttfamily\footnotesize uniquify} (Rfun-2);
  7759. \path[->,bend left=15] (Rfun-2) edge [right] node
  7760. {\ttfamily\footnotesize ~~reveal-functions} (F1-1);
  7761. \path[->,bend left=15] (F1-1) edge [below] node
  7762. {\ttfamily\footnotesize limit-functions} (F1-2);
  7763. \path[->,bend right=15] (F1-2) edge [above] node
  7764. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  7765. \path[->,bend right=15] (F1-3) edge [above] node
  7766. {\ttfamily\footnotesize remove-complex.} (F1-4);
  7767. \path[->,bend left=15] (F1-4) edge [right] node
  7768. {\ttfamily\footnotesize explicate-control} (C3-2);
  7769. \path[->,bend right=15] (C3-2) edge [left] node
  7770. {\ttfamily\footnotesize select-instr.} (x86-2);
  7771. \path[->,bend left=15] (x86-2) edge [left] node
  7772. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  7773. \path[->,bend right=15] (x86-2-1) edge [below] node
  7774. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  7775. \path[->,bend right=15] (x86-2-2) edge [left] node
  7776. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7777. \path[->,bend left=15] (x86-3) edge [above] node
  7778. {\ttfamily\footnotesize patch-instr.} (x86-4);
  7779. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  7780. \end{tikzpicture}
  7781. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  7782. \label{fig:Rfun-passes}
  7783. \end{figure}
  7784. Figure~\ref{fig:Rfun-passes} gives an overview of the passes for
  7785. compiling \LangFun{} to x86.
  7786. \section{An Example Translation}
  7787. \label{sec:functions-example}
  7788. Figure~\ref{fig:add-fun} shows an example translation of a simple
  7789. function in \LangFun{} to x86. The figure also includes the results of the
  7790. \code{explicate-control} and \code{select-instructions} passes.
  7791. \begin{figure}[htbp]
  7792. \begin{tabular}{ll}
  7793. \begin{minipage}{0.5\textwidth}
  7794. % s3_2.rkt
  7795. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7796. (define (add [x : Integer] [y : Integer])
  7797. : Integer
  7798. (+ x y))
  7799. (add 40 2)
  7800. \end{lstlisting}
  7801. $\Downarrow$
  7802. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7803. (define (add86 [x87 : Integer]
  7804. [y88 : Integer]) : Integer
  7805. add86start:
  7806. return (+ x87 y88);
  7807. )
  7808. (define (main) : Integer ()
  7809. mainstart:
  7810. tmp89 = (fun-ref add86);
  7811. (tail-call tmp89 40 2)
  7812. )
  7813. \end{lstlisting}
  7814. \end{minipage}
  7815. &
  7816. $\Rightarrow$
  7817. \begin{minipage}{0.5\textwidth}
  7818. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7819. (define (add86) : Integer
  7820. add86start:
  7821. movq %rdi, x87
  7822. movq %rsi, y88
  7823. movq x87, %rax
  7824. addq y88, %rax
  7825. jmp add11389conclusion
  7826. )
  7827. (define (main) : Integer
  7828. mainstart:
  7829. leaq (fun-ref add86), tmp89
  7830. movq $40, %rdi
  7831. movq $2, %rsi
  7832. tail-jmp tmp89
  7833. )
  7834. \end{lstlisting}
  7835. $\Downarrow$
  7836. \end{minipage}
  7837. \end{tabular}
  7838. \begin{tabular}{ll}
  7839. \begin{minipage}{0.3\textwidth}
  7840. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7841. .globl add86
  7842. .align 16
  7843. add86:
  7844. pushq %rbp
  7845. movq %rsp, %rbp
  7846. jmp add86start
  7847. add86start:
  7848. movq %rdi, %rax
  7849. addq %rsi, %rax
  7850. jmp add86conclusion
  7851. add86conclusion:
  7852. popq %rbp
  7853. retq
  7854. \end{lstlisting}
  7855. \end{minipage}
  7856. &
  7857. \begin{minipage}{0.5\textwidth}
  7858. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7859. .globl main
  7860. .align 16
  7861. main:
  7862. pushq %rbp
  7863. movq %rsp, %rbp
  7864. movq $16384, %rdi
  7865. movq $16384, %rsi
  7866. callq initialize
  7867. movq rootstack_begin(%rip), %r15
  7868. jmp mainstart
  7869. mainstart:
  7870. leaq add86(%rip), %rcx
  7871. movq $40, %rdi
  7872. movq $2, %rsi
  7873. movq %rcx, %rax
  7874. popq %rbp
  7875. jmp *%rax
  7876. mainconclusion:
  7877. popq %rbp
  7878. retq
  7879. \end{lstlisting}
  7880. \end{minipage}
  7881. \end{tabular}
  7882. \caption{Example compilation of a simple function to x86.}
  7883. \label{fig:add-fun}
  7884. \end{figure}
  7885. % Challenge idea: inlining! (simple version)
  7886. % Further Reading
  7887. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7888. \chapter{Lexically Scoped Functions}
  7889. \label{ch:Rlam}
  7890. \index{lambda}
  7891. \index{lexical scoping}
  7892. This chapter studies lexically scoped functions as they appear in
  7893. functional languages such as Racket. By lexical scoping we mean that a
  7894. function's body may refer to variables whose binding site is outside
  7895. of the function, in an enclosing scope.
  7896. %
  7897. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  7898. \LangLam{}, which extends \LangFun{} with anonymous functions using the
  7899. \key{lambda} form. The body of the \key{lambda}, refers to three
  7900. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  7901. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  7902. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  7903. parameter of function \code{f}. The \key{lambda} is returned from the
  7904. function \code{f}. The main expression of the program includes two
  7905. calls to \code{f} with different arguments for \code{x}, first
  7906. \code{5} then \code{3}. The functions returned from \code{f} are bound
  7907. to variables \code{g} and \code{h}. Even though these two functions
  7908. were created by the same \code{lambda}, they are really different
  7909. functions because they use different values for \code{x}. Applying
  7910. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  7911. \code{15} produces \code{22}. The result of this program is \code{42}.
  7912. \begin{figure}[btp]
  7913. % s4_6.rkt
  7914. \begin{lstlisting}
  7915. (define (f [x : Integer]) : (Integer -> Integer)
  7916. (let ([y 4])
  7917. (lambda: ([z : Integer]) : Integer
  7918. (+ x (+ y z)))))
  7919. (let ([g (f 5)])
  7920. (let ([h (f 3)])
  7921. (+ (g 11) (h 15))))
  7922. \end{lstlisting}
  7923. \caption{Example of a lexically scoped function.}
  7924. \label{fig:lexical-scoping}
  7925. \end{figure}
  7926. The approach that we take for implementing lexically scoped
  7927. functions is to compile them into top-level function definitions,
  7928. translating from \LangLam{} into \LangFun{}. However, the compiler will need to
  7929. provide special treatment for variable occurrences such as \code{x}
  7930. and \code{y} in the body of the \code{lambda} of
  7931. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function may not
  7932. refer to variables defined outside of it. To identify such variable
  7933. occurrences, we review the standard notion of free variable.
  7934. \begin{definition}
  7935. A variable is \emph{free in expression} $e$ if the variable occurs
  7936. inside $e$ but does not have an enclosing binding in $e$.\index{free
  7937. variable}
  7938. \end{definition}
  7939. For example, in the expression \code{(+ x (+ y z))} the variables
  7940. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  7941. only \code{x} and \code{y} are free in the following expression
  7942. because \code{z} is bound by the \code{lambda}.
  7943. \begin{lstlisting}
  7944. (lambda: ([z : Integer]) : Integer
  7945. (+ x (+ y z)))
  7946. \end{lstlisting}
  7947. So the free variables of a \code{lambda} are the ones that will need
  7948. special treatment. We need to arrange for some way to transport, at
  7949. runtime, the values of those variables from the point where the
  7950. \code{lambda} was created to the point where the \code{lambda} is
  7951. applied. An efficient solution to the problem, due to
  7952. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  7953. free variables together with the function pointer for the lambda's
  7954. code, an arrangement called a \emph{flat closure} (which we shorten to
  7955. just ``closure''). \index{closure}\index{flat closure} Fortunately,
  7956. we have all the ingredients to make closures, Chapter~\ref{ch:Rvec}
  7957. gave us vectors and Chapter~\ref{ch:Rfun} gave us function
  7958. pointers. The function pointer resides at index $0$ and the
  7959. values for the free variables will fill in the rest of the vector.
  7960. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  7961. how closures work. It's a three-step dance. The program first calls
  7962. function \code{f}, which creates a closure for the \code{lambda}. The
  7963. closure is a vector whose first element is a pointer to the top-level
  7964. function that we will generate for the \code{lambda}, the second
  7965. element is the value of \code{x}, which is \code{5}, and the third
  7966. element is \code{4}, the value of \code{y}. The closure does not
  7967. contain an element for \code{z} because \code{z} is not a free
  7968. variable of the \code{lambda}. Creating the closure is step 1 of the
  7969. dance. The closure is returned from \code{f} and bound to \code{g}, as
  7970. shown in Figure~\ref{fig:closures}.
  7971. %
  7972. The second call to \code{f} creates another closure, this time with
  7973. \code{3} in the second slot (for \code{x}). This closure is also
  7974. returned from \code{f} but bound to \code{h}, which is also shown in
  7975. Figure~\ref{fig:closures}.
  7976. \begin{figure}[tbp]
  7977. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  7978. \caption{Example closure representation for the \key{lambda}'s
  7979. in Figure~\ref{fig:lexical-scoping}.}
  7980. \label{fig:closures}
  7981. \end{figure}
  7982. Continuing with the example, consider the application of \code{g} to
  7983. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  7984. obtain the function pointer in the first element of the closure and
  7985. call it, passing in the closure itself and then the regular arguments,
  7986. in this case \code{11}. This technique for applying a closure is step
  7987. 2 of the dance.
  7988. %
  7989. But doesn't this \code{lambda} only take 1 argument, for parameter
  7990. \code{z}? The third and final step of the dance is generating a
  7991. top-level function for a \code{lambda}. We add an additional
  7992. parameter for the closure and we insert a \code{let} at the beginning
  7993. of the function for each free variable, to bind those variables to the
  7994. appropriate elements from the closure parameter.
  7995. %
  7996. This three-step dance is known as \emph{closure conversion}. We
  7997. discuss the details of closure conversion in
  7998. Section~\ref{sec:closure-conversion} and the code generated from the
  7999. example in Section~\ref{sec:example-lambda}. But first we define the
  8000. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  8001. \section{The \LangLam{} Language}
  8002. \label{sec:r5}
  8003. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  8004. functions and lexical scoping, is defined in
  8005. Figures~\ref{fig:Rlam-concrete-syntax} and ~\ref{fig:Rlam-syntax}. It adds
  8006. the \key{lambda} form to the grammar for \LangFun{}, which already has
  8007. syntax for function application.
  8008. \begin{figure}[tp]
  8009. \centering
  8010. \fbox{
  8011. \begin{minipage}{0.96\textwidth}
  8012. \small
  8013. \[
  8014. \begin{array}{lcl}
  8015. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  8016. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}
  8017. \mid (\Type\ldots \; \key{->}\; \Type)} \\
  8018. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  8019. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  8020. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  8021. &\mid& \gray{\key{\#t} \mid \key{\#f}
  8022. \mid (\key{and}\;\Exp\;\Exp)
  8023. \mid (\key{or}\;\Exp\;\Exp)
  8024. \mid (\key{not}\;\Exp) } \\
  8025. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  8026. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  8027. (\key{vector-ref}\;\Exp\;\Int)} \\
  8028. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  8029. \mid (\Exp \; \Exp\ldots) } \\
  8030. &\mid& \LP \key{procedure-arity}~\Exp\RP \\
  8031. &\mid& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  8032. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  8033. \LangLam{} &::=& \gray{\Def\ldots \; \Exp}
  8034. \end{array}
  8035. \]
  8036. \end{minipage}
  8037. }
  8038. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-concrete-syntax})
  8039. with \key{lambda}.}
  8040. \label{fig:Rlam-concrete-syntax}
  8041. \end{figure}
  8042. \begin{figure}[tp]
  8043. \centering
  8044. \fbox{
  8045. \begin{minipage}{0.96\textwidth}
  8046. \small
  8047. \[
  8048. \begin{array}{lcl}
  8049. \itm{op} &::=& \ldots \mid \code{procedure-arity} \\
  8050. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  8051. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  8052. &\mid& \gray{ \BOOL{\itm{bool}}
  8053. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  8054. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  8055. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  8056. &\mid& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  8057. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  8058. \LangLam{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  8059. \end{array}
  8060. \]
  8061. \end{minipage}
  8062. }
  8063. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-syntax}).}
  8064. \label{fig:Rlam-syntax}
  8065. \end{figure}
  8066. \index{interpreter}
  8067. \label{sec:interp-Rlambda}
  8068. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  8069. \LangLam{}. The case for \key{lambda} saves the current environment
  8070. inside the returned \key{lambda}. Then the case for \key{Apply} uses
  8071. the environment from the \key{lambda}, the \code{lam-env}, when
  8072. interpreting the body of the \key{lambda}. The \code{lam-env}
  8073. environment is extended with the mapping of parameters to argument
  8074. values.
  8075. \begin{figure}[tbp]
  8076. \begin{lstlisting}
  8077. (define interp-Rlambda-class
  8078. (class interp-Rfun-class
  8079. (super-new)
  8080. (define/override (interp-op op)
  8081. (match op
  8082. ['procedure-arity
  8083. (lambda (v)
  8084. (match v
  8085. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  8086. [else (error 'interp-op "expected a function, not ~a" v)]))]
  8087. [else (super interp-op op)]))
  8088. (define/override ((interp-exp env) e)
  8089. (define recur (interp-exp env))
  8090. (match e
  8091. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  8092. `(function ,xs ,body ,env)]
  8093. [else ((super interp-exp env) e)]))
  8094. ))
  8095. (define (interp-Rlambda p)
  8096. (send (new interp-Rlambda-class) interp-program p))
  8097. \end{lstlisting}
  8098. \caption{Interpreter for \LangLam{}.}
  8099. \label{fig:interp-Rlambda}
  8100. \end{figure}
  8101. \label{sec:type-check-r5}
  8102. \index{type checking}
  8103. Figure~\ref{fig:type-check-Rlambda} shows how to type check the new
  8104. \key{lambda} form. The body of the \key{lambda} is checked in an
  8105. environment that includes the current environment (because it is
  8106. lexically scoped) and also includes the \key{lambda}'s parameters. We
  8107. require the body's type to match the declared return type.
  8108. \begin{figure}[tbp]
  8109. \begin{lstlisting}
  8110. (define (type-check-Rlambda env)
  8111. (lambda (e)
  8112. (match e
  8113. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  8114. (define-values (new-body bodyT)
  8115. ((type-check-exp (append (map cons xs Ts) env)) body))
  8116. (define ty `(,@Ts -> ,rT))
  8117. (cond
  8118. [(equal? rT bodyT)
  8119. (values (HasType (Lambda params rT new-body) ty) ty)]
  8120. [else
  8121. (error "mismatch in return type" bodyT rT)])]
  8122. ...
  8123. )))
  8124. \end{lstlisting}
  8125. \caption{Type checking the \key{lambda}'s in \LangLam{}.}
  8126. \label{fig:type-check-Rlambda}
  8127. \end{figure}
  8128. \section{Reveal Functions and the $F_2$ language}
  8129. \label{sec:reveal-functions-r5}
  8130. To support the \code{procedure-arity} operator we need to communicate
  8131. the arity of a function to the point of closure creation. We can
  8132. accomplish this by replacing the $\FUNREF{\Var}$ struct with one that
  8133. has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$. The
  8134. output of this pass is the language $F_2$, whose syntax is defined in
  8135. Figure~\ref{fig:f2-syntax}.
  8136. \begin{figure}[tp]
  8137. \centering
  8138. \fbox{
  8139. \begin{minipage}{0.96\textwidth}
  8140. \[
  8141. \begin{array}{lcl}
  8142. \Exp &::=& \ldots \mid \FUNREFARITY{\Var}{\Int}\\
  8143. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  8144. F_2 &::=& \gray{\PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}}
  8145. \end{array}
  8146. \]
  8147. \end{minipage}
  8148. }
  8149. \caption{The abstract syntax $F_2$, an extension of \LangLam{}
  8150. (Figure~\ref{fig:Rlam-syntax}).}
  8151. \label{fig:f2-syntax}
  8152. \end{figure}
  8153. \section{Closure Conversion}
  8154. \label{sec:closure-conversion}
  8155. \index{closure conversion}
  8156. The compiling of lexically-scoped functions into top-level function
  8157. definitions is accomplished in the pass \code{convert-to-closures}
  8158. that comes after \code{reveal-functions} and before
  8159. \code{limit-functions}.
  8160. As usual, we implement the pass as a recursive function over the
  8161. AST. All of the action is in the cases for \key{Lambda} and
  8162. \key{Apply}. We transform a \key{Lambda} expression into an expression
  8163. that creates a closure, that is, a vector whose first element is a
  8164. function pointer and the rest of the elements are the free variables
  8165. of the \key{Lambda}. We use the struct \code{Closure} here instead of
  8166. using \code{vector} so that we can distinguish closures from vectors
  8167. in Section~\ref{sec:optimize-closures} and to record the arity. In
  8168. the generated code below, the \itm{name} is a unique symbol generated
  8169. to identify the function and the \itm{arity} is the number of
  8170. parameters (the length of \itm{ps}).
  8171. \begin{lstlisting}
  8172. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  8173. |$\Rightarrow$|
  8174. (Closure |\itm{arity}| (cons (FunRef |\itm{name}|) |\itm{fvs}|))
  8175. \end{lstlisting}
  8176. In addition to transforming each \key{Lambda} into a \key{Closure}, we
  8177. create a top-level function definition for each \key{Lambda}, as
  8178. shown below.\\
  8179. \begin{minipage}{0.8\textwidth}
  8180. \begin{lstlisting}
  8181. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  8182. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  8183. ...
  8184. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  8185. |\itm{body'}|)...))
  8186. \end{lstlisting}
  8187. \end{minipage}\\
  8188. The \code{clos} parameter refers to the closure. Translate the type
  8189. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  8190. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The types
  8191. $\itm{fvts}$ are the types of the free variables in the lambda and the
  8192. underscore \code{\_} is a dummy type that we use because it is rather
  8193. difficult to give a type to the function in the closure's
  8194. type.\footnote{To give an accurate type to a closure, we would need to
  8195. add existential types to the type checker~\citep{Minamide:1996ys}.}
  8196. The dummy type is considered to be equal to any other type during type
  8197. checking. The sequence of \key{Let} forms bind the free variables to
  8198. their values obtained from the closure.
  8199. Closure conversion turns functions into vectors, so the type
  8200. annotations in the program must also be translated. We recommend
  8201. defining a auxiliary recursive function for this purpose. Function
  8202. types should be translated as follows.
  8203. \begin{lstlisting}
  8204. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  8205. |$\Rightarrow$|
  8206. (Vector ((Vector _) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  8207. \end{lstlisting}
  8208. The above type says that the first thing in the vector is a function
  8209. pointer. The first parameter of the function pointer is a vector (a
  8210. closure) and the rest of the parameters are the ones from the original
  8211. function, with types $T'_1, \ldots, T'_n$. The \code{Vector} type for
  8212. the closure omits the types of the free variables because 1) those
  8213. types are not available in this context and 2) we do not need them in
  8214. the code that is generated for function application.
  8215. We transform function application into code that retrieves the
  8216. function pointer from the closure and then calls the function, passing
  8217. in the closure as the first argument. We bind $e'$ to a temporary
  8218. variable to avoid code duplication.
  8219. \begin{lstlisting}
  8220. (Apply |$e$| |\itm{es}|)
  8221. |$\Rightarrow$|
  8222. (Let |\itm{tmp}| |$e'$|
  8223. (Apply (Prim 'vector-ref (list (Var |\itm{tmp}|) (Int 0))) (cons |\itm{tmp}| |\itm{es'}|)))
  8224. \end{lstlisting}
  8225. There is also the question of what to do with references top-level
  8226. function definitions. To maintain a uniform translation of function
  8227. application, we turn function references into closures.
  8228. \begin{tabular}{lll}
  8229. \begin{minipage}{0.3\textwidth}
  8230. \begin{lstlisting}
  8231. (FunRefArity |$f$| |$n$|)
  8232. \end{lstlisting}
  8233. \end{minipage}
  8234. &
  8235. $\Rightarrow$
  8236. &
  8237. \begin{minipage}{0.5\textwidth}
  8238. \begin{lstlisting}
  8239. (Closure |$n$| (FunRef |$f$|) '())
  8240. \end{lstlisting}
  8241. \end{minipage}
  8242. \end{tabular} \\
  8243. %
  8244. The top-level function definitions need to be updated as well to take
  8245. an extra closure parameter.
  8246. \section{An Example Translation}
  8247. \label{sec:example-lambda}
  8248. Figure~\ref{fig:lexical-functions-example} shows the result of
  8249. \code{reveal-functions} and \code{convert-to-closures} for the example
  8250. program demonstrating lexical scoping that we discussed at the
  8251. beginning of this chapter.
  8252. \begin{figure}[tbp]
  8253. \begin{minipage}{0.8\textwidth}
  8254. % tests/lambda_test_6.rkt
  8255. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8256. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  8257. (let ([y8 4])
  8258. (lambda: ([z9 : Integer]) : Integer
  8259. (+ x7 (+ y8 z9)))))
  8260. (define (main) : Integer
  8261. (let ([g0 ((fun-ref-arity f6 1) 5)])
  8262. (let ([h1 ((fun-ref-arity f6 1) 3)])
  8263. (+ (g0 11) (h1 15)))))
  8264. \end{lstlisting}
  8265. $\Rightarrow$
  8266. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8267. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  8268. (let ([y8 4])
  8269. (closure 1 (list (fun-ref lambda2) x7 y8))))
  8270. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  8271. (let ([x7 (vector-ref fvs3 1)])
  8272. (let ([y8 (vector-ref fvs3 2)])
  8273. (+ x7 (+ y8 z9)))))
  8274. (define (main) : Integer
  8275. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6)))])
  8276. ((vector-ref clos5 0) clos5 5))])
  8277. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6)))])
  8278. ((vector-ref clos6 0) clos6 3))])
  8279. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  8280. \end{lstlisting}
  8281. \end{minipage}
  8282. \caption{Example of closure conversion.}
  8283. \label{fig:lexical-functions-example}
  8284. \end{figure}
  8285. \begin{exercise}\normalfont
  8286. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  8287. Create 5 new programs that use \key{lambda} functions and make use of
  8288. lexical scoping. Test your compiler on these new programs and all of
  8289. your previously created test programs.
  8290. \end{exercise}
  8291. \section{Expose Allocation}
  8292. \label{sec:expose-allocation-r5}
  8293. Compile the $\CLOSURE{\itm{arity}}{\LP\Exp\ldots\RP}$ form into code
  8294. that allocates and initializes a vector, similar to the translation of
  8295. the \code{vector} operator in Section~\ref{sec:expose-allocation}.
  8296. The only difference is replacing the use of
  8297. \ALLOC{\itm{len}}{\itm{type}} with
  8298. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  8299. \section{Explicate Control and \LangCLam{}}
  8300. \label{sec:explicate-r5}
  8301. The output language of \code{explicate-control} is \LangCLam{} whose
  8302. abstract syntax is defined in Figure~\ref{fig:c4-syntax}. The only
  8303. difference with respect to \LangCFun{} is the addition of the
  8304. \code{AllocateClosure} form to the grammar for $\Exp$. The handling
  8305. of \code{AllocateClosure} in the \code{explicate-control} pass is
  8306. similar to the handling of other expressions such as primitive
  8307. operators.
  8308. \begin{figure}[tp]
  8309. \fbox{
  8310. \begin{minipage}{0.96\textwidth}
  8311. \small
  8312. \[
  8313. \begin{array}{lcl}
  8314. \Exp &::= & \ldots
  8315. \mid \ALLOCCLOS{\Int}{\Type}{\Int} \\
  8316. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  8317. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  8318. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  8319. \mid \GOTO{\itm{label}} } \\
  8320. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  8321. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  8322. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  8323. \LangCLam{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  8324. \end{array}
  8325. \]
  8326. \end{minipage}
  8327. }
  8328. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  8329. \label{fig:c4-syntax}
  8330. \end{figure}
  8331. \section{Select Instructions}
  8332. \label{sec:select-instructions-Rlambda}
  8333. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  8334. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  8335. (Section~\ref{sec:select-instructions-gc}). The only difference is
  8336. that you should place the \itm{arity} in the tag that is stored at
  8337. position $0$ of the vector. Recall that in
  8338. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  8339. was not used. We store the arity in the $5$ bits starting at position
  8340. $58$.
  8341. Compile the \code{procedure-arity} operator into a sequence of
  8342. instructions that access the tag from position $0$ of the vector and
  8343. extract the $5$-bits starting at position $58$ from the tag.
  8344. \begin{figure}[p]
  8345. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8346. \node (Rfun) at (0,2) {\large \LangFun{}};
  8347. \node (Rfun-2) at (3,2) {\large \LangFun{}};
  8348. \node (Rfun-3) at (6,2) {\large \LangFun{}};
  8349. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  8350. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  8351. \node (F1-3) at (6,0) {\large $F_1$};
  8352. \node (F1-4) at (3,0) {\large $F_1$};
  8353. \node (F1-5) at (0,0) {\large $F_1$};
  8354. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  8355. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  8356. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  8357. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  8358. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  8359. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  8360. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  8361. \path[->,bend left=15] (Rfun) edge [above] node
  8362. {\ttfamily\footnotesize shrink} (Rfun-2);
  8363. \path[->,bend left=15] (Rfun-2) edge [above] node
  8364. {\ttfamily\footnotesize uniquify} (Rfun-3);
  8365. \path[->,bend left=15] (Rfun-3) edge [right] node
  8366. {\ttfamily\footnotesize reveal-functions} (F1-1);
  8367. \path[->,bend left=15] (F1-1) edge [below] node
  8368. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  8369. \path[->,bend right=15] (F1-2) edge [above] node
  8370. {\ttfamily\footnotesize limit-fun.} (F1-3);
  8371. \path[->,bend right=15] (F1-3) edge [above] node
  8372. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  8373. \path[->,bend right=15] (F1-4) edge [above] node
  8374. {\ttfamily\footnotesize remove-complex.} (F1-5);
  8375. \path[->,bend right=15] (F1-5) edge [right] node
  8376. {\ttfamily\footnotesize explicate-control} (C3-2);
  8377. \path[->,bend left=15] (C3-2) edge [left] node
  8378. {\ttfamily\footnotesize select-instr.} (x86-2);
  8379. \path[->,bend right=15] (x86-2) edge [left] node
  8380. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  8381. \path[->,bend right=15] (x86-2-1) edge [below] node
  8382. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  8383. \path[->,bend right=15] (x86-2-2) edge [left] node
  8384. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  8385. \path[->,bend left=15] (x86-3) edge [above] node
  8386. {\ttfamily\footnotesize patch-instr.} (x86-4);
  8387. \path[->,bend left=15] (x86-4) edge [right] node
  8388. {\ttfamily\footnotesize print-x86} (x86-5);
  8389. \end{tikzpicture}
  8390. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  8391. functions.}
  8392. \label{fig:Rlambda-passes}
  8393. \end{figure}
  8394. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  8395. for the compilation of \LangLam{}.
  8396. \clearpage
  8397. \section{Challenge: Optimize Closures}
  8398. \label{sec:optimize-closures}
  8399. In this chapter we compiled lexically-scoped functions into a
  8400. relatively efficient representation: flat closures. However, even this
  8401. representation comes with some overhead. For example, consider the
  8402. following program with a function \code{tail-sum} that does not have
  8403. any free variables and where all the uses of \code{tail-sum} are in
  8404. applications where we know that only \code{tail-sum} is being applied
  8405. (and not any other functions).
  8406. \begin{center}
  8407. \begin{minipage}{0.95\textwidth}
  8408. \begin{lstlisting}
  8409. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  8410. (if (eq? n 0)
  8411. r
  8412. (tail-sum (- n 1) (+ n r))))
  8413. (+ (tail-sum 5 0) 27)
  8414. \end{lstlisting}
  8415. \end{minipage}
  8416. \end{center}
  8417. As described in this chapter, we uniformly apply closure conversion to
  8418. all functions, obtaining the following output for this program.
  8419. \begin{center}
  8420. \begin{minipage}{0.95\textwidth}
  8421. \begin{lstlisting}
  8422. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [r3 : Integer]) : Integer
  8423. (if (eq? n2 0)
  8424. r3
  8425. (let ([clos4 (closure (list (fun-ref tail_sum1)))])
  8426. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 r3)))))
  8427. (define (main) : Integer
  8428. (+ (let ([clos6 (closure (list (fun-ref tail_sum1)))])
  8429. ((vector-ref clos6 0) clos6 5 0)) 27))
  8430. \end{lstlisting}
  8431. \end{minipage}
  8432. \end{center}
  8433. In the previous Chapter, there would be no allocation in the program
  8434. and the calls to \code{tail-sum} would be direct calls. In contrast,
  8435. the above program allocates memory for each \code{closure} and the
  8436. calls to \code{tail-sum} are indirect. These two differences incur
  8437. considerable overhead in a program such as this one, where the
  8438. allocations and indirect calls occur inside a tight loop.
  8439. One might think that this problem is trivial to solve: can't we just
  8440. recognize calls of the form \code{((fun-ref $f$) $e_1 \ldots e_n$)}
  8441. and compile them to direct calls \code{((fun-ref $f$) $e'_1 \ldots
  8442. e'_n$)} instead of treating it like a call to a closure? We would
  8443. also drop the \code{fvs5} parameter of \code{tail\_sum1}.
  8444. %
  8445. However, this problem is not so trivial because a global function may
  8446. ``escape'' and become involved in applications that also involve
  8447. closures. Consider the following example in which the application
  8448. \code{(f 41)} needs to be compiled into a closure application, because
  8449. the \code{lambda} may get bound to \code{f}, but the \code{add1}
  8450. function might also get bound to \code{f}.
  8451. \begin{lstlisting}
  8452. (define (add1 [x : Integer]) : Integer
  8453. (+ x 1))
  8454. (let ([y (read)])
  8455. (let ([f (if (eq? (read) 0)
  8456. add1
  8457. (lambda: ([x : Integer]) : Integer (- x y)))])
  8458. (f 41)))
  8459. \end{lstlisting}
  8460. If a global function name is used in any way other than as the
  8461. operator in a direct call, then we say that the function
  8462. \emph{escapes}. If a global function does not escape, then we do not
  8463. need to perform closure conversion on the function.
  8464. \begin{exercise}\normalfont
  8465. Implement an auxiliary function for detecting which global
  8466. functions escape. Using that function, implement an improved version
  8467. of closure conversion that does not apply closure conversion to
  8468. global functions that do not escape but instead compiles them as
  8469. regular functions. Create several new test cases that check whether
  8470. you properly detect whether global functions escape or not.
  8471. \end{exercise}
  8472. So far we have reduced the overhead of calling global functions, but
  8473. it would also be nice to reduce the overhead of calling a
  8474. \code{lambda} when we can determine at compile time which
  8475. \code{lambda} will be called. We refer to such calls as \emph{known
  8476. calls}. Consider the following example in which a \code{lambda} is
  8477. bound to \code{f} and then applied.
  8478. \begin{lstlisting}
  8479. (let ([y (read)])
  8480. (let ([f (lambda: ([x : Integer]) : Integer
  8481. (+ x y))])
  8482. (f 21)))
  8483. \end{lstlisting}
  8484. Closure conversion compiles \code{(f 21)} into an indirect call:
  8485. \begin{lstlisting}
  8486. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  8487. (let ([y2 (vector-ref fvs6 1)])
  8488. (+ x3 y2)))
  8489. (define (main) : Integer
  8490. (let ([y2 (read)])
  8491. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  8492. ((vector-ref f4 0) f4 21))))
  8493. \end{lstlisting}
  8494. but we can instead compile the application \code{(f 21)} into a direct call
  8495. to \code{lambda5}:
  8496. \begin{lstlisting}
  8497. (define (main) : Integer
  8498. (let ([y2 (read)])
  8499. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  8500. ((fun-ref lambda5) f4 21))))
  8501. \end{lstlisting}
  8502. The problem of determining which lambda will be called from a
  8503. particular application is quite challenging in general and the topic
  8504. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  8505. following exercise we recommend that you compile an application to a
  8506. direct call when the operator is a variable and the variable is
  8507. \code{let}-bound to a closure. This can be accomplished by maintaining
  8508. an environment mapping \code{let}-bound variables to function names.
  8509. Extend the environment whenever you encounter a closure on the
  8510. right-hand side of a \code{let}, mapping the \code{let}-bound variable
  8511. to the name of the global function for the closure. This pass should
  8512. come after closure conversion.
  8513. \begin{exercise}\normalfont
  8514. Implement a compiler pass, named \code{optimize-known-calls}, that
  8515. compiles known calls into direct calls. Verify that your compiler is
  8516. successful in this regard on several example programs.
  8517. \end{exercise}
  8518. These exercises only scratches the surface of optimizing of
  8519. closures. A good next step for the interested reader is to look at the
  8520. work of \citet{Keep:2012ab}.
  8521. \section{Further Reading}
  8522. The notion of lexically scoped anonymous functions predates modern
  8523. computers by about a decade. They were invented by
  8524. \citet{Church:1932aa}, who proposed the $\lambda$ calculus as a
  8525. foundation for logic. Anonymous functions were included in the
  8526. LISP~\citep{McCarthy:1960dz} programming language but were initially
  8527. dynamically scoped. The Scheme dialect of LISP adopted lexical scoping
  8528. and \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently
  8529. compile Scheme programs. However, environments were represented as
  8530. linked lists, so variable lookup was linear in the size of the
  8531. environment. In this chapter we represent environments using flat
  8532. closures, which were invented by
  8533. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  8534. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  8535. closures, variable lookup is constant time but the time to create a
  8536. closure is proportional to the number of its free variables. Flat
  8537. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  8538. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  8539. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8540. \chapter{Dynamic Typing}
  8541. \label{ch:Rdyn}
  8542. \index{dynamic typing}
  8543. In this chapter we discuss the compilation of \LangDyn{}, a dynamically
  8544. typed language that is a subset of Racket. This is in contrast to the
  8545. previous chapters, which have studied the compilation of Typed
  8546. Racket. In dynamically typed languages such as \LangDyn{}, a given
  8547. expression may produce a value of a different type each time it is
  8548. executed. Consider the following example with a conditional \code{if}
  8549. expression that may return a Boolean or an integer depending on the
  8550. input to the program.
  8551. % part of dynamic_test_25.rkt
  8552. \begin{lstlisting}
  8553. (not (if (eq? (read) 1) #f 0))
  8554. \end{lstlisting}
  8555. Languages that allow expressions to produce different kinds of values
  8556. are called \emph{polymorphic}, a word composed of the Greek roots
  8557. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  8558. are several kinds of polymorphism in programming languages, such as
  8559. subtype polymorphism and parametric
  8560. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  8561. study in this chapter does not have a special name but it is the kind
  8562. that arises in dynamically typed languages.
  8563. Another characteristic of dynamically typed languages is that
  8564. primitive operations, such as \code{not}, are often defined to operate
  8565. on many different types of values. In fact, in Racket, the \code{not}
  8566. operator produces a result for any kind of value: given \code{\#f} it
  8567. returns \code{\#t} and given anything else it returns \code{\#f}.
  8568. Furthermore, even when primitive operations restrict their inputs to
  8569. values of a certain type, this restriction is enforced at runtime
  8570. instead of during compilation. For example, the following vector
  8571. reference results in a run-time contract violation because the index
  8572. must be in integer, not a Boolean such as \code{\#t}.
  8573. \begin{lstlisting}
  8574. (vector-ref (vector 42) #t)
  8575. \end{lstlisting}
  8576. \begin{figure}[tp]
  8577. \centering
  8578. \fbox{
  8579. \begin{minipage}{0.97\textwidth}
  8580. \[
  8581. \begin{array}{rcl}
  8582. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  8583. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp}
  8584. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} \\
  8585. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  8586. &\mid& \key{\#t} \mid \key{\#f}
  8587. \mid \CBINOP{\key{and}}{\Exp}{\Exp}
  8588. \mid \CBINOP{\key{or}}{\Exp}{\Exp}
  8589. \mid \CUNIOP{\key{not}}{\Exp} \\
  8590. &\mid& \LP\itm{cmp}\;\Exp\;\Exp\RP \mid \CIF{\Exp}{\Exp}{\Exp} \\
  8591. &\mid& \LP\key{vector}\;\Exp\ldots\RP \mid
  8592. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  8593. &\mid& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \mid \LP\key{void}\RP \\
  8594. &\mid& \LP\Exp \; \Exp\ldots\RP
  8595. \mid \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  8596. & \mid & \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP\\
  8597. & \mid & \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \mid \LP\key{void?}\;\Exp\RP \\
  8598. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  8599. \LangDyn{} &::=& \Def\ldots\; \Exp
  8600. \end{array}
  8601. \]
  8602. \end{minipage}
  8603. }
  8604. \caption{Syntax of \LangDyn{}, an untyped language (a subset of Racket).}
  8605. \label{fig:r7-concrete-syntax}
  8606. \end{figure}
  8607. \begin{figure}[tp]
  8608. \centering
  8609. \fbox{
  8610. \begin{minipage}{0.96\textwidth}
  8611. \small
  8612. \[
  8613. \begin{array}{lcl}
  8614. \Exp &::=& \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  8615. &\mid& \PRIM{\itm{op}}{\Exp\ldots} \\
  8616. &\mid& \BOOL{\itm{bool}}
  8617. \mid \IF{\Exp}{\Exp}{\Exp} \\
  8618. &\mid& \VOID{} \mid \APPLY{\Exp}{\Exp\ldots} \\
  8619. &\mid& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  8620. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  8621. \LangDyn{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  8622. \end{array}
  8623. \]
  8624. \end{minipage}
  8625. }
  8626. \caption{The abstract syntax of \LangDyn{}.}
  8627. \label{fig:r7-syntax}
  8628. \end{figure}
  8629. The concrete and abstract syntax of \LangDyn{}, our subset of Racket, is
  8630. defined in Figures~\ref{fig:r7-concrete-syntax} and
  8631. \ref{fig:r7-syntax}.
  8632. %
  8633. There is no type checker for \LangDyn{} because it is not a statically
  8634. typed language (it's dynamically typed!).
  8635. The definitional interpreter for \LangDyn{} is presented in
  8636. Figure~\ref{fig:interp-Rdyn} and its auxiliary functions are defined i
  8637. Figure~\ref{fig:interp-Rdyn-aux}. Consider the match case for
  8638. \code{(Int n)}. Instead of simply returning the integer \code{n} (as
  8639. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Rvar}), the
  8640. interpreter for \LangDyn{} creates a \emph{tagged value}\index{tagged
  8641. value} that combines an underlying value with a tag that identifies
  8642. what kind of value it is. We define the following struct
  8643. to represented tagged values.
  8644. \begin{lstlisting}
  8645. (struct Tagged (value tag) #:transparent)
  8646. \end{lstlisting}
  8647. The tags are \code{Integer}, \code{Boolean}, \code{Void},
  8648. \code{Vector}, and \code{Procedure}. Tags are closely related to types
  8649. but don't always capture all the information that a type does. For
  8650. example, a vector of type \code{(Vector Any Any)} is tagged with
  8651. \code{Vector} and a procedure of type \code{(Any Any -> Any)}
  8652. is tagged with \code{Procedure}.
  8653. Next consider the match case for \code{vector-ref}. The
  8654. \code{check-tag} auxiliary function (Figure~\ref{fig:interp-Rdyn-aux})
  8655. is used to ensure that the first argument is a vector and the second
  8656. is an integer. If they are not, a \code{trapped-error} is raised.
  8657. Recall from Section~\ref{sec:interp-Rint} that when a definition
  8658. interpreter raises a \code{trapped-error} error, the compiled code
  8659. must also signal an error by exiting with return code \code{255}. A
  8660. \code{trapped-error} is also raised if the index is not less than
  8661. length of the vector.
  8662. \begin{figure}[tbp]
  8663. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8664. (define ((interp-Rdyn-exp env) ast)
  8665. (define recur (interp-Rdyn-exp env))
  8666. (match ast
  8667. [(Var x) (lookup x env)]
  8668. [(Int n) (Tagged n 'Integer)]
  8669. [(Bool b) (Tagged b 'Boolean)]
  8670. [(Lambda xs rt body)
  8671. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  8672. [(Prim 'vector es)
  8673. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  8674. [(Prim 'vector-ref (list e1 e2))
  8675. (define vec (recur e1)) (define i (recur e2))
  8676. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  8677. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  8678. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  8679. (vector-ref (Tagged-value vec) (Tagged-value i))]
  8680. [(Prim 'vector-set! (list e1 e2 e3))
  8681. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  8682. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  8683. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  8684. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  8685. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  8686. (Tagged (void) 'Void)]
  8687. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  8688. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  8689. [(Prim 'or (list e1 e2))
  8690. (define v1 (recur e1))
  8691. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  8692. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  8693. [(Prim op (list e1))
  8694. #:when (set-member? type-predicates op)
  8695. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  8696. [(Prim op es)
  8697. (define args (map recur es))
  8698. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  8699. (unless (for/or ([expected-tags (op-tags op)])
  8700. (equal? expected-tags tags))
  8701. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  8702. (tag-value
  8703. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  8704. [(If q t f)
  8705. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  8706. [(Apply f es)
  8707. (define new-f (recur f)) (define args (map recur es))
  8708. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  8709. (match f-val
  8710. [`(function ,xs ,body ,lam-env)
  8711. (unless (eq? (length xs) (length args))
  8712. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  8713. (define new-env (append (map cons xs args) lam-env))
  8714. ((interp-Rdyn-exp new-env) body)]
  8715. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  8716. \end{lstlisting}
  8717. \caption{Interpreter for the \LangDyn{} language.}
  8718. \label{fig:interp-Rdyn}
  8719. \end{figure}
  8720. \begin{figure}[tbp]
  8721. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8722. (define (interp-op op)
  8723. (match op
  8724. ['+ fx+]
  8725. ['- fx-]
  8726. ['read read-fixnum]
  8727. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  8728. ['< (lambda (v1 v2)
  8729. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  8730. ['<= (lambda (v1 v2)
  8731. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  8732. ['> (lambda (v1 v2)
  8733. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  8734. ['>= (lambda (v1 v2)
  8735. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  8736. ['boolean? boolean?]
  8737. ['integer? fixnum?]
  8738. ['void? void?]
  8739. ['vector? vector?]
  8740. ['vector-length vector-length]
  8741. ['procedure? (match-lambda
  8742. [`(functions ,xs ,body ,env) #t] [else #f])]
  8743. [else (error 'interp-op "unknown operator" op)]))
  8744. (define (op-tags op)
  8745. (match op
  8746. ['+ '((Integer Integer))]
  8747. ['- '((Integer Integer) (Integer))]
  8748. ['read '(())]
  8749. ['not '((Boolean))]
  8750. ['< '((Integer Integer))]
  8751. ['<= '((Integer Integer))]
  8752. ['> '((Integer Integer))]
  8753. ['>= '((Integer Integer))]
  8754. ['vector-length '((Vector))]))
  8755. (define type-predicates
  8756. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  8757. (define (tag-value v)
  8758. (cond [(boolean? v) (Tagged v 'Boolean)]
  8759. [(fixnum? v) (Tagged v 'Integer)]
  8760. [(procedure? v) (Tagged v 'Procedure)]
  8761. [(vector? v) (Tagged v 'Vector)]
  8762. [(void? v) (Tagged v 'Void)]
  8763. [else (error 'tag-value "unidentified value ~a" v)]))
  8764. (define (check-tag val expected ast)
  8765. (define tag (Tagged-tag val))
  8766. (unless (eq? tag expected)
  8767. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  8768. \end{lstlisting}
  8769. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  8770. \label{fig:interp-Rdyn-aux}
  8771. \end{figure}
  8772. \clearpage
  8773. \section{Representation of Tagged Values}
  8774. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  8775. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  8776. values at the bit level. Because almost every operation in \LangDyn{}
  8777. involves manipulating tagged values, the representation must be
  8778. efficient. Recall that all of our values are 64 bits. We shall steal
  8779. the 3 right-most bits to encode the tag. We use $001$ to identify
  8780. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  8781. and $101$ for the void value. We define the following auxiliary
  8782. function for mapping types to tag codes.
  8783. \begin{align*}
  8784. \itm{tagof}(\key{Integer}) &= 001 \\
  8785. \itm{tagof}(\key{Boolean}) &= 100 \\
  8786. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  8787. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  8788. \itm{tagof}(\key{Void}) &= 101
  8789. \end{align*}
  8790. This stealing of 3 bits comes at some price: our integers are reduced
  8791. to ranging from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  8792. affect vectors and procedures because those values are addresses, and
  8793. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  8794. they are always $000$. Thus, we do not lose information by overwriting
  8795. the rightmost 3 bits with the tag and we can simply zero-out the tag
  8796. to recover the original address.
  8797. To make tagged values into first-class entities, we can give them a
  8798. type, called \code{Any}, and define operations such as \code{Inject}
  8799. and \code{Project} for creating and using them, yielding the \LangAny{}
  8800. intermediate language. We describe how to compile \LangDyn{} to \LangAny{} in
  8801. Section~\ref{sec:compile-r7} but first we describe the \LangAny{} language
  8802. in greater detail.
  8803. \section{The \LangAny{} Language}
  8804. \label{sec:Rany-lang}
  8805. \begin{figure}[tp]
  8806. \centering
  8807. \fbox{
  8808. \begin{minipage}{0.96\textwidth}
  8809. \small
  8810. \[
  8811. \begin{array}{lcl}
  8812. \Type &::= & \ldots \mid \key{Any} \\
  8813. \itm{op} &::= & \ldots \mid \code{any-vector-length}
  8814. \mid \code{any-vector-ref} \mid \code{any-vector-set!}\\
  8815. &\mid& \code{boolean?} \mid \code{integer?} \mid \code{vector?}
  8816. \mid \code{procedure?} \mid \code{void?} \\
  8817. \Exp &::=& \ldots
  8818. \mid \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  8819. &\mid& \INJECT{\Exp}{\FType} \mid \PROJECT{\Exp}{\FType} \\
  8820. \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  8821. \LangAny{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  8822. \end{array}
  8823. \]
  8824. \end{minipage}
  8825. }
  8826. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Rlam-syntax}).}
  8827. \label{fig:Rany-syntax}
  8828. \end{figure}
  8829. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Rany-syntax}.
  8830. (The concrete syntax of \LangAny{} is in the Appendix,
  8831. Figure~\ref{fig:Rany-concrete-syntax}.) The $\INJECT{e}{T}$ form
  8832. converts the value produced by expression $e$ of type $T$ into a
  8833. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  8834. produced by expression $e$ into a value of type $T$ or else halts the
  8835. program if the type tag is not equivalent to $T$.
  8836. %
  8837. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  8838. restricted to a flat type $\FType$, which simplifies the
  8839. implementation and corresponds with what is needed for compiling \LangDyn{}.
  8840. The \code{any-vector} operators adapt the vector operations so that
  8841. they can be applied to a value of type \code{Any}. They also
  8842. generalize the vector operations in that the index is not restricted
  8843. to be a literal integer in the grammar but is allowed to be any
  8844. expression.
  8845. The type predicates such as \key{boolean?} expect their argument to
  8846. produce a tagged value; they return \key{\#t} if the tag corresponds
  8847. to the predicate and they return \key{\#f} otherwise.
  8848. The type checker for \LangAny{} is shown in
  8849. Figures~\ref{fig:type-check-Rany-part-1} and
  8850. \ref{fig:type-check-Rany-part-2} and uses the auxiliary functions in
  8851. Figure~\ref{fig:type-check-Rany-aux}.
  8852. %
  8853. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Rany} and the
  8854. auxiliary functions \code{apply-inject} and \code{apply-project} are
  8855. in Figure~\ref{fig:apply-project}.
  8856. \begin{figure}[btp]
  8857. \begin{lstlisting}[basicstyle=\ttfamily\small]
  8858. (define type-check-Rany-class
  8859. (class type-check-Rlambda-class
  8860. (super-new)
  8861. (inherit check-type-equal?)
  8862. (define/override (type-check-exp env)
  8863. (lambda (e)
  8864. (define recur (type-check-exp env))
  8865. (match e
  8866. [(Inject e1 ty)
  8867. (unless (flat-ty? ty)
  8868. (error 'type-check "may only inject from flat type, not ~a" ty))
  8869. (define-values (new-e1 e-ty) (recur e1))
  8870. (check-type-equal? e-ty ty e)
  8871. (values (Inject new-e1 ty) 'Any)]
  8872. [(Project e1 ty)
  8873. (unless (flat-ty? ty)
  8874. (error 'type-check "may only project to flat type, not ~a" ty))
  8875. (define-values (new-e1 e-ty) (recur e1))
  8876. (check-type-equal? e-ty 'Any e)
  8877. (values (Project new-e1 ty) ty)]
  8878. [(Prim 'any-vector-length (list e1))
  8879. (define-values (e1^ t1) (recur e1))
  8880. (check-type-equal? t1 'Any e)
  8881. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  8882. [(Prim 'any-vector-ref (list e1 e2))
  8883. (define-values (e1^ t1) (recur e1))
  8884. (define-values (e2^ t2) (recur e2))
  8885. (check-type-equal? t1 'Any e)
  8886. (check-type-equal? t2 'Integer e)
  8887. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  8888. [(Prim 'any-vector-set! (list e1 e2 e3))
  8889. (define-values (e1^ t1) (recur e1))
  8890. (define-values (e2^ t2) (recur e2))
  8891. (define-values (e3^ t3) (recur e3))
  8892. (check-type-equal? t1 'Any e)
  8893. (check-type-equal? t2 'Integer e)
  8894. (check-type-equal? t3 'Any e)
  8895. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  8896. \end{lstlisting}
  8897. \caption{Type checker for the \LangAny{} language, part 1.}
  8898. \label{fig:type-check-Rany-part-1}
  8899. \end{figure}
  8900. \begin{figure}[btp]
  8901. \begin{lstlisting}[basicstyle=\ttfamily\small]
  8902. [(ValueOf e ty)
  8903. (define-values (new-e e-ty) (recur e))
  8904. (values (ValueOf new-e ty) ty)]
  8905. [(Prim pred (list e1))
  8906. #:when (set-member? (type-predicates) pred)
  8907. (define-values (new-e1 e-ty) (recur e1))
  8908. (check-type-equal? e-ty 'Any e)
  8909. (values (Prim pred (list new-e1)) 'Boolean)]
  8910. [(If cnd thn els)
  8911. (define-values (cnd^ Tc) (recur cnd))
  8912. (define-values (thn^ Tt) (recur thn))
  8913. (define-values (els^ Te) (recur els))
  8914. (check-type-equal? Tc 'Boolean cnd)
  8915. (check-type-equal? Tt Te e)
  8916. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  8917. [(Exit) (values (Exit) '_)]
  8918. [(Prim 'eq? (list arg1 arg2))
  8919. (define-values (e1 t1) (recur arg1))
  8920. (define-values (e2 t2) (recur arg2))
  8921. (match* (t1 t2)
  8922. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  8923. [(other wise) (check-type-equal? t1 t2 e)])
  8924. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  8925. [else ((super type-check-exp env) e)])))
  8926. ))
  8927. \end{lstlisting}
  8928. \caption{Type checker for the \LangAny{} language, part 2.}
  8929. \label{fig:type-check-Rany-part-2}
  8930. \end{figure}
  8931. \begin{figure}[tbp]
  8932. \begin{lstlisting}
  8933. (define/override (operator-types)
  8934. (append
  8935. '((integer? . ((Any) . Boolean))
  8936. (vector? . ((Any) . Boolean))
  8937. (procedure? . ((Any) . Boolean))
  8938. (void? . ((Any) . Boolean))
  8939. (tag-of-any . ((Any) . Integer))
  8940. (make-any . ((_ Integer) . Any))
  8941. )
  8942. (super operator-types)))
  8943. (define/public (type-predicates)
  8944. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  8945. (define/public (combine-types t1 t2)
  8946. (match (list t1 t2)
  8947. [(list '_ t2) t2]
  8948. [(list t1 '_) t1]
  8949. [(list `(Vector ,ts1 ...)
  8950. `(Vector ,ts2 ...))
  8951. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  8952. (combine-types t1 t2)))]
  8953. [(list `(,ts1 ... -> ,rt1)
  8954. `(,ts2 ... -> ,rt2))
  8955. `(,@(for/list ([t1 ts1] [t2 ts2])
  8956. (combine-types t1 t2))
  8957. -> ,(combine-types rt1 rt2))]
  8958. [else t1]))
  8959. (define/public (flat-ty? ty)
  8960. (match ty
  8961. [(or `Integer `Boolean '_ `Void) #t]
  8962. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  8963. [`(,ts ... -> ,rt)
  8964. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  8965. [else #f]))
  8966. \end{lstlisting}
  8967. \caption{Auxiliary methods for type checking \LangAny{}.}
  8968. \label{fig:type-check-Rany-aux}
  8969. \end{figure}
  8970. \begin{figure}[btp]
  8971. \begin{lstlisting}
  8972. (define interp-Rany-class
  8973. (class interp-Rlambda-class
  8974. (super-new)
  8975. (define/override (interp-op op)
  8976. (match op
  8977. ['boolean? (match-lambda
  8978. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  8979. [else #f])]
  8980. ['integer? (match-lambda
  8981. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  8982. [else #f])]
  8983. ['vector? (match-lambda
  8984. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  8985. [else #f])]
  8986. ['procedure? (match-lambda
  8987. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  8988. [else #f])]
  8989. ['eq? (match-lambda*
  8990. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  8991. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  8992. [ls (apply (super interp-op op) ls)])]
  8993. ['any-vector-ref (lambda (v i)
  8994. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  8995. ['any-vector-set! (lambda (v i a)
  8996. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  8997. ['any-vector-length (lambda (v)
  8998. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  8999. [else (super interp-op op)]))
  9000. (define/override ((interp-exp env) e)
  9001. (define recur (interp-exp env))
  9002. (match e
  9003. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  9004. [(Project e ty2) (apply-project (recur e) ty2)]
  9005. [else ((super interp-exp env) e)]))
  9006. ))
  9007. (define (interp-Rany p)
  9008. (send (new interp-Rany-class) interp-program p))
  9009. \end{lstlisting}
  9010. \caption{Interpreter for \LangAny{}.}
  9011. \label{fig:interp-Rany}
  9012. \end{figure}
  9013. \begin{figure}[tbp]
  9014. \begin{lstlisting}
  9015. (define/public (apply-inject v tg) (Tagged v tg))
  9016. (define/public (apply-project v ty2)
  9017. (define tag2 (any-tag ty2))
  9018. (match v
  9019. [(Tagged v1 tag1)
  9020. (cond
  9021. [(eq? tag1 tag2)
  9022. (match ty2
  9023. [`(Vector ,ts ...)
  9024. (define l1 ((interp-op 'vector-length) v1))
  9025. (cond
  9026. [(eq? l1 (length ts)) v1]
  9027. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  9028. l1 (length ts))])]
  9029. [`(,ts ... -> ,rt)
  9030. (match v1
  9031. [`(function ,xs ,body ,env)
  9032. (cond [(eq? (length xs) (length ts)) v1]
  9033. [else
  9034. (error 'apply-project "arity mismatch ~a != ~a"
  9035. (length xs) (length ts))])]
  9036. [else (error 'apply-project "expected function not ~a" v1)])]
  9037. [else v1])]
  9038. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  9039. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  9040. \end{lstlisting}
  9041. \caption{Auxiliary functions for injection and projection.}
  9042. \label{fig:apply-project}
  9043. \end{figure}
  9044. \clearpage
  9045. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  9046. \label{sec:compile-r7}
  9047. The \code{cast-insert} pass compiles from \LangDyn{} to \LangAny{}.
  9048. Figure~\ref{fig:compile-r7-Rany} shows the compilation of many of the
  9049. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  9050. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  9051. an expression $e'$ in \LangAny{} that has type \key{Any}. For example, the
  9052. first row in Figure~\ref{fig:compile-r7-Rany} shows the compilation of
  9053. the Boolean \code{\#t}, which must be injected to produce an
  9054. expression of type \key{Any}.
  9055. %
  9056. The second row of Figure~\ref{fig:compile-r7-Rany}, the compilation of
  9057. addition, is representative of compilation for many primitive
  9058. operations: the arguments have type \key{Any} and must be projected to
  9059. \key{Integer} before the addition can be performed.
  9060. The compilation of \key{lambda} (third row of
  9061. Figure~\ref{fig:compile-r7-Rany}) shows what happens when we need to
  9062. produce type annotations: we simply use \key{Any}.
  9063. %
  9064. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  9065. has to account for some differences in behavior between \LangDyn{} and
  9066. \LangAny{}. The \LangDyn{} language is more permissive than \LangAny{} regarding what
  9067. kind of values can be used in various places. For example, the
  9068. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  9069. the arguments need not be of the same type (in that case the
  9070. result is \code{\#f}).
  9071. \begin{figure}[btp]
  9072. \centering
  9073. \begin{tabular}{|lll|} \hline
  9074. \begin{minipage}{0.27\textwidth}
  9075. \begin{lstlisting}
  9076. #t
  9077. \end{lstlisting}
  9078. \end{minipage}
  9079. &
  9080. $\Rightarrow$
  9081. &
  9082. \begin{minipage}{0.65\textwidth}
  9083. \begin{lstlisting}
  9084. (inject #t Boolean)
  9085. \end{lstlisting}
  9086. \end{minipage}
  9087. \\[2ex]\hline
  9088. \begin{minipage}{0.27\textwidth}
  9089. \begin{lstlisting}
  9090. (+ |$e_1$| |$e_2$|)
  9091. \end{lstlisting}
  9092. \end{minipage}
  9093. &
  9094. $\Rightarrow$
  9095. &
  9096. \begin{minipage}{0.65\textwidth}
  9097. \begin{lstlisting}
  9098. (inject
  9099. (+ (project |$e'_1$| Integer)
  9100. (project |$e'_2$| Integer))
  9101. Integer)
  9102. \end{lstlisting}
  9103. \end{minipage}
  9104. \\[2ex]\hline
  9105. \begin{minipage}{0.27\textwidth}
  9106. \begin{lstlisting}
  9107. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  9108. \end{lstlisting}
  9109. \end{minipage}
  9110. &
  9111. $\Rightarrow$
  9112. &
  9113. \begin{minipage}{0.65\textwidth}
  9114. \begin{lstlisting}
  9115. (inject
  9116. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  9117. (Any|$\ldots$|Any -> Any))
  9118. \end{lstlisting}
  9119. \end{minipage}
  9120. \\[2ex]\hline
  9121. \begin{minipage}{0.27\textwidth}
  9122. \begin{lstlisting}
  9123. (|$e_0$| |$e_1 \ldots e_n$|)
  9124. \end{lstlisting}
  9125. \end{minipage}
  9126. &
  9127. $\Rightarrow$
  9128. &
  9129. \begin{minipage}{0.65\textwidth}
  9130. \begin{lstlisting}
  9131. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  9132. \end{lstlisting}
  9133. \end{minipage}
  9134. \\[2ex]\hline
  9135. \begin{minipage}{0.27\textwidth}
  9136. \begin{lstlisting}
  9137. (vector-ref |$e_1$| |$e_2$|)
  9138. \end{lstlisting}
  9139. \end{minipage}
  9140. &
  9141. $\Rightarrow$
  9142. &
  9143. \begin{minipage}{0.65\textwidth}
  9144. \begin{lstlisting}
  9145. (any-vector-ref |$e_1'$| |$e_2'$|)
  9146. \end{lstlisting}
  9147. \end{minipage}
  9148. \\[2ex]\hline
  9149. \begin{minipage}{0.27\textwidth}
  9150. \begin{lstlisting}
  9151. (if |$e_1$| |$e_2$| |$e_3$|)
  9152. \end{lstlisting}
  9153. \end{minipage}
  9154. &
  9155. $\Rightarrow$
  9156. &
  9157. \begin{minipage}{0.65\textwidth}
  9158. \begin{lstlisting}
  9159. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  9160. \end{lstlisting}
  9161. \end{minipage}
  9162. \\[2ex]\hline
  9163. \begin{minipage}{0.27\textwidth}
  9164. \begin{lstlisting}
  9165. (eq? |$e_1$| |$e_2$|)
  9166. \end{lstlisting}
  9167. \end{minipage}
  9168. &
  9169. $\Rightarrow$
  9170. &
  9171. \begin{minipage}{0.65\textwidth}
  9172. \begin{lstlisting}
  9173. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  9174. \end{lstlisting}
  9175. \end{minipage}
  9176. \\[2ex]\hline
  9177. \begin{minipage}{0.27\textwidth}
  9178. \begin{lstlisting}
  9179. (not |$e_1$|)
  9180. \end{lstlisting}
  9181. \end{minipage}
  9182. &
  9183. $\Rightarrow$
  9184. &
  9185. \begin{minipage}{0.65\textwidth}
  9186. \begin{lstlisting}
  9187. (if (eq? |$e'_1$| (inject #f Boolean))
  9188. (inject #t Boolean) (inject #f Boolean))
  9189. \end{lstlisting}
  9190. \end{minipage}
  9191. \\[2ex]\hline
  9192. \end{tabular}
  9193. \caption{Cast Insertion}
  9194. \label{fig:compile-r7-Rany}
  9195. \end{figure}
  9196. \section{Reveal Casts}
  9197. \label{sec:reveal-casts-Rany}
  9198. % TODO: define R'_6
  9199. In the \code{reveal-casts} pass we recommend compiling \code{project}
  9200. into an \code{if} expression that checks whether the value's tag
  9201. matches the target type; if it does, the value is converted to a value
  9202. of the target type by removing the tag; if it does not, the program
  9203. exits. To perform these actions we need a new primitive operation,
  9204. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  9205. The \code{tag-of-any} operation retrieves the type tag from a tagged
  9206. value of type \code{Any}. The \code{ValueOf} form retrieves the
  9207. underlying value from a tagged value. The \code{ValueOf} form
  9208. includes the type for the underlying value which is used by the type
  9209. checker. Finally, the \code{Exit} form ends the execution of the
  9210. program.
  9211. If the target type of the projection is \code{Boolean} or
  9212. \code{Integer}, then \code{Project} can be translated as follows.
  9213. \begin{center}
  9214. \begin{minipage}{1.0\textwidth}
  9215. \begin{lstlisting}
  9216. (Project |$e$| |$\FType$|)
  9217. |$\Rightarrow$|
  9218. (Let |$\itm{tmp}$| |$e'$|
  9219. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  9220. (Int |$\itm{tagof}(\FType)$|)))
  9221. (ValueOf |$\itm{tmp}$| |$\FType$|)
  9222. (Exit)))
  9223. \end{lstlisting}
  9224. \end{minipage}
  9225. \end{center}
  9226. If the target type of the projection is a vector or function type,
  9227. then there is a bit more work to do. For vectors, check that the
  9228. length of the vector type matches the length of the vector (using the
  9229. \code{vector-length} primitive). For functions, check that the number
  9230. of parameters in the function type matches the function's arity (using
  9231. \code{procedure-arity}).
  9232. Regarding \code{inject}, we recommend compiling it to a slightly
  9233. lower-level primitive operation named \code{make-any}. This operation
  9234. takes a tag instead of a type.
  9235. \begin{center}
  9236. \begin{minipage}{1.0\textwidth}
  9237. \begin{lstlisting}
  9238. (Inject |$e$| |$\FType$|)
  9239. |$\Rightarrow$|
  9240. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  9241. \end{lstlisting}
  9242. \end{minipage}
  9243. \end{center}
  9244. The type predicates (\code{boolean?}, etc.) can be translated into
  9245. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  9246. translation of \code{Project}.
  9247. The \code{any-vector-ref} and \code{any-vector-set!} operations
  9248. combine the projection action with the vector operation. Also, the
  9249. read and write operations allow arbitrary expressions for the index so
  9250. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany-part-1})
  9251. cannot guarantee that the index is within bounds. Thus, we insert code
  9252. to perform bounds checking at runtime. The translation for
  9253. \code{any-vector-ref} is as follows and the other two operations are
  9254. translated in a similar way.
  9255. \begin{lstlisting}
  9256. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  9257. |$\Rightarrow$|
  9258. (Let |$v$| |$e'_1$|
  9259. (Let |$i$| |$e'_2$|
  9260. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  9261. (If (Prim '< (list (Var |$i$|)
  9262. (Prim 'any-vector-length (list (Var |$v$|)))))
  9263. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  9264. (Exit))))
  9265. \end{lstlisting}
  9266. \section{Remove Complex Operands}
  9267. \label{sec:rco-Rany}
  9268. The \code{ValueOf} and \code{Exit} forms are both complex expressions.
  9269. The subexpression of \code{ValueOf} must be atomic.
  9270. \section{Explicate Control and \LangCAny{}}
  9271. \label{sec:explicate-Rany}
  9272. The output of \code{explicate-control} is the \LangCAny{} language whose
  9273. syntax is defined in Figure~\ref{fig:c5-syntax}. The \code{ValueOf}
  9274. form that we added to \LangAny{} remains an expression and the \code{Exit}
  9275. expression becomes a $\Tail$. Also, note that the index argument of
  9276. \code{vector-ref} and \code{vector-set!} is an $\Atm$ instead
  9277. of an integer, as in \LangCVec{} (Figure~\ref{fig:c2-syntax}).
  9278. \begin{figure}[tp]
  9279. \fbox{
  9280. \begin{minipage}{0.96\textwidth}
  9281. \small
  9282. \[
  9283. \begin{array}{lcl}
  9284. \Exp &::= & \ldots
  9285. \mid \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  9286. &\mid& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  9287. &\mid& \VALUEOF{\Exp}{\FType} \\
  9288. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  9289. \mid \LP\key{Collect} \,\itm{int}\RP }\\
  9290. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  9291. \mid \GOTO{\itm{label}} } \\
  9292. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  9293. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  9294. \mid \LP\key{Exit}\RP \\
  9295. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  9296. \LangCLam{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  9297. \end{array}
  9298. \]
  9299. \end{minipage}
  9300. }
  9301. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  9302. \label{fig:c5-syntax}
  9303. \end{figure}
  9304. \section{Select Instructions}
  9305. \label{sec:select-Rany}
  9306. In the \code{select-instructions} pass we translate the primitive
  9307. operations on the \code{Any} type to x86 instructions that involve
  9308. manipulating the 3 tag bits of the tagged value.
  9309. \paragraph{Make-any}
  9310. We recommend compiling the \key{make-any} primitive as follows if the
  9311. tag is for \key{Integer} or \key{Boolean}. The \key{salq} instruction
  9312. shifts the destination to the left by the number of bits specified its
  9313. source argument (in this case $3$, the length of the tag) and it
  9314. preserves the sign of the integer. We use the \key{orq} instruction to
  9315. combine the tag and the value to form the tagged value. \\
  9316. \begin{lstlisting}
  9317. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  9318. |$\Rightarrow$|
  9319. movq |$e'$|, |\itm{lhs'}|
  9320. salq $3, |\itm{lhs'}|
  9321. orq $|$\itm{tag}$|, |\itm{lhs'}|
  9322. \end{lstlisting}
  9323. The instruction selection for vectors and procedures is different
  9324. because their is no need to shift them to the left. The rightmost 3
  9325. bits are already zeros as described at the beginning of this
  9326. chapter. So we just combine the value and the tag using \key{orq}. \\
  9327. \begin{lstlisting}
  9328. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  9329. |$\Rightarrow$|
  9330. movq |$e'$|, |\itm{lhs'}|
  9331. orq $|$\itm{tag}$|, |\itm{lhs'}|
  9332. \end{lstlisting}
  9333. \paragraph{Tag-of-any}
  9334. Recall that the \code{tag-of-any} operation extracts the type tag from
  9335. a value of type \code{Any}. The type tag is the bottom three bits, so
  9336. we obtain the tag by taking the bitwise-and of the value with $111$
  9337. ($7$ in decimal).
  9338. \begin{lstlisting}
  9339. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  9340. |$\Rightarrow$|
  9341. movq |$e'$|, |\itm{lhs'}|
  9342. andq $7, |\itm{lhs'}|
  9343. \end{lstlisting}
  9344. \paragraph{ValueOf}
  9345. Like \key{make-any}, the instructions for \key{ValueOf} are different
  9346. depending on whether the type $T$ is a pointer (vector or procedure)
  9347. or not (Integer or Boolean). The following shows the instruction
  9348. selection for Integer and Boolean. We produce an untagged value by
  9349. shifting it to the right by 3 bits.
  9350. \begin{lstlisting}
  9351. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  9352. |$\Rightarrow$|
  9353. movq |$e'$|, |\itm{lhs'}|
  9354. sarq $3, |\itm{lhs'}|
  9355. \end{lstlisting}
  9356. %
  9357. In the case for vectors and procedures, there is no need to
  9358. shift. Instead we just need to zero-out the rightmost 3 bits. We
  9359. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  9360. decimal) and apply \code{bitwise-not} to obtain $\ldots 11111000$ (-8
  9361. in decimal) which we \code{movq} into the destination $\itm{lhs}$. We
  9362. then apply \code{andq} with the tagged value to get the desired
  9363. result. \\
  9364. \begin{lstlisting}
  9365. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  9366. |$\Rightarrow$|
  9367. movq $|$-8$|, |\itm{lhs'}|
  9368. andq |$e'$|, |\itm{lhs'}|
  9369. \end{lstlisting}
  9370. %% \paragraph{Type Predicates} We leave it to the reader to
  9371. %% devise a sequence of instructions to implement the type predicates
  9372. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  9373. \paragraph{Any-vector-length}
  9374. \begin{lstlisting}
  9375. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$a_1$|)))
  9376. |$\Longrightarrow$|
  9377. movq |$\neg 111$|, %r11
  9378. andq |$a_1'$|, %r11
  9379. movq 0(%r11), %r11
  9380. andq $126, %r11
  9381. sarq $1, %r11
  9382. movq %r11, |$\itm{lhs'}$|
  9383. \end{lstlisting}
  9384. \paragraph{Any-vector-ref}
  9385. The index may be an arbitrary atom so instead of computing the offset
  9386. at compile time, instructions need to be generated to compute the
  9387. offset at runtime as follows. Note the use of the new instruction
  9388. \code{imulq}.
  9389. \begin{center}
  9390. \begin{minipage}{0.96\textwidth}
  9391. \begin{lstlisting}
  9392. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$a_1$| |$a_2$|)))
  9393. |$\Longrightarrow$|
  9394. movq |$\neg 111$|, %r11
  9395. andq |$a_1'$|, %r11
  9396. movq |$a_2'$|, %rax
  9397. addq $1, %rax
  9398. imulq $8, %rax
  9399. addq %rax, %r11
  9400. movq 0(%r11) |$\itm{lhs'}$|
  9401. \end{lstlisting}
  9402. \end{minipage}
  9403. \end{center}
  9404. \paragraph{Any-vector-set!}
  9405. The code generation for \code{any-vector-set!} is similar to the other
  9406. \code{any-vector} operations.
  9407. \section{Register Allocation for \LangAny{}}
  9408. \label{sec:register-allocation-Rany}
  9409. \index{register allocation}
  9410. There is an interesting interaction between tagged values and garbage
  9411. collection that has an impact on register allocation. A variable of
  9412. type \code{Any} might refer to a vector and therefore it might be a
  9413. root that needs to be inspected and copied during garbage
  9414. collection. Thus, we need to treat variables of type \code{Any} in a
  9415. similar way to variables of type \code{Vector} for purposes of
  9416. register allocation. In particular,
  9417. \begin{itemize}
  9418. \item If a variable of type \code{Any} is live during a function call,
  9419. then it must be spilled. This can be accomplished by changing
  9420. \code{build-interference} to mark all variables of type \code{Any}
  9421. that are live after a \code{callq} as interfering with all the
  9422. registers.
  9423. \item If a variable of type \code{Any} is spilled, it must be spilled
  9424. to the root stack instead of the normal procedure call stack.
  9425. \end{itemize}
  9426. Another concern regarding the root stack is that the garbage collector
  9427. needs to differentiate between (1) plain old pointers to tuples, (2) a
  9428. tagged value that points to a tuple, and (3) a tagged value that is
  9429. not a tuple. We enable this differentiation by choosing not to use the
  9430. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  9431. reserved for identifying plain old pointers to tuples. That way, if
  9432. one of the first three bits is set, then we have a tagged value and
  9433. inspecting the tag can differentiation between vectors ($010$) and the
  9434. other kinds of values.
  9435. \begin{exercise}\normalfont
  9436. Expand your compiler to handle \LangAny{} as discussed in the last few
  9437. sections. Create 5 new programs that use the \code{Any} type and the
  9438. new operations (\code{inject}, \code{project}, \code{boolean?},
  9439. etc.). Test your compiler on these new programs and all of your
  9440. previously created test programs.
  9441. \end{exercise}
  9442. \begin{exercise}\normalfont
  9443. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  9444. Create tests for \LangDyn{} by adapting ten of your previous test programs
  9445. by removing type annotations. Add 5 more tests programs that
  9446. specifically rely on the language being dynamically typed. That is,
  9447. they should not be legal programs in a statically typed language, but
  9448. nevertheless, they should be valid \LangDyn{} programs that run to
  9449. completion without error.
  9450. \end{exercise}
  9451. \begin{figure}[p]
  9452. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9453. \node (Rfun) at (0,4) {\large \LangDyn{}};
  9454. \node (Rfun-2) at (3,4) {\large \LangDyn{}};
  9455. \node (Rfun-3) at (6,4) {\large \LangDyn{}};
  9456. \node (Rfun-4) at (9,4) {\large \LangDynFunRef{}};
  9457. \node (Rfun-5) at (9,2) {\large \LangAnyFunRef{}};
  9458. \node (Rfun-6) at (12,2) {\large \LangAnyFunRef{}};
  9459. \node (Rfun-7) at (12,0) {\large \LangAnyFunRef{}};
  9460. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  9461. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  9462. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  9463. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  9464. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  9465. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  9466. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  9467. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  9468. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  9469. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  9470. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  9471. \path[->,bend left=15] (Rfun) edge [above] node
  9472. {\ttfamily\footnotesize shrink} (Rfun-2);
  9473. \path[->,bend left=15] (Rfun-2) edge [above] node
  9474. {\ttfamily\footnotesize uniquify} (Rfun-3);
  9475. \path[->,bend left=15] (Rfun-3) edge [above] node
  9476. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  9477. \path[->,bend right=15] (Rfun-4) edge [left] node
  9478. {\ttfamily\footnotesize cast-insert} (Rfun-5);
  9479. \path[->,bend left=15] (Rfun-5) edge [above] node
  9480. {\ttfamily\footnotesize check-bounds} (Rfun-6);
  9481. \path[->,bend left=15] (Rfun-6) edge [left] node
  9482. {\ttfamily\footnotesize reveal-casts} (Rfun-7);
  9483. \path[->,bend left=15] (Rfun-7) edge [below] node
  9484. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  9485. \path[->,bend right=15] (F1-2) edge [above] node
  9486. {\ttfamily\footnotesize limit-fun.} (F1-3);
  9487. \path[->,bend right=15] (F1-3) edge [above] node
  9488. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9489. \path[->,bend right=15] (F1-4) edge [above] node
  9490. {\ttfamily\footnotesize remove-complex.} (F1-5);
  9491. \path[->,bend right=15] (F1-5) edge [right] node
  9492. {\ttfamily\footnotesize explicate-control} (C3-2);
  9493. \path[->,bend left=15] (C3-2) edge [left] node
  9494. {\ttfamily\footnotesize select-instr.} (x86-2);
  9495. \path[->,bend right=15] (x86-2) edge [left] node
  9496. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  9497. \path[->,bend right=15] (x86-2-1) edge [below] node
  9498. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  9499. \path[->,bend right=15] (x86-2-2) edge [left] node
  9500. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  9501. \path[->,bend left=15] (x86-3) edge [above] node
  9502. {\ttfamily\footnotesize patch-instr.} (x86-4);
  9503. \path[->,bend left=15] (x86-4) edge [right] node
  9504. {\ttfamily\footnotesize print-x86} (x86-5);
  9505. \end{tikzpicture}
  9506. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  9507. \label{fig:Rdyn-passes}
  9508. \end{figure}
  9509. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  9510. for the compilation of \LangDyn{}.
  9511. % Further Reading
  9512. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9513. \chapter{Loops and Assignment}
  9514. \label{ch:Rwhile}
  9515. % TODO: define R'_8
  9516. % TODO: multi-graph
  9517. In this chapter we study two features that are the hallmarks of
  9518. imperative programming languages: loops and assignments to local
  9519. variables. The following example demonstrates these new features by
  9520. computing the sum of the first five positive integers.
  9521. % similar to loop_test_1.rkt
  9522. \begin{lstlisting}
  9523. (let ([sum 0])
  9524. (let ([i 5])
  9525. (begin
  9526. (while (> i 0)
  9527. (begin
  9528. (set! sum (+ sum i))
  9529. (set! i (- i 1))))
  9530. sum)))
  9531. \end{lstlisting}
  9532. The \code{while} loop consists of a condition and a body.
  9533. %
  9534. The \code{set!} consists of a variable and a right-hand-side expression.
  9535. %
  9536. The primary purpose of both the \code{while} loop and \code{set!} is
  9537. to cause side effects, so it is convenient to also include in a
  9538. language feature for sequencing side effects: the \code{begin}
  9539. expression. It consists of one or more subexpressions that are
  9540. evaluated left-to-right.
  9541. \section{The \LangLoop{} Language}
  9542. \begin{figure}[tp]
  9543. \centering
  9544. \fbox{
  9545. \begin{minipage}{0.96\textwidth}
  9546. \small
  9547. \[
  9548. \begin{array}{lcl}
  9549. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  9550. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  9551. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  9552. &\mid& \gray{\key{\#t} \mid \key{\#f}
  9553. \mid (\key{and}\;\Exp\;\Exp)
  9554. \mid (\key{or}\;\Exp\;\Exp)
  9555. \mid (\key{not}\;\Exp) } \\
  9556. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  9557. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  9558. (\key{vector-ref}\;\Exp\;\Int)} \\
  9559. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  9560. \mid (\Exp \; \Exp\ldots) } \\
  9561. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP
  9562. \mid \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  9563. &\mid& \CSETBANG{\Var}{\Exp}
  9564. \mid \CBEGIN{\Exp\ldots}{\Exp}
  9565. \mid \CWHILE{\Exp}{\Exp} \\
  9566. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  9567. \LangLoop{} &::=& \gray{\Def\ldots \; \Exp}
  9568. \end{array}
  9569. \]
  9570. \end{minipage}
  9571. }
  9572. \caption{The concrete syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-concrete-syntax}).}
  9573. \label{fig:Rwhile-concrete-syntax}
  9574. \end{figure}
  9575. \begin{figure}[tp]
  9576. \centering
  9577. \fbox{
  9578. \begin{minipage}{0.96\textwidth}
  9579. \small
  9580. \[
  9581. \begin{array}{lcl}
  9582. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  9583. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  9584. &\mid& \gray{ \BOOL{\itm{bool}}
  9585. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  9586. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  9587. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  9588. &\mid& \gray{ \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp} }\\
  9589. &\mid& \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  9590. \mid \WHILE{\Exp}{\Exp} \\
  9591. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  9592. \LangLoop{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  9593. \end{array}
  9594. \]
  9595. \end{minipage}
  9596. }
  9597. \caption{The abstract syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-syntax}).}
  9598. \label{fig:Rwhile-syntax}
  9599. \end{figure}
  9600. The concrete syntax of \LangLoop{} is defined in
  9601. Figure~\ref{fig:Rwhile-concrete-syntax} and its abstract syntax is defined
  9602. in Figure~\ref{fig:Rwhile-syntax}.
  9603. %
  9604. The definitional interpreter for \LangLoop{} is shown in
  9605. Figure~\ref{fig:interp-Rwhile}. We add three new cases for \code{SetBang},
  9606. \code{WhileLoop}, and \code{Begin} and we make changes to the cases
  9607. for \code{Var}, \code{Let}, and \code{Apply} regarding variables. To
  9608. support assignment to variables and to make their lifetimes indefinite
  9609. (see the second example in Section~\ref{sec:assignment-scoping}), we
  9610. box the value that is bound to each variable (in \code{Let}) and
  9611. function parameter (in \code{Apply}). The case for \code{Var} unboxes
  9612. the value.
  9613. %
  9614. Now to discuss the new cases. For \code{SetBang}, we lookup the
  9615. variable in the environment to obtain a boxed value and then we change
  9616. it using \code{set-box!} to the result of evaluating the right-hand
  9617. side. The result value of a \code{SetBang} is \code{void}.
  9618. %
  9619. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  9620. if the result is true, 2) evaluate the body.
  9621. The result value of a \code{while} loop is also \code{void}.
  9622. %
  9623. Finally, the $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  9624. subexpressions \itm{es} for their effects and then evaluates
  9625. and returns the result from \itm{body}.
  9626. \begin{figure}[tbp]
  9627. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9628. (define interp-Rwhile-class
  9629. (class interp-Rany-class
  9630. (super-new)
  9631. (define/override ((interp-exp env) e)
  9632. (define recur (interp-exp env))
  9633. (match e
  9634. [(SetBang x rhs)
  9635. (set-box! (lookup x env) (recur rhs))]
  9636. [(WhileLoop cnd body)
  9637. (define (loop)
  9638. (cond [(recur cnd) (recur body) (loop)]
  9639. [else (void)]))
  9640. (loop)]
  9641. [(Begin es body)
  9642. (for ([e es]) (recur e))
  9643. (recur body)]
  9644. [else ((super interp-exp env) e)]))
  9645. ))
  9646. (define (interp-Rwhile p)
  9647. (send (new interp-Rwhile-class) interp-program p))
  9648. \end{lstlisting}
  9649. \caption{Interpreter for \LangLoop{}.}
  9650. \label{fig:interp-Rwhile}
  9651. \end{figure}
  9652. The type checker for \LangLoop{} is define in
  9653. Figure~\ref{fig:type-check-Rwhile}. For \code{SetBang}, the type of the
  9654. variable and the right-hand-side must agree. The result type is
  9655. \code{Void}. For the \code{WhileLoop}, the condition must be a
  9656. \code{Boolean}. The result type is also \code{Void}. For
  9657. \code{Begin}, the result type is the type of its last subexpression.
  9658. \begin{figure}[tbp]
  9659. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9660. (define type-check-Rwhile-class
  9661. (class type-check-Rany-class
  9662. (super-new)
  9663. (inherit check-type-equal?)
  9664. (define/override (type-check-exp env)
  9665. (lambda (e)
  9666. (define recur (type-check-exp env))
  9667. (match e
  9668. [(SetBang x rhs)
  9669. (define-values (rhs^ rhsT) (recur rhs))
  9670. (define varT (dict-ref env x))
  9671. (check-type-equal? rhsT varT e)
  9672. (values (SetBang x rhs^) 'Void)]
  9673. [(WhileLoop cnd body)
  9674. (define-values (cnd^ Tc) (recur cnd))
  9675. (check-type-equal? Tc 'Boolean e)
  9676. (define-values (body^ Tbody) ((type-check-exp env) body))
  9677. (values (WhileLoop cnd^ body^) 'Void)]
  9678. [(Begin es body)
  9679. (define-values (es^ ts)
  9680. (for/lists (l1 l2) ([e es]) (recur e)))
  9681. (define-values (body^ Tbody) (recur body))
  9682. (values (Begin es^ body^) Tbody)]
  9683. [else ((super type-check-exp env) e)])))
  9684. ))
  9685. (define (type-check-Rwhile p)
  9686. (send (new type-check-Rwhile-class) type-check-program p))
  9687. \end{lstlisting}
  9688. \caption{Type checking \key{SetBang}, \key{WhileLoop},
  9689. and \code{Begin} in \LangLoop{}.}
  9690. \label{fig:type-check-Rwhile}
  9691. \end{figure}
  9692. At first glance, the translation of these language features to x86
  9693. seems straightforward because the \LangCFun{} intermediate language already
  9694. supports all of the ingredients that we need: assignment, \code{goto},
  9695. conditional branching, and sequencing. However, there are two
  9696. complications that arise which we discuss in the next two
  9697. sections. After that we introduce one new compiler pass and the
  9698. changes necessary to the existing passes.
  9699. \section{Assignment and Lexically Scoped Functions}
  9700. \label{sec:assignment-scoping}
  9701. The addition of assignment raises a problem with our approach to
  9702. implementing lexically-scoped functions. Consider the following
  9703. example in which function \code{f} has a free variable \code{x} that
  9704. is changed after \code{f} is created but before the call to \code{f}.
  9705. % loop_test_11.rkt
  9706. \begin{lstlisting}
  9707. (let ([x 0])
  9708. (let ([y 0])
  9709. (let ([z 20])
  9710. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  9711. (begin
  9712. (set! x 10)
  9713. (set! y 12)
  9714. (f y))))))
  9715. \end{lstlisting}
  9716. The correct output for this example is \code{42} because the call to
  9717. \code{f} is required to use the current value of \code{x} (which is
  9718. \code{10}). Unfortunately, the closure conversion pass
  9719. (Section~\ref{sec:closure-conversion}) generates code for the
  9720. \code{lambda} that copies the old value of \code{x} into a
  9721. closure. Thus, if we naively add support for assignment to our current
  9722. compiler, the output of this program would be \code{32}.
  9723. A first attempt at solving this problem would be to save a pointer to
  9724. \code{x} in the closure and change the occurrences of \code{x} inside
  9725. the lambda to dereference the pointer. Of course, this would require
  9726. assigning \code{x} to the stack and not to a register. However, the
  9727. problem goes a bit deeper. Consider the following example in which we
  9728. create a counter abstraction by creating a pair of functions that
  9729. share the free variable \code{x}.
  9730. % similar to loop_test_10.rkt
  9731. \begin{lstlisting}
  9732. (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  9733. (vector
  9734. (lambda: () : Integer x)
  9735. (lambda: () : Void (set! x (+ 1 x)))))
  9736. (let ([counter (f 0)])
  9737. (let ([get (vector-ref counter 0)])
  9738. (let ([inc (vector-ref counter 1)])
  9739. (begin
  9740. (inc)
  9741. (get)))))
  9742. \end{lstlisting}
  9743. In this example, the lifetime of \code{x} extends beyond the lifetime
  9744. of the call to \code{f}. Thus, if we were to store \code{x} on the
  9745. stack frame for the call to \code{f}, it would be gone by the time we
  9746. call \code{inc} and \code{get}, leaving us with dangling pointers for
  9747. \code{x}. This example demonstrates that when a variable occurs free
  9748. inside a \code{lambda}, its lifetime becomes indefinite. Thus, the
  9749. value of the variable needs to live on the heap. The verb ``box'' is
  9750. often used for allocating a single value on the heap, producing a
  9751. pointer, and ``unbox'' for dereferencing the pointer.
  9752. We recommend solving these problems by ``boxing'' the local variables
  9753. that are in the intersection of 1) variables that appear on the
  9754. left-hand-side of a \code{set!} and 2) variables that occur free
  9755. inside a \code{lambda}. We shall introduce a new pass named
  9756. \code{convert-assignments} in Section~\ref{sec:convert-assignments} to
  9757. perform this translation. But before diving into the compiler passes,
  9758. we one more problem to discuss.
  9759. \section{Cyclic Control Flow and Dataflow Analysis}
  9760. \label{sec:dataflow-analysis}
  9761. Up until this point the control-flow graphs generated in
  9762. \code{explicate-control} were guaranteed to be acyclic. However, each
  9763. \code{while} loop introduces a cycle in the control-flow graph.
  9764. But does that matter?
  9765. %
  9766. Indeed it does. Recall that for register allocation, the compiler
  9767. performs liveness analysis to determine which variables can share the
  9768. same register. In Section~\ref{sec:liveness-analysis-Rif} we analyze
  9769. the control-flow graph in reverse topological order, but topological
  9770. order is only well-defined for acyclic graphs.
  9771. Let us return to the example of computing the sum of the first five
  9772. positive integers. Here is the program after instruction selection but
  9773. before register allocation.
  9774. \begin{center}
  9775. \begin{minipage}{0.45\textwidth}
  9776. \begin{lstlisting}
  9777. (define (main) : Integer
  9778. mainstart:
  9779. movq $0, sum1
  9780. movq $5, i2
  9781. jmp block5
  9782. block5:
  9783. movq i2, tmp3
  9784. cmpq tmp3, $0
  9785. jl block7
  9786. jmp block8
  9787. \end{lstlisting}
  9788. \end{minipage}
  9789. \begin{minipage}{0.45\textwidth}
  9790. \begin{lstlisting}
  9791. block7:
  9792. addq i2, sum1
  9793. movq $1, tmp4
  9794. negq tmp4
  9795. addq tmp4, i2
  9796. jmp block5
  9797. block8:
  9798. movq $27, %rax
  9799. addq sum1, %rax
  9800. jmp mainconclusion
  9801. )
  9802. \end{lstlisting}
  9803. \end{minipage}
  9804. \end{center}
  9805. Recall that liveness analysis works backwards, starting at the end
  9806. of each function. For this example we could start with \code{block8}
  9807. because we know what is live at the beginning of the conclusion,
  9808. just \code{rax} and \code{rsp}. So the live-before set
  9809. for \code{block8} is $\{\ttm{rsp},\ttm{sum1}\}$.
  9810. %
  9811. Next we might try to analyze \code{block5} or \code{block7}, but
  9812. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9813. we are stuck.
  9814. The way out of this impasse comes from the realization that one can
  9815. perform liveness analysis starting with an empty live-after set to
  9816. compute an under-approximation of the live-before set. By
  9817. \emph{under-approximation}, we mean that the set only contains
  9818. variables that are really live, but it may be missing some. Next, the
  9819. under-approximations for each block can be improved by 1) updating the
  9820. live-after set for each block using the approximate live-before sets
  9821. from the other blocks and 2) perform liveness analysis again on each
  9822. block. In fact, by iterating this process, the under-approximations
  9823. eventually become the correct solutions!
  9824. %
  9825. This approach of iteratively analyzing a control-flow graph is
  9826. applicable to many static analysis problems and goes by the name
  9827. \emph{dataflow analysis}\index{dataflow analysis}. It was invented by
  9828. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  9829. Washington.
  9830. Let us apply this approach to the above example. We use the empty set
  9831. for the initial live-before set for each block. Let $m_0$ be the
  9832. following mapping from label names to sets of locations (variables and
  9833. registers).
  9834. \begin{center}
  9835. \begin{lstlisting}
  9836. mainstart: {}
  9837. block5: {}
  9838. block7: {}
  9839. block8: {}
  9840. \end{lstlisting}
  9841. \end{center}
  9842. Using the above live-before approximations, we determine the
  9843. live-after for each block and then apply liveness analysis to each
  9844. block. This produces our next approximation $m_1$ of the live-before
  9845. sets.
  9846. \begin{center}
  9847. \begin{lstlisting}
  9848. mainstart: {}
  9849. block5: {i2}
  9850. block7: {i2, sum1}
  9851. block8: {rsp, sum1}
  9852. \end{lstlisting}
  9853. \end{center}
  9854. For the second round, the live-after for \code{mainstart} is the
  9855. current live-before for \code{block5}, which is \code{\{i2\}}. So the
  9856. liveness analysis for \code{mainstart} computes the empty set. The
  9857. live-after for \code{block5} is the union of the live-before sets for
  9858. \code{block7} and \code{block8}, which is \code{\{i2 , rsp, sum1\}}.
  9859. So the liveness analysis for \code{block5} computes \code{\{i2 , rsp,
  9860. sum1\}}. The live-after for \code{block7} is the live-before for
  9861. \code{block5} (from the previous iteration), which is \code{\{i2\}}.
  9862. So the liveness analysis for \code{block7} remains \code{\{i2,
  9863. sum1\}}. Together these yield the following approximation $m_2$ of
  9864. the live-before sets.
  9865. \begin{center}
  9866. \begin{lstlisting}
  9867. mainstart: {}
  9868. block5: {i2, rsp, sum1}
  9869. block7: {i2, sum1}
  9870. block8: {rsp, sum1}
  9871. \end{lstlisting}
  9872. \end{center}
  9873. In the preceding iteration, only \code{block5} changed, so we can
  9874. limit our attention to \code{mainstart} and \code{block7}, the two
  9875. blocks that jump to \code{block5}. As a result, the live-before sets
  9876. for \code{mainstart} and \code{block7} are updated to include
  9877. \code{rsp}, yielding the following approximation $m_3$.
  9878. \begin{center}
  9879. \begin{lstlisting}
  9880. mainstart: {rsp}
  9881. block5: {i2, rsp, sum1}
  9882. block7: {i2, rsp, sum1}
  9883. block8: {rsp, sum1}
  9884. \end{lstlisting}
  9885. \end{center}
  9886. Because \code{block7} changed, we analyze \code{block5} once more, but
  9887. its live-before set remains \code{\{ i2, rsp, sum1 \}}. At this point
  9888. our approximations have converged, so $m_3$ is the solution.
  9889. This iteration process is guaranteed to converge to a solution by the
  9890. Kleene Fixed-Point Theorem, a general theorem about functions on
  9891. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9892. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9893. elements, a least element $\bot$ (pronounced bottom), and a join
  9894. operator $\sqcup$.\index{lattice}\index{bottom}\index{partial
  9895. ordering}\index{join}\footnote{Technically speaking, we will be
  9896. working with join semi-lattices.} When two elements are ordered $m_i
  9897. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  9898. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  9899. approximation than $m_i$. The bottom element $\bot$ represents the
  9900. complete lack of information, i.e., the worst approximation. The join
  9901. operator takes two lattice elements and combines their information,
  9902. i.e., it produces the least upper bound of the two.\index{least upper
  9903. bound}
  9904. A dataflow analysis typically involves two lattices: one lattice to
  9905. represent abstract states and another lattice that aggregates the
  9906. abstract states of all the blocks in the control-flow graph. For
  9907. liveness analysis, an abstract state is a set of locations. We form
  9908. the lattice $L$ by taking its elements to be sets of locations, the
  9909. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9910. set, and the join operator to be set union.
  9911. %
  9912. We form a second lattice $M$ by taking its elements to be mappings
  9913. from the block labels to sets of locations (elements of $L$). We
  9914. order the mappings point-wise, using the ordering of $L$. So given any
  9915. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9916. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9917. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9918. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  9919. We can think of one iteration of liveness analysis as being a function
  9920. $f$ on the lattice $M$. It takes a mapping as input and computes a new
  9921. mapping.
  9922. \[
  9923. f(m_i) = m_{i+1}
  9924. \]
  9925. Next let us think for a moment about what a final solution $m_s$
  9926. should look like. If we perform liveness analysis using the solution
  9927. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9928. solution should be a \emph{fixed point} of the function $f$.\index{fixed point}
  9929. \[
  9930. f(m_s) = m_s
  9931. \]
  9932. Furthermore, the solution should only include locations that are
  9933. forced to be there by performing liveness analysis on the program, so
  9934. the solution should be the \emph{least} fixed point.\index{least fixed point}
  9935. The Kleene Fixed-Point Theorem states that if a function $f$ is
  9936. monotone (better inputs produce better outputs), then the least fixed
  9937. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9938. chain} obtained by starting at $\bot$ and iterating $f$ as
  9939. follows.\index{Kleene Fixed-Point Theorem}
  9940. \[
  9941. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9942. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9943. \]
  9944. When a lattice contains only finitely-long ascending chains, then
  9945. every Kleene chain tops out at some fixed point after a number of
  9946. iterations of $f$. So that fixed point is also a least upper
  9947. bound of the chain.
  9948. \[
  9949. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9950. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9951. \]
  9952. The liveness analysis is indeed a monotone function and the lattice
  9953. $M$ only has finitely-long ascending chains because there are only a
  9954. finite number of variables and blocks in the program. Thus we are
  9955. guaranteed that iteratively applying liveness analysis to all blocks
  9956. in the program will eventually produce the least fixed point solution.
  9957. Next let us consider dataflow analysis in general and discuss the
  9958. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  9959. %
  9960. The algorithm has four parameters: the control-flow graph \code{G}, a
  9961. function \code{transfer} that applies the analysis to one block, the
  9962. \code{bottom} and \code{join} operator for the lattice of abstract
  9963. states. The algorithm begins by creating the bottom mapping,
  9964. represented by a hash table. It then pushes all of the nodes in the
  9965. control-flow graph onto the work list (a queue). The algorithm repeats
  9966. the \code{while} loop as long as there are items in the work list. In
  9967. each iteration, a node is popped from the work list and processed. The
  9968. \code{input} for the node is computed by taking the join of the
  9969. abstract states of all the predecessor nodes. The \code{transfer}
  9970. function is then applied to obtain the \code{output} abstract
  9971. state. If the output differs from the previous state for this block,
  9972. the mapping for this block is updated and its successor nodes are
  9973. pushed onto the work list.
  9974. \begin{figure}[tb]
  9975. \begin{lstlisting}
  9976. (define (analyze-dataflow G transfer bottom join)
  9977. (define mapping (make-hash))
  9978. (for ([v (in-vertices G)])
  9979. (dict-set! mapping v bottom))
  9980. (define worklist (make-queue))
  9981. (for ([v (in-vertices G)])
  9982. (enqueue! worklist v))
  9983. (define trans-G (transpose G))
  9984. (while (not (queue-empty? worklist))
  9985. (define node (dequeue! worklist))
  9986. (define input (for/fold ([state bottom])
  9987. ([pred (in-neighbors trans-G node)])
  9988. (join state (dict-ref mapping pred))))
  9989. (define output (transfer node input))
  9990. (cond [(not (equal? output (dict-ref mapping node)))
  9991. (dict-set! mapping node output)
  9992. (for ([v (in-neighbors G node)])
  9993. (enqueue! worklist v))]))
  9994. mapping)
  9995. \end{lstlisting}
  9996. \caption{Generic work list algorithm for dataflow analysis}
  9997. \label{fig:generic-dataflow}
  9998. \end{figure}
  9999. Having discussed the two complications that arise from adding support
  10000. for assignment and loops, we turn to discussing the one new compiler
  10001. pass and the significant changes to existing passes.
  10002. \section{Convert Assignments}
  10003. \label{sec:convert-assignments}
  10004. Recall that in Section~\ref{sec:assignment-scoping} we learned that
  10005. the combination of assignments and lexically-scoped functions requires
  10006. that we box those variables that are both assigned-to and that appear
  10007. free inside a \code{lambda}. The purpose of the
  10008. \code{convert-assignments} pass is to carry out that transformation.
  10009. We recommend placing this pass after \code{uniquify} but before
  10010. \code{reveal-functions}.
  10011. Consider again the first example from
  10012. Section~\ref{sec:assignment-scoping}:
  10013. \begin{lstlisting}
  10014. (let ([x 0])
  10015. (let ([y 0])
  10016. (let ([z 20])
  10017. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  10018. (begin
  10019. (set! x 10)
  10020. (set! y 12)
  10021. (f y))))))
  10022. \end{lstlisting}
  10023. The variables \code{x} and \code{y} are assigned-to. The variables
  10024. \code{x} and \code{z} occur free inside the \code{lambda}. Thus,
  10025. variable \code{x} needs to be boxed but not \code{y} and \code{z}.
  10026. The boxing of \code{x} consists of three transformations: initialize
  10027. \code{x} with a vector, replace reads from \code{x} with
  10028. \code{vector-ref}'s, and replace each \code{set!} on \code{x} with a
  10029. \code{vector-set!}. The output of \code{convert-assignments} for this
  10030. example is as follows.
  10031. \begin{lstlisting}
  10032. (define (main) : Integer
  10033. (let ([x0 (vector 0)])
  10034. (let ([y1 0])
  10035. (let ([z2 20])
  10036. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  10037. (+ a3 (+ (vector-ref x0 0) z2)))])
  10038. (begin
  10039. (vector-set! x0 0 10)
  10040. (set! y1 12)
  10041. (f4 y1)))))))
  10042. \end{lstlisting}
  10043. \paragraph{Assigned \& Free}
  10044. We recommend defining an auxiliary function named
  10045. \code{assigned\&free} that takes an expression and simultaneously
  10046. computes 1) a set of assigned variables $A$, 2) a set $F$ of variables
  10047. that occur free within lambda's, and 3) a new version of the
  10048. expression that records which bound variables occurred in the
  10049. intersection of $A$ and $F$. You can use the struct
  10050. \code{AssignedFree} to do this. Consider the case for
  10051. $\LET{x}{\itm{rhs}}{\itm{body}}$. Suppose the the recursive call on
  10052. $\itm{rhs}$ produces $\itm{rhs}'$, $A_r$, and $F_r$ and the recursive
  10053. call on the $\itm{body}$ produces $\itm{body}'$, $A_b$, and $F_b$. If
  10054. $x$ is in $A_b\cap F_b$, then transforms the \code{Let} as follows.
  10055. \begin{lstlisting}
  10056. (Let |$x$| |$rhs$| |$body$|)
  10057. |$\Rightarrow$|
  10058. (Let (AssignedFree |$x$|) |$rhs'$| |$body'$|)
  10059. \end{lstlisting}
  10060. If $x$ is not in $A_b\cap F_b$ then omit the use of \code{AssignedFree}.
  10061. The set of assigned variables for this \code{Let} is
  10062. $A_r \cup (A_b - \{x\})$
  10063. and the set of variables free in lambda's is
  10064. $F_r \cup (F_b - \{x\})$.
  10065. The case for $\SETBANG{x}{\itm{rhs}}$ is straightforward but
  10066. important. Recursively process \itm{rhs} to obtain \itm{rhs'}, $A_r$,
  10067. and $F_r$. The result is $\SETBANG{x}{\itm{rhs'}}$, $\{x\} \cup A_r$,
  10068. and $F_r$.
  10069. The case for $\LAMBDA{\itm{params}}{T}{\itm{body}}$ is a bit more
  10070. involved. Let \itm{body'}, $A_b$, and $F_b$ be the result of
  10071. recursively processing \itm{body}. Wrap each of parameter that occurs
  10072. in $A_b \cap F_b$ with \code{AssignedFree} to produce \itm{params'}.
  10073. Let $P$ be the set of parameter names in \itm{params}. The result is
  10074. $\LAMBDA{\itm{params'}}{T}{\itm{body'}}$, $A_b - P$, and $(F_b \cup
  10075. \mathrm{FV}(\itm{body})) - P$, where $\mathrm{FV}$ computes the free
  10076. variables of an expression (see Chapter~\ref{ch:Rlam}).
  10077. \paragraph{Convert Assignments}
  10078. Next we discuss the \code{convert-assignment} pass with its auxiliary
  10079. functions for expressions and definitions. The function for
  10080. expressions, \code{cnvt-assign-exp}, should take an expression and a
  10081. set of assigned-and-free variables (obtained from the result of
  10082. \code{assigned\&free}. In the case for $\VAR{x}$, if $x$ is
  10083. assigned-and-free, then unbox it by translating $\VAR{x}$ to a
  10084. \code{vector-ref}.
  10085. \begin{lstlisting}
  10086. (Var |$x$|)
  10087. |$\Rightarrow$|
  10088. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  10089. \end{lstlisting}
  10090. %
  10091. In the case for $\LET{\LP\code{AssignedFree}\,
  10092. x\RP}{\itm{rhs}}{\itm{body}}$, recursively process \itm{rhs} to
  10093. obtain \itm{rhs'}. Next, recursively process \itm{body} to obtain
  10094. \itm{body'} but with $x$ added to the set of assigned-and-free
  10095. variables. Translate the let-expression as follows to bind $x$ to a
  10096. boxed value.
  10097. \begin{lstlisting}
  10098. (Let (AssignedFree |$x$|) |$rhs$| |$body$|)
  10099. |$\Rightarrow$|
  10100. (Let |$x$| (Prim 'vector (list |$rhs'$|)) |$body'$|)
  10101. \end{lstlisting}
  10102. %
  10103. In the case for $\SETBANG{x}{\itm{rhs}}$, recursively process
  10104. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in the assigned-and-free
  10105. variables, translate the \code{set!} into a \code{vector-set!}
  10106. as follows.
  10107. \begin{lstlisting}
  10108. (SetBang |$x$| |$\itm{rhs}$|)
  10109. |$\Rightarrow$|
  10110. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  10111. \end{lstlisting}
  10112. %
  10113. The case for \code{Lambda} is non-trivial, but it is similar to the
  10114. case for function definitions, which we discuss next.
  10115. The auxiliary function for definitions, \code{cnvt-assign-def},
  10116. applies assignment conversion to function definitions.
  10117. We translate a function definition as follows.
  10118. \begin{lstlisting}
  10119. (Def |$f$| |$\itm{params}$| |$T$| |$\itm{info}$| |$\itm{body_1}$|)
  10120. |$\Rightarrow$|
  10121. (Def |$f$| |$\itm{params'}$| |$T$| |$\itm{info}$| |$\itm{body_4}$|)
  10122. \end{lstlisting}
  10123. So it remains to explain \itm{params'} and $\itm{body}_4$.
  10124. Let \itm{body_2}, $A_b$, and $F_b$ be the result of
  10125. \code{assigned\&free} on $\itm{body_1}$.
  10126. Let $P$ be the parameter names in \itm{params}.
  10127. We then apply \code{cnvt-assign-exp} to $\itm{body_2}$ to
  10128. obtain \itm{body_3}, passing $A_b \cap F_b \cap P$
  10129. as the set of assigned-and-free variables.
  10130. Finally, we obtain \itm{body_4} by wrapping \itm{body_3}
  10131. in a sequence of let-expressions that box the parameters
  10132. that are in $A_b \cap F_b$.
  10133. %
  10134. Regarding \itm{params'}, change the names of the parameters that are
  10135. in $A_b \cap F_b$ to maintain uniqueness (and so the let-bound
  10136. variables can retain the original names). Recall the second example in
  10137. Section~\ref{sec:assignment-scoping} involving a counter
  10138. abstraction. The following is the output of assignment version for
  10139. function \code{f}.
  10140. \begin{lstlisting}
  10141. (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  10142. (vector
  10143. (lambda: () : Integer x1)
  10144. (lambda: () : Void (set! x1 (+ 1 x1)))))
  10145. |$\Rightarrow$|
  10146. (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  10147. (let ([x1 (vector param_x1)])
  10148. (vector (lambda: () : Integer (vector-ref x1 0))
  10149. (lambda: () : Void
  10150. (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  10151. \end{lstlisting}
  10152. \section{Remove Complex Operands}
  10153. \label{sec:rco-loop}
  10154. The three new language forms, \code{while}, \code{set!}, and
  10155. \code{begin} are all complex expressions and their subexpressions are
  10156. allowed to be complex. Figure~\ref{fig:Rfun-anf-syntax} defines the
  10157. output language \LangFunANF{} of this pass.
  10158. \begin{figure}[tp]
  10159. \centering
  10160. \fbox{
  10161. \begin{minipage}{0.96\textwidth}
  10162. \small
  10163. \[
  10164. \begin{array}{rcl}
  10165. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  10166. \mid \VOID{} } \\
  10167. \Exp &::=& \ldots \mid \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  10168. &\mid& \WHILE{\Exp}{\Exp} \mid \SETBANG{\Var}{\Exp}
  10169. \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  10170. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  10171. R^{\dagger}_8 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  10172. \end{array}
  10173. \]
  10174. \end{minipage}
  10175. }
  10176. \caption{\LangLoopANF{} is \LangLoop{} in administrative normal form (ANF).}
  10177. \label{fig:Rwhile-anf-syntax}
  10178. \end{figure}
  10179. As usual, when a complex expression appears in a grammar position that
  10180. needs to be atomic, such as the argument of a primitive operator, we
  10181. must introduce a temporary variable and bind it to the complex
  10182. expression. This approach applies, unchanged, to handle the new
  10183. language forms. For example, in the following code there are two
  10184. \code{begin} expressions appearing as arguments to \code{+}. The
  10185. output of \code{rco-exp} is shown below, in which the \code{begin}
  10186. expressions have been bound to temporary variables. Recall that
  10187. \code{let} expressions in \LangLoopANF{} are allowed to have
  10188. arbitrary expressions in their right-hand-side expression, so it is
  10189. fine to place \code{begin} there.
  10190. \begin{lstlisting}
  10191. (let ([x0 10])
  10192. (let ([y1 0])
  10193. (+ (+ (begin (set! y1 (read)) x0)
  10194. (begin (set! x0 (read)) y1))
  10195. x0)))
  10196. |$\Rightarrow$|
  10197. (let ([x0 10])
  10198. (let ([y1 0])
  10199. (let ([tmp2 (begin (set! y1 (read)) x0)])
  10200. (let ([tmp3 (begin (set! x0 (read)) y1)])
  10201. (let ([tmp4 (+ tmp2 tmp3)])
  10202. (+ tmp4 x0))))))
  10203. \end{lstlisting}
  10204. \section{Explicate Control and \LangCLoop{}}
  10205. \label{sec:explicate-loop}
  10206. Recall that in the \code{explicate-control} pass we define one helper
  10207. function for each kind of position in the program. For the \LangVar{}
  10208. language of integers and variables we needed kinds of positions:
  10209. assignment and tail. The \code{if} expressions of \LangIf{} introduced
  10210. predicate positions. For \LangLoop{}, the \code{begin} expression introduces
  10211. yet another kind of position: effect position. Except for the last
  10212. subexpression, the subexpressions inside a \code{begin} are evaluated
  10213. only for their effect. Their result values are discarded. We can
  10214. generate better code by taking this fact into account.
  10215. The output language of \code{explicate-control} is \LangCLoop{}
  10216. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  10217. \LangCLam{}. The only syntactic difference is that \code{Call},
  10218. \code{vector-set!}, and \code{read} may also appear as statements.
  10219. The most significant difference between \LangCLam{} and \LangCLoop{}
  10220. is that the control-flow graphs of the later may contain cycles.
  10221. \begin{figure}[tp]
  10222. \fbox{
  10223. \begin{minipage}{0.96\textwidth}
  10224. \small
  10225. \[
  10226. \begin{array}{lcl}
  10227. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  10228. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  10229. &\mid& \CALL{\Atm}{\LP\Atm\ldots\RP} \mid \READ{}\\
  10230. &\mid& \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP \\
  10231. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  10232. \LangCLoop{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  10233. \end{array}
  10234. \]
  10235. \end{minipage}
  10236. }
  10237. \caption{The abstract syntax of \LangCLoop{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  10238. \label{fig:c7-syntax}
  10239. \end{figure}
  10240. The new auxiliary function \code{explicate-effect} takes an expression
  10241. (in an effect position) and a promise of a continuation block. The
  10242. function returns a promise for a $\Tail$ that includes the generated
  10243. code for the input expression followed by the continuation block. If
  10244. the expression is obviously pure, that is, never causes side effects,
  10245. then the expression can be removed, so the result is just the
  10246. continuation block.
  10247. %
  10248. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  10249. case. First, you will need a fresh label $\itm{loop}$ for the top of
  10250. the loop. Recursively process the \itm{body} (in effect position)
  10251. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  10252. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  10253. \itm{body'} as the then-branch and the continuation block as the
  10254. else-branch. The result should be added to the control-flow graph with
  10255. the label \itm{loop}. The result for the whole \code{while} loop is a
  10256. \code{goto} to the \itm{loop} label. Note that the loop should only be
  10257. added to the control-flow graph if the loop is indeed used, which can
  10258. be accomplished using \code{delay}.
  10259. The auxiliary functions for tail, assignment, and predicate positions
  10260. need to be updated. The three new language forms, \code{while},
  10261. \code{set!}, and \code{begin}, can appear in assignment and tail
  10262. positions. Only \code{begin} may appear in predicate positions; the
  10263. other two have result type \code{Void}.
  10264. \section{Select Instructions}
  10265. \label{sec:select-instructions-loop}
  10266. Only three small additions are needed in the
  10267. \code{select-instructions} pass to handle the changes to \LangCLoop{}. That
  10268. is, \code{Call}, \code{read}, and \code{vector-set!} may now appear as
  10269. stand-alone statements instead of only appearing on the right-hand
  10270. side of an assignment statement. The code generation is nearly
  10271. identical; just leave off the instruction for moving the result into
  10272. the left-hand side.
  10273. \section{Register Allocation}
  10274. \label{sec:register-allocation-loop}
  10275. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  10276. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  10277. which complicates the liveness analysis needed for register
  10278. allocation.
  10279. \subsection{Liveness Analysis}
  10280. \label{sec:liveness-analysis-r8}
  10281. We recommend using the generic \code{analyze-dataflow} function that
  10282. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  10283. perform liveness analysis, replacing the code in
  10284. \code{uncover-live-CFG} that processed the basic blocks in topological
  10285. order (Section~\ref{sec:liveness-analysis-Rif}).
  10286. The \code{analyze-dataflow} function has four parameters.
  10287. \begin{enumerate}
  10288. \item The first parameter \code{G} should be a directed graph from the
  10289. \code{racket/graph} package (see the sidebar in
  10290. Section~\ref{sec:build-interference}) that represents the
  10291. control-flow graph.
  10292. \item The second parameter \code{transfer} is a function that applies
  10293. liveness analysis to a basic block. It takes two parameters: the
  10294. label for the block to analyze and the live-after set for that
  10295. block. The transfer function should return the live-before set for
  10296. the block. Also, as a side-effect, it should update the block's
  10297. $\itm{info}$ with the liveness information for each instruction. To
  10298. implement the \code{transfer} function, you should be able to reuse
  10299. the code you already have for analyzing basic blocks.
  10300. \item The third and fourth parameters of \code{analyze-dataflow} are
  10301. \code{bottom} and \code{join} for the lattice of abstract states,
  10302. i.e. sets of locations. The bottom of the lattice is the empty set
  10303. \code{(set)} and the join operator is \code{set-union}.
  10304. \end{enumerate}
  10305. \begin{figure}[p]
  10306. \begin{tikzpicture}[baseline=(current bounding box.center)]
  10307. \node (Rfun) at (0,2) {\large \LangLoop{}};
  10308. \node (Rfun-2) at (3,2) {\large \LangLoop{}};
  10309. \node (Rfun-3) at (6,2) {\large \LangLoop{}};
  10310. \node (Rfun-4) at (9,2) {\large \LangLoopFunRef{}};
  10311. \node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  10312. \node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  10313. \node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  10314. \node (F1-4) at (3,0) {\large \LangLoopAlloc{}};
  10315. \node (F1-5) at (0,0) {\large \LangLoopAlloc{}};
  10316. \node (C3-2) at (3,-2) {\large \LangCLoop{}};
  10317. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  10318. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  10319. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  10320. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  10321. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  10322. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  10323. %% \path[->,bend left=15] (Rfun) edge [above] node
  10324. %% {\ttfamily\footnotesize type-check} (Rfun-2);
  10325. \path[->,bend left=15] (Rfun) edge [above] node
  10326. {\ttfamily\footnotesize shrink} (Rfun-2);
  10327. \path[->,bend left=15] (Rfun-2) edge [above] node
  10328. {\ttfamily\footnotesize uniquify} (Rfun-3);
  10329. \path[->,bend left=15] (Rfun-3) edge [above] node
  10330. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  10331. \path[->,bend left=15] (Rfun-4) edge [right] node
  10332. {\ttfamily\footnotesize convert-assignments} (F1-1);
  10333. \path[->,bend left=15] (F1-1) edge [below] node
  10334. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  10335. \path[->,bend right=15] (F1-2) edge [above] node
  10336. {\ttfamily\footnotesize limit-fun.} (F1-3);
  10337. \path[->,bend right=15] (F1-3) edge [above] node
  10338. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  10339. \path[->,bend right=15] (F1-4) edge [above] node
  10340. {\ttfamily\footnotesize remove-complex.} (F1-5);
  10341. \path[->,bend right=15] (F1-5) edge [right] node
  10342. {\ttfamily\footnotesize explicate-control} (C3-2);
  10343. \path[->,bend left=15] (C3-2) edge [left] node
  10344. {\ttfamily\footnotesize select-instr.} (x86-2);
  10345. \path[->,bend right=15] (x86-2) edge [left] node
  10346. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  10347. \path[->,bend right=15] (x86-2-1) edge [below] node
  10348. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  10349. \path[->,bend right=15] (x86-2-2) edge [left] node
  10350. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  10351. \path[->,bend left=15] (x86-3) edge [above] node
  10352. {\ttfamily\footnotesize patch-instr.} (x86-4);
  10353. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  10354. \end{tikzpicture}
  10355. \caption{Diagram of the passes for \LangLoop{} (loops and assignment).}
  10356. \label{fig:Rwhile-passes}
  10357. \end{figure}
  10358. Figure~\ref{fig:Rwhile-passes} provides an overview of all the passes needed
  10359. for the compilation of \LangLoop{}.
  10360. \section{Challenge: Arrays}
  10361. \label{sec:arrays}
  10362. In Chapter~\ref{ch:Rvec} we studied tuples, that is, sequences of
  10363. elements whose length is determined at compile-time and where each
  10364. element of a tuple may have a different type (they are
  10365. heterogeous). This challenge is also about sequences, but this time
  10366. the length is determined at run-time and all the elements have the same
  10367. type (they are homogeneous). We use the term ``array'' for this later
  10368. kind of sequence.
  10369. The Racket language does not distinguish between tuples and arrays,
  10370. they are both represented by vectors. However, Typed Racket
  10371. distinguishes between tuples and arrays: the \code{Vector} type is for
  10372. tuples and the \code{Vectorof} type is for arrays.
  10373. %
  10374. Figure~\ref{fig:Rvecof-concrete-syntax} defines the concrete syntax
  10375. for \LangArray{}, extending \LangLoop{} with the \code{Vectorof} type
  10376. and the \code{make-vector} primitive operator for creating an array,
  10377. whose arguments are the length of the array and an initial value for
  10378. all the elements in the array. The \code{vector-length},
  10379. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  10380. for tuples become overloaded for use with arrays.
  10381. %
  10382. We also include integer multiplication in \LangArray{}, as it is
  10383. useful in many examples involving arrays such as computing the
  10384. inner-product of two arrays (Figure~\ref{fig:inner-product}).
  10385. \begin{figure}[tp]
  10386. \centering
  10387. \fbox{
  10388. \begin{minipage}{0.96\textwidth}
  10389. \small
  10390. \[
  10391. \begin{array}{lcl}
  10392. \Type &::=& \ldots \mid \LP \key{Vectorof}~\Type \RP \\
  10393. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  10394. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \mid \CMUL{\Exp}{\Exp}\\
  10395. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  10396. &\mid& \gray{\key{\#t} \mid \key{\#f}
  10397. \mid \LP\key{and}\;\Exp\;\Exp\RP
  10398. \mid \LP\key{or}\;\Exp\;\Exp\RP
  10399. \mid \LP\key{not}\;\Exp\RP } \\
  10400. &\mid& \gray{ \LP\key{eq?}\;\Exp\;\Exp\RP \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  10401. &\mid& \gray{ \LP\key{vector}\;\Exp\ldots\RP \mid
  10402. \LP\key{vector-ref}\;\Exp\;\Int\RP} \\
  10403. &\mid& \gray{\LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP\mid \LP\key{void}\RP
  10404. \mid \LP\Exp \; \Exp\ldots\RP } \\
  10405. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP
  10406. \mid \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  10407. &\mid& \gray{ \CSETBANG{\Var}{\Exp}
  10408. \mid \CBEGIN{\Exp\ldots}{\Exp}
  10409. \mid \CWHILE{\Exp}{\Exp} } \\
  10410. &\mid& \CMAKEVEC{\Exp}{\Exp} \\
  10411. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  10412. \LangArray{} &::=& \gray{\Def\ldots \; \Exp}
  10413. \end{array}
  10414. \]
  10415. \end{minipage}
  10416. }
  10417. \caption{The concrete syntax of \LangArray{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  10418. \label{fig:Rvecof-concrete-syntax}
  10419. \end{figure}
  10420. \begin{figure}[tp]
  10421. \begin{lstlisting}
  10422. (define (inner-product [A : (Vectorof Integer)] [B : (Vectorof Integer)]
  10423. [n : Integer]) : Integer
  10424. (let ([i 0])
  10425. (let ([prod 0])
  10426. (begin
  10427. (while (< i n)
  10428. (begin
  10429. (set! prod (+ prod (* (vector-ref A i)
  10430. (vector-ref B i))))
  10431. (set! i (+ i 1))
  10432. ))
  10433. prod))))
  10434. (let ([A (make-vector 2 2)])
  10435. (let ([B (make-vector 2 3)])
  10436. (+ (inner-product A B 2)
  10437. 30)))
  10438. \end{lstlisting}
  10439. \caption{Example program that computes the inner-product.}
  10440. \label{fig:inner-product}
  10441. \end{figure}
  10442. The type checker for \LangArray{} is define in
  10443. Figure~\ref{fig:type-check-Rvecof}. The result type of
  10444. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  10445. of the intializing expression. The length expression is required to
  10446. have type \code{Integer}. The type checking of the operators
  10447. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  10448. updated to handle the situation where the vector has type
  10449. \code{Vectorof}. In these cases we translate the operators to their
  10450. \code{vectorof} form so that later passes can easily distinguish
  10451. between operations on tuples versus arrays. We override the
  10452. \code{operator-types} method to provide the type signature for
  10453. multiplication: it takes two integers and returns an integer. To
  10454. support injection and projection of arrays to the \code{Any} type
  10455. (Section~\ref{sec:Rany-lang}), we also override the \code{flat-ty?}
  10456. predicate.
  10457. \begin{figure}[tbp]
  10458. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10459. (define type-check-Rvecof-class
  10460. (class type-check-Rwhile-class
  10461. (super-new)
  10462. (inherit check-type-equal?)
  10463. (define/override (flat-ty? ty)
  10464. (match ty
  10465. ['(Vectorof Any) #t]
  10466. [else (super flat-ty? ty)]))
  10467. (define/override (operator-types)
  10468. (append '((* . ((Integer Integer) . Integer)))
  10469. (super operator-types)))
  10470. (define/override (type-check-exp env)
  10471. (lambda (e)
  10472. (define recur (type-check-exp env))
  10473. (match e
  10474. [(Prim 'make-vector (list e1 e2))
  10475. (define-values (e1^ t1) (recur e1))
  10476. (define-values (e2^ elt-type) (recur e2))
  10477. (define vec-type `(Vectorof ,elt-type))
  10478. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  10479. vec-type)]
  10480. [(Prim 'vector-ref (list e1 e2))
  10481. (define-values (e1^ t1) (recur e1))
  10482. (define-values (e2^ t2) (recur e2))
  10483. (match* (t1 t2)
  10484. [(`(Vectorof ,elt-type) 'Integer)
  10485. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  10486. [(other wise) ((super type-check-exp env) e)])]
  10487. [(Prim 'vector-set! (list e1 e2 e3) )
  10488. (define-values (e-vec t-vec) (recur e1))
  10489. (define-values (e2^ t2) (recur e2))
  10490. (define-values (e-arg^ t-arg) (recur e3))
  10491. (match t-vec
  10492. [`(Vectorof ,elt-type)
  10493. (check-type-equal? elt-type t-arg e)
  10494. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  10495. [else ((super type-check-exp env) e)])]
  10496. [(Prim 'vector-length (list e1))
  10497. (define-values (e1^ t1) (recur e1))
  10498. (match t1
  10499. [`(Vectorof ,t)
  10500. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  10501. [else ((super type-check-exp env) e)])]
  10502. [else ((super type-check-exp env) e)])))
  10503. ))
  10504. (define (type-check-Rvecof p)
  10505. (send (new type-check-Rvecof-class) type-check-program p))
  10506. \end{lstlisting}
  10507. \caption{Type checker for the \LangArray{} language.}
  10508. \label{fig:type-check-Rvecof}
  10509. \end{figure}
  10510. The interpreter for \LangArray{} is defined in
  10511. Figure~\ref{fig:interp-Rvecof}. The \code{make-vector} operator is
  10512. implemented with Racket's \code{make-vector} function and
  10513. multiplication is \code{fx*}, multiplication for \code{fixnum}
  10514. integers.
  10515. \begin{figure}[tbp]
  10516. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10517. (define interp-Rvecof-class
  10518. (class interp-Rwhile-class
  10519. (super-new)
  10520. (define/override (interp-op op)
  10521. (verbose "Rvecof/interp-op" op)
  10522. (match op
  10523. ['make-vector make-vector]
  10524. ['* fx*]
  10525. [else (super interp-op op)]))
  10526. ))
  10527. (define (interp-Rvecof p)
  10528. (send (new interp-Rvecof-class) interp-program p))
  10529. \end{lstlisting}
  10530. \caption{Interpreter for \LangArray{}.}
  10531. \label{fig:interp-Rvecof}
  10532. \end{figure}
  10533. \subsection{Data Representation}
  10534. \label{sec:array-rep}
  10535. Just like tuples, we store arrays on the heap which means that the
  10536. garbage collector will need to inspect arrays. An immediate thought is
  10537. to use the same representation for arrays that we use for tuples.
  10538. However, we limit tuples to a length of $50$ so that their length and
  10539. pointer mask can fit into the 64-bit tag at the beginning of each
  10540. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  10541. millions of elements, so we need more bits to store the length.
  10542. However, because arrays are homogeneous, we only need $1$ bit for the
  10543. pointer mask instead of one bit per array elements. Finally, the
  10544. garbage collector will need to be able to distinguish between tuples
  10545. and arrays, so we need to reserve $1$ bit for that purpose. So we
  10546. arrive at the following layout for the 64-bit tag at the beginning of
  10547. an array:
  10548. \begin{itemize}
  10549. \item The right-most bit is the forwarding bit, just like in a tuple.
  10550. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  10551. it is not.
  10552. \item The next bit to the left is the pointer mask. A $0$ indicates
  10553. that none of the elements are pointers to the heap and a $1$
  10554. indicates that all of the elements are pointers.
  10555. \item The next $61$ bits store the length of the array.
  10556. \item The left-most bit distinguishes between a tuple ($0$) versus an
  10557. array ($1$).
  10558. \end{itemize}
  10559. Recall that in Chapter~\ref{ch:Rdyn}, we use a $3$-bit tag to
  10560. differentiate the kinds of values that have been injected into the
  10561. \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  10562. to indicate that the value is an array.
  10563. In the following subsections we provide hints regarding how to update
  10564. the passes to handle arrays.
  10565. \subsection{Reveal Casts}
  10566. The array-access operators \code{vectorof-ref} and
  10567. \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  10568. \code{any-vector-set!} operators of Chapter~\ref{ch:Rdyn} in
  10569. that the type checker cannot tell whether the index will be in bounds,
  10570. so the bounds check must be performed at run time. Recall that the
  10571. \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  10572. an \code{If} arround a vector reference for update to check whether
  10573. the index is less than the length. You should do the same for
  10574. \code{vectorof-ref} and \code{vectorof-set!} .
  10575. In addition, the handling of the \code{any-vector} operators in
  10576. \code{reveal-casts} needs to be updated to account for arrays that are
  10577. injected to \code{Any}. For the \code{any-vector-length} operator, the
  10578. generated code should test whether the tag is for tuples (\code{010})
  10579. or arrays (\code{110}) and then dispatch to either
  10580. \code{any-vector-length} or \code{any-vectorof-length}. For the later
  10581. we add a case in \code{select-instructions} to generate the
  10582. appropriate instructions for accessing the array length from the
  10583. header of an array.
  10584. For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  10585. the generated code needs to check that the index is less than the
  10586. vector length, so like the code for \code{any-vector-length}, check
  10587. the tag to determine whether to use \code{any-vector-length} or
  10588. \code{any-vectorof-length} for this purpose. Once the bounds checking
  10589. is complete, the generated code can use \code{any-vector-ref} and
  10590. \code{any-vector-set!} for both tuples and arrays because the
  10591. instructions used for those operators do not look at the tag at the
  10592. front of the tuple or array.
  10593. \subsection{Expose Allocation}
  10594. This pass should translate the \code{make-vector} operator into
  10595. lower-level operations. In particular, the new AST node
  10596. $\LP\key{AllocateArray}~\Exp~\Type\RP$ allocates an array of the
  10597. length specified by the $\Exp$, but does not initialize the elements
  10598. of the array. (Analogous to the \code{Allocate} AST node for tuples.)
  10599. The $\Type$ argument must be $\LP\key{Vectorof}~T\RP$ where $T$ is the
  10600. element type for the array. Regarding the initialization of the array,
  10601. we recommend generated a \code{while} loop that uses
  10602. \code{vector-set!} to put the initializing value into every element of
  10603. the array.
  10604. \subsection{Remove Complex Operands}
  10605. Add cases in the \code{rco-atom} and \code{rco-exp} for
  10606. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  10607. complex and its subexpression must be atomic.
  10608. \subsection{Explicate Control}
  10609. Add cases for \code{AllocateArray} to \code{explicate-tail} and
  10610. \code{explicate-assign}.
  10611. \subsection{Select Instructions}
  10612. Generate instructions for \code{AllocateArray} similar to those for
  10613. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  10614. that the tag at the front of the array should instead use the
  10615. representation discussed in Section~\ref{sec:array-rep}.
  10616. Regarding \code{vectorof-length}, extract the length from the tag
  10617. according to the representation discussed in
  10618. Section~\ref{sec:array-rep}.
  10619. The instructions generated for \code{vectorof-ref} differ from those
  10620. for \code{vector-ref} (Section~\ref{sec:select-instructions-gc}) in
  10621. that the index is not a constant so the offset must be computed at
  10622. runtime, similar to the instructions generated for
  10623. \code{any-vector-of-ref} (Section~\ref{sec:select-Rany}). The same is
  10624. true for \code{vectorof-set!}. Also, the \code{vectorof-set!} may
  10625. appear in an assignment and as a stand-alone statement, so make sure
  10626. to handle both situations in this pass.
  10627. Finally, the instructions for \code{any-vectorof-length} should be
  10628. similar to those for \code{vectorof-length}, except that one must
  10629. first project the array by writing zeroes into the $3$-bit tag
  10630. \begin{exercise}\normalfont
  10631. Implement a compiler for the \LangArray{} language by extending your
  10632. compiler for \LangLoop{}. Test your compiler on a half dozen new
  10633. programs, including the one in Figure~\ref{fig:inner-product} and also
  10634. a program that multiplies two matrices. Note that matrices are
  10635. 2-dimensional arrays, but those can be encoded into 1-dimensional
  10636. arrays by laying out each row in the array, one after the next.
  10637. \end{exercise}
  10638. % Further Reading: dataflow analysis
  10639. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10640. \chapter{Gradual Typing}
  10641. \label{ch:Rgrad}
  10642. \index{gradual typing}
  10643. This chapter studies a language, \LangGrad{}, in which the programmer
  10644. can choose between static and dynamic type checking in different parts
  10645. of a program, thereby mixing the statically typed \LangLoop{} language
  10646. with the dynamically typed \LangDyn{}. There are several approaches to
  10647. mixing static and dynamic typing, including multi-language
  10648. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  10649. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  10650. we focus on \emph{gradual typing}\index{gradual typing}, in which the
  10651. programmer controls the amount of static versus dynamic checking by
  10652. adding or removing type annotations on parameters and
  10653. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  10654. %
  10655. The concrete syntax of \LangGrad{} is defined in
  10656. Figure~\ref{fig:Rgrad-concrete-syntax} and its abstract syntax is defined
  10657. in Figure~\ref{fig:Rgrad-syntax}. The main syntactic difference between
  10658. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  10659. non-terminals that make type annotations optional. The return types
  10660. are not optional in the abstract syntax; the parser fills in
  10661. \code{Any} when the return type is not specified in the concrete
  10662. syntax.
  10663. \begin{figure}[tp]
  10664. \centering
  10665. \fbox{
  10666. \begin{minipage}{0.96\textwidth}
  10667. \small
  10668. \[
  10669. \begin{array}{lcl}
  10670. \itm{param} &::=& \Var \mid \LS\Var \key{:} \Type\RS \\
  10671. \itm{ret} &::=& \epsilon \mid \key{:} \Type \\
  10672. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  10673. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  10674. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  10675. &\mid& \gray{\key{\#t} \mid \key{\#f}
  10676. \mid (\key{and}\;\Exp\;\Exp)
  10677. \mid (\key{or}\;\Exp\;\Exp)
  10678. \mid (\key{not}\;\Exp) } \\
  10679. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  10680. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  10681. (\key{vector-ref}\;\Exp\;\Int)} \\
  10682. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  10683. \mid (\Exp \; \Exp\ldots) } \\
  10684. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  10685. \mid \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  10686. &\mid& \gray{ \CSETBANG{\Var}{\Exp}
  10687. \mid \CBEGIN{\Exp\ldots}{\Exp}
  10688. \mid \CWHILE{\Exp}{\Exp} } \\
  10689. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  10690. \LangGrad{} &::=& \gray{\Def\ldots \; \Exp}
  10691. \end{array}
  10692. \]
  10693. \end{minipage}
  10694. }
  10695. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  10696. \label{fig:Rgrad-concrete-syntax}
  10697. \end{figure}
  10698. \begin{figure}[tp]
  10699. \centering
  10700. \fbox{
  10701. \begin{minipage}{0.96\textwidth}
  10702. \small
  10703. \[
  10704. \begin{array}{lcl}
  10705. \itm{param} &::=& \Var \mid \LS\Var \key{:} \Type\RS \\
  10706. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  10707. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  10708. &\mid& \gray{ \BOOL{\itm{bool}}
  10709. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  10710. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  10711. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  10712. &\mid& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  10713. &\mid& \gray{ \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  10714. &\mid& \gray{ \WHILE{\Exp}{\Exp} } \\
  10715. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  10716. \LangGrad{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  10717. \end{array}
  10718. \]
  10719. \end{minipage}
  10720. }
  10721. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  10722. \label{fig:Rgrad-syntax}
  10723. \end{figure}
  10724. Both the type checker and the interpreter for \LangGrad{} require some
  10725. interesting changes to enable gradual typing, which we discuss in the
  10726. next two sections in the context of the \code{map-vec} example from
  10727. Chapter~\ref{ch:Rfun}. In Figure~\ref{fig:gradual-map-vec} we
  10728. revised the \code{map-vec} example, omitting the type annotations from
  10729. the \code{add1} function.
  10730. \begin{figure}[btp]
  10731. % gradual_test_9.rkt
  10732. \begin{lstlisting}
  10733. (define (map-vec [f : (Integer -> Integer)]
  10734. [v : (Vector Integer Integer)])
  10735. : (Vector Integer Integer)
  10736. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10737. (define (add1 x) (+ x 1))
  10738. (vector-ref (map-vec add1 (vector 0 41)) 1)
  10739. \end{lstlisting}
  10740. \caption{A partially-typed version of the \code{map-vec} example.}
  10741. \label{fig:gradual-map-vec}
  10742. \end{figure}
  10743. \section{Type Checking \LangGrad{}, Casts, and \LangCast{}}
  10744. \label{sec:gradual-type-check}
  10745. The type checker for \LangGrad{} uses the \code{Any} type for missing
  10746. parameter and return types. For example, the \code{x} parameter of
  10747. \code{add1} in Figure~\ref{fig:gradual-map-vec} is given the type
  10748. \code{Any} and the return type of \code{add1} is \code{Any}. Next
  10749. consider the \code{+} operator inside \code{add1}. It expects both
  10750. arguments to have type \code{Integer}, but its first argument \code{x}
  10751. has type \code{Any}. In a gradually typed language, such differences
  10752. are allowed so long as the types are \emph{consistent}, that is, they
  10753. are equal except in places where there is an \code{Any} type. The type
  10754. \code{Any} is consistent with every other type.
  10755. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  10756. \begin{figure}[tbp]
  10757. \begin{lstlisting}
  10758. (define/public (consistent? t1 t2)
  10759. (match* (t1 t2)
  10760. [('Integer 'Integer) #t]
  10761. [('Boolean 'Boolean) #t]
  10762. [('Void 'Void) #t]
  10763. [('Any t2) #t]
  10764. [(t1 'Any) #t]
  10765. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10766. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  10767. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10768. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  10769. (consistent? rt1 rt2))]
  10770. [(other wise) #f]))
  10771. \end{lstlisting}
  10772. \caption{The consistency predicate on types.}
  10773. \label{fig:consistent}
  10774. \end{figure}
  10775. Returning to the \code{map-vec} example of
  10776. Figure~\ref{fig:gradual-map-vec}, the \code{add1} function has type
  10777. \code{(Any -> Any)} but parameter \code{f} of \code{map-vec} has type
  10778. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  10779. because the two types are consistent. In particular, \code{->} is
  10780. equal to \code{->} and because \code{Any} is consistent with
  10781. \code{Integer}.
  10782. Next consider a program with an error, such as applying the
  10783. \code{map-vec} to a function that sometimes returns a Boolean, as
  10784. shown in Figure~\ref{fig:map-vec-maybe-add1}. The type checker for
  10785. \LangGrad{} accepts this program because the type of \code{maybe-add1} is
  10786. consistent with the type of parameter \code{f} of \code{map-vec}, that
  10787. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  10788. Integer)}. One might say that a gradual type checker is optimistic
  10789. in that it accepts programs that might execute without a runtime type
  10790. error.
  10791. %
  10792. Unfortunately, running this program with input \code{1} triggers an
  10793. error when the \code{maybe-add1} function returns \code{\#t}. \LangGrad{}
  10794. performs checking at runtime to ensure the integrity of the static
  10795. types, such as the \code{(Integer -> Integer)} annotation on parameter
  10796. \code{f} of \code{map-vec}. This runtime checking is carried out by a
  10797. new \code{Cast} form that is inserted by the type checker. Thus, the
  10798. output of the type checker is a program in the \LangCast{} language, which
  10799. adds \code{Cast} to \LangLoop{}, as shown in
  10800. Figure~\ref{fig:Rgrad-prime-syntax}.
  10801. \begin{figure}[tp]
  10802. \centering
  10803. \fbox{
  10804. \begin{minipage}{0.96\textwidth}
  10805. \small
  10806. \[
  10807. \begin{array}{lcl}
  10808. \Exp &::=& \ldots \mid \CAST{\Exp}{\Type}{\Type} \\
  10809. \LangCast{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  10810. \end{array}
  10811. \]
  10812. \end{minipage}
  10813. }
  10814. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  10815. \label{fig:Rgrad-prime-syntax}
  10816. \end{figure}
  10817. \begin{figure}[tbp]
  10818. \begin{lstlisting}
  10819. (define (map-vec [f : (Integer -> Integer)]
  10820. [v : (Vector Integer Integer)])
  10821. : (Vector Integer Integer)
  10822. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10823. (define (add1 x) (+ x 1))
  10824. (define (true) #t)
  10825. (define (maybe-add1 x) (if (eq? 0 (read)) (add1 x) (true)))
  10826. (vector-ref (map-vec maybe-add1 (vector 0 41)) 0)
  10827. \end{lstlisting}
  10828. \caption{A variant of the \code{map-vec} example with an error.}
  10829. \label{fig:map-vec-maybe-add1}
  10830. \end{figure}
  10831. Figure~\ref{fig:map-vec-cast} shows the output of the type checker for
  10832. \code{map-vec} and \code{maybe-add1}. The idea is that \code{Cast} is
  10833. inserted every time the type checker sees two types that are
  10834. consistent but not equal. In the \code{add1} function, \code{x} is
  10835. cast to \code{Integer} and the result of the \code{+} is cast to
  10836. \code{Any}. In the call to \code{map-vec}, the \code{add1} argument
  10837. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  10838. \begin{figure}[btp]
  10839. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10840. (define (map-vec [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  10841. : (Vector Integer Integer)
  10842. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10843. (define (add1 [x : Any]) : Any
  10844. (cast (+ (cast x Any Integer) 1) Integer Any))
  10845. (define (true) : Any (cast #t Boolean Any))
  10846. (define (maybe-add1 [x : Any]) : Any
  10847. (if (eq? 0 (read)) (add1 x) (true)))
  10848. (vector-ref (map-vec (cast maybe-add1 (Any -> Any) (Integer -> Integer))
  10849. (vector 0 41)) 0)
  10850. \end{lstlisting}
  10851. \caption{Output of type checking \code{map-vec}
  10852. and \code{maybe-add1}.}
  10853. \label{fig:map-vec-cast}
  10854. \end{figure}
  10855. The type checker for \LangGrad{} is defined in
  10856. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  10857. and \ref{fig:type-check-Rgradual-3}.
  10858. \begin{figure}[tbp]
  10859. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10860. (define type-check-gradual-class
  10861. (class type-check-Rwhile-class
  10862. (super-new)
  10863. (inherit operator-types type-predicates)
  10864. (define/override (type-check-exp env)
  10865. (lambda (e)
  10866. (define recur (type-check-exp env))
  10867. (match e
  10868. [(Prim 'vector-length (list e1))
  10869. (define-values (e1^ t) (recur e1))
  10870. (match t
  10871. [`(Vector ,ts ...)
  10872. (values (Prim 'vector-length (list e1^)) 'Integer)]
  10873. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  10874. [(Prim 'vector-ref (list e1 e2))
  10875. (define-values (e1^ t1) (recur e1))
  10876. (define-values (e2^ t2) (recur e2))
  10877. (check-consistent? t2 'Integer e)
  10878. (match t1
  10879. [`(Vector ,ts ...)
  10880. (match e2^
  10881. [(Int i)
  10882. (unless (and (0 . <= . i) (i . < . (length ts)))
  10883. (error 'type-check "invalid index ~a in ~a" i e))
  10884. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10885. [else (define e1^^ (make-cast e1^ t1 'Any))
  10886. (define e2^^ (make-cast e2^ t2 'Integer))
  10887. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  10888. ['Any
  10889. (define e2^^ (make-cast e2^ t2 'Integer))
  10890. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  10891. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  10892. [(Prim 'vector-set! (list e1 e2 e3) )
  10893. (define-values (e1^ t1) (recur e1))
  10894. (define-values (e2^ t2) (recur e2))
  10895. (define-values (e3^ t3) (recur e3))
  10896. (check-consistent? t2 'Integer e)
  10897. (match t1
  10898. [`(Vector ,ts ...)
  10899. (match e2^
  10900. [(Int i)
  10901. (unless (and (0 . <= . i) (i . < . (length ts)))
  10902. (error 'type-check "invalid index ~a in ~a" i e))
  10903. (check-consistent? (list-ref ts i) t3 e)
  10904. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  10905. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  10906. [else
  10907. (define e1^^ (make-cast e1^ t1 'Any))
  10908. (define e2^^ (make-cast e2^ t2 'Integer))
  10909. (define e3^^ (make-cast e3^ t3 'Any))
  10910. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  10911. ['Any
  10912. (define e2^^ (make-cast e2^ t2 'Integer))
  10913. (define e3^^ (make-cast e3^ t3 'Any))
  10914. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  10915. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  10916. \end{lstlisting}
  10917. \caption{Type checker for the \LangGrad{} language, part 1.}
  10918. \label{fig:type-check-Rgradual-1}
  10919. \end{figure}
  10920. \begin{figure}[tbp]
  10921. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10922. [(Prim 'eq? (list e1 e2))
  10923. (define-values (e1^ t1) (recur e1))
  10924. (define-values (e2^ t2) (recur e2))
  10925. (check-consistent? t1 t2 e)
  10926. (define T (meet t1 t2))
  10927. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  10928. 'Boolean)]
  10929. [(Prim 'not (list e1))
  10930. (define-values (e1^ t1) (recur e1))
  10931. (match t1
  10932. ['Any
  10933. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  10934. (Bool #t) (Bool #f)))]
  10935. [else
  10936. (define-values (t-ret new-es^)
  10937. (type-check-op 'not (list t1) (list e1^) e))
  10938. (values (Prim 'not new-es^) t-ret)])]
  10939. [(Prim 'and (list e1 e2))
  10940. (recur (If e1 e2 (Bool #f)))]
  10941. [(Prim 'or (list e1 e2))
  10942. (define tmp (gensym 'tmp))
  10943. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  10944. [(Prim op es)
  10945. #:when (not (set-member? explicit-prim-ops op))
  10946. (define-values (new-es ts)
  10947. (for/lists (exprs types) ([e es])
  10948. (recur e)))
  10949. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  10950. (values (Prim op new-es^) t-ret)]
  10951. [(If e1 e2 e3)
  10952. (define-values (e1^ T1) (recur e1))
  10953. (define-values (e2^ T2) (recur e2))
  10954. (define-values (e3^ T3) (recur e3))
  10955. (check-consistent? T2 T3 e)
  10956. (match T1
  10957. ['Boolean
  10958. (define Tif (join T2 T3))
  10959. (values (If e1^ (make-cast e2^ T2 Tif)
  10960. (make-cast e3^ T3 Tif)) Tif)]
  10961. ['Any
  10962. (define Tif (meet T2 T3))
  10963. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  10964. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  10965. Tif)]
  10966. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  10967. [(HasType e1 T)
  10968. (define-values (e1^ T1) (recur e1))
  10969. (check-consistent? T1 T)
  10970. (values (make-cast e1^ T1 T) T)]
  10971. [(SetBang x e1)
  10972. (define-values (e1^ T1) (recur e1))
  10973. (define varT (dict-ref env x))
  10974. (check-consistent? T1 varT e)
  10975. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  10976. [(WhileLoop e1 e2)
  10977. (define-values (e1^ T1) (recur e1))
  10978. (check-consistent? T1 'Boolean e)
  10979. (define-values (e2^ T2) ((type-check-exp env) e2))
  10980. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  10981. \end{lstlisting}
  10982. \caption{Type checker for the \LangGrad{} language, part 2.}
  10983. \label{fig:type-check-Rgradual-2}
  10984. \end{figure}
  10985. \begin{figure}[tbp]
  10986. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10987. [(Apply e1 e2s)
  10988. (define-values (e1^ T1) (recur e1))
  10989. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  10990. (match T1
  10991. [`(,T1ps ... -> ,T1rt)
  10992. (for ([T2 T2s] [Tp T1ps])
  10993. (check-consistent? T2 Tp e))
  10994. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  10995. (make-cast e2 src tgt)))
  10996. (values (Apply e1^ e2s^^) T1rt)]
  10997. [`Any
  10998. (define e1^^ (make-cast e1^ 'Any
  10999. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  11000. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  11001. (make-cast e2 src 'Any)))
  11002. (values (Apply e1^^ e2s^^) 'Any)]
  11003. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  11004. [(Lambda params Tr e1)
  11005. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  11006. (match p
  11007. [`[,x : ,T] (values x T)]
  11008. [(? symbol? x) (values x 'Any)])))
  11009. (define-values (e1^ T1)
  11010. ((type-check-exp (append (map cons xs Ts) env)) e1))
  11011. (check-consistent? Tr T1 e)
  11012. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  11013. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  11014. [else ((super type-check-exp env) e)]
  11015. )))
  11016. \end{lstlisting}
  11017. \caption{Type checker for the \LangGrad{} language, part 3.}
  11018. \label{fig:type-check-Rgradual-3}
  11019. \end{figure}
  11020. \begin{figure}[tbp]
  11021. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11022. (define/public (join t1 t2)
  11023. (match* (t1 t2)
  11024. [('Integer 'Integer) 'Integer]
  11025. [('Boolean 'Boolean) 'Boolean]
  11026. [('Void 'Void) 'Void]
  11027. [('Any t2) t2]
  11028. [(t1 'Any) t1]
  11029. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11030. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  11031. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11032. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  11033. -> ,(join rt1 rt2))]))
  11034. (define/public (meet t1 t2)
  11035. (match* (t1 t2)
  11036. [('Integer 'Integer) 'Integer]
  11037. [('Boolean 'Boolean) 'Boolean]
  11038. [('Void 'Void) 'Void]
  11039. [('Any t2) 'Any]
  11040. [(t1 'Any) 'Any]
  11041. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11042. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  11043. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11044. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  11045. -> ,(meet rt1 rt2))]))
  11046. (define/public (make-cast e src tgt)
  11047. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  11048. (define/public (check-consistent? t1 t2 e)
  11049. (unless (consistent? t1 t2)
  11050. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  11051. (define/override (type-check-op op arg-types args e)
  11052. (match (dict-ref (operator-types) op)
  11053. [`(,param-types . ,return-type)
  11054. (for ([at arg-types] [pt param-types])
  11055. (check-consistent? at pt e))
  11056. (values return-type
  11057. (for/list ([e args] [s arg-types] [t param-types])
  11058. (make-cast e s t)))]
  11059. [else (error 'type-check-op "unrecognized ~a" op)]))
  11060. (define explicit-prim-ops
  11061. (set-union
  11062. (type-predicates)
  11063. (set 'procedure-arity 'eq?
  11064. 'vector 'vector-length 'vector-ref 'vector-set!
  11065. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  11066. (define/override (fun-def-type d)
  11067. (match d
  11068. [(Def f params rt info body)
  11069. (define ps
  11070. (for/list ([p params])
  11071. (match p
  11072. [`[,x : ,T] T]
  11073. [(? symbol?) 'Any]
  11074. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  11075. `(,@ps -> ,rt)]
  11076. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  11077. \end{lstlisting}
  11078. \caption{Auxiliary functions for type checking \LangGrad{}.}
  11079. \label{fig:type-check-Rgradual-aux}
  11080. \end{figure}
  11081. \clearpage
  11082. \section{Interpreting \LangCast{}}
  11083. \label{sec:interp-casts}
  11084. The runtime behavior of first-order casts is straightforward, that is,
  11085. casts involving simple types such as \code{Integer} and
  11086. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  11087. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  11088. puts the integer into a tagged value
  11089. (Figure~\ref{fig:interp-Rany}). Similarly, a cast from \code{Any} to
  11090. \code{Integer} is accomplished with the \code{Project} operator, that
  11091. is, by checking the value's tag and either retrieving the underlying
  11092. integer or signaling an error if it the tag is not the one for
  11093. integers (Figure~\ref{fig:apply-project}).
  11094. %
  11095. Things get more interesting for higher-order casts, that is, casts
  11096. involving function or vector types.
  11097. Consider the cast of the function \code{maybe-add1} from \code{(Any ->
  11098. Any)} to \code{(Integer -> Integer)}. When a function flows through
  11099. this cast at runtime, we can't know in general whether the function
  11100. will always return an integer.\footnote{Predicting the return value of
  11101. a function is equivalent to the halting problem, which is
  11102. undecidable.} The \LangCast{} interpreter therefore delays the checking
  11103. of the cast until the function is applied. This is accomplished by
  11104. wrapping \code{maybe-add1} in a new function that casts its parameter
  11105. from \code{Integer} to \code{Any}, applies \code{maybe-add1}, and then
  11106. casts the return value from \code{Any} to \code{Integer}.
  11107. Turning our attention to casts involving vector types, we consider the
  11108. example in Figure~\ref{fig:map-vec-bang} that defines a
  11109. partially-typed version of \code{map-vec} whose parameter \code{v} has
  11110. type \code{(Vector Any Any)} and that updates \code{v} in place
  11111. instead of returning a new vector. So we name this function
  11112. \code{map-vec!}. We apply \code{map-vec!} to a vector of integers, so
  11113. the type checker inserts a cast from \code{(Vector Integer Integer)}
  11114. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  11115. cast between vector types would be a build a new vector whose elements
  11116. are the result of casting each of the original elements to the
  11117. appropriate target type. However, this approach is only valid for
  11118. immutable vectors; and our vectors are mutable. In the example of
  11119. Figure~\ref{fig:map-vec-bang}, if the cast created a new vector, then
  11120. the updates inside of \code{map-vec!} would happen to the new vector
  11121. and not the original one.
  11122. \begin{figure}[tbp]
  11123. % gradual_test_11.rkt
  11124. \begin{lstlisting}
  11125. (define (map-vec! [f : (Any -> Any)]
  11126. [v : (Vector Any Any)]) : Void
  11127. (begin
  11128. (vector-set! v 0 (f (vector-ref v 0)))
  11129. (vector-set! v 1 (f (vector-ref v 1)))))
  11130. (define (add1 x) (+ x 1))
  11131. (let ([v (vector 0 41)])
  11132. (begin (map-vec! add1 v) (vector-ref v 1)))
  11133. \end{lstlisting}
  11134. \caption{An example involving casts on vectors.}
  11135. \label{fig:map-vec-bang}
  11136. \end{figure}
  11137. Instead the interpreter needs to create a new kind of value, a
  11138. \emph{vector proxy}, that intercepts every vector operation. On a
  11139. read, the proxy reads from the underlying vector and then applies a
  11140. cast to the resulting value. On a write, the proxy casts the argument
  11141. value and then performs the write to the underlying vector. For the
  11142. first \code{(vector-ref v 0)} in \code{map-vec!}, the proxy casts
  11143. \code{0} from \code{Integer} to \code{Any}. For the first
  11144. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  11145. to \code{Integer}.
  11146. The final category of cast that we need to consider are casts between
  11147. the \code{Any} type and either a function or a vector
  11148. type. Figure~\ref{fig:map-vec-any} shows a variant of \code{map-vec!}
  11149. in which parameter \code{v} does not have a type annotation, so it is
  11150. given type \code{Any}. In the call to \code{map-vec!}, the vector has
  11151. type \code{(Vector Integer Integer)} so the type checker inserts a
  11152. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  11153. thought is to use \code{Inject}, but that doesn't work because
  11154. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  11155. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  11156. to \code{Any}.
  11157. \begin{figure}[tbp]
  11158. \begin{lstlisting}
  11159. (define (map-vec! [f : (Any -> Any)] v) : Void
  11160. (begin
  11161. (vector-set! v 0 (f (vector-ref v 0)))
  11162. (vector-set! v 1 (f (vector-ref v 1)))))
  11163. (define (add1 x) (+ x 1))
  11164. (let ([v (vector 0 41)])
  11165. (begin (map-vec! add1 v) (vector-ref v 1)))
  11166. \end{lstlisting}
  11167. \caption{Casting a vector to \code{Any}.}
  11168. \label{fig:map-vec-any}
  11169. \end{figure}
  11170. The \LangCast{} interpreter uses an auxiliary function named
  11171. \code{apply-cast} to cast a value from a source type to a target type,
  11172. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  11173. of the kinds of casts that we've discussed in this section.
  11174. \begin{figure}[tbp]
  11175. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11176. (define/public (apply-cast v s t)
  11177. (match* (s t)
  11178. [(t1 t2) #:when (equal? t1 t2) v]
  11179. [('Any t2)
  11180. (match t2
  11181. [`(,ts ... -> ,rt)
  11182. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  11183. (define v^ (apply-project v any->any))
  11184. (apply-cast v^ any->any `(,@ts -> ,rt))]
  11185. [`(Vector ,ts ...)
  11186. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  11187. (define v^ (apply-project v vec-any))
  11188. (apply-cast v^ vec-any `(Vector ,@ts))]
  11189. [else (apply-project v t2)])]
  11190. [(t1 'Any)
  11191. (match t1
  11192. [`(,ts ... -> ,rt)
  11193. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  11194. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  11195. (apply-inject v^ (any-tag any->any))]
  11196. [`(Vector ,ts ...)
  11197. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  11198. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  11199. (apply-inject v^ (any-tag vec-any))]
  11200. [else (apply-inject v (any-tag t1))])]
  11201. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11202. (define x (gensym 'x))
  11203. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  11204. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  11205. (define cast-writes
  11206. (for/list ([t1 ts1] [t2 ts2])
  11207. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  11208. `(vector-proxy ,(vector v (apply vector cast-reads)
  11209. (apply vector cast-writes)))]
  11210. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11211. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  11212. `(function ,xs ,(Cast
  11213. (Apply (Value v)
  11214. (for/list ([x xs][t1 ts1][t2 ts2])
  11215. (Cast (Var x) t2 t1)))
  11216. rt1 rt2) ())]
  11217. ))
  11218. \end{lstlisting}
  11219. \caption{The \code{apply-cast} auxiliary method.}
  11220. \label{fig:apply-cast}
  11221. \end{figure}
  11222. The interpreter for \LangCast{} is defined in
  11223. Figure~\ref{fig:interp-Rcast}, with the case for \code{Cast}
  11224. dispatching to \code{apply-cast}. To handle the addition of vector
  11225. proxies, we update the vector primitives in \code{interp-op} using the
  11226. functions in Figure~\ref{fig:guarded-vector}.
  11227. \begin{figure}[tbp]
  11228. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11229. (define interp-Rcast-class
  11230. (class interp-Rwhile-class
  11231. (super-new)
  11232. (inherit apply-fun apply-inject apply-project)
  11233. (define/override (interp-op op)
  11234. (match op
  11235. ['vector-length guarded-vector-length]
  11236. ['vector-ref guarded-vector-ref]
  11237. ['vector-set! guarded-vector-set!]
  11238. ['any-vector-ref (lambda (v i)
  11239. (match v [`(tagged ,v^ ,tg)
  11240. (guarded-vector-ref v^ i)]))]
  11241. ['any-vector-set! (lambda (v i a)
  11242. (match v [`(tagged ,v^ ,tg)
  11243. (guarded-vector-set! v^ i a)]))]
  11244. ['any-vector-length (lambda (v)
  11245. (match v [`(tagged ,v^ ,tg)
  11246. (guarded-vector-length v^)]))]
  11247. [else (super interp-op op)]
  11248. ))
  11249. (define/override ((interp-exp env) e)
  11250. (define (recur e) ((interp-exp env) e))
  11251. (match e
  11252. [(Value v) v]
  11253. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  11254. [else ((super interp-exp env) e)]))
  11255. ))
  11256. (define (interp-Rcast p)
  11257. (send (new interp-Rcast-class) interp-program p))
  11258. \end{lstlisting}
  11259. \caption{The interpreter for \LangCast{}.}
  11260. \label{fig:interp-Rcast}
  11261. \end{figure}
  11262. \begin{figure}[tbp]
  11263. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11264. (define (guarded-vector-ref vec i)
  11265. (match vec
  11266. [`(vector-proxy ,proxy)
  11267. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  11268. (define rd (vector-ref (vector-ref proxy 1) i))
  11269. (apply-fun rd (list val) 'guarded-vector-ref)]
  11270. [else (vector-ref vec i)]))
  11271. (define (guarded-vector-set! vec i arg)
  11272. (match vec
  11273. [`(vector-proxy ,proxy)
  11274. (define wr (vector-ref (vector-ref proxy 2) i))
  11275. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  11276. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  11277. [else (vector-set! vec i arg)]))
  11278. (define (guarded-vector-length vec)
  11279. (match vec
  11280. [`(vector-proxy ,proxy)
  11281. (guarded-vector-length (vector-ref proxy 0))]
  11282. [else (vector-length vec)]))
  11283. \end{lstlisting}
  11284. \caption{The guarded-vector auxiliary functions.}
  11285. \label{fig:guarded-vector}
  11286. \end{figure}
  11287. \section{Lower Casts}
  11288. \label{sec:lower-casts}
  11289. The next step in the journey towards x86 is the \code{lower-casts}
  11290. pass that translates the casts in \LangCast{} to the lower-level
  11291. \code{Inject} and \code{Project} operators and a new operator for
  11292. creating vector proxies, extending the \LangLoop{} language to create
  11293. \LangProxy{}. We recommend creating an auxiliary function named
  11294. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  11295. and a target type, and translates it to expression in \LangProxy{} that has
  11296. the same behavior as casting the expression from the source to the
  11297. target type in the interpreter.
  11298. The \code{lower-cast} function can follow a code structure similar to
  11299. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  11300. the interpreter for \LangCast{} because it must handle the same cases as
  11301. \code{apply-cast} and it needs to mimic the behavior of
  11302. \code{apply-cast}. The most interesting cases are those concerning the
  11303. casts between two vector types and between two function types.
  11304. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  11305. type to another vector type is accomplished by creating a proxy that
  11306. intercepts the operations on the underlying vector. Here we make the
  11307. creation of the proxy explicit with the \code{vector-proxy} primitive
  11308. operation. It takes three arguments, the first is an expression for
  11309. the vector, the second is a vector of functions for casting an element
  11310. that is being read from the vector, and the third is a vector of
  11311. functions for casting an element that is being written to the vector.
  11312. You can create the functions using \code{Lambda}. Also, as we shall
  11313. see in the next section, we need to differentiate these vectors from
  11314. the user-created ones, so we recommend using a new primitive operator
  11315. named \code{raw-vector} instead of \code{vector} to create these
  11316. vectors of functions. Figure~\ref{fig:map-vec-bang-lower-cast} shows
  11317. the output of \code{lower-casts} on the example in
  11318. Figure~\ref{fig:map-vec-bang} that involved casting a vector of
  11319. integers to a vector of \code{Any}.
  11320. \begin{figure}[tbp]
  11321. \begin{lstlisting}
  11322. (define (map-vec! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  11323. (begin
  11324. (vector-set! v 0 (f (vector-ref v 0)))
  11325. (vector-set! v 1 (f (vector-ref v 1)))))
  11326. (define (add1 [x : Any]) : Any
  11327. (inject (+ (project x Integer) 1) Integer))
  11328. (let ([v (vector 0 41)])
  11329. (begin
  11330. (map-vec! add1 (vector-proxy v
  11331. (raw-vector (lambda: ([x9 : Integer]) : Any
  11332. (inject x9 Integer))
  11333. (lambda: ([x9 : Integer]) : Any
  11334. (inject x9 Integer)))
  11335. (raw-vector (lambda: ([x9 : Any]) : Integer
  11336. (project x9 Integer))
  11337. (lambda: ([x9 : Any]) : Integer
  11338. (project x9 Integer)))))
  11339. (vector-ref v 1)))
  11340. \end{lstlisting}
  11341. \caption{Output of \code{lower-casts} on the example in
  11342. Figure~\ref{fig:map-vec-bang}.}
  11343. \label{fig:map-vec-bang-lower-cast}
  11344. \end{figure}
  11345. A cast from one function type to another function type is accomplished
  11346. by generating a \code{Lambda} whose parameter and return types match
  11347. the target function type. The body of the \code{Lambda} should cast
  11348. the parameters from the target type to the source type (yes,
  11349. backwards! functions are contravariant\index{contravariant} in the
  11350. parameters), then call the underlying function, and finally cast the
  11351. result from the source return type to the target return type.
  11352. Figure~\ref{fig:map-vec-lower-cast} shows the output of the
  11353. \code{lower-casts} pass on the \code{map-vec} example in
  11354. Figure~\ref{fig:gradual-map-vec}. Note that the \code{add1} argument
  11355. in the call to \code{map-vec} is wrapped in a \code{lambda}.
  11356. \begin{figure}[tbp]
  11357. \begin{lstlisting}
  11358. (define (map-vec [f : (Integer -> Integer)]
  11359. [v : (Vector Integer Integer)])
  11360. : (Vector Integer Integer)
  11361. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11362. (define (add1 [x : Any]) : Any
  11363. (inject (+ (project x Integer) 1) Integer))
  11364. (vector-ref (map-vec (lambda: ([x9 : Integer]) : Integer
  11365. (project (add1 (inject x9 Integer)) Integer))
  11366. (vector 0 41)) 1)
  11367. \end{lstlisting}
  11368. \caption{Output of \code{lower-casts} on the example in
  11369. Figure~\ref{fig:gradual-map-vec}.}
  11370. \label{fig:map-vec-lower-cast}
  11371. \end{figure}
  11372. \section{Differentiate Proxies}
  11373. \label{sec:differentiate-proxies}
  11374. So far the job of differentiating vectors and vector proxies has been
  11375. the job of the interpreter. For example, the interpreter for \LangCast{}
  11376. implements \code{vector-ref} using the \code{guarded-vector-ref}
  11377. function in Figure~\ref{fig:guarded-vector}. In the
  11378. \code{differentiate-proxies} pass we shift this responsibility to the
  11379. generated code.
  11380. We begin by designing the output language $R^p_8$. In
  11381. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  11382. proxies. In $R^p_8$ we return the \code{Vector} type to
  11383. its original meaning, as the type of real vectors, and we introduce a
  11384. new type, \code{PVector}, whose values can be either real vectors or
  11385. vector proxies. This new type comes with a suite of new primitive
  11386. operations for creating and using values of type \code{PVector}. We
  11387. don't need to introduce a new type to represent vector proxies. A
  11388. proxy is represented by a vector containing three things: 1) the
  11389. underlying vector, 2) a vector of functions for casting elements that
  11390. are read from the vector, and 3) a vector of functions for casting
  11391. values to be written to the vector. So we define the following
  11392. abbreviation for the type of a vector proxy:
  11393. \[
  11394. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  11395. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  11396. \to (\key{PVector}~ T' \ldots)
  11397. \]
  11398. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  11399. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  11400. %
  11401. Next we describe each of the new primitive operations.
  11402. \begin{description}
  11403. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  11404. (\key{PVector} $T \ldots$)]\ \\
  11405. %
  11406. This operation brands a vector as a value of the \code{PVector} type.
  11407. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  11408. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  11409. %
  11410. This operation brands a vector proxy as value of the \code{PVector} type.
  11411. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  11412. \code{Boolean}] \ \\
  11413. %
  11414. returns true if the value is a vector proxy and false if it is a
  11415. real vector.
  11416. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  11417. (\key{Vector} $T \ldots$)]\ \\
  11418. %
  11419. Assuming that the input is a vector (and not a proxy), this
  11420. operation returns the vector.
  11421. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  11422. $\to$ \code{Boolean}]\ \\
  11423. %
  11424. Given a vector proxy, this operation returns the length of the
  11425. underlying vector.
  11426. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  11427. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  11428. %
  11429. Given a vector proxy, this operation returns the $i$th element of
  11430. the underlying vector.
  11431. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  11432. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  11433. proxy, this operation writes a value to the $i$th element of the
  11434. underlying vector.
  11435. \end{description}
  11436. Now to discuss the translation that differentiates vectors from
  11437. proxies. First, every type annotation in the program must be
  11438. translated (recursively) to replace \code{Vector} with \code{PVector}.
  11439. Next, we must insert uses of \code{PVector} operations in the
  11440. appropriate places. For example, we wrap every vector creation with an
  11441. \code{inject-vector}.
  11442. \begin{lstlisting}
  11443. (vector |$e_1 \ldots e_n$|)
  11444. |$\Rightarrow$|
  11445. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  11446. \end{lstlisting}
  11447. The \code{raw-vector} operator that we introduced in the previous
  11448. section does not get injected.
  11449. \begin{lstlisting}
  11450. (raw-vector |$e_1 \ldots e_n$|)
  11451. |$\Rightarrow$|
  11452. (vector |$e'_1 \ldots e'_n$|)
  11453. \end{lstlisting}
  11454. The \code{vector-proxy} primitive translates as follows.
  11455. \begin{lstlisting}
  11456. (vector-proxy |$e_1~e_2~e_3$|)
  11457. |$\Rightarrow$|
  11458. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  11459. \end{lstlisting}
  11460. We translate the vector operations into conditional expressions that
  11461. check whether the value is a proxy and then dispatch to either the
  11462. appropriate proxy vector operation or the regular vector operation.
  11463. For example, the following is the translation for \code{vector-ref}.
  11464. \begin{lstlisting}
  11465. (vector-ref |$e_1$| |$i$|)
  11466. |$\Rightarrow$|
  11467. (let ([|$v~e_1$|])
  11468. (if (proxy? |$v$|)
  11469. (proxy-vector-ref |$v$| |$i$|)
  11470. (vector-ref (project-vector |$v$|) |$i$|)
  11471. \end{lstlisting}
  11472. Note in the case of a real vector, we must apply \code{project-vector}
  11473. before the \code{vector-ref}.
  11474. \section{Reveal Casts}
  11475. \label{sec:reveal-casts-gradual}
  11476. Recall that the \code{reveal-casts} pass
  11477. (Section~\ref{sec:reveal-casts-Rany}) is responsible for lowering
  11478. \code{Inject} and \code{Project} into lower-level operations. In
  11479. particular, \code{Project} turns into a conditional expression that
  11480. inspects the tag and retrieves the underlying value. Here we need to
  11481. augment the translation of \code{Project} to handle the situation when
  11482. the target type is \code{PVector}. Instead of using
  11483. \code{vector-length} we need to use \code{proxy-vector-length}.
  11484. \begin{lstlisting}
  11485. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  11486. |$\Rightarrow$|
  11487. (let |$\itm{tmp}$| |$e'$|
  11488. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  11489. (let |$\itm{vec}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  11490. (if (eq? (proxy-vector-length |$\itm{vec}$|) |$n$|) |$\itm{vec}$| (exit)))
  11491. (exit)))
  11492. \end{lstlisting}
  11493. \section{Closure Conversion}
  11494. \label{sec:closure-conversion-gradual}
  11495. The closure conversion pass only requires one minor adjustment. The
  11496. auxiliary function that translates type annotations needs to be
  11497. updated to handle the \code{PVector} type.
  11498. \section{Explicate Control}
  11499. \label{sec:explicate-control-gradual}
  11500. Update the \code{explicate-control} pass to handle the new primitive
  11501. operations on the \code{PVector} type.
  11502. \section{Select Instructions}
  11503. \label{sec:select-instructions-gradual}
  11504. Recall that the \code{select-instructions} pass is responsible for
  11505. lowering the primitive operations into x86 instructions. So we need
  11506. to translate the new \code{PVector} operations to x86. To do so, the
  11507. first question we need to answer is how will we differentiate the two
  11508. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  11509. We need just one bit to accomplish this, and use the bit in position
  11510. $57$ of the 64-bit tag at the front of every vector (see
  11511. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  11512. for \code{inject-vector} we leave it that way.
  11513. \begin{lstlisting}
  11514. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  11515. |$\Rightarrow$|
  11516. movq |$e'_1$|, |$\itm{lhs'}$|
  11517. \end{lstlisting}
  11518. On the other hand, \code{inject-proxy} sets bit $57$ to $1$.
  11519. \begin{lstlisting}
  11520. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  11521. |$\Rightarrow$|
  11522. movq |$e'_1$|, %r11
  11523. movq |$(1 << 57)$|, %rax
  11524. orq 0(%r11), %rax
  11525. movq %rax, 0(%r11)
  11526. movq %r11, |$\itm{lhs'}$|
  11527. \end{lstlisting}
  11528. The \code{proxy?} operation consumes the information so carefully
  11529. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  11530. isolates the $57$th bit to tell whether the value is a real vector or
  11531. a proxy.
  11532. \begin{lstlisting}
  11533. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  11534. |$\Rightarrow$|
  11535. movq |$e_1'$|, %r11
  11536. movq 0(%r11), %rax
  11537. sarq $57, %rax
  11538. andq $1, %rax
  11539. movq %rax, |$\itm{lhs'}$|
  11540. \end{lstlisting}
  11541. The \code{project-vector} operation is straightforward to translate,
  11542. so we leave it up to the reader.
  11543. Regarding the \code{proxy-vector} operations, the runtime provides
  11544. procedures that implement them (they are recursive functions!) so
  11545. here we simply need to translate these vector operations into the
  11546. appropriate function call. For example, here is the translation for
  11547. \code{proxy-vector-ref}.
  11548. \begin{lstlisting}
  11549. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  11550. |$\Rightarrow$|
  11551. movq |$e_1'$|, %rdi
  11552. movq |$e_2'$|, %rsi
  11553. callq proxy_vector_ref
  11554. movq %rax, |$\itm{lhs'}$|
  11555. \end{lstlisting}
  11556. We have another batch of vector operations to deal with, those for the
  11557. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  11558. \code{any-vector-ref} when there is a \code{vector-ref} on something
  11559. of type \code{Any}, and similarly for \code{any-vector-set!} and
  11560. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  11561. Section~\ref{sec:select-Rany} we selected instructions for these
  11562. operations based on the idea that the underlying value was a real
  11563. vector. But in the current setting, the underlying value is of type
  11564. \code{PVector}. So \code{any-vector-ref} can be translates to
  11565. pseudo-x86 as follows. We begin by projecting the underlying value out
  11566. of the tagged value and then call the \code{proxy\_vector\_ref}
  11567. procedure in the runtime.
  11568. \begin{lstlisting}
  11569. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  11570. movq |$\neg 111$|, %rdi
  11571. andq |$e_1'$|, %rdi
  11572. movq |$e_2'$|, %rsi
  11573. callq proxy_vector_ref
  11574. movq %rax, |$\itm{lhs'}$|
  11575. \end{lstlisting}
  11576. The \code{any-vector-set!} and \code{any-vector-length} operators can
  11577. be translated in a similar way.
  11578. \begin{exercise}\normalfont
  11579. Implement a compiler for the gradually-typed \LangGrad{} language by
  11580. extending and adapting your compiler for \LangLoop{}. Create 10 new
  11581. partially-typed test programs. In addition to testing with these
  11582. new programs, also test your compiler on all the tests for \LangLoop{}
  11583. and tests for \LangDyn{}. Sometimes you may get a type checking error
  11584. on the \LangDyn{} programs but you can adapt them by inserting
  11585. a cast to the \code{Any} type around each subexpression
  11586. causing a type error. While \LangDyn{} doesn't have explicit casts,
  11587. you can induce one by wrapping the subexpression \code{e}
  11588. with a call to an un-annotated identity function, like this:
  11589. \code{((lambda (x) x) e)}.
  11590. \end{exercise}
  11591. \begin{figure}[p]
  11592. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11593. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  11594. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  11595. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  11596. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  11597. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  11598. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  11599. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  11600. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  11601. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  11602. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  11603. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  11604. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  11605. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  11606. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  11607. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  11608. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  11609. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  11610. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  11611. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  11612. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  11613. \path[->,bend right=15] (Rgradual) edge [above] node
  11614. {\ttfamily\footnotesize type-check} (Rgradualp);
  11615. \path[->,bend right=15] (Rgradualp) edge [above] node
  11616. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  11617. \path[->,bend right=15] (Rwhilepp) edge [right] node
  11618. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  11619. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  11620. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  11621. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  11622. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  11623. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  11624. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  11625. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  11626. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  11627. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  11628. {\ttfamily\footnotesize convert-assignments} (F1-1);
  11629. \path[->,bend left=15] (F1-1) edge [below] node
  11630. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  11631. \path[->,bend right=15] (F1-2) edge [above] node
  11632. {\ttfamily\footnotesize limit-fun.} (F1-3);
  11633. \path[->,bend right=15] (F1-3) edge [above] node
  11634. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  11635. \path[->,bend right=15] (F1-4) edge [above] node
  11636. {\ttfamily\footnotesize remove-complex.} (F1-5);
  11637. \path[->,bend right=15] (F1-5) edge [right] node
  11638. {\ttfamily\footnotesize explicate-control} (C3-2);
  11639. \path[->,bend left=15] (C3-2) edge [left] node
  11640. {\ttfamily\footnotesize select-instr.} (x86-2);
  11641. \path[->,bend right=15] (x86-2) edge [left] node
  11642. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  11643. \path[->,bend right=15] (x86-2-1) edge [below] node
  11644. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  11645. \path[->,bend right=15] (x86-2-2) edge [left] node
  11646. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  11647. \path[->,bend left=15] (x86-3) edge [above] node
  11648. {\ttfamily\footnotesize patch-instr.} (x86-4);
  11649. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  11650. \end{tikzpicture}
  11651. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  11652. \label{fig:Rgradual-passes}
  11653. \end{figure}
  11654. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  11655. for the compilation of \LangGrad{}.
  11656. \section{Further Reading}
  11657. This chapter just scratches the surface of gradual typing. The basic
  11658. approach described here is missing two key ingredients that one would
  11659. want in a implementation of gradual typing: blame
  11660. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  11661. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  11662. problem addressed by blame tracking is that when a cast on a
  11663. higher-order value fails, it often does so at a point in the program
  11664. that is far removed from the original cast. Blame tracking is a
  11665. technique for propagating extra information through casts and proxies
  11666. so that when a cast fails, the error message can point back to the
  11667. original location of the cast in the source program.
  11668. The problem addressed by space-efficient casts also relates to
  11669. higher-order casts. It turns out that in partially typed programs, a
  11670. function or vector can flow through very-many casts at runtime. With
  11671. the approach described in this chapter, each cast adds another
  11672. \code{lambda} wrapper or a vector proxy. Not only does this take up
  11673. considerable space, but it also makes the function calls and vector
  11674. operations slow. For example, a partially-typed version of quicksort
  11675. could, in the worst case, build a chain of proxies of length $O(n)$
  11676. around the vector, changing the overall time complexity of the
  11677. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  11678. solution to this problem by representing casts using the coercion
  11679. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  11680. long chains of proxies by compressing them into a concise normal
  11681. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  11682. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  11683. the Grift compiler.
  11684. \begin{center}
  11685. \url{https://github.com/Gradual-Typing/Grift}
  11686. \end{center}
  11687. There are also interesting interactions between gradual typing and
  11688. other language features, such as parametetric polymorphism,
  11689. information-flow types, and type inference, to name a few. We
  11690. recommend the reader to the online gradual typing bibliography:
  11691. \begin{center}
  11692. \url{http://samth.github.io/gradual-typing-bib/}
  11693. \end{center}
  11694. % TODO: challenge problem:
  11695. % type analysis and type specialization?
  11696. % coercions?
  11697. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11698. \chapter{Parametric Polymorphism}
  11699. \label{ch:Rpoly}
  11700. \index{parametric polymorphism}
  11701. \index{generics}
  11702. This chapter studies the compilation of parametric
  11703. polymorphism\index{parametric polymorphism}
  11704. (aka. generics\index{generics}) in the subset \LangPoly{} of Typed
  11705. Racket. Parametric polymorphism enables improved code reuse by
  11706. parameterizing functions and data structures with respect to the types
  11707. that they operate on. For example, Figure~\ref{fig:map-vec-poly}
  11708. revisits the \code{map-vec} example but this time gives it a more
  11709. fitting type. This \code{map-vec} function is parameterized with
  11710. respect to the element type of the vector. The type of \code{map-vec}
  11711. is the following polymorphic type as specified by the \code{All} and
  11712. the type parameter \code{a}.
  11713. \begin{lstlisting}
  11714. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  11715. \end{lstlisting}
  11716. The idea is that \code{map-vec} can be used at \emph{all} choices of a
  11717. type for parameter \code{a}. In Figure~\ref{fig:map-vec-poly} we apply
  11718. \code{map-vec} to a vector of integers, a choice of \code{Integer} for
  11719. \code{a}, but we could have just as well applied \code{map-vec} to a
  11720. vector of Booleans (and a function on Booleans).
  11721. \begin{figure}[tbp]
  11722. % poly_test_2.rkt
  11723. \begin{lstlisting}
  11724. (: map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  11725. (define (map-vec f v)
  11726. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11727. (define (add1 [x : Integer]) : Integer (+ x 1))
  11728. (vector-ref (map-vec add1 (vector 0 41)) 1)
  11729. \end{lstlisting}
  11730. \caption{The \code{map-vec} example using parametric polymorphism.}
  11731. \label{fig:map-vec-poly}
  11732. \end{figure}
  11733. Figure~\ref{fig:Rpoly-concrete-syntax} defines the concrete syntax of
  11734. \LangPoly{} and Figure~\ref{fig:Rpoly-syntax} defines the abstract
  11735. syntax. We add a second form for function definitions in which a type
  11736. declaration comes before the \code{define}. In the abstract syntax,
  11737. the return type in the \code{Def} is \code{Any}, but that should be
  11738. ignored in favor of the return type in the type declaration. (The
  11739. \code{Any} comes from using the same parser as in
  11740. Chapter~\ref{ch:Rdyn}.) The presence of a type declaration
  11741. enables the use of an \code{All} type for a function, thereby making
  11742. it polymorphic. The grammar for types is extended to include
  11743. polymorphic types and type variables.
  11744. \begin{figure}[tp]
  11745. \centering
  11746. \fbox{
  11747. \begin{minipage}{0.96\textwidth}
  11748. \small
  11749. \[
  11750. \begin{array}{lcl}
  11751. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11752. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  11753. &\mid& \LP\key{:}~\Var~\Type\RP \\
  11754. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  11755. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  11756. \end{array}
  11757. \]
  11758. \end{minipage}
  11759. }
  11760. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  11761. (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  11762. \label{fig:Rpoly-concrete-syntax}
  11763. \end{figure}
  11764. \begin{figure}[tp]
  11765. \centering
  11766. \fbox{
  11767. \begin{minipage}{0.96\textwidth}
  11768. \small
  11769. \[
  11770. \begin{array}{lcl}
  11771. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11772. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  11773. &\mid& \DECL{\Var}{\Type} \\
  11774. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  11775. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11776. \end{array}
  11777. \]
  11778. \end{minipage}
  11779. }
  11780. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  11781. (Figure~\ref{fig:Rwhile-syntax}).}
  11782. \label{fig:Rpoly-syntax}
  11783. \end{figure}
  11784. By including polymorphic types in the $\Type$ non-terminal we choose
  11785. to make them first-class which has interesting repercussions on the
  11786. compiler. Many languages with polymorphism, such as
  11787. C++~\citep{stroustrup88:_param_types} and Standard
  11788. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  11789. it is useful to see an example of first-class polymorphism. In
  11790. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  11791. whose parameter is a polymorphic function. The occurrence of a
  11792. polymorphic type underneath a function type is enabled by the normal
  11793. recursive structure of the grammar for $\Type$ and the categorization
  11794. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  11795. applies the polymorphic function to a Boolean and to an integer.
  11796. \begin{figure}[tbp]
  11797. \begin{lstlisting}
  11798. (: apply-twice ((All (b) (b -> b)) -> Integer))
  11799. (define (apply-twice f)
  11800. (if (f #t) (f 42) (f 777)))
  11801. (: id (All (a) (a -> a)))
  11802. (define (id x) x)
  11803. (apply-twice id)
  11804. \end{lstlisting}
  11805. \caption{An example illustrating first-class polymorphism.}
  11806. \label{fig:apply-twice}
  11807. \end{figure}
  11808. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Rvar0} has
  11809. three new responsibilities (compared to \LangLoop{}). The type checking of
  11810. function application is extended to handle the case where the operator
  11811. expression is a polymorphic function. In that case the type arguments
  11812. are deduced by matching the type of the parameters with the types of
  11813. the arguments.
  11814. %
  11815. The \code{match-types} auxiliary function carries out this deduction
  11816. by recursively descending through a parameter type \code{pt} and the
  11817. corresponding argument type \code{at}, making sure that they are equal
  11818. except when there is a type parameter on the left (in the parameter
  11819. type). If it's the first time that the type parameter has been
  11820. encountered, then the algorithm deduces an association of the type
  11821. parameter to the corresponding type on the right (in the argument
  11822. type). If it's not the first time that the type parameter has been
  11823. encountered, the algorithm looks up its deduced type and makes sure
  11824. that it is equal to the type on the right.
  11825. %
  11826. Once the type arguments are deduced, the operator expression is
  11827. wrapped in an \code{Inst} AST node (for instantiate) that records the
  11828. type of the operator, but more importantly, records the deduced type
  11829. arguments. The return type of the application is the return type of
  11830. the polymorphic function, but with the type parameters replaced by the
  11831. deduced type arguments, using the \code{subst-type} function.
  11832. The second responsibility of the type checker is extending the
  11833. function \code{type-equal?} to handle the \code{All} type. This is
  11834. not quite a simple as equal on other types, such as function and
  11835. vector types, because two polymorphic types can be syntactically
  11836. different even though they are equivalent types. For example,
  11837. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  11838. Two polymorphic types should be considered equal if they differ only
  11839. in the choice of the names of the type parameters. The
  11840. \code{type-equal?} function in Figure~\ref{fig:type-check-Rvar0-aux}
  11841. renames the type parameters of the first type to match the type
  11842. parameters of the second type.
  11843. The third responsibility of the type checker is making sure that only
  11844. defined type variables appear in type annotations. The
  11845. \code{check-well-formed} function defined in
  11846. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  11847. sure that each type variable has been defined.
  11848. The output language of the type checker is \LangInst{}, defined in
  11849. Figure~\ref{fig:Rpoly-prime-syntax}. The type checker combines the type
  11850. declaration and polymorphic function into a single definition, using
  11851. the \code{Poly} form, to make polymorphic functions more convenient to
  11852. process in next pass of the compiler.
  11853. \begin{figure}[tp]
  11854. \centering
  11855. \fbox{
  11856. \begin{minipage}{0.96\textwidth}
  11857. \small
  11858. \[
  11859. \begin{array}{lcl}
  11860. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11861. \Exp &::=& \ldots \mid \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  11862. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  11863. &\mid& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  11864. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11865. \end{array}
  11866. \]
  11867. \end{minipage}
  11868. }
  11869. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  11870. (Figure~\ref{fig:Rwhile-syntax}).}
  11871. \label{fig:Rpoly-prime-syntax}
  11872. \end{figure}
  11873. The output of the type checker on the polymorphic \code{map-vec}
  11874. example is listed in Figure~\ref{fig:map-vec-type-check}.
  11875. \begin{figure}[tbp]
  11876. % poly_test_2.rkt
  11877. \begin{lstlisting}
  11878. (poly (a) (define (map-vec [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  11879. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  11880. (define (add1 [x : Integer]) : Integer (+ x 1))
  11881. (vector-ref ((inst map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  11882. (Integer))
  11883. add1 (vector 0 41)) 1)
  11884. \end{lstlisting}
  11885. \caption{Output of the type checker on the \code{map-vec} example.}
  11886. \label{fig:map-vec-type-check}
  11887. \end{figure}
  11888. \begin{figure}[tbp]
  11889. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11890. (define type-check-poly-class
  11891. (class type-check-Rwhile-class
  11892. (super-new)
  11893. (inherit check-type-equal?)
  11894. (define/override (type-check-apply env e1 es)
  11895. (define-values (e^ ty) ((type-check-exp env) e1))
  11896. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  11897. ((type-check-exp env) e)))
  11898. (match ty
  11899. [`(,ty^* ... -> ,rt)
  11900. (for ([arg-ty ty*] [param-ty ty^*])
  11901. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  11902. (values e^ es^ rt)]
  11903. [`(All ,xs (,tys ... -> ,rt))
  11904. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  11905. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  11906. (match-types env^^ param-ty arg-ty)))
  11907. (define targs
  11908. (for/list ([x xs])
  11909. (match (dict-ref env^^ x (lambda () #f))
  11910. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  11911. x (Apply e1 es))]
  11912. [ty ty])))
  11913. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  11914. [else (error 'type-check "expected a function, not ~a" ty)]))
  11915. (define/override ((type-check-exp env) e)
  11916. (match e
  11917. [(Lambda `([,xs : ,Ts] ...) rT body)
  11918. (for ([T Ts]) ((check-well-formed env) T))
  11919. ((check-well-formed env) rT)
  11920. ((super type-check-exp env) e)]
  11921. [(HasType e1 ty)
  11922. ((check-well-formed env) ty)
  11923. ((super type-check-exp env) e)]
  11924. [else ((super type-check-exp env) e)]))
  11925. (define/override ((type-check-def env) d)
  11926. (verbose 'type-check "poly/def" d)
  11927. (match d
  11928. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  11929. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  11930. (for ([p ps]) ((check-well-formed ts-env) p))
  11931. ((check-well-formed ts-env) rt)
  11932. (define new-env (append ts-env (map cons xs ps) env))
  11933. (define-values (body^ ty^) ((type-check-exp new-env) body))
  11934. (check-type-equal? ty^ rt body)
  11935. (Generic ts (Def f p:t* rt info body^))]
  11936. [else ((super type-check-def env) d)]))
  11937. (define/override (type-check-program p)
  11938. (match p
  11939. [(Program info body)
  11940. (type-check-program (ProgramDefsExp info '() body))]
  11941. [(ProgramDefsExp info ds body)
  11942. (define ds^ (combine-decls-defs ds))
  11943. (define new-env (for/list ([d ds^])
  11944. (cons (def-name d) (fun-def-type d))))
  11945. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  11946. (define-values (body^ ty) ((type-check-exp new-env) body))
  11947. (check-type-equal? ty 'Integer body)
  11948. (ProgramDefsExp info ds^^ body^)]))
  11949. ))
  11950. \end{lstlisting}
  11951. \caption{Type checker for the \LangPoly{} language.}
  11952. \label{fig:type-check-Rvar0}
  11953. \end{figure}
  11954. \begin{figure}[tbp]
  11955. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11956. (define/override (type-equal? t1 t2)
  11957. (match* (t1 t2)
  11958. [(`(All ,xs ,T1) `(All ,ys ,T2))
  11959. (define env (map cons xs ys))
  11960. (type-equal? (subst-type env T1) T2)]
  11961. [(other wise)
  11962. (super type-equal? t1 t2)]))
  11963. (define/public (match-types env pt at)
  11964. (match* (pt at)
  11965. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  11966. [('Void 'Void) env] [('Any 'Any) env]
  11967. [(`(Vector ,pts ...) `(Vector ,ats ...))
  11968. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  11969. (match-types env^ pt1 at1))]
  11970. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  11971. (define env^ (match-types env prt art))
  11972. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  11973. (match-types env^^ pt1 at1))]
  11974. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  11975. (define env^ (append (map cons pxs axs) env))
  11976. (match-types env^ pt1 at1)]
  11977. [((? symbol? x) at)
  11978. (match (dict-ref env x (lambda () #f))
  11979. [#f (error 'type-check "undefined type variable ~a" x)]
  11980. ['Type (cons (cons x at) env)]
  11981. [t^ (check-type-equal? at t^ 'matching) env])]
  11982. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  11983. (define/public (subst-type env pt)
  11984. (match pt
  11985. ['Integer 'Integer] ['Boolean 'Boolean]
  11986. ['Void 'Void] ['Any 'Any]
  11987. [`(Vector ,ts ...)
  11988. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  11989. [`(,ts ... -> ,rt)
  11990. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  11991. [`(All ,xs ,t)
  11992. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  11993. [(? symbol? x) (dict-ref env x)]
  11994. [else (error 'type-check "expected a type not ~a" pt)]))
  11995. (define/public (combine-decls-defs ds)
  11996. (match ds
  11997. ['() '()]
  11998. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  11999. (unless (equal? name f)
  12000. (error 'type-check "name mismatch, ~a != ~a" name f))
  12001. (match type
  12002. [`(All ,xs (,ps ... -> ,rt))
  12003. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  12004. (cons (Generic xs (Def name params^ rt info body))
  12005. (combine-decls-defs ds^))]
  12006. [`(,ps ... -> ,rt)
  12007. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  12008. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  12009. [else (error 'type-check "expected a function type, not ~a" type) ])]
  12010. [`(,(Def f params rt info body) . ,ds^)
  12011. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  12012. \end{lstlisting}
  12013. \caption{Auxiliary functions for type checking \LangPoly{}.}
  12014. \label{fig:type-check-Rvar0-aux}
  12015. \end{figure}
  12016. \begin{figure}[tbp]
  12017. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  12018. (define/public ((check-well-formed env) ty)
  12019. (match ty
  12020. ['Integer (void)]
  12021. ['Boolean (void)]
  12022. ['Void (void)]
  12023. [(? symbol? a)
  12024. (match (dict-ref env a (lambda () #f))
  12025. ['Type (void)]
  12026. [else (error 'type-check "undefined type variable ~a" a)])]
  12027. [`(Vector ,ts ...)
  12028. (for ([t ts]) ((check-well-formed env) t))]
  12029. [`(,ts ... -> ,t)
  12030. (for ([t ts]) ((check-well-formed env) t))
  12031. ((check-well-formed env) t)]
  12032. [`(All ,xs ,t)
  12033. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  12034. ((check-well-formed env^) t)]
  12035. [else (error 'type-check "unrecognized type ~a" ty)]))
  12036. \end{lstlisting}
  12037. \caption{Well-formed types.}
  12038. \label{fig:well-formed-types}
  12039. \end{figure}
  12040. % TODO: interpreter for R'_10
  12041. \section{Compiling Polymorphism}
  12042. \label{sec:compiling-poly}
  12043. Broadly speaking, there are four approaches to compiling parametric
  12044. polymorphism, which we describe below.
  12045. \begin{description}
  12046. \item[Monomorphization] generates a different version of a polymorphic
  12047. function for each set of type arguments that it is used with,
  12048. producing type-specialized code. This approach results in the most
  12049. efficient code but requires whole-program compilation (no separate
  12050. compilation) and increases code size. For our current purposes
  12051. monomorphization is a non-starter because, with first-class
  12052. polymorphism, it is sometimes not possible to determine which
  12053. generic functions are used with which type arguments during
  12054. compilation. (It can be done at runtime, with just-in-time
  12055. compilation.) This approach is used to compile C++
  12056. templates~\citep{stroustrup88:_param_types} and polymorphic
  12057. functions in NESL~\citep{Blelloch:1993aa} and
  12058. ML~\citep{Weeks:2006aa}.
  12059. \item[Uniform representation] generates one version of each
  12060. polymorphic function but requires all values have a common ``boxed''
  12061. format, such as the tagged values of type \code{Any} in
  12062. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  12063. similarly to code in a dynamically typed language (like \LangDyn{}),
  12064. in which primitive operators require their arguments to be projected
  12065. from \code{Any} and their results are injected into \code{Any}. (In
  12066. object-oriented languages, the projection is accomplished via
  12067. virtual method dispatch.) The uniform representation approach is
  12068. compatible with separate compilation and with first-class
  12069. polymorphism. However, it produces the least-efficient code because
  12070. it introduces overhead in the entire program, including
  12071. non-polymorphic code. This approach is used in implementations of
  12072. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  12073. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  12074. Java~\citep{Bracha:1998fk}.
  12075. \item[Mixed representation] generates one version of each polymorphic
  12076. function, using a boxed representation for type
  12077. variables. Monomorphic code is compiled as usual (as in \LangLoop{})
  12078. and conversions are performed at the boundaries between monomorphic
  12079. and polymorphic (e.g. when a polymorphic function is instantiated
  12080. and called). This approach is compatible with separate compilation
  12081. and first-class polymorphism and maintains the efficiency of
  12082. monomorphic code. The tradeoff is increased overhead at the boundary
  12083. between monomorphic and polymorphic code. This approach is used in
  12084. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  12085. Java 5 with the addition of autoboxing.
  12086. \item[Type passing] uses the unboxed representation in both
  12087. monomorphic and polymorphic code. Each polymorphic function is
  12088. compiled to a single function with extra parameters that describe
  12089. the type arguments. The type information is used by the generated
  12090. code to know how to access the unboxed values at runtime. This
  12091. approach is used in implementation of the Napier88
  12092. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. Type
  12093. passing is compatible with separate compilation and first-class
  12094. polymorphism and maintains the efficiency for monomorphic
  12095. code. There is runtime overhead in polymorphic code from dispatching
  12096. on type information.
  12097. \end{description}
  12098. In this chapter we use the mixed representation approach, partly
  12099. because of its favorable attributes, and partly because it is
  12100. straightforward to implement using the tools that we have already
  12101. built to support gradual typing. To compile polymorphic functions, we
  12102. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  12103. \LangCast{}.
  12104. \section{Erase Types}
  12105. \label{sec:erase-types}
  12106. We use the \code{Any} type from Chapter~\ref{ch:Rdyn} to
  12107. represent type variables. For example, Figure~\ref{fig:map-vec-erase}
  12108. shows the output of the \code{erase-types} pass on the polymorphic
  12109. \code{map-vec} (Figure~\ref{fig:map-vec-poly}). The occurrences of
  12110. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  12111. \code{All} types are removed from the type of \code{map-vec}.
  12112. \begin{figure}[tbp]
  12113. \begin{lstlisting}
  12114. (define (map-vec [f : (Any -> Any)] [v : (Vector Any Any)])
  12115. : (Vector Any Any)
  12116. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12117. (define (add1 [x : Integer]) : Integer (+ x 1))
  12118. (vector-ref ((cast map-vec
  12119. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  12120. ((Integer -> Integer) (Vector Integer Integer)
  12121. -> (Vector Integer Integer)))
  12122. add1 (vector 0 41)) 1)
  12123. \end{lstlisting}
  12124. \caption{The polymorphic \code{map-vec} example after type erasure.}
  12125. \label{fig:map-vec-erase}
  12126. \end{figure}
  12127. This process of type erasure creates a challenge at points of
  12128. instantiation. For example, consider the instantiation of
  12129. \code{map-vec} in Figure~\ref{fig:map-vec-type-check}.
  12130. The type of \code{map-vec} is
  12131. \begin{lstlisting}
  12132. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  12133. \end{lstlisting}
  12134. and it is instantiated to
  12135. \begin{lstlisting}
  12136. ((Integer -> Integer) (Vector Integer Integer)
  12137. -> (Vector Integer Integer))
  12138. \end{lstlisting}
  12139. After erasure, the type of \code{map-vec} is
  12140. \begin{lstlisting}
  12141. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  12142. \end{lstlisting}
  12143. but we need to convert it to the instantiated type. This is easy to
  12144. do in the target language \LangCast{} with a single \code{cast}. In
  12145. Figure~\ref{fig:map-vec-erase}, the instantiation of \code{map-vec}
  12146. has been compiled to a \code{cast} from the type of \code{map-vec} to
  12147. the instantiated type. The source and target type of a cast must be
  12148. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  12149. because both the source and target are obtained from the same
  12150. polymorphic type of \code{map-vec}, replacing the type parameters with
  12151. \code{Any} in the former and with the deduced type arguments in the
  12152. later. (Recall that the \code{Any} type is consistent with any type.)
  12153. To implement the \code{erase-types} pass, we recommend defining a
  12154. recursive auxiliary function named \code{erase-type} that applies the
  12155. following two transformations. It replaces type variables with
  12156. \code{Any}
  12157. \begin{lstlisting}
  12158. |$x$|
  12159. |$\Rightarrow$|
  12160. Any
  12161. \end{lstlisting}
  12162. and it removes the polymorphic \code{All} types.
  12163. \begin{lstlisting}
  12164. (All |$xs$| |$T_1$|)
  12165. |$\Rightarrow$|
  12166. |$T'_1$|
  12167. \end{lstlisting}
  12168. Apply the \code{erase-type} function to all of the type annotations in
  12169. the program.
  12170. Regarding the translation of expressions, the case for \code{Inst} is
  12171. the interesting one. We translate it into a \code{Cast}, as shown
  12172. below. The type of the subexpression $e$ is the polymorphic type
  12173. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  12174. $T$, the type $T'$. The target type $T''$ is the result of
  12175. substituting the arguments types $ts$ for the type parameters $xs$ in
  12176. $T$ followed by doing type erasure.
  12177. \begin{lstlisting}
  12178. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  12179. |$\Rightarrow$|
  12180. (Cast |$e'$| |$T'$| |$T''$|)
  12181. \end{lstlisting}
  12182. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  12183. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  12184. Finally, each polymorphic function is translated to a regular
  12185. functions in which type erasure has been applied to all the type
  12186. annotations and the body.
  12187. \begin{lstlisting}
  12188. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  12189. |$\Rightarrow$|
  12190. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  12191. \end{lstlisting}
  12192. \begin{exercise}\normalfont
  12193. Implement a compiler for the polymorphic language \LangPoly{} by
  12194. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  12195. programs that use polymorphic functions. Some of them should make
  12196. use of first-class polymorphism.
  12197. \end{exercise}
  12198. \begin{figure}[p]
  12199. \begin{tikzpicture}[baseline=(current bounding box.center)]
  12200. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  12201. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  12202. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  12203. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  12204. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  12205. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  12206. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  12207. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  12208. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  12209. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  12210. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  12211. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  12212. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  12213. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  12214. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  12215. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  12216. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  12217. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  12218. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  12219. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  12220. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  12221. \path[->,bend right=15] (Rpoly) edge [above] node
  12222. {\ttfamily\footnotesize type-check} (Rpolyp);
  12223. \path[->,bend right=15] (Rpolyp) edge [above] node
  12224. {\ttfamily\footnotesize erase-types} (Rgradualp);
  12225. \path[->,bend right=15] (Rgradualp) edge [above] node
  12226. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  12227. \path[->,bend right=15] (Rwhilepp) edge [right] node
  12228. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  12229. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  12230. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  12231. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  12232. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  12233. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  12234. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  12235. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  12236. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  12237. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  12238. {\ttfamily\footnotesize convert-assignments} (F1-1);
  12239. \path[->,bend left=15] (F1-1) edge [below] node
  12240. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  12241. \path[->,bend right=15] (F1-2) edge [above] node
  12242. {\ttfamily\footnotesize limit-fun.} (F1-3);
  12243. \path[->,bend right=15] (F1-3) edge [above] node
  12244. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  12245. \path[->,bend right=15] (F1-4) edge [above] node
  12246. {\ttfamily\footnotesize remove-complex.} (F1-5);
  12247. \path[->,bend right=15] (F1-5) edge [right] node
  12248. {\ttfamily\footnotesize explicate-control} (C3-2);
  12249. \path[->,bend left=15] (C3-2) edge [left] node
  12250. {\ttfamily\footnotesize select-instr.} (x86-2);
  12251. \path[->,bend right=15] (x86-2) edge [left] node
  12252. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  12253. \path[->,bend right=15] (x86-2-1) edge [below] node
  12254. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  12255. \path[->,bend right=15] (x86-2-2) edge [left] node
  12256. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  12257. \path[->,bend left=15] (x86-3) edge [above] node
  12258. {\ttfamily\footnotesize patch-instr.} (x86-4);
  12259. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  12260. \end{tikzpicture}
  12261. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  12262. \label{fig:Rpoly-passes}
  12263. \end{figure}
  12264. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  12265. for the compilation of \LangPoly{}.
  12266. % TODO: challenge problem: specialization of instantiations
  12267. % Further Reading
  12268. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12269. \chapter{Appendix}
  12270. \section{Interpreters}
  12271. \label{appendix:interp}
  12272. \index{interpreter}
  12273. We provide interpreters for each of the source languages \LangInt{},
  12274. \LangVar{}, $\ldots$ in the files \code{interp-Rint.rkt},
  12275. \code{interp-Rvar.rkt}, etc. The interpreters for the intermediate
  12276. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  12277. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  12278. and x86 are in the \key{interp.rkt} file.
  12279. \section{Utility Functions}
  12280. \label{appendix:utilities}
  12281. The utility functions described in this section are in the
  12282. \key{utilities.rkt} file of the support code.
  12283. \paragraph{\code{interp-tests}}
  12284. The \key{interp-tests} function runs the compiler passes and the
  12285. interpreters on each of the specified tests to check whether each pass
  12286. is correct. The \key{interp-tests} function has the following
  12287. parameters:
  12288. \begin{description}
  12289. \item[name (a string)] a name to identify the compiler,
  12290. \item[typechecker] a function of exactly one argument that either
  12291. raises an error using the \code{error} function when it encounters a
  12292. type error, or returns \code{\#f} when it encounters a type
  12293. error. If there is no type error, the type checker returns the
  12294. program.
  12295. \item[passes] a list with one entry per pass. An entry is a list with
  12296. four things:
  12297. \begin{enumerate}
  12298. \item a string giving the name of the pass,
  12299. \item the function that implements the pass (a translator from AST
  12300. to AST),
  12301. \item a function that implements the interpreter (a function from
  12302. AST to result value) for the output language,
  12303. \item and a type checker for the output language. Type checkers for
  12304. the $R$ and $C$ languages are provided in the support code. For
  12305. example, the type checkers for \LangVar{} and \LangCVar{} are in
  12306. \code{type-check-Rvar.rkt} and \code{type-check-Cvar.rkt}. The
  12307. type checker entry is optional. The support code does not provide
  12308. type checkers for the x86 languages.
  12309. \end{enumerate}
  12310. \item[source-interp] an interpreter for the source language. The
  12311. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  12312. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  12313. \item[tests] a list of test numbers that specifies which tests to
  12314. run. (see below)
  12315. \end{description}
  12316. %
  12317. The \key{interp-tests} function assumes that the subdirectory
  12318. \key{tests} has a collection of Racket programs whose names all start
  12319. with the family name, followed by an underscore and then the test
  12320. number, ending with the file extension \key{.rkt}. Also, for each test
  12321. program that calls \code{read} one or more times, there is a file with
  12322. the same name except that the file extension is \key{.in} that
  12323. provides the input for the Racket program. If the test program is
  12324. expected to fail type checking, then there should be an empty file of
  12325. the same name but with extension \key{.tyerr}.
  12326. \paragraph{\code{compiler-tests}}
  12327. runs the compiler passes to generate x86 (a \key{.s} file) and then
  12328. runs the GNU C compiler (gcc) to generate machine code. It runs the
  12329. machine code and checks that the output is $42$. The parameters to the
  12330. \code{compiler-tests} function are similar to those of the
  12331. \code{interp-tests} function, and consist of
  12332. \begin{itemize}
  12333. \item a compiler name (a string),
  12334. \item a type checker,
  12335. \item description of the passes,
  12336. \item name of a test-family, and
  12337. \item a list of test numbers.
  12338. \end{itemize}
  12339. \paragraph{\code{compile-file}}
  12340. takes a description of the compiler passes (see the comment for
  12341. \key{interp-tests}) and returns a function that, given a program file
  12342. name (a string ending in \key{.rkt}), applies all of the passes and
  12343. writes the output to a file whose name is the same as the program file
  12344. name but with \key{.rkt} replaced with \key{.s}.
  12345. \paragraph{\code{read-program}}
  12346. takes a file path and parses that file (it must be a Racket program)
  12347. into an abstract syntax tree.
  12348. \paragraph{\code{parse-program}}
  12349. takes an S-expression representation of an abstract syntax tree and converts it into
  12350. the struct-based representation.
  12351. \paragraph{\code{assert}}
  12352. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  12353. and displays the message \key{msg} if the Boolean \key{bool} is false.
  12354. \paragraph{\code{lookup}}
  12355. % remove discussion of lookup? -Jeremy
  12356. takes a key and an alist, and returns the first value that is
  12357. associated with the given key, if there is one. If not, an error is
  12358. triggered. The alist may contain both immutable pairs (built with
  12359. \key{cons}) and mutable pairs (built with \key{mcons}).
  12360. %The \key{map2} function ...
  12361. \section{x86 Instruction Set Quick-Reference}
  12362. \label{sec:x86-quick-reference}
  12363. \index{x86}
  12364. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  12365. do. We write $A \to B$ to mean that the value of $A$ is written into
  12366. location $B$. Address offsets are given in bytes. The instruction
  12367. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  12368. registers (such as \code{\%rax}), or memory references (such as
  12369. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  12370. reference per instruction. Other operands must be immediates or
  12371. registers.
  12372. \begin{table}[tbp]
  12373. \centering
  12374. \begin{tabular}{l|l}
  12375. \textbf{Instruction} & \textbf{Operation} \\ \hline
  12376. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  12377. \texttt{negq} $A$ & $- A \to A$ \\
  12378. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  12379. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  12380. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  12381. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  12382. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  12383. \texttt{retq} & Pops the return address and jumps to it \\
  12384. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  12385. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  12386. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  12387. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  12388. be an immediate) \\
  12389. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  12390. matches the condition code of the instruction, otherwise go to the
  12391. next instructions. The condition codes are \key{e} for ``equal'',
  12392. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  12393. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  12394. \texttt{jl} $L$ & \\
  12395. \texttt{jle} $L$ & \\
  12396. \texttt{jg} $L$ & \\
  12397. \texttt{jge} $L$ & \\
  12398. \texttt{jmp} $L$ & Jump to label $L$ \\
  12399. \texttt{movq} $A$, $B$ & $A \to B$ \\
  12400. \texttt{movzbq} $A$, $B$ &
  12401. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  12402. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  12403. and the extra bytes of $B$ are set to zero.} \\
  12404. & \\
  12405. & \\
  12406. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  12407. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  12408. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  12409. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  12410. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  12411. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  12412. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  12413. description of the condition codes. $A$ must be a single byte register
  12414. (e.g., \texttt{al} or \texttt{cl}).} \\
  12415. \texttt{setl} $A$ & \\
  12416. \texttt{setle} $A$ & \\
  12417. \texttt{setg} $A$ & \\
  12418. \texttt{setge} $A$ &
  12419. \end{tabular}
  12420. \vspace{5pt}
  12421. \caption{Quick-reference for the x86 instructions used in this book.}
  12422. \label{tab:x86-instr}
  12423. \end{table}
  12424. \cleardoublepage
  12425. \section{Concrete Syntax for Intermediate Languages}
  12426. The concrete syntax of \LangAny{} is defined in
  12427. Figure~\ref{fig:Rany-concrete-syntax}.
  12428. \begin{figure}[tp]
  12429. \centering
  12430. \fbox{
  12431. \begin{minipage}{0.97\textwidth}\small
  12432. \[
  12433. \begin{array}{lcl}
  12434. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  12435. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \key{Void}} \\
  12436. &\mid& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \mid \key{Any} \\
  12437. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void}
  12438. \mid \LP\key{Vector}\; \key{Any}\ldots\RP \\
  12439. &\mid& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  12440. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \mid \CPROJECT{\Exp}{\FType}\\
  12441. &\mid& \LP\key{any-vector-length}\;\Exp\RP
  12442. \mid \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  12443. &\mid& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  12444. &\mid& \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP
  12445. \mid \LP\key{void?}\;\Exp\RP \\
  12446. &\mid& \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \\
  12447. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  12448. \LangAny{} &::=& \gray{\Def\ldots \; \Exp}
  12449. \end{array}
  12450. \]
  12451. \end{minipage}
  12452. }
  12453. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  12454. (Figure~\ref{fig:Rlam-syntax}).}
  12455. \label{fig:Rany-concrete-syntax}
  12456. \end{figure}
  12457. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and \LangCFun{} is
  12458. defined in Figures~\ref{fig:c0-concrete-syntax},
  12459. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax},
  12460. and \ref{fig:c3-concrete-syntax}, respectively.
  12461. \begin{figure}[tbp]
  12462. \fbox{
  12463. \begin{minipage}{0.96\textwidth}
  12464. \[
  12465. \begin{array}{lcl}
  12466. \Atm &::=& \Int \mid \Var \\
  12467. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  12468. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  12469. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  12470. \LangCVar{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  12471. \end{array}
  12472. \]
  12473. \end{minipage}
  12474. }
  12475. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  12476. \label{fig:c0-concrete-syntax}
  12477. \end{figure}
  12478. \begin{figure}[tbp]
  12479. \fbox{
  12480. \begin{minipage}{0.96\textwidth}
  12481. \small
  12482. \[
  12483. \begin{array}{lcl}
  12484. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  12485. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  12486. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  12487. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  12488. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  12489. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  12490. \mid \key{goto}~\itm{label}\key{;}\\
  12491. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  12492. \LangCIf{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  12493. \end{array}
  12494. \]
  12495. \end{minipage}
  12496. }
  12497. \caption{The concrete syntax of the \LangCIf{} intermediate language.}
  12498. \label{fig:c1-concrete-syntax}
  12499. \end{figure}
  12500. \begin{figure}[tbp]
  12501. \fbox{
  12502. \begin{minipage}{0.96\textwidth}
  12503. \small
  12504. \[
  12505. \begin{array}{lcl}
  12506. \Atm &::=& \gray{ \Int \mid \Var \mid \itm{bool} } \\
  12507. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  12508. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  12509. &\mid& \gray{ \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP } \\
  12510. &\mid& \LP \key{allocate}~\Int~\Type \RP \\
  12511. &\mid& (\key{vector-ref}\;\Atm\;\Int) \mid (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  12512. &\mid& \LP \key{global-value}~\Var \RP \mid \LP \key{void} \RP \\
  12513. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \mid \LP\key{collect}~\Int \RP\\
  12514. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  12515. \mid \gray{ \key{goto}~\itm{label}\key{;} }\\
  12516. &\mid& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  12517. \LangCVec{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  12518. \end{array}
  12519. \]
  12520. \end{minipage}
  12521. }
  12522. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  12523. \label{fig:c2-concrete-syntax}
  12524. \end{figure}
  12525. \begin{figure}[tp]
  12526. \fbox{
  12527. \begin{minipage}{0.96\textwidth}
  12528. \small
  12529. \[
  12530. \begin{array}{lcl}
  12531. \Atm &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  12532. \\
  12533. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  12534. \Exp &::= & \gray{ \Atm \mid \LP\key{read}\RP \mid \LP\key{-}\;\Atm\RP \mid \LP\key{+} \; \Atm\;\Atm\RP
  12535. \mid \LP\key{not}\;\Atm\RP \mid \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  12536. &\mid& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  12537. \mid \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  12538. &\mid& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \mid \LP\key{global-value} \,\itm{name}\RP \mid \LP\key{void}\RP } \\
  12539. &\mid& \LP\key{fun-ref}~\itm{label}\RP \mid \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  12540. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  12541. \mid \LP\key{collect} \,\itm{int}\RP }\\
  12542. \Tail &::= & \gray{\RETURN{\Exp} \mid \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  12543. &\mid& \gray{\LP\key{goto}\,\itm{label}\RP
  12544. \mid \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  12545. &\mid& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  12546. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  12547. \LangCFun{} & ::= & \Def\ldots
  12548. \end{array}
  12549. \]
  12550. \end{minipage}
  12551. }
  12552. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  12553. \label{fig:c3-concrete-syntax}
  12554. \end{figure}
  12555. \cleardoublepage
  12556. \addcontentsline{toc}{chapter}{Index}
  12557. \printindex
  12558. \cleardoublepage
  12559. \bibliographystyle{plainnat}
  12560. \bibliography{all}
  12561. \addcontentsline{toc}{chapter}{Bibliography}
  12562. \end{document}
  12563. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  12564. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  12565. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  12566. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  12567. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator jane
  12568. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  12569. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  12570. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  12571. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs Tt
  12572. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  12573. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  12574. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  12575. %% LocalWords: boolean type-check notq cmpq sete movzbq jmp al xorq
  12576. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  12577. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  12578. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  12579. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  12580. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  12581. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  12582. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  12583. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  12584. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  12585. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  12586. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  12587. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  12588. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  12589. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  12590. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  12591. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  12592. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  12593. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  12594. % LocalWords: struct Friedman's MacOS Nystrom alist sam kate
  12595. % LocalWords: alists arity github unordered pqueue exprs ret param
  12596. % LocalWords: tyerr bytereg dh dl JmpIf HasType Osterlund Jacek TODO
  12597. % LocalWords: Gamari GlobalValue ProgramDefsExp prm ProgramDefs vn
  12598. % LocalWords: FunRef TailCall tailjmp IndirectCallq TailJmp Gilray
  12599. % LocalWords: dereference unbox Dataflow versa dataflow Kildall rhs
  12600. % LocalWords: Kleene enqueue dequeue AssignedFree FV cnvt SetBang tg
  12601. % LocalWords: ValueOf typechecker