book.tex 511 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259
  1. % Why direct style instead of continuation passing style?
  2. %% Student project ideas:
  3. %% * high-level optimizations like procedure inlining, etc.
  4. %% * closure optimization
  5. %% * adding letrec to the language
  6. %% (Thought: in the book and regular course, replace top-level defines
  7. %% with letrec.)
  8. %% * alternative back ends (ARM!, LLVM)
  9. %% * alternative calling convention (a la Dybvig)
  10. %% * lazy evaluation
  11. %% * continuations (frames in heap a la SML or segmented stack a la Dybvig)
  12. %% * exceptions
  13. %% * self hosting
  14. %% * I/O
  15. %% * foreign function interface
  16. %% * quasi-quote and unquote
  17. %% * macros (too difficult?)
  18. %% * alternative garbage collector
  19. %% * alternative register allocator
  20. %% * type classes
  21. %% * loop optimization (fusion, etc.)
  22. %% * deforestation
  23. %% * records with subtyping
  24. %% * object-oriented features
  25. %% - objects, object types, and structural subtyping (e.g. Abadi & Cardelli)
  26. %% - class-based objects and nominal subtyping (e.g. Featherweight Java)
  27. %% * multi-threading, fork join, futures, implicit parallelism
  28. %% * type analysis and specialization
  29. \documentclass[11pt]{book}
  30. \usepackage[T1]{fontenc}
  31. \usepackage[utf8]{inputenc}
  32. \usepackage{lmodern}
  33. \usepackage{hyperref}
  34. \usepackage{graphicx}
  35. \usepackage[english]{babel}
  36. \usepackage{listings}
  37. \usepackage{amsmath}
  38. \usepackage{amsthm}
  39. \usepackage{amssymb}
  40. \usepackage[numbers]{natbib}
  41. \usepackage{stmaryrd}
  42. \usepackage{xypic}
  43. \usepackage{semantic}
  44. \usepackage{wrapfig}
  45. \usepackage{tcolorbox}
  46. \usepackage{multirow}
  47. \usepackage{color}
  48. \usepackage{upquote}
  49. \usepackage{makeidx}
  50. \makeindex
  51. \definecolor{lightgray}{gray}{1}
  52. \newcommand{\black}[1]{{\color{black} #1}}
  53. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  54. \newcommand{\gray}[1]{{\color{gray} #1}}
  55. %% For pictures
  56. \usepackage{tikz}
  57. \usetikzlibrary{arrows.meta}
  58. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  59. % Computer Modern is already the default. -Jeremy
  60. %\renewcommand{\ttdefault}{cmtt}
  61. \definecolor{comment-red}{rgb}{0.8,0,0}
  62. \if01
  63. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  64. \newcommand{\margincomment}[1]{\marginpar{\color{comment-red}\tiny #1}}
  65. \else
  66. \newcommand{\rn}[1]{}
  67. \newcommand{\margincomment}[1]{}
  68. \fi
  69. \lstset{%
  70. language=Lisp,
  71. basicstyle=\ttfamily\small,
  72. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  73. deletekeywords={read,mapping,vector},
  74. escapechar=|,
  75. columns=flexible,
  76. moredelim=[is][\color{red}]{~}{~},
  77. showstringspaces=false
  78. }
  79. \newtheorem{theorem}{Theorem}
  80. \newtheorem{lemma}[theorem]{Lemma}
  81. \newtheorem{corollary}[theorem]{Corollary}
  82. \newtheorem{proposition}[theorem]{Proposition}
  83. \newtheorem{constraint}[theorem]{Constraint}
  84. \newtheorem{definition}[theorem]{Definition}
  85. \newtheorem{exercise}[theorem]{Exercise}
  86. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  87. % 'dedication' environment: To add a dedication paragraph at the start of book %
  88. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  89. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  90. \newenvironment{dedication}
  91. {
  92. \cleardoublepage
  93. \thispagestyle{empty}
  94. \vspace*{\stretch{1}}
  95. \hfill\begin{minipage}[t]{0.66\textwidth}
  96. \raggedright
  97. }
  98. {
  99. \end{minipage}
  100. \vspace*{\stretch{3}}
  101. \clearpage
  102. }
  103. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  104. % Chapter quote at the start of chapter %
  105. % Source: http://tex.stackexchange.com/a/53380 %
  106. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  107. \makeatletter
  108. \renewcommand{\@chapapp}{}% Not necessary...
  109. \newenvironment{chapquote}[2][2em]
  110. {\setlength{\@tempdima}{#1}%
  111. \def\chapquote@author{#2}%
  112. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  113. \itshape}
  114. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  115. \makeatother
  116. \input{defs}
  117. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  118. \title{\Huge \textbf{Essentials of Compilation} \\
  119. \huge The Incremental, Nano-Pass Approach}
  120. \author{\textsc{Jeremy G. Siek} \\
  121. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  122. Indiana University \\
  123. \\
  124. with contributions from: \\
  125. Carl Factora \\
  126. Andre Kuhlenschmidt \\
  127. Ryan R. Newton \\
  128. Ryan Scott \\
  129. Cameron Swords \\
  130. Michael M. Vitousek \\
  131. Michael Vollmer
  132. }
  133. \begin{document}
  134. \frontmatter
  135. \maketitle
  136. \begin{dedication}
  137. This book is dedicated to the programming language wonks at Indiana
  138. University.
  139. \end{dedication}
  140. \tableofcontents
  141. \listoffigures
  142. %\listoftables
  143. \mainmatter
  144. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  145. \chapter*{Preface}
  146. The tradition of compiler writing at Indiana University goes back to
  147. research and courses on programming languages by Professor Daniel
  148. Friedman in the 1970's and 1980's. Friedman conducted research on lazy
  149. evaluation~\citep{Friedman:1976aa} in the context of
  150. Lisp~\citep{McCarthy:1960dz} and then studied
  151. continuations~\citep{Felleisen:kx} and
  152. macros~\citep{Kohlbecker:1986dk} in the context of the
  153. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  154. of those courses, Kent Dybvig, went on to build Chez
  155. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  156. compiler for Scheme. After completing his Ph.D. at the University of
  157. North Carolina, he returned to teach at Indiana University.
  158. Throughout the 1990's and 2000's, Professor Dybvig continued
  159. development of Chez Scheme and taught the compiler course.
  160. The compiler course evolved to incorporate novel pedagogical ideas
  161. while also including elements of effective real-world compilers. One
  162. of Friedman's ideas was to split the compiler into many small
  163. ``passes'' so that the code for each pass would be easy to understood
  164. in isolation. In contrast, most compilers of the time were organized
  165. into only a few monolithic passes for reasons of compile-time
  166. efficiency. Another idea, called ``the game'', was to test the code
  167. generated by each pass on interpreters for each intermediate language,
  168. thereby helping to pinpoint errors in individual passes.
  169. %
  170. Dybvig, with later help from his students Dipanwita Sarkar and Andrew
  171. Keep, developed infrastructure to support this approach and evolved
  172. the course, first to use smaller micro-passes and then into even
  173. smaller nano-passes~\citep{Sarkar:2004fk,Keep:2012aa}. I was a student
  174. in this compiler course in the early 2000's as part of my
  175. Ph.D. studies at Indiana University. Needless to say, I enjoyed the
  176. course immensely!
  177. During that time, another graduate student named Abdulaziz Ghuloum
  178. observed that the front-to-back organization of the course made it
  179. difficult for students to understand the rationale for the compiler
  180. design. Ghuloum proposed an incremental approach in which the students
  181. start by implementing a complete compiler for a very small subset of
  182. the language. In each subsequent stage they add a feature to the
  183. language and then add or modify passes to handle the new
  184. feature~\citep{Ghuloum:2006bh}. In this way, the students see how the
  185. language features motivate aspects of the compiler design.
  186. After graduating from Indiana University in 2005, I went on to teach
  187. at the University of Colorado. I adapted the nano-pass and incremental
  188. approaches to compiling a subset of the Python
  189. language~\citep{Siek:2012ab}.
  190. %% Python and Scheme are quite different
  191. %% on the surface but there is a large overlap in the compiler techniques
  192. %% required for the two languages. Thus, I was able to teach much of the
  193. %% same content from the Indiana compiler course.
  194. I very much enjoyed teaching the course organized in this way, and
  195. even better, many of the students learned a lot and got excited about
  196. compilers.
  197. I returned to Indiana University in 2013. In my absence the compiler
  198. course had switched from the front-to-back organization to a
  199. back-to-front~\citep{Dybvig:2010aa}. While that organization also works
  200. well, I prefer the incremental approach and started porting and
  201. adapting the structure of the Colorado course back into the land of
  202. Scheme. In the meantime Indiana University had moved on from Scheme to
  203. Racket~\citep{plt-tr}, so the course is now about compiling a subset
  204. of Racket (and Typed Racket) to the x86 assembly language.
  205. This is the textbook for the incremental version of the compiler
  206. course at Indiana University (Spring 2016 - present). With this book
  207. I hope to make the Indiana compiler course available to people that
  208. have not had the chance to study compilers at Indiana University.
  209. %% I have captured what
  210. %% I think are the most important topics from \cite{Dybvig:2010aa} but
  211. %% have omitted topics that are less interesting conceptually. I have
  212. %% also made simplifications to reduce complexity. In this way, this
  213. %% book leans more towards pedagogy than towards the efficiency of the
  214. %% generated code. Also, the book differs in places where we I the
  215. %% opportunity to make the topics more fun, such as in relating register
  216. %% allocation to Sudoku (Chapter~\ref{ch:register-allocation-r1}).
  217. \section*{Prerequisites}
  218. The material in this book is challenging but rewarding. It is meant to
  219. prepare students for a lifelong career in programming languages.
  220. The book uses the Racket language both for the implementation of the
  221. compiler and for the language that is compiled, so a student should be
  222. proficient with Racket or Scheme prior to reading this book. There are
  223. many excellent resources for learning Scheme and
  224. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  225. It is helpful but not necessary for the student to have prior exposure
  226. to the x86 assembly language~\citep{Intel:2015aa}, as one might obtain
  227. from a computer systems
  228. course~\citep{Bryant:2010aa}. This book introduces the
  229. parts of x86-64 assembly language that are needed.
  230. %
  231. We follow the System V calling
  232. conventions~\citep{Bryant:2005aa,Matz:2013aa}, which means that the
  233. assembly code that we generate will work properly with our runtime
  234. system (written in C) when it is compiled using the GNU C compiler
  235. (\code{gcc}) on the Linux and MacOS operating systems. (Minor
  236. adjustments are needed for MacOS which we note as they arise.)
  237. %
  238. The GNU C compiler, when running on the Microsoft Windows operating
  239. system, follows the Microsoft x64 calling
  240. convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the assembly
  241. code that we generate will \emph{not} work properly with our runtime
  242. system on Windows. One option to consider for using a Windows computer
  243. is to run a virtual machine with Linux as the guest operating system.
  244. %\section*{Structure of book}
  245. % You might want to add short description about each chapter in this book.
  246. %\section*{About the companion website}
  247. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  248. %\begin{itemize}
  249. % \item A link to (freely downlodable) latest version of this document.
  250. % \item Link to download LaTeX source for this document.
  251. % \item Miscellaneous material (e.g. suggested readings etc).
  252. %\end{itemize}
  253. \section*{Acknowledgments}
  254. Many people have contributed to the ideas, techniques, and
  255. organization of this book and have taught courses based on it. Many
  256. of the compiler design decisions in this book are drawn from the
  257. assignment descriptions of \cite{Dybvig:2010aa}. We also would like
  258. to thank John Clements, Bor-Yuh Evan Chang, Daniel P. Friedman, Ronald
  259. Garcia, Abdulaziz Ghuloum, Jay McCarthy, Nate Nystrom, Dipanwita
  260. Sarkar, Oscar Waddell, and Michael Wollowski.
  261. \mbox{}\\
  262. \noindent Jeremy G. Siek \\
  263. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  264. %\noindent Spring 2016
  265. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  266. \chapter{Preliminaries}
  267. \label{ch:trees-recur}
  268. In this chapter we review the basic tools that are needed to implement
  269. a compiler. Programs are typically input by a programmer as text,
  270. i.e., a sequence of characters. The program-as-text representation is
  271. called \emph{concrete syntax}. We use concrete syntax to concisely
  272. write down and talk about programs. Inside the compiler, we use
  273. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  274. that efficiently supports the operations that the compiler needs to
  275. perform.\index{concrete syntax}\index{abstract syntax}\index{abstract
  276. syntax tree}\index{AST}\index{program}\index{parse} The translation
  277. from concrete syntax to abstract syntax is a process called
  278. \emph{parsing}~\citep{Aho:1986qf}. We do not cover the theory and
  279. implementation of parsing in this book. A parser is provided in the
  280. supporting materials for translating from concrete to abstract syntax.
  281. ASTs can be represented in many different ways inside the compiler,
  282. depending on the programming language used to write the compiler.
  283. %
  284. We use Racket's
  285. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  286. feature to represent ASTs (Section~\ref{sec:ast}). We use grammars to
  287. define the abstract syntax of programming languages
  288. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  289. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  290. recursive functions to construct and deconstruct ASTs
  291. (Section~\ref{sec:recursion}). This chapter provides an brief
  292. introduction to these ideas. \index{struct}
  293. \section{Abstract Syntax Trees and Racket Structures}
  294. \label{sec:ast}
  295. Compilers use abstract syntax trees to represent programs because they
  296. often need to ask questions like: for a given part of a program, what
  297. kind of language feature is it? What are its sub-parts? Consider the
  298. program on the left and its AST on the right. This program is an
  299. addition operation and it has two sub-parts, a read operation and a
  300. negation. The negation has another sub-part, the integer constant
  301. \code{8}. By using a tree to represent the program, we can easily
  302. follow the links to go from one part of a program to its sub-parts.
  303. \begin{center}
  304. \begin{minipage}{0.4\textwidth}
  305. \begin{lstlisting}
  306. (+ (read) (- 8))
  307. \end{lstlisting}
  308. \end{minipage}
  309. \begin{minipage}{0.4\textwidth}
  310. \begin{equation}
  311. \begin{tikzpicture}
  312. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  313. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  314. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  315. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  316. \draw[->] (plus) to (read);
  317. \draw[->] (plus) to (minus);
  318. \draw[->] (minus) to (8);
  319. \end{tikzpicture}
  320. \label{eq:arith-prog}
  321. \end{equation}
  322. \end{minipage}
  323. \end{center}
  324. We use the standard terminology for trees to describe ASTs: each
  325. circle above is called a \emph{node}. The arrows connect a node to its
  326. \emph{children} (which are also nodes). The top-most node is the
  327. \emph{root}. Every node except for the root has a \emph{parent} (the
  328. node it is the child of). If a node has no children, it is a
  329. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  330. \index{node}
  331. \index{children}
  332. \index{root}
  333. \index{parent}
  334. \index{leaf}
  335. \index{internal node}
  336. %% Recall that an \emph{symbolic expression} (S-expression) is either
  337. %% \begin{enumerate}
  338. %% \item an atom, or
  339. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  340. %% where $e_1$ and $e_2$ are each an S-expression.
  341. %% \end{enumerate}
  342. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  343. %% null value \code{'()}, etc. We can create an S-expression in Racket
  344. %% simply by writing a backquote (called a quasi-quote in Racket)
  345. %% followed by the textual representation of the S-expression. It is
  346. %% quite common to use S-expressions to represent a list, such as $a, b
  347. %% ,c$ in the following way:
  348. %% \begin{lstlisting}
  349. %% `(a . (b . (c . ())))
  350. %% \end{lstlisting}
  351. %% Each element of the list is in the first slot of a pair, and the
  352. %% second slot is either the rest of the list or the null value, to mark
  353. %% the end of the list. Such lists are so common that Racket provides
  354. %% special notation for them that removes the need for the periods
  355. %% and so many parenthesis:
  356. %% \begin{lstlisting}
  357. %% `(a b c)
  358. %% \end{lstlisting}
  359. %% The following expression creates an S-expression that represents AST
  360. %% \eqref{eq:arith-prog}.
  361. %% \begin{lstlisting}
  362. %% `(+ (read) (- 8))
  363. %% \end{lstlisting}
  364. %% When using S-expressions to represent ASTs, the convention is to
  365. %% represent each AST node as a list and to put the operation symbol at
  366. %% the front of the list. The rest of the list contains the children. So
  367. %% in the above case, the root AST node has operation \code{`+} and its
  368. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  369. %% diagram \eqref{eq:arith-prog}.
  370. %% To build larger S-expressions one often needs to splice together
  371. %% several smaller S-expressions. Racket provides the comma operator to
  372. %% splice an S-expression into a larger one. For example, instead of
  373. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  374. %% we could have first created an S-expression for AST
  375. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  376. %% S-expression.
  377. %% \begin{lstlisting}
  378. %% (define ast1.4 `(- 8))
  379. %% (define ast1.1 `(+ (read) ,ast1.4))
  380. %% \end{lstlisting}
  381. %% In general, the Racket expression that follows the comma (splice)
  382. %% can be any expression that produces an S-expression.
  383. We define a Racket \code{struct} for each kind of node. For this
  384. chapter we require just two kinds of nodes: one for integer constants
  385. and one for primitive operations. The following is the \code{struct}
  386. definition for integer constants.
  387. \begin{lstlisting}
  388. (struct Int (value))
  389. \end{lstlisting}
  390. An integer node includes just one thing: the integer value.
  391. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  392. \begin{lstlisting}
  393. (define eight (Int 8))
  394. \end{lstlisting}
  395. We say that the value created by \code{(Int 8)} is an
  396. \emph{instance} of the \code{Int} structure.
  397. The following is the \code{struct} definition for primitives operations.
  398. \begin{lstlisting}
  399. (struct Prim (op args))
  400. \end{lstlisting}
  401. A primitive operation node includes an operator symbol \code{op}
  402. and a list of children \code{args}. For example, to create
  403. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  404. \begin{lstlisting}
  405. (define neg-eight (Prim '- (list eight)))
  406. \end{lstlisting}
  407. Primitive operations may have zero or more children. The \code{read}
  408. operator has zero children:
  409. \begin{lstlisting}
  410. (define rd (Prim 'read '()))
  411. \end{lstlisting}
  412. whereas the addition operator has two children:
  413. \begin{lstlisting}
  414. (define ast1.1 (Prim '+ (list rd neg-eight)))
  415. \end{lstlisting}
  416. We have made a design choice regarding the \code{Prim} structure.
  417. Instead of using one structure for many different operations
  418. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  419. structure for each operation, as follows.
  420. \begin{lstlisting}
  421. (struct Read ())
  422. (struct Add (left right))
  423. (struct Neg (value))
  424. \end{lstlisting}
  425. The reason we choose to use just one structure is that in many parts
  426. of the compiler the code for the different primitive operators is the
  427. same, so we might as well just write that code once, which is enabled
  428. by using a single structure.
  429. When compiling a program such as \eqref{eq:arith-prog}, we need to
  430. know that the operation associated with the root node is addition and
  431. we need to be able to access its two children. Racket provides pattern
  432. matching to support these kinds of queries, as we see in
  433. Section~\ref{sec:pattern-matching}.
  434. In this book, we often write down the concrete syntax of a program
  435. even when we really have in mind the AST because the concrete syntax
  436. is more concise. We recommend that, in your mind, you always think of
  437. programs as abstract syntax trees.
  438. \section{Grammars}
  439. \label{sec:grammar}
  440. \index{integer}
  441. \index{literal}
  442. \index{constant}
  443. A programming language can be thought of as a \emph{set} of programs.
  444. The set is typically infinite (one can always create larger and larger
  445. programs), so one cannot simply describe a language by listing all of
  446. the programs in the language. Instead we write down a set of rules, a
  447. \emph{grammar}, for building programs. Grammars are often used to
  448. define the concrete syntax of a language, but they can also be used to
  449. describe the abstract syntax. We write our rules in a variant of
  450. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  451. \index{Backus-Naur Form}\index{BNF}
  452. As an example, we describe a small language, named \LangInt{}, that consists of
  453. integers and arithmetic operations.
  454. \index{grammar}
  455. The first grammar rule for the abstract syntax of \LangInt{} says that an
  456. instance of the \code{Int} structure is an expression:
  457. \begin{equation}
  458. \Exp ::= \INT{\Int} \label{eq:arith-int}
  459. \end{equation}
  460. %
  461. Each rule has a left-hand-side and a right-hand-side. The way to read
  462. a rule is that if you have an AST node that matches the
  463. right-hand-side, then you can categorize it according to the
  464. left-hand-side.
  465. %
  466. A name such as $\Exp$ that is defined by the grammar rules is a
  467. \emph{non-terminal}. \index{non-terminal}
  468. %
  469. The name $\Int$ is a also a non-terminal, but instead of defining it
  470. with a grammar rule, we define it with the following explanation. We
  471. make the simplifying design decision that all of the languages in this
  472. book only handle machine-representable integers. On most modern
  473. machines this corresponds to integers represented with 64-bits, i.e.,
  474. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  475. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  476. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  477. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  478. that the sequence of decimals represent an integer in range $-2^{62}$
  479. to $2^{62}-1$.
  480. The second grammar rule is the \texttt{read} operation that receives
  481. an input integer from the user of the program.
  482. \begin{equation}
  483. \Exp ::= \READ{} \label{eq:arith-read}
  484. \end{equation}
  485. The third rule says that, given an $\Exp$ node, the negation of that
  486. node is also an $\Exp$.
  487. \begin{equation}
  488. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  489. \end{equation}
  490. Symbols in typewriter font such as \key{-} and \key{read} are
  491. \emph{terminal} symbols and must literally appear in the program for
  492. the rule to be applicable.
  493. \index{terminal}
  494. We can apply these rules to categorize the ASTs that are in the
  495. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  496. \texttt{(Int 8)} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  497. following AST is an $\Exp$.
  498. \begin{center}
  499. \begin{minipage}{0.4\textwidth}
  500. \begin{lstlisting}
  501. (Prim '- (list (Int 8)))
  502. \end{lstlisting}
  503. \end{minipage}
  504. \begin{minipage}{0.25\textwidth}
  505. \begin{equation}
  506. \begin{tikzpicture}
  507. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  508. \node[draw, circle] (8) at (0, -1.2) {$8$};
  509. \draw[->] (minus) to (8);
  510. \end{tikzpicture}
  511. \label{eq:arith-neg8}
  512. \end{equation}
  513. \end{minipage}
  514. \end{center}
  515. The next grammar rule is for addition expressions:
  516. \begin{equation}
  517. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  518. \end{equation}
  519. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  520. \LangInt{}. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  521. \eqref{eq:arith-read} and we have already categorized \code{(Prim '-
  522. (list (Int 8)))} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  523. to show that
  524. \begin{lstlisting}
  525. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  526. \end{lstlisting}
  527. is an $\Exp$ in the \LangInt{} language.
  528. If you have an AST for which the above rules do not apply, then the
  529. AST is not in \LangInt{}. For example, the program \code{(- (read) (+ 8))}
  530. is not in \LangInt{} because there are no rules for \code{+} with only one
  531. argument, nor for \key{-} with two arguments. Whenever we define a
  532. language with a grammar, the language only includes those programs
  533. that are justified by the rules.
  534. The last grammar rule for \LangInt{} states that there is a \code{Program}
  535. node to mark the top of the whole program:
  536. \[
  537. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  538. \]
  539. The \code{Program} structure is defined as follows
  540. \begin{lstlisting}
  541. (struct Program (info body))
  542. \end{lstlisting}
  543. where \code{body} is an expression. In later chapters, the \code{info}
  544. part will be used to store auxiliary information but for now it is
  545. just the empty list.
  546. It is common to have many grammar rules with the same left-hand side
  547. but different right-hand sides, such as the rules for $\Exp$ in the
  548. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  549. combine several right-hand-sides into a single rule.
  550. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  551. in Figure~\ref{fig:r0-syntax}. The concrete syntax for \LangInt{} is
  552. defined in Figure~\ref{fig:r0-concrete-syntax}.
  553. The \code{read-program} function provided in \code{utilities.rkt} of
  554. the support materials reads a program in from a file (the sequence of
  555. characters in the concrete syntax of Racket) and parses it into an
  556. abstract syntax tree. See the description of \code{read-program} in
  557. Appendix~\ref{appendix:utilities} for more details.
  558. \begin{figure}[tp]
  559. \fbox{
  560. \begin{minipage}{0.96\textwidth}
  561. \[
  562. \begin{array}{rcl}
  563. \begin{array}{rcl}
  564. \Exp &::=& \Int \mid \LP\key{read}\RP \mid \LP\key{-}\;\Exp\RP \mid \LP\key{+} \; \Exp\;\Exp\RP\\
  565. \LangInt{} &::=& \Exp
  566. \end{array}
  567. \end{array}
  568. \]
  569. \end{minipage}
  570. }
  571. \caption{The concrete syntax of \LangInt{}.}
  572. \label{fig:r0-concrete-syntax}
  573. \end{figure}
  574. \begin{figure}[tp]
  575. \fbox{
  576. \begin{minipage}{0.96\textwidth}
  577. \[
  578. \begin{array}{rcl}
  579. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  580. &\mid& \ADD{\Exp}{\Exp} \\
  581. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  582. \end{array}
  583. \]
  584. \end{minipage}
  585. }
  586. \caption{The abstract syntax of \LangInt{}.}
  587. \label{fig:r0-syntax}
  588. \end{figure}
  589. \section{Pattern Matching}
  590. \label{sec:pattern-matching}
  591. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  592. the parts of an AST node. Racket provides the \texttt{match} form to
  593. access the parts of a structure. Consider the following example and
  594. the output on the right. \index{match} \index{pattern matching}
  595. \begin{center}
  596. \begin{minipage}{0.5\textwidth}
  597. \begin{lstlisting}
  598. (match ast1.1
  599. [(Prim op (list child1 child2))
  600. (print op)])
  601. \end{lstlisting}
  602. \end{minipage}
  603. \vrule
  604. \begin{minipage}{0.25\textwidth}
  605. \begin{lstlisting}
  606. '+
  607. \end{lstlisting}
  608. \end{minipage}
  609. \end{center}
  610. In the above example, the \texttt{match} form takes an AST
  611. \eqref{eq:arith-prog} and binds its parts to the three pattern
  612. variables \texttt{op}, \texttt{child1}, and \texttt{child2}, and then
  613. prints out the operator. In general, a match clause consists of a
  614. \emph{pattern} and a \emph{body}.\index{pattern} Patterns are
  615. recursively defined to be either a pattern variable, a structure name
  616. followed by a pattern for each of the structure's arguments, or an
  617. S-expression (symbols, lists, etc.). (See Chapter 12 of The Racket
  618. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  619. and Chapter 9 of The Racket
  620. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  621. for a complete description of \code{match}.)
  622. %
  623. The body of a match clause may contain arbitrary Racket code. The
  624. pattern variables can be used in the scope of the body, such as
  625. \code{op} in \code{(print op)}.
  626. A \code{match} form may contain several clauses, as in the following
  627. function \code{leaf?} that recognizes when an \LangInt{} node is a leaf in
  628. the AST. The \code{match} proceeds through the clauses in order,
  629. checking whether the pattern can match the input AST. The body of the
  630. first clause that matches is executed. The output of \code{leaf?} for
  631. several ASTs is shown on the right.
  632. \begin{center}
  633. \begin{minipage}{0.6\textwidth}
  634. \begin{lstlisting}
  635. (define (leaf? arith)
  636. (match arith
  637. [(Int n) #t]
  638. [(Prim 'read '()) #t]
  639. [(Prim '- (list e1)) #f]
  640. [(Prim '+ (list e1 e2)) #f]))
  641. (leaf? (Prim 'read '()))
  642. (leaf? (Prim '- (list (Int 8))))
  643. (leaf? (Int 8))
  644. \end{lstlisting}
  645. \end{minipage}
  646. \vrule
  647. \begin{minipage}{0.25\textwidth}
  648. \begin{lstlisting}
  649. #t
  650. #f
  651. #t
  652. \end{lstlisting}
  653. \end{minipage}
  654. \end{center}
  655. When writing a \code{match}, we refer to the grammar definition to
  656. identify which non-terminal we are expecting to match against, then we
  657. make sure that 1) we have one clause for each alternative of that
  658. non-terminal and 2) that the pattern in each clause corresponds to the
  659. corresponding right-hand side of a grammar rule. For the \code{match}
  660. in the \code{leaf?} function, we refer to the grammar for \LangInt{} in
  661. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  662. alternatives, so the \code{match} has 4 clauses. The pattern in each
  663. clause corresponds to the right-hand side of a grammar rule. For
  664. example, the pattern \code{(Prim '+ (list e1 e2))} corresponds to the
  665. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  666. patterns, replace non-terminals such as $\Exp$ with pattern variables
  667. of your choice (e.g. \code{e1} and \code{e2}).
  668. \section{Recursive Functions}
  669. \label{sec:recursion}
  670. \index{recursive function}
  671. Programs are inherently recursive. For example, an \LangInt{} expression is
  672. often made of smaller expressions. Thus, the natural way to process an
  673. entire program is with a recursive function. As a first example of
  674. such a recursive function, we define \texttt{exp?} below, which takes
  675. an arbitrary value and determines whether or not it is an \LangInt{}
  676. expression.
  677. %
  678. We say that a function is defined by \emph{structural recursion} when
  679. it is defined using a sequence of match clauses that correspond to a
  680. grammar, and the body of each clause makes a recursive call on each
  681. child node.\footnote{This principle of structuring code according to
  682. the data definition is advocated in the book \emph{How to Design
  683. Programs} \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}.
  684. Below we also define a second function, named \code{Rint?}, that
  685. determines whether an AST is an \LangInt{} program. In general we can
  686. expect to write one recursive function to handle each non-terminal in
  687. a grammar.\index{structural recursion}
  688. %
  689. \begin{center}
  690. \begin{minipage}{0.7\textwidth}
  691. \begin{lstlisting}
  692. (define (exp? ast)
  693. (match ast
  694. [(Int n) #t]
  695. [(Prim 'read '()) #t]
  696. [(Prim '- (list e)) (exp? e)]
  697. [(Prim '+ (list e1 e2))
  698. (and (exp? e1) (exp? e2))]
  699. [else #f]))
  700. (define (Rint? ast)
  701. (match ast
  702. [(Program '() e) (exp? e)]
  703. [else #f]))
  704. (Rint? (Program '() ast1.1)
  705. (Rint? (Program '()
  706. (Prim '- (list (Prim 'read '())
  707. (Prim '+ (list (Num 8)))))))
  708. \end{lstlisting}
  709. \end{minipage}
  710. \vrule
  711. \begin{minipage}{0.25\textwidth}
  712. \begin{lstlisting}
  713. #t
  714. #f
  715. \end{lstlisting}
  716. \end{minipage}
  717. \end{center}
  718. You may be tempted to merge the two functions into one, like this:
  719. \begin{center}
  720. \begin{minipage}{0.5\textwidth}
  721. \begin{lstlisting}
  722. (define (Rint? ast)
  723. (match ast
  724. [(Int n) #t]
  725. [(Prim 'read '()) #t]
  726. [(Prim '- (list e)) (Rint? e)]
  727. [(Prim '+ (list e1 e2)) (and (Rint? e1) (Rint? e2))]
  728. [(Program '() e) (Rint? e)]
  729. [else #f]))
  730. \end{lstlisting}
  731. \end{minipage}
  732. \end{center}
  733. %
  734. Sometimes such a trick will save a few lines of code, especially when
  735. it comes to the \code{Program} wrapper. Yet this style is generally
  736. \emph{not} recommended because it can get you into trouble.
  737. %
  738. For example, the above function is subtly wrong:
  739. \lstinline{(Rint? (Program '() (Program '() (Int 3))))}
  740. returns true when it should return false.
  741. \section{Interpreters}
  742. \label{sec:interp-Rint}
  743. \index{interpreter}
  744. In general, the intended behavior of a program is defined by the
  745. specification of the language. For example, the Scheme language is
  746. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  747. defined in its reference manual~\citep{plt-tr}. In this book we use
  748. interpreters to specify each language that we consider. An interpreter
  749. that is designated as the definition of a language is called a
  750. \emph{definitional interpreter}~\citep{reynolds72:_def_interp}.
  751. \index{definitional interpreter} We warm up by creating a definitional
  752. interpreter for the \LangInt{} language, which serves as a second example
  753. of structural recursion. The \texttt{interp-Rint} function is defined in
  754. Figure~\ref{fig:interp-Rint}. The body of the function is a match on the
  755. input program followed by a call to the \lstinline{interp-exp} helper
  756. function, which in turn has one match clause per grammar rule for
  757. \LangInt{} expressions.
  758. \begin{figure}[tp]
  759. \begin{lstlisting}
  760. (define (interp-exp e)
  761. (match e
  762. [(Int n) n]
  763. [(Prim 'read '())
  764. (define r (read))
  765. (cond [(fixnum? r) r]
  766. [else (error 'interp-exp "read expected an integer" r)])]
  767. [(Prim '- (list e))
  768. (define v (interp-exp e))
  769. (fx- 0 v)]
  770. [(Prim '+ (list e1 e2))
  771. (define v1 (interp-exp e1))
  772. (define v2 (interp-exp e2))
  773. (fx+ v1 v2)]))
  774. (define (interp-Rint p)
  775. (match p
  776. [(Program '() e) (interp-exp e)]))
  777. \end{lstlisting}
  778. \caption{Interpreter for the \LangInt{} language.}
  779. \label{fig:interp-Rint}
  780. \end{figure}
  781. Let us consider the result of interpreting a few \LangInt{} programs. The
  782. following program adds two integers.
  783. \begin{lstlisting}
  784. (+ 10 32)
  785. \end{lstlisting}
  786. The result is \key{42}, the answer to life, the universe, and
  787. everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to the
  788. Galaxy} by Douglas Adams.}.
  789. %
  790. We wrote the above program in concrete syntax whereas the parsed
  791. abstract syntax is:
  792. \begin{lstlisting}
  793. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  794. \end{lstlisting}
  795. The next example demonstrates that expressions may be nested within
  796. each other, in this case nesting several additions and negations.
  797. \begin{lstlisting}
  798. (+ 10 (- (+ 12 20)))
  799. \end{lstlisting}
  800. What is the result of the above program?
  801. As mentioned previously, the \LangInt{} language does not support
  802. arbitrarily-large integers, but only $63$-bit integers, so we
  803. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  804. in Racket.
  805. Suppose
  806. \[
  807. n = 999999999999999999
  808. \]
  809. which indeed fits in $63$-bits. What happens when we run the
  810. following program in our interpreter?
  811. \begin{lstlisting}
  812. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  813. \end{lstlisting}
  814. It produces an error:
  815. \begin{lstlisting}
  816. fx+: result is not a fixnum
  817. \end{lstlisting}
  818. We establish the convention that if running the definitional
  819. interpreter on a program produces an error then the meaning of that
  820. program is \emph{unspecified}\index{unspecified behavior}, unless the
  821. error is a \code{trapped-error}. A compiler for the language is under
  822. no obligations regarding programs with unspecified behavior; it does
  823. not have to produce an executable, and if it does, that executable can
  824. do anything. On the other hand, if the error is a
  825. \code{trapped-error}, then the compiler must produce an executable and
  826. it is required to report that an error occurred. To signal an error,
  827. exit with a return code of \code{255}. The interpreters in chapters
  828. \ref{ch:type-dynamic} and \ref{ch:gradual-typing} use
  829. \code{trapped-error}.
  830. %% This convention applies to the languages defined in this
  831. %% book, as a way to simplify the student's task of implementing them,
  832. %% but this convention is not applicable to all programming languages.
  833. %%
  834. Moving on to the last feature of the \LangInt{} language, the \key{read}
  835. operation prompts the user of the program for an integer. Recall that
  836. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  837. \code{8}. So if we run
  838. \begin{lstlisting}
  839. (interp-Rint (Program '() ast1.1))
  840. \end{lstlisting}
  841. and if the input is \code{50}, the result is \code{42}.
  842. We include the \key{read} operation in \LangInt{} so a clever student
  843. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  844. during compilation to obtain the output and then generates the trivial
  845. code to produce the output. (Yes, a clever student did this in the
  846. first instance of this course.)
  847. The job of a compiler is to translate a program in one language into a
  848. program in another language so that the output program behaves the
  849. same way as the input program does. This idea is depicted in the
  850. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  851. $\mathcal{L}_2$, and a definitional interpreter for each language.
  852. Given a compiler that translates from language $\mathcal{L}_1$ to
  853. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  854. compiler must translate it into some program $P_2$ such that
  855. interpreting $P_1$ and $P_2$ on their respective interpreters with
  856. same input $i$ yields the same output $o$.
  857. \begin{equation} \label{eq:compile-correct}
  858. \begin{tikzpicture}[baseline=(current bounding box.center)]
  859. \node (p1) at (0, 0) {$P_1$};
  860. \node (p2) at (3, 0) {$P_2$};
  861. \node (o) at (3, -2.5) {$o$};
  862. \path[->] (p1) edge [above] node {compile} (p2);
  863. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  864. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  865. \end{tikzpicture}
  866. \end{equation}
  867. In the next section we see our first example of a compiler.
  868. \section{Example Compiler: a Partial Evaluator}
  869. \label{sec:partial-evaluation}
  870. In this section we consider a compiler that translates \LangInt{} programs
  871. into \LangInt{} programs that may be more efficient, that is, this compiler
  872. is an optimizer. This optimizer eagerly computes the parts of the
  873. program that do not depend on any inputs, a process known as
  874. \emph{partial evaluation}~\citep{Jones:1993uq}.
  875. \index{partial evaluation}
  876. For example, given the following program
  877. \begin{lstlisting}
  878. (+ (read) (- (+ 5 3)))
  879. \end{lstlisting}
  880. our compiler will translate it into the program
  881. \begin{lstlisting}
  882. (+ (read) -8)
  883. \end{lstlisting}
  884. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  885. evaluator for the \LangInt{} language. The output of the partial evaluator
  886. is an \LangInt{} program. In Figure~\ref{fig:pe-arith}, the structural
  887. recursion over $\Exp$ is captured in the \code{pe-exp} function
  888. whereas the code for partially evaluating the negation and addition
  889. operations is factored into two separate helper functions:
  890. \code{pe-neg} and \code{pe-add}. The input to these helper
  891. functions is the output of partially evaluating the children.
  892. \begin{figure}[tp]
  893. \begin{lstlisting}
  894. (define (pe-neg r)
  895. (match r
  896. [(Int n) (Int (fx- 0 n))]
  897. [else (Prim '- (list r))]))
  898. (define (pe-add r1 r2)
  899. (match* (r1 r2)
  900. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  901. [(_ _) (Prim '+ (list r1 r2))]))
  902. (define (pe-exp e)
  903. (match e
  904. [(Int n) (Int n)]
  905. [(Prim 'read '()) (Prim 'read '())]
  906. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  907. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]))
  908. (define (pe-Rint p)
  909. (match p
  910. [(Program '() e) (Program '() (pe-exp e))]))
  911. \end{lstlisting}
  912. \caption{A partial evaluator for \LangInt{}.}
  913. \label{fig:pe-arith}
  914. \end{figure}
  915. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  916. arguments are integers and if they are, perform the appropriate
  917. arithmetic. Otherwise, they create an AST node for the arithmetic
  918. operation.
  919. To gain some confidence that the partial evaluator is correct, we can
  920. test whether it produces programs that get the same result as the
  921. input programs. That is, we can test whether it satisfies Diagram
  922. \ref{eq:compile-correct}. The following code runs the partial
  923. evaluator on several examples and tests the output program. The
  924. \texttt{parse-program} and \texttt{assert} functions are defined in
  925. Appendix~\ref{appendix:utilities}.\\
  926. \begin{minipage}{1.0\textwidth}
  927. \begin{lstlisting}
  928. (define (test-pe p)
  929. (assert "testing pe-Rint"
  930. (equal? (interp-Rint p) (interp-Rint (pe-Rint p)))))
  931. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  932. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  933. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  934. \end{lstlisting}
  935. \end{minipage}
  936. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  937. \chapter{Integers and Variables}
  938. \label{ch:int-exp}
  939. This chapter is about compiling a subset of Racket to x86-64 assembly
  940. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  941. integer arithmetic and local variable binding. We often refer to
  942. x86-64 simply as x86. The chapter begins with a description of the
  943. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  944. to of x86 assembly (Section~\ref{sec:x86}). The x86 assembly language
  945. is large so we discuss only the instructions needed for compiling
  946. \LangVar{}. We introduce more x86 instructions in later chapters.
  947. After introducing \LangVar{} and x86, we reflect on their differences
  948. and come up with a plan to break down the translation from \LangVar{}
  949. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  950. rest of the sections in this chapter give detailed hints regarding
  951. each step (Sections~\ref{sec:uniquify-Rvar} through \ref{sec:patch-s0}).
  952. We hope to give enough hints that the well-prepared reader, together
  953. with a few friends, can implement a compiler from \LangVar{} to x86 in
  954. a couple weeks. To give the reader a feeling for the scale of this
  955. first compiler, the instructor solution for the \LangVar{} compiler is
  956. approximately 500 lines of code.
  957. \section{The \LangVar{} Language}
  958. \label{sec:s0}
  959. \index{variable}
  960. The \LangVar{} language extends the \LangInt{} language with variable
  961. definitions. The concrete syntax of the \LangVar{} language is defined by
  962. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  963. syntax is defined in Figure~\ref{fig:r1-syntax}. The non-terminal
  964. \Var{} may be any Racket identifier. As in \LangInt{}, \key{read} is a
  965. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  966. operator. Similar to \LangInt{}, the abstract syntax of \LangVar{} includes the
  967. \key{Program} struct to mark the top of the program.
  968. %% The $\itm{info}$
  969. %% field of the \key{Program} structure contains an \emph{association
  970. %% list} (a list of key-value pairs) that is used to communicate
  971. %% auxiliary data from one compiler pass the next.
  972. Despite the simplicity of the \LangVar{} language, it is rich enough to
  973. exhibit several compilation techniques.
  974. \begin{figure}[tp]
  975. \centering
  976. \fbox{
  977. \begin{minipage}{0.96\textwidth}
  978. \[
  979. \begin{array}{rcl}
  980. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp}\\
  981. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  982. \LangVar{} &::=& \Exp
  983. \end{array}
  984. \]
  985. \end{minipage}
  986. }
  987. \caption{The concrete syntax of \LangVar{}.}
  988. \label{fig:r1-concrete-syntax}
  989. \end{figure}
  990. \begin{figure}[tp]
  991. \centering
  992. \fbox{
  993. \begin{minipage}{0.96\textwidth}
  994. \[
  995. \begin{array}{rcl}
  996. \Exp &::=& \INT{\Int} \mid \READ{} \\
  997. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  998. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  999. \LangVar{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1000. \end{array}
  1001. \]
  1002. \end{minipage}
  1003. }
  1004. \caption{The abstract syntax of \LangVar{}.}
  1005. \label{fig:r1-syntax}
  1006. \end{figure}
  1007. Let us dive further into the syntax and semantics of the \LangVar{}
  1008. language. The \key{let} feature defines a variable for use within its
  1009. body and initializes the variable with the value of an expression.
  1010. The abstract syntax for \key{let} is defined in
  1011. Figure~\ref{fig:r1-syntax}. The concrete syntax for \key{let} is
  1012. \begin{lstlisting}
  1013. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1014. \end{lstlisting}
  1015. For example, the following program initializes \code{x} to $32$ and then
  1016. evaluates the body \code{(+ 10 x)}, producing $42$.
  1017. \begin{lstlisting}
  1018. (let ([x (+ 12 20)]) (+ 10 x))
  1019. \end{lstlisting}
  1020. When there are multiple \key{let}'s for the same variable, the closest
  1021. enclosing \key{let} is used. That is, variable definitions overshadow
  1022. prior definitions. Consider the following program with two \key{let}'s
  1023. that define variables named \code{x}. Can you figure out the result?
  1024. \begin{lstlisting}
  1025. (let ([x 32]) (+ (let ([x 10]) x) x))
  1026. \end{lstlisting}
  1027. For the purposes of depicting which variable uses correspond to which
  1028. definitions, the following shows the \code{x}'s annotated with
  1029. subscripts to distinguish them. Double check that your answer for the
  1030. above is the same as your answer for this annotated version of the
  1031. program.
  1032. \begin{lstlisting}
  1033. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1034. \end{lstlisting}
  1035. The initializing expression is always evaluated before the body of the
  1036. \key{let}, so in the following, the \key{read} for \code{x} is
  1037. performed before the \key{read} for \code{y}. Given the input
  1038. $52$ then $10$, the following produces $42$ (not $-42$).
  1039. \begin{lstlisting}
  1040. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1041. \end{lstlisting}
  1042. \subsection{Extensible Interpreters via Method Overriding}
  1043. \label{sec:extensible-interp}
  1044. To prepare for discussing the interpreter for \LangVar{}, we need to
  1045. explain why we choose to implement the interpreter using
  1046. object-oriented programming, that is, as a collection of methods
  1047. inside of a class. Throughout this book we define many interpreters,
  1048. one for each of the languages that we study. Because each language
  1049. builds on the prior one, there is a lot of commonality between their
  1050. interpreters. We want to write down those common parts just once
  1051. instead of many times. A naive approach would be to have, for example,
  1052. the interpreter for \LangIf{} handle all of the new features in that
  1053. language and then have a default case that dispatches to the
  1054. interpreter for \LangVar{}. The following code sketches this idea.
  1055. \begin{center}
  1056. \begin{minipage}{0.45\textwidth}
  1057. \begin{lstlisting}
  1058. (define (interp-Rvar e)
  1059. (match e
  1060. [(Prim '- (list e))
  1061. (fx- 0 (interp-Rvar e))]
  1062. ...))
  1063. \end{lstlisting}
  1064. \end{minipage}
  1065. \begin{minipage}{0.45\textwidth}
  1066. \begin{lstlisting}
  1067. (define (interp-Rif e)
  1068. (match e
  1069. [(If cnd thn els)
  1070. (match (interp-Rif cnd)
  1071. [#t (interp-Rif thn)]
  1072. [#f (interp-Rif els)])]
  1073. ...
  1074. [else (interp-Rvar e)]))
  1075. \end{lstlisting}
  1076. \end{minipage}
  1077. \end{center}
  1078. The problem with this approach is that it does not handle situations
  1079. in which an \LangIf{} feature, like \code{If}, is nested inside an \LangVar{}
  1080. feature, like the \code{-} operator, as in the following program.
  1081. \begin{lstlisting}
  1082. (Prim '- (list (If (Bool #t) (Int 42) (Int 0))))
  1083. \end{lstlisting}
  1084. If we invoke \code{interp-Rif} on this program, it dispatches to
  1085. \code{interp-Rvar} to handle the \code{-} operator, but then it
  1086. recurisvely calls \code{interp-Rvar} again on the argument of \code{-},
  1087. which is an \code{If}. But there is no case for \code{If} in
  1088. \code{interp-Rvar}, so we get an error!
  1089. To make our interpreters extensible we need something called
  1090. \emph{open recursion}\index{open recursion}, where the tying of the
  1091. recursive knot is delayed to when the functions are
  1092. composed. Object-oriented languages provide open recursion with the
  1093. late-binding of overridden methods\index{method overriding}. The
  1094. following code sketches this idea for interpreting \LangVar{} and
  1095. \LangIf{} using the
  1096. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1097. \index{class} feature of Racket. We define one class for each
  1098. language and define a method for interpreting expressions inside each
  1099. class. The class for \LangIf{} inherits from the class for \LangVar{}
  1100. and the method \code{interp-exp} in \LangIf{} overrides the
  1101. \code{interp-exp} in \LangVar{}. Note that the default case of
  1102. \code{interp-exp} in \LangIf{} uses \code{super} to invoke
  1103. \code{interp-exp}, and because \LangIf{} inherits from \LangVar{},
  1104. that dispatches to the \code{interp-exp} in \LangVar{}.
  1105. \begin{center}
  1106. \begin{minipage}{0.45\textwidth}
  1107. \begin{lstlisting}
  1108. (define interp-Rvar-class
  1109. (class object%
  1110. (define/public (interp-exp e)
  1111. (match e
  1112. [(Prim '- (list e))
  1113. (fx- 0 (interp-exp e))]
  1114. ...))
  1115. ...))
  1116. \end{lstlisting}
  1117. \end{minipage}
  1118. \begin{minipage}{0.45\textwidth}
  1119. \begin{lstlisting}
  1120. (define interp-Rif-class
  1121. (class interp-Rvar-class
  1122. (define/override (interp-exp e)
  1123. (match e
  1124. [(If cnd thn els)
  1125. (match (interp-exp cnd)
  1126. [#t (interp-exp thn)]
  1127. [#f (interp-exp els)])]
  1128. ...
  1129. [else (super interp-exp e)]))
  1130. ...
  1131. ))
  1132. \end{lstlisting}
  1133. \end{minipage}
  1134. \end{center}
  1135. Getting back to the troublesome example, repeated here:
  1136. \begin{lstlisting}
  1137. (define e0 (Prim '- (list (If (Bool #t) (Int 42) (Int 0)))))
  1138. \end{lstlisting}
  1139. We can invoke the \code{interp-exp} method for \LangIf{} on this
  1140. expression by creating an object of the \LangIf{} class and sending it the
  1141. \code{interp-exp} method with the argument \code{e0}.
  1142. \begin{lstlisting}
  1143. (send (new interp-Rif-class) interp-exp e0)
  1144. \end{lstlisting}
  1145. The default case of \code{interp-exp} in \LangIf{} handles it by
  1146. dispatching to the \code{interp-exp} method in \LangVar{}, which
  1147. handles the \code{-} operator. But then for the recursive method call,
  1148. it dispatches back to \code{interp-exp} in \LangIf{}, where the
  1149. \code{If} is handled correctly. Thus, method overriding gives us the
  1150. open recursion that we need to implement our interpreters in an
  1151. extensible way.
  1152. \newpage
  1153. \subsection{Definitional Interpreter for \LangVar{}}
  1154. \begin{wrapfigure}[25]{r}[1.0in]{0.6\textwidth}
  1155. \small
  1156. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1157. An \emph{association list} (alist) is a list of key-value pairs.
  1158. For example, we can map people to their ages with an alist.
  1159. \index{alist}\index{association list}
  1160. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1161. (define ages
  1162. '((jane . 25) (sam . 24) (kate . 45)))
  1163. \end{lstlisting}
  1164. The \emph{dictionary} interface is for mapping keys to values.
  1165. Every alist implements this interface. \index{dictionary} The package
  1166. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1167. provides many functions for working with dictionaries. Here
  1168. are a few of them:
  1169. \begin{description}
  1170. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1171. returns the value associated with the given $\itm{key}$.
  1172. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1173. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1174. but otherwise is the same as $\itm{dict}$.
  1175. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1176. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1177. of keys and values in $\itm{dict}$. For example, the following
  1178. creates a new alist in which the ages are incremented.
  1179. \end{description}
  1180. \vspace{-10pt}
  1181. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1182. (for/list ([(k v) (in-dict ages)])
  1183. (cons k (add1 v)))
  1184. \end{lstlisting}
  1185. \end{tcolorbox}
  1186. \end{wrapfigure}
  1187. Having justified the use of classes and methods to implement
  1188. interpreters, we turn to the definitional interpreter for \LangVar{}
  1189. in Figure~\ref{fig:interp-Rvar}. It is similar to the interpreter for
  1190. \LangInt{} but adds two new \key{match} clauses for variables and
  1191. \key{let}. For \key{let} we need a way to communicate the value bound
  1192. to a variable to all the uses of the variable. To accomplish this, we
  1193. maintain a mapping from variables to values. Throughout the compiler
  1194. we often need to map variables to information about them. We refer to
  1195. these mappings as
  1196. \emph{environments}\index{environment}.\footnote{Another common term
  1197. for environment in the compiler literature is \emph{symbol
  1198. table}\index{symbol table}.}
  1199. %
  1200. For simplicity, we use an association list (alist) to represent the
  1201. environment. The sidebar to the right gives a brief introduction to
  1202. alists and the \code{racket/dict} package. The \code{interp-exp}
  1203. function takes the current environment, \code{env}, as an extra
  1204. parameter. When the interpreter encounters a variable, it finds the
  1205. corresponding value using the \code{dict-ref} function. When the
  1206. interpreter encounters a \key{Let}, it evaluates the initializing
  1207. expression, extends the environment with the result value bound to the
  1208. variable, using \code{dict-set}, then evaluates the body of the
  1209. \key{Let}.
  1210. \begin{figure}[tp]
  1211. \begin{lstlisting}
  1212. (define interp-Rvar-class
  1213. (class object%
  1214. (super-new)
  1215. (define/public ((interp-exp env) e)
  1216. (match e
  1217. [(Int n) n]
  1218. [(Prim 'read '())
  1219. (define r (read))
  1220. (cond [(fixnum? r) r]
  1221. [else (error 'interp-exp "expected an integer" r)])]
  1222. [(Prim '- (list e)) (fx- 0 ((interp-exp env) e))]
  1223. [(Prim '+ (list e1 e2))
  1224. (fx+ ((interp-exp env) e1) ((interp-exp env) e2))]
  1225. [(Var x) (dict-ref env x)]
  1226. [(Let x e body)
  1227. (define new-env (dict-set env x ((interp-exp env) e)))
  1228. ((interp-exp new-env) body)]))
  1229. (define/public (interp-program p)
  1230. (match p
  1231. [(Program '() e) ((interp-exp '()) e)]))
  1232. ))
  1233. (define (interp-Rvar p)
  1234. (send (new interp-Rvar-class) interp-program p))
  1235. \end{lstlisting}
  1236. \caption{Interpreter for the \LangVar{} language.}
  1237. \label{fig:interp-Rvar}
  1238. \end{figure}
  1239. The goal for this chapter is to implement a compiler that translates
  1240. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  1241. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1242. computer as the $P_1$ program interpreted by \code{interp-Rvar}. That
  1243. is, they output the same integer $n$. We depict this correctness
  1244. criteria in the following diagram.
  1245. \[
  1246. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1247. \node (p1) at (0, 0) {$P_1$};
  1248. \node (p2) at (4, 0) {$P_2$};
  1249. \node (o) at (4, -2) {$n$};
  1250. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1251. \path[->] (p1) edge [left] node {\footnotesize\code{interp-Rvar}} (o);
  1252. \path[->] (p2) edge [right] node {\footnotesize\code{interp-x86int}} (o);
  1253. \end{tikzpicture}
  1254. \]
  1255. In the next section we introduce the \LangXASTInt{} subset of x86 that
  1256. suffices for compiling \LangVar{}.
  1257. \section{The \LangXASTInt{} Assembly Language}
  1258. \label{sec:x86}
  1259. \index{x86}
  1260. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  1261. \LangXASTInt{}. We use the AT\&T syntax expected by the GNU
  1262. assembler.
  1263. %
  1264. A program begins with a \code{main} label followed by a sequence of
  1265. instructions. The \key{globl} directive says that the \key{main}
  1266. procedure is externally visible, which is necessary so that the
  1267. operating system can call it. In the grammar, ellipses such as
  1268. $\ldots$ are used to indicate a sequence of items, e.g., $\Instr
  1269. \ldots$ is a sequence of instructions.\index{instruction}
  1270. %
  1271. An x86 program is stored in the computer's memory. For our purposes,
  1272. the computer's memory is as a mapping of 64-bit addresses to 64-bit
  1273. values. The computer has a \emph{program counter} (PC)\index{program
  1274. counter}\index{PC} stored in the \code{rip} register that points to
  1275. the address of the next instruction to be executed. For most
  1276. instructions, the program counter is incremented after the instruction
  1277. is executed, so it points to the next instruction in memory. Most x86
  1278. instructions take two operands, where each operand is either an
  1279. integer constant (called \emph{immediate value}\index{immediate
  1280. value}), a \emph{register}\index{register}, or a memory location.
  1281. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1282. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1283. && \key{r8} \mid \key{r9} \mid \key{r10}
  1284. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1285. \mid \key{r14} \mid \key{r15}}
  1286. \begin{figure}[tp]
  1287. \fbox{
  1288. \begin{minipage}{0.96\textwidth}
  1289. \[
  1290. \begin{array}{lcl}
  1291. \Reg &::=& \allregisters{} \\
  1292. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1293. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1294. \key{subq} \; \Arg\key{,} \Arg \mid
  1295. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1296. && \key{callq} \; \mathit{label} \mid
  1297. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} \\
  1298. && \itm{label}\key{:}\; \Instr \\
  1299. \LangXInt{} &::= & \key{.globl main}\\
  1300. & & \key{main:} \; \Instr\ldots
  1301. \end{array}
  1302. \]
  1303. \end{minipage}
  1304. }
  1305. \caption{The syntax of the \LangXASTInt{} assembly language (AT\&T syntax).}
  1306. \label{fig:x86-int-concrete}
  1307. \end{figure}
  1308. A register is a special kind of variable. Each one holds a 64-bit
  1309. value; there are 16 general-purpose registers in the computer and
  1310. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  1311. is written with a \key{\%} followed by the register name, such as
  1312. \key{\%rax}.
  1313. An immediate value is written using the notation \key{\$}$n$ where $n$
  1314. is an integer.
  1315. %
  1316. %
  1317. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1318. which obtains the address stored in register $r$ and then adds $n$
  1319. bytes to the address. The resulting address is used to load or store
  1320. to memory depending on whether it occurs as a source or destination
  1321. argument of an instruction.
  1322. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1323. source $s$ and destination $d$, applies the arithmetic operation, then
  1324. writes the result back to the destination $d$.
  1325. %
  1326. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1327. stores the result in $d$.
  1328. %
  1329. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  1330. specified by the label and $\key{retq}$ returns from a procedure to
  1331. its caller.
  1332. %
  1333. We discuss procedure calls in more detail later in this chapter and in
  1334. Chapter~\ref{ch:functions}. The instruction $\key{jmp}\,\itm{label}$
  1335. updates the program counter to the address of the instruction after
  1336. the specified label.
  1337. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  1338. all of the x86 instructions used in this book.
  1339. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent to
  1340. \code{(+ 10 32)}. The instruction \lstinline{movq $10, %rax}
  1341. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  1342. adds $32$ to the $10$ in \key{rax} and
  1343. puts the result, $42$, back into \key{rax}.
  1344. %
  1345. The last instruction, \key{retq}, finishes the \key{main} function by
  1346. returning the integer in \key{rax} to the operating system. The
  1347. operating system interprets this integer as the program's exit
  1348. code. By convention, an exit code of 0 indicates that a program
  1349. completed successfully, and all other exit codes indicate various
  1350. errors. Nevertheless, in this book we return the result of the program
  1351. as the exit code.
  1352. \begin{figure}[tbp]
  1353. \begin{lstlisting}
  1354. .globl main
  1355. main:
  1356. movq $10, %rax
  1357. addq $32, %rax
  1358. retq
  1359. \end{lstlisting}
  1360. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1361. \label{fig:p0-x86}
  1362. \end{figure}
  1363. The x86 assembly language varies in a couple ways depending on what
  1364. operating system it is assembled in. The code examples shown here are
  1365. correct on Linux and most Unix-like platforms, but when assembled on
  1366. Mac OS X, labels like \key{main} must be prefixed with an underscore,
  1367. as in \key{\_main}.
  1368. We exhibit the use of memory for storing intermediate results in the
  1369. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1370. equivalent to \code{(+ 52 (- 10))}. This program uses a region of
  1371. memory called the \emph{procedure call stack} (or \emph{stack} for
  1372. short). \index{stack}\index{procedure call stack} The stack consists
  1373. of a separate \emph{frame}\index{frame} for each procedure call. The
  1374. memory layout for an individual frame is shown in
  1375. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1376. \emph{stack pointer}\index{stack pointer} and points to the item at
  1377. the top of the stack. The stack grows downward in memory, so we
  1378. increase the size of the stack by subtracting from the stack pointer.
  1379. In the context of a procedure call, the \emph{return
  1380. address}\index{return address} is the instruction after the call
  1381. instruction on the caller side. The function call instruction,
  1382. \code{callq}, pushes the return address onto the stack prior to
  1383. jumping to the procedure. The register \key{rbp} is the \emph{base
  1384. pointer}\index{base pointer} and is used to access variables that
  1385. are stored in the frame of the current procedure call. The base
  1386. pointer of the caller is pushed onto the stack after the return
  1387. address and then the base pointer is set to the location of the old
  1388. base pointer. In Figure~\ref{fig:frame} we number the variables from
  1389. $1$ to $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$,
  1390. variable $2$ at $-16\key{(\%rbp)}$, etc.
  1391. \begin{figure}[tbp]
  1392. \begin{lstlisting}
  1393. start:
  1394. movq $10, -8(%rbp)
  1395. negq -8(%rbp)
  1396. movq -8(%rbp), %rax
  1397. addq $52, %rax
  1398. jmp conclusion
  1399. .globl main
  1400. main:
  1401. pushq %rbp
  1402. movq %rsp, %rbp
  1403. subq $16, %rsp
  1404. jmp start
  1405. conclusion:
  1406. addq $16, %rsp
  1407. popq %rbp
  1408. retq
  1409. \end{lstlisting}
  1410. \caption{An x86 program equivalent to \code{(+ 52 (- 10))}.}
  1411. \label{fig:p1-x86}
  1412. \end{figure}
  1413. \begin{figure}[tbp]
  1414. \centering
  1415. \begin{tabular}{|r|l|} \hline
  1416. Position & Contents \\ \hline
  1417. 8(\key{\%rbp}) & return address \\
  1418. 0(\key{\%rbp}) & old \key{rbp} \\
  1419. -8(\key{\%rbp}) & variable $1$ \\
  1420. -16(\key{\%rbp}) & variable $2$ \\
  1421. \ldots & \ldots \\
  1422. 0(\key{\%rsp}) & variable $n$\\ \hline
  1423. \end{tabular}
  1424. \caption{Memory layout of a frame.}
  1425. \label{fig:frame}
  1426. \end{figure}
  1427. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  1428. control is transferred from the operating system to the \code{main}
  1429. function. The operating system issues a \code{callq main} instruction
  1430. which pushes its return address on the stack and then jumps to
  1431. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  1432. by 16 bytes prior to the execution of any \code{callq} instruction, so
  1433. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  1434. alignment (because the \code{callq} pushed the return address). The
  1435. first three instructions are the typical \emph{prelude}\index{prelude}
  1436. for a procedure. The instruction \code{pushq \%rbp} saves the base
  1437. pointer for the caller onto the stack and subtracts $8$ from the stack
  1438. pointer. The second instruction \code{movq \%rsp, \%rbp} changes the
  1439. base pointer so that it points the location of the old base
  1440. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  1441. pointer down to make enough room for storing variables. This program
  1442. needs one variable ($8$ bytes) but we round up to 16 bytes so that
  1443. \code{rsp} is 16-byte aligned and we're ready to make calls to other
  1444. functions. The last instruction of the prelude is \code{jmp start},
  1445. which transfers control to the instructions that were generated from
  1446. the Racket expression \code{(+ 52 (- 10))}.
  1447. The first instruction under the \code{start} label is
  1448. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  1449. %
  1450. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  1451. %
  1452. The next instruction moves the $-10$ from variable $1$ into the
  1453. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  1454. the value in \code{rax}, updating its contents to $42$.
  1455. The three instructions under the label \code{conclusion} are the
  1456. typical \emph{conclusion}\index{conclusion} of a procedure. The first
  1457. two instructions restore the \code{rsp} and \code{rbp} registers to
  1458. the state they were in at the beginning of the procedure. The
  1459. instruction \key{addq \$16, \%rsp} moves the stack pointer back to
  1460. point at the old base pointer. Then \key{popq \%rbp} returns the old
  1461. base pointer to \key{rbp} and adds $8$ to the stack pointer. The last
  1462. instruction, \key{retq}, jumps back to the procedure that called this
  1463. one and adds $8$ to the stack pointer.
  1464. The compiler needs a convenient representation for manipulating x86
  1465. programs, so we define an abstract syntax for x86 in
  1466. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  1467. \LangXASTInt{}. The main difference compared to the concrete syntax of
  1468. \LangXInt{} (Figure~\ref{fig:x86-int-concrete}) is that labels are not
  1469. allowed in front of every instructions. Instead instructions are
  1470. grouped into \emph{blocks}\index{block}\index{basic block} with a
  1471. label associated with every block, which is why the \key{X86Program}
  1472. struct includes an alist mapping labels to blocks. The reason for this
  1473. organization becomes apparent in Chapter~\ref{ch:bool-types} when we
  1474. introduce conditional branching. The \code{Block} structure includes
  1475. an $\itm{info}$ field that is not needed for this chapter, but becomes
  1476. useful in Chapter~\ref{ch:register-allocation-r1}. For now, the
  1477. $\itm{info}$ field should contain an empty list. Also, regarding the
  1478. abstract syntax for \code{callq}, the \code{Callq} struct includes an
  1479. integer for representing the arity of the function, i.e., the number
  1480. of arguments, which is helpful to know during register allocation
  1481. (Chapter~\ref{ch:register-allocation-r1}).
  1482. \begin{figure}[tp]
  1483. \fbox{
  1484. \begin{minipage}{0.98\textwidth}
  1485. \small
  1486. \[
  1487. \begin{array}{lcl}
  1488. \Reg &::=& \allregisters{} \\
  1489. \Arg &::=& \IMM{\Int} \mid \REG{\Reg}
  1490. \mid \DEREF{\Reg}{\Int} \\
  1491. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  1492. \mid \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  1493. &\mid& \BININSTR{\code{movq}}{\Arg}{\Arg}
  1494. \mid \UNIINSTR{\code{negq}}{\Arg}\\
  1495. &\mid& \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  1496. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  1497. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP} \\
  1498. \LangXASTInt{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  1499. \end{array}
  1500. \]
  1501. \end{minipage}
  1502. }
  1503. \caption{The abstract syntax of \LangXASTInt{} assembly.}
  1504. \label{fig:x86-int-ast}
  1505. \end{figure}
  1506. \section{Planning the trip to x86 via the \LangCVar{} language}
  1507. \label{sec:plan-s0-x86}
  1508. To compile one language to another it helps to focus on the
  1509. differences between the two languages because the compiler will need
  1510. to bridge those differences. What are the differences between \LangVar{}
  1511. and x86 assembly? Here are some of the most important ones:
  1512. \begin{enumerate}
  1513. \item[(a)] x86 arithmetic instructions typically have two arguments
  1514. and update the second argument in place. In contrast, \LangVar{}
  1515. arithmetic operations take two arguments and produce a new value.
  1516. An x86 instruction may have at most one memory-accessing argument.
  1517. Furthermore, some instructions place special restrictions on their
  1518. arguments.
  1519. \item[(b)] An argument of an \LangVar{} operator can be a deeply-nested
  1520. expression, whereas x86 instructions restrict their arguments to be
  1521. integers constants, registers, and memory locations.
  1522. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1523. sequence of instructions and jumps to labeled positions, whereas in
  1524. \LangVar{} the order of evaluation is a left-to-right depth-first
  1525. traversal of the abstract syntax tree.
  1526. \item[(d)] A program in \LangVar{} can have any number of variables
  1527. whereas x86 has 16 registers and the procedure calls stack.
  1528. \item[(e)] Variables in \LangVar{} can overshadow other variables with the
  1529. same name. In x86, registers have unique names and memory locations
  1530. have unique addresses.
  1531. \end{enumerate}
  1532. We ease the challenge of compiling from \LangVar{} to x86 by breaking down
  1533. the problem into several steps, dealing with the above differences one
  1534. at a time. Each of these steps is called a \emph{pass} of the
  1535. compiler.\index{pass}\index{compiler pass}
  1536. %
  1537. This terminology comes from the way each step passes over the AST of
  1538. the program.
  1539. %
  1540. We begin by sketching how we might implement each pass, and give them
  1541. names. We then figure out an ordering of the passes and the
  1542. input/output language for each pass. The very first pass has
  1543. \LangVar{} as its input language and the last pass has \LangXInt{} as
  1544. its output language. In between we can choose whichever language is
  1545. most convenient for expressing the output of each pass, whether that
  1546. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  1547. our own design. Finally, to implement each pass we write one
  1548. recursive function per non-terminal in the grammar of the input
  1549. language of the pass. \index{intermediate language}
  1550. \begin{description}
  1551. \item[\key{select-instructions}] handles the difference between
  1552. \LangVar{} operations and x86 instructions. This pass converts each
  1553. \LangVar{} operation to a short sequence of instructions that
  1554. accomplishes the same task.
  1555. \item[\key{remove-complex-opera*}] ensures that each subexpression of
  1556. a primitive operation is a variable or integer, that is, an
  1557. \emph{atomic} expression. We refer to non-atomic expressions as
  1558. \emph{complex}. This pass introduces temporary variables to hold
  1559. the results of complex subexpressions.\index{atomic
  1560. expression}\index{complex expression}%
  1561. \footnote{The subexpressions of an operation are often called
  1562. operators and operands which explains the presence of
  1563. \code{opera*} in the name of this pass.}
  1564. \item[\key{explicate-control}] makes the execution order of the
  1565. program explicit. It convert the abstract syntax tree representation
  1566. into a control-flow graph in which each node contains a sequence of
  1567. statements and the edges between nodes say which nodes contain jumps
  1568. to other nodes.
  1569. \item[\key{assign-homes}] replaces the variables in \LangVar{} with
  1570. registers or stack locations in x86.
  1571. \item[\key{uniquify}] deals with the shadowing of variables by
  1572. renaming every variable to a unique name.
  1573. \end{description}
  1574. The next question is: in what order should we apply these passes? This
  1575. question can be challenging because it is difficult to know ahead of
  1576. time which orderings will be better (easier to implement, produce more
  1577. efficient code, etc.) so oftentimes trial-and-error is
  1578. involved. Nevertheless, we can try to plan ahead and make educated
  1579. choices regarding the ordering.
  1580. What should be the ordering of \key{explicate-control} with respect to
  1581. \key{uniquify}? The \key{uniquify} pass should come first because
  1582. \key{explicate-control} changes all the \key{let}-bound variables to
  1583. become local variables whose scope is the entire program, which would
  1584. confuse variables with the same name.
  1585. %
  1586. We place \key{remove-complex-opera*} before \key{explicate-control}
  1587. because the later removes the \key{let} form, but it is convenient to
  1588. use \key{let} in the output of \key{remove-complex-opera*}.
  1589. %
  1590. The ordering of \key{uniquify} with respect to
  1591. \key{remove-complex-opera*} does not matter so we arbitrarily choose
  1592. \key{uniquify} to come first.
  1593. Last, we consider \key{select-instructions} and \key{assign-homes}.
  1594. These two passes are intertwined. In Chapter~\ref{ch:functions} we
  1595. learn that, in x86, registers are used for passing arguments to
  1596. functions and it is preferable to assign parameters to their
  1597. corresponding registers. On the other hand, by selecting instructions
  1598. first we may run into a dead end in \key{assign-homes}. Recall that
  1599. only one argument of an x86 instruction may be a memory access but
  1600. \key{assign-homes} might fail to assign even one of them to a
  1601. register.
  1602. %
  1603. A sophisticated approach is to iteratively repeat the two passes until
  1604. a solution is found. However, to reduce implementation complexity we
  1605. recommend a simpler approach in which \key{select-instructions} comes
  1606. first, followed by the \key{assign-homes}, then a third pass named
  1607. \key{patch-instructions} that uses a reserved register to fix
  1608. outstanding problems.
  1609. \begin{figure}[tbp]
  1610. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1611. \node (Rvar) at (0,2) {\large \LangVar{}};
  1612. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  1613. \node (Rvar-3) at (6,2) {\large \LangVarANF{}};
  1614. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  1615. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  1616. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  1617. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  1618. \node (x86-4) at (9,-2) {\large \LangXASTInt{}};
  1619. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  1620. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  1621. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvar-3);
  1622. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate-control} (Cvar-2);
  1623. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1624. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1625. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1626. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1627. \end{tikzpicture}
  1628. \caption{Diagram of the passes for compiling \LangVar{}. }
  1629. \label{fig:Rvar-passes}
  1630. \end{figure}
  1631. Figure~\ref{fig:Rvar-passes} presents the ordering of the compiler
  1632. passes and identifies the input and output language of each pass. The
  1633. last pass, \key{print-x86}, converts from the abstract syntax of
  1634. \LangXASTInt{} to the concrete syntax. In the following two sections
  1635. we discuss the \LangCVar{} intermediate language and the \LangXVar{}
  1636. dialect of x86. The remainder of this chapter gives hints regarding
  1637. the implementation of each of the compiler passes in
  1638. Figure~\ref{fig:Rvar-passes}.
  1639. %% The output of \key{uniquify} and \key{remove-complex-opera*}
  1640. %% are programs that are still in the \LangVar{} language, though the
  1641. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  1642. %% (Section~\ref{sec:remove-complex-opera-Rvar}).
  1643. %% %
  1644. %% The output of \key{explicate-control} is in an intermediate language
  1645. %% \LangCVar{} designed to make the order of evaluation explicit in its
  1646. %% syntax, which we introduce in the next section. The
  1647. %% \key{select-instruction} pass translates from \LangCVar{} to
  1648. %% \LangXVar{}. The \key{assign-homes} and
  1649. %% \key{patch-instructions}
  1650. %% passes input and output variants of x86 assembly.
  1651. \subsection{The \LangCVar{} Intermediate Language}
  1652. The output of \key{explicate-control} is similar to the $C$
  1653. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1654. categories for expressions and statements, so we name it \LangCVar{}. The
  1655. abstract syntax for \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  1656. (The concrete syntax for \LangCVar{} is in the Appendix,
  1657. Figure~\ref{fig:c0-concrete-syntax}.)
  1658. %
  1659. The \LangCVar{} language supports the same operators as \LangVar{} but
  1660. the arguments of operators are restricted to atomic
  1661. expressions. Instead of \key{let} expressions, \LangCVar{} has
  1662. assignment statements which can be executed in sequence using the
  1663. \key{Seq} form. A sequence of statements always ends with
  1664. \key{Return}, a guarantee that is baked into the grammar rules for
  1665. \itm{tail}. The naming of this non-terminal comes from the term
  1666. \emph{tail position}\index{tail position}, which refers to an
  1667. expression that is the last one to execute within a function.
  1668. A \LangCVar{} program consists of a control-flow graph represented as
  1669. an alist mapping labels to tails. This is more general than necessary
  1670. for the present chapter, as we do not yet introduce \key{goto} for
  1671. jumping to labels, but it saves us from having to change the syntax in
  1672. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1673. \key{start}, and the whole program is its tail.
  1674. %
  1675. The $\itm{info}$ field of the \key{CProgram} form, after the
  1676. \key{explicate-control} pass, contains a mapping from the symbol
  1677. \key{locals} to a list of variables, that is, a list of all the
  1678. variables used in the program. At the start of the program, these
  1679. variables are uninitialized; they become initialized on their first
  1680. assignment.
  1681. \begin{figure}[tbp]
  1682. \fbox{
  1683. \begin{minipage}{0.96\textwidth}
  1684. \[
  1685. \begin{array}{lcl}
  1686. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1687. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1688. &\mid& \ADD{\Atm}{\Atm}\\
  1689. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  1690. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1691. \LangCVar{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  1692. \end{array}
  1693. \]
  1694. \end{minipage}
  1695. }
  1696. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  1697. \label{fig:c0-syntax}
  1698. \end{figure}
  1699. The definitional interpreter for \LangCVar{} is in the support code
  1700. for this book, in the file \code{interp-Cvar.rkt}. The support code is
  1701. in a \code{github} repository at the following URL:
  1702. \begin{center}\footnotesize
  1703. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  1704. \end{center}
  1705. \subsection{The \LangXVar{} dialect}
  1706. The \LangXVar{} language is the output of the pass
  1707. \key{select-instructions}. It extends \LangXASTInt{} with an unbounded
  1708. number of program-scope variables and removes the restrictions
  1709. regarding instruction arguments.
  1710. \section{Uniquify Variables}
  1711. \label{sec:uniquify-Rvar}
  1712. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  1713. programs in which every \key{let} binds a unique variable name. For
  1714. example, the \code{uniquify} pass should translate the program on the
  1715. left into the program on the right. \\
  1716. \begin{tabular}{lll}
  1717. \begin{minipage}{0.4\textwidth}
  1718. \begin{lstlisting}
  1719. (let ([x 32])
  1720. (+ (let ([x 10]) x) x))
  1721. \end{lstlisting}
  1722. \end{minipage}
  1723. &
  1724. $\Rightarrow$
  1725. &
  1726. \begin{minipage}{0.4\textwidth}
  1727. \begin{lstlisting}
  1728. (let ([x.1 32])
  1729. (+ (let ([x.2 10]) x.2) x.1))
  1730. \end{lstlisting}
  1731. \end{minipage}
  1732. \end{tabular} \\
  1733. %
  1734. The following is another example translation, this time of a program
  1735. with a \key{let} nested inside the initializing expression of another
  1736. \key{let}.\\
  1737. \begin{tabular}{lll}
  1738. \begin{minipage}{0.4\textwidth}
  1739. \begin{lstlisting}
  1740. (let ([x (let ([x 4])
  1741. (+ x 1))])
  1742. (+ x 2))
  1743. \end{lstlisting}
  1744. \end{minipage}
  1745. &
  1746. $\Rightarrow$
  1747. &
  1748. \begin{minipage}{0.4\textwidth}
  1749. \begin{lstlisting}
  1750. (let ([x.2 (let ([x.1 4])
  1751. (+ x.1 1))])
  1752. (+ x.2 2))
  1753. \end{lstlisting}
  1754. \end{minipage}
  1755. \end{tabular}
  1756. We recommend implementing \code{uniquify} by creating a structurally
  1757. recursive function named \code{uniquify-exp} that mostly just copies
  1758. an expression. However, when encountering a \key{let}, it should
  1759. generate a unique name for the variable and associate the old name
  1760. with the new name in an alist.\footnote{The Racket function
  1761. \code{gensym} is handy for generating unique variable names.} The
  1762. \code{uniquify-exp} function needs to access this alist when it gets
  1763. to a variable reference, so we add a parameter to \code{uniquify-exp}
  1764. for the alist.
  1765. The skeleton of the \code{uniquify-exp} function is shown in
  1766. Figure~\ref{fig:uniquify-Rvar}. The function is curried so that it is
  1767. convenient to partially apply it to an alist and then apply it to
  1768. different expressions, as in the last clause for primitive operations
  1769. in Figure~\ref{fig:uniquify-Rvar}. The
  1770. %
  1771. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  1772. %
  1773. form of Racket is useful for transforming each element of a list to
  1774. produce a new list.\index{for/list}
  1775. \begin{exercise}
  1776. \normalfont % I don't like the italics for exercises. -Jeremy
  1777. Complete the \code{uniquify} pass by filling in the blanks in
  1778. Figure~\ref{fig:uniquify-Rvar}, that is, implement the clauses for
  1779. variables and for the \key{let} form in the file \code{compiler.rkt}
  1780. in the support code.
  1781. \end{exercise}
  1782. \begin{figure}[tbp]
  1783. \begin{lstlisting}
  1784. (define (uniquify-exp env)
  1785. (lambda (e)
  1786. (match e
  1787. [(Var x) ___]
  1788. [(Int n) (Int n)]
  1789. [(Let x e body) ___]
  1790. [(Prim op es)
  1791. (Prim op (for/list ([e es]) ((uniquify-exp env) e)))])))
  1792. (define (uniquify p)
  1793. (match p
  1794. [(Program '() e) (Program '() ((uniquify-exp '()) e))]))
  1795. \end{lstlisting}
  1796. \caption{Skeleton for the \key{uniquify} pass.}
  1797. \label{fig:uniquify-Rvar}
  1798. \end{figure}
  1799. \begin{exercise}
  1800. \normalfont % I don't like the italics for exercises. -Jeremy
  1801. Creating five \LangVar{} programs to test the most interesting parts
  1802. of the \key{uniquify} pass, that is, the programs should include
  1803. \key{let} forms, variables, and variables that overshadow each other.
  1804. The five programs should be placed in the subdirectory named
  1805. \key{tests} and the file names should start with \code{var\_test\_}
  1806. followed by a unique integer and end with the file extension
  1807. \key{.rkt}. Run the \key{run-tests.rkt} script in the support code to
  1808. check whether the output programs produce the same result as the input
  1809. programs. The script uses the \key{interp-tests} function
  1810. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1811. your \key{uniquify} pass on the example programs.
  1812. \end{exercise}
  1813. \section{Remove Complex Operands}
  1814. \label{sec:remove-complex-opera-Rvar}
  1815. The \code{remove-complex-opera*} pass compiles \LangVar{} programs into
  1816. \LangVar{} programs in which the arguments of operations are atomic
  1817. expressions. Put another way, this pass removes complex
  1818. operands\index{complex operand}, such as the expression \code{(- 10)}
  1819. in the program below. This is accomplished by introducing a new
  1820. \key{let}-bound variable, binding the complex operand to the new
  1821. variable, and then using the new variable in place of the complex
  1822. operand, as shown in the output of \code{remove-complex-opera*} on the
  1823. right.\\
  1824. \begin{tabular}{lll}
  1825. \begin{minipage}{0.4\textwidth}
  1826. % s0_19.rkt
  1827. \begin{lstlisting}
  1828. (+ 52 (- 10))
  1829. \end{lstlisting}
  1830. \end{minipage}
  1831. &
  1832. $\Rightarrow$
  1833. &
  1834. \begin{minipage}{0.4\textwidth}
  1835. \begin{lstlisting}
  1836. (let ([tmp.1 (- 10)])
  1837. (+ 52 tmp.1))
  1838. \end{lstlisting}
  1839. \end{minipage}
  1840. \end{tabular}
  1841. \begin{figure}[tp]
  1842. \centering
  1843. \fbox{
  1844. \begin{minipage}{0.96\textwidth}
  1845. \[
  1846. \begin{array}{rcl}
  1847. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1848. \Exp &::=& \Atm \mid \READ{} \\
  1849. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  1850. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  1851. R^{\dagger}_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1852. \end{array}
  1853. \]
  1854. \end{minipage}
  1855. }
  1856. \caption{\LangVarANF{} is \LangVar{} in administrative normal form (ANF).}
  1857. \label{fig:r1-anf-syntax}
  1858. \end{figure}
  1859. Figure~\ref{fig:r1-anf-syntax} presents the grammar for the output of
  1860. this pass, the language \LangVarANF{}. The only difference is that
  1861. operator arguments are required to be atomic expressions. In the
  1862. literature, this is called \emph{administrative normal form}, or ANF
  1863. for short~\citep{Danvy:1991fk,Flanagan:1993cg}. \index{administrative
  1864. normal form} \index{ANF}
  1865. We recommend implementing this pass with two mutually recursive
  1866. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1867. \code{rco-atom} to subexpressions that are required to be atomic and
  1868. to apply \code{rco-exp} to subexpressions that can be atomic or
  1869. complex (see Figure~\ref{fig:r1-anf-syntax}). Both functions take an
  1870. \LangVar{} expression as input. The \code{rco-exp} function returns an
  1871. expression. The \code{rco-atom} function returns two things: an
  1872. atomic expression and alist mapping temporary variables to complex
  1873. subexpressions. You can return multiple things from a function using
  1874. Racket's \key{values} form and you can receive multiple things from a
  1875. function call using the \key{define-values} form. If you are not
  1876. familiar with these features, review the Racket documentation. Also,
  1877. the \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  1878. form is useful for applying a function to each
  1879. element of a list, in the case where the function returns multiple
  1880. values.
  1881. \index{for/lists}
  1882. The following shows the output of \code{rco-atom} on the expression
  1883. \code{(- 10)} (using concrete syntax to be concise).
  1884. \begin{tabular}{lll}
  1885. \begin{minipage}{0.4\textwidth}
  1886. \begin{lstlisting}
  1887. (- 10)
  1888. \end{lstlisting}
  1889. \end{minipage}
  1890. &
  1891. $\Rightarrow$
  1892. &
  1893. \begin{minipage}{0.4\textwidth}
  1894. \begin{lstlisting}
  1895. tmp.1
  1896. ((tmp.1 . (- 10)))
  1897. \end{lstlisting}
  1898. \end{minipage}
  1899. \end{tabular}
  1900. Take special care of programs such as the following one that binds a
  1901. variable to an atomic expression. You should leave such variable
  1902. bindings unchanged, as shown in to the program on the right \\
  1903. \begin{tabular}{lll}
  1904. \begin{minipage}{0.4\textwidth}
  1905. % s0_20.rkt
  1906. \begin{lstlisting}
  1907. (let ([a 42])
  1908. (let ([b a])
  1909. b))
  1910. \end{lstlisting}
  1911. \end{minipage}
  1912. &
  1913. $\Rightarrow$
  1914. &
  1915. \begin{minipage}{0.4\textwidth}
  1916. \begin{lstlisting}
  1917. (let ([a 42])
  1918. (let ([b a])
  1919. b))
  1920. \end{lstlisting}
  1921. \end{minipage}
  1922. \end{tabular} \\
  1923. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  1924. produce the following output with unnecessary temporary variables.\\
  1925. \begin{minipage}{0.4\textwidth}
  1926. \begin{lstlisting}
  1927. (let ([tmp.1 42])
  1928. (let ([a tmp.1])
  1929. (let ([tmp.2 a])
  1930. (let ([b tmp.2])
  1931. b))))
  1932. \end{lstlisting}
  1933. \end{minipage}
  1934. \begin{exercise}
  1935. \normalfont Implement the \code{remove-complex-opera*} in
  1936. \code{compiler.rkt}. Create three new \LangInt{} programs that are
  1937. designed to exercise the interesting code in the
  1938. \code{remove-complex-opera*} pass (Following the same file name
  1939. guidelines as before.). In the \code{run-tests.rkt} script,
  1940. uncomment the line for this pass in the list of \code{passes} and
  1941. then run the script to test your compiler.
  1942. \end{exercise}
  1943. \section{Explicate Control}
  1944. \label{sec:explicate-control-r1}
  1945. The \code{explicate-control} pass compiles \LangVar{} programs into \LangCVar{}
  1946. programs that make the order of execution explicit in their
  1947. syntax. For now this amounts to flattening \key{let} constructs into a
  1948. sequence of assignment statements. For example, consider the following
  1949. \LangVar{} program.\\
  1950. % s0_11.rkt
  1951. \begin{minipage}{0.96\textwidth}
  1952. \begin{lstlisting}
  1953. (let ([y (let ([x 20])
  1954. (+ x (let ([x 22]) x)))])
  1955. y)
  1956. \end{lstlisting}
  1957. \end{minipage}\\
  1958. %
  1959. The output of the previous pass and of \code{explicate-control} is
  1960. shown below. Recall that the right-hand-side of a \key{let} executes
  1961. before its body, so the order of evaluation for this program is to
  1962. assign \code{20} to \code{x.1}, \code{22} to \code{x.2}, and
  1963. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  1964. output of \code{explicate-control} makes this ordering explicit.\\
  1965. \begin{tabular}{lll}
  1966. \begin{minipage}{0.4\textwidth}
  1967. \begin{lstlisting}
  1968. (let ([y (let ([x.1 20])
  1969. (let ([x.2 22])
  1970. (+ x.1 x.2)))])
  1971. y)
  1972. \end{lstlisting}
  1973. \end{minipage}
  1974. &
  1975. $\Rightarrow$
  1976. &
  1977. \begin{minipage}{0.4\textwidth}
  1978. \begin{lstlisting}[language=C]
  1979. start:
  1980. x.1 = 20;
  1981. x.2 = 22;
  1982. y = (+ x.1 x.2);
  1983. return y;
  1984. \end{lstlisting}
  1985. \end{minipage}
  1986. \end{tabular}
  1987. \begin{figure}[tbp]
  1988. \begin{lstlisting}
  1989. (define (explicate-tail e)
  1990. (match e
  1991. [(Var x) ___]
  1992. [(Int n) (Return (Int n))]
  1993. [(Let x rhs body) ___]
  1994. [(Prim op es) ___]
  1995. [else (error "explicate-tail unhandled case" e)]))
  1996. (define (explicate-assign e x cont)
  1997. (match e
  1998. [(Var x) ___]
  1999. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  2000. [(Let y rhs body) ___]
  2001. [(Prim op es) ___]
  2002. [else (error "explicate-assign unhandled case" e)]))
  2003. (define (explicate-control p)
  2004. (match p
  2005. [(Program info body) ___]))
  2006. \end{lstlisting}
  2007. \caption{Skeleton for the \key{explicate-control} pass.}
  2008. \label{fig:explicate-control-Rvar}
  2009. \end{figure}
  2010. The organization of this pass depends on the notion of tail position
  2011. that we have alluded to earlier. Formally, \emph{tail
  2012. position}\index{tail position} in the context of \LangVar{} is
  2013. defined recursively by the following two rules.
  2014. \begin{enumerate}
  2015. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  2016. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  2017. \end{enumerate}
  2018. We recommend implementing \code{explicate-control} using two mutually
  2019. recursive functions, \code{explicate-tail} and
  2020. \code{explicate-assign}, as suggested in the skeleton code in
  2021. Figure~\ref{fig:explicate-control-Rvar}. The \code{explicate-tail}
  2022. function should be applied to expressions in tail position whereas the
  2023. \code{explicate-assign} should be applied to expressions that occur on
  2024. the right-hand-side of a \key{let}.
  2025. %
  2026. The \code{explicate-tail} function takes an \Exp{} in \LangVar{} as
  2027. input and produces a \Tail{} in \LangCVar{} (see
  2028. Figure~\ref{fig:c0-syntax}).
  2029. %
  2030. The \code{explicate-assign} function takes an \Exp{} in \LangVar{},
  2031. the variable that it is to be assigned to, and a \Tail{} in
  2032. \LangCVar{} for the code that will come after the assignment. The
  2033. \code{explicate-assign} function returns a $\Tail$ in \LangCVar{}.
  2034. The \code{explicate-assign} function is in accumulator-passing style
  2035. in that the \code{cont} parameter is used for accumulating the
  2036. output. The reader might be tempted to instead organize
  2037. \code{explicate-assign} in a more direct fashion, without the
  2038. \code{cont} parameter and perhaps using \code{append} to combine
  2039. statements. We warn against that alternative because the
  2040. accumulator-passing style is key to how we generate high-quality code
  2041. for conditional expressions in Chapter~\ref{ch:bool-types}.
  2042. \section{Select Instructions}
  2043. \label{sec:select-r1}
  2044. \index{instruction selection}
  2045. In the \code{select-instructions} pass we begin the work of
  2046. translating from \LangCVar{} to \LangXVar{}. The target language of
  2047. this pass is a variant of x86 that still uses variables, so we add an
  2048. AST node of the form $\VAR{\itm{var}}$ to the \Arg{} non-terminal of
  2049. the \LangXASTInt{} abstract syntax (Figure~\ref{fig:x86-int-ast}). We
  2050. recommend implementing the \code{select-instructions} with
  2051. three auxiliary functions, one for each of the non-terminals of
  2052. \LangCVar{}: $\Atm$, $\Stmt$, and $\Tail$.
  2053. The cases for $\Atm$ are straightforward, variables stay
  2054. the same and integer constants are changed to immediates:
  2055. $\INT{n}$ changes to $\IMM{n}$.
  2056. Next we consider the cases for $\Stmt$, starting with arithmetic
  2057. operations. For example, consider the addition operation. We can use
  2058. the \key{addq} instruction, but it performs an in-place update. So we
  2059. could move $\itm{arg}_1$ into the left-hand side \itm{var} and then
  2060. add $\itm{arg}_2$ to \itm{var}. \\
  2061. \begin{tabular}{lll}
  2062. \begin{minipage}{0.4\textwidth}
  2063. \begin{lstlisting}
  2064. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{arg}_2$|);
  2065. \end{lstlisting}
  2066. \end{minipage}
  2067. &
  2068. $\Rightarrow$
  2069. &
  2070. \begin{minipage}{0.4\textwidth}
  2071. \begin{lstlisting}
  2072. movq |$\itm{arg}_1$|, |$\itm{var}$|
  2073. addq |$\itm{arg}_2$|, |$\itm{var}$|
  2074. \end{lstlisting}
  2075. \end{minipage}
  2076. \end{tabular} \\
  2077. %
  2078. There are also cases that require special care to avoid generating
  2079. needlessly complicated code. For example, if one of the arguments of
  2080. the addition is the same variable as the left-hand side of the
  2081. assignment, then there is no need for the extra move instruction. The
  2082. assignment statement can be translated into a single \key{addq}
  2083. instruction as follows.\\
  2084. \begin{tabular}{lll}
  2085. \begin{minipage}{0.4\textwidth}
  2086. \begin{lstlisting}
  2087. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{var}$|);
  2088. \end{lstlisting}
  2089. \end{minipage}
  2090. &
  2091. $\Rightarrow$
  2092. &
  2093. \begin{minipage}{0.4\textwidth}
  2094. \begin{lstlisting}
  2095. addq |$\itm{arg}_1$|, |$\itm{var}$|
  2096. \end{lstlisting}
  2097. \end{minipage}
  2098. \end{tabular}
  2099. The \key{read} operation does not have a direct counterpart in x86
  2100. assembly, so we provide this functionality with the function
  2101. \code{read\_int} in the file \code{runtime.c}, written in
  2102. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  2103. functionality in this file as the \emph{runtime system}\index{runtime
  2104. system}, or simply the \emph{runtime} for short. When compiling your
  2105. generated x86 assembly code, you need to compile \code{runtime.c} to
  2106. \code{runtime.o} (an ``object file'', using \code{gcc} option
  2107. \code{-c}) and link it into the executable. For our purposes of code
  2108. generation, all you need to do is translate an assignment of
  2109. \key{read} into a call to the \code{read\_int} function followed by a
  2110. move from \code{rax} to the left-hand-side variable. (Recall that the
  2111. return value of a function goes into \code{rax}.) \\
  2112. \begin{tabular}{lll}
  2113. \begin{minipage}{0.3\textwidth}
  2114. \begin{lstlisting}
  2115. |$\itm{var}$| = (read);
  2116. \end{lstlisting}
  2117. \end{minipage}
  2118. &
  2119. $\Rightarrow$
  2120. &
  2121. \begin{minipage}{0.3\textwidth}
  2122. \begin{lstlisting}
  2123. callq read_int
  2124. movq %rax, |$\itm{var}$|
  2125. \end{lstlisting}
  2126. \end{minipage}
  2127. \end{tabular}
  2128. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  2129. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  2130. assignment to the \key{rax} register followed by a jump to the
  2131. conclusion of the program (so the conclusion needs to be labeled).
  2132. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  2133. recursively and then append the resulting instructions.
  2134. \begin{exercise}
  2135. \normalfont Implement the \key{select-instructions} pass in
  2136. \code{compiler.rkt}. Create three new example programs that are
  2137. designed to exercise all of the interesting cases in this pass. In
  2138. the \code{run-tests.rkt} script, uncomment the line for this pass in
  2139. the list of \code{passes} and then run the script to test your
  2140. compiler.
  2141. \end{exercise}
  2142. \section{Assign Homes}
  2143. \label{sec:assign-r1}
  2144. The \key{assign-homes} pass compiles \LangXVar{} programs to
  2145. \LangXVar{} programs that no longer use program variables.
  2146. Thus, the \key{assign-homes} pass is responsible for placing all of
  2147. the program variables in registers or on the stack. For runtime
  2148. efficiency, it is better to place variables in registers, but as there
  2149. are only 16 registers, some programs must necessarily resort to
  2150. placing some variables on the stack. In this chapter we focus on the
  2151. mechanics of placing variables on the stack. We study an algorithm for
  2152. placing variables in registers in
  2153. Chapter~\ref{ch:register-allocation-r1}.
  2154. Consider again the following \LangVar{} program from
  2155. Section~\ref{sec:remove-complex-opera-Rvar}.
  2156. % s0_20.rkt
  2157. \begin{lstlisting}
  2158. (let ([a 42])
  2159. (let ([b a])
  2160. b))
  2161. \end{lstlisting}
  2162. The output of \code{select-instructions} is shown on the left and the
  2163. output of \code{assign-homes} on the right. In this example, we
  2164. assign variable \code{a} to stack location \code{-8(\%rbp)} and
  2165. variable \code{b} to location \code{-16(\%rbp)}.\\
  2166. \begin{tabular}{l}
  2167. \begin{minipage}{0.4\textwidth}
  2168. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2169. locals-types:
  2170. a : Integer, b : Integer
  2171. start:
  2172. movq $42, a
  2173. movq a, b
  2174. movq b, %rax
  2175. jmp conclusion
  2176. \end{lstlisting}
  2177. \end{minipage}
  2178. {$\Rightarrow$}
  2179. \begin{minipage}{0.4\textwidth}
  2180. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2181. stack-space: 16
  2182. start:
  2183. movq $42, -8(%rbp)
  2184. movq -8(%rbp), -16(%rbp)
  2185. movq -16(%rbp), %rax
  2186. jmp conclusion
  2187. \end{lstlisting}
  2188. \end{minipage}
  2189. \end{tabular}
  2190. The \code{locals-types} entry in the $\itm{info}$ of the
  2191. \code{X86Program} node is an alist mapping all the variables in the
  2192. program to their types (for now just \code{Integer}). The
  2193. \code{assign-homes} pass should replace all uses of those variables
  2194. with stack locations. As an aside, the \code{locals-types} entry is
  2195. computed by \code{type-check-Cvar} in the support code, which installs
  2196. it in the $\itm{info}$ field of the \code{CProgram} node, which should
  2197. be propagated to the \code{X86Program} node.
  2198. In the process of assigning variables to stack locations, it is
  2199. convenient for you to compute and store the size of the frame (in
  2200. bytes) in the $\itm{info}$ field of the \key{X86Program} node, with
  2201. the key \code{stack-space}, which is needed later to generate the
  2202. conclusion of the \code{main} procedure. The x86-64 standard requires
  2203. the frame size to be a multiple of 16 bytes.\index{frame}
  2204. \begin{exercise}\normalfont
  2205. Implement the \key{assign-homes} pass in \code{compiler.rkt}, defining
  2206. auxiliary functions for the non-terminals \Arg{}, \Instr{}, and
  2207. \Block{}. We recommend that the auxiliary functions take an extra
  2208. parameter that is an alist mapping variable names to homes (stack
  2209. locations for now). In the \code{run-tests.rkt} script, uncomment the
  2210. line for this pass in the list of \code{passes} and then run the
  2211. script to test your compiler.
  2212. \end{exercise}
  2213. \section{Patch Instructions}
  2214. \label{sec:patch-s0}
  2215. The \code{patch-instructions} pass compiles from \LangXVar{} to
  2216. \LangXASTInt{} by making sure that each instruction adheres to the
  2217. restriction that at most one argument of an instruction may be a
  2218. memory reference.
  2219. We return to the following example.
  2220. % s0_20.rkt
  2221. \begin{lstlisting}
  2222. (let ([a 42])
  2223. (let ([b a])
  2224. b))
  2225. \end{lstlisting}
  2226. The \key{assign-homes} pass produces the following output
  2227. for this program. \\
  2228. \begin{minipage}{0.5\textwidth}
  2229. \begin{lstlisting}
  2230. stack-space: 16
  2231. start:
  2232. movq $42, -8(%rbp)
  2233. movq -8(%rbp), -16(%rbp)
  2234. movq -16(%rbp), %rax
  2235. jmp conclusion
  2236. \end{lstlisting}
  2237. \end{minipage}\\
  2238. The second \key{movq} instruction is problematic because both
  2239. arguments are stack locations. We suggest fixing this problem by
  2240. moving from the source location to the register \key{rax} and then
  2241. from \key{rax} to the destination location, as follows.
  2242. \begin{lstlisting}
  2243. movq -8(%rbp), %rax
  2244. movq %rax, -16(%rbp)
  2245. \end{lstlisting}
  2246. \begin{exercise}
  2247. \normalfont Implement the \key{patch-instructions} pass in
  2248. \code{compiler.rkt}. Create three new example programs that are
  2249. designed to exercise all of the interesting cases in this pass. In
  2250. the \code{run-tests.rkt} script, uncomment the line for this pass in
  2251. the list of \code{passes} and then run the script to test your
  2252. compiler.
  2253. \end{exercise}
  2254. \section{Print x86}
  2255. \label{sec:print-x86}
  2256. The last step of the compiler from \LangVar{} to x86 is to convert the
  2257. \LangXASTInt{} AST (defined in Figure~\ref{fig:x86-int-ast}) to the
  2258. string representation (defined in
  2259. Figure~\ref{fig:x86-int-concrete}). The Racket \key{format} and
  2260. \key{string-append} functions are useful in this regard. The main work
  2261. that this step needs to perform is to create the \key{main} function
  2262. and the standard instructions for its prelude and conclusion, as shown
  2263. in Figure~\ref{fig:p1-x86} of Section~\ref{sec:x86}. You will need to
  2264. know the amount of space needed for the stack frame, which you can
  2265. obtain from the \code{stack-space} entry in the $\itm{info}$ field of
  2266. the \key{X86Program} node.
  2267. When running on Mac OS X, you compiler should prefix an underscore to
  2268. labels like \key{main}. The Racket call \code{(system-type 'os)} is
  2269. useful for determining which operating system the compiler is running
  2270. on. It returns \code{'macosx}, \code{'unix}, or \code{'windows}.
  2271. \begin{exercise}
  2272. \normalfont Implement the \key{print-x86} pass in
  2273. \code{compiler.rkt}. Uncomment the line for this pass in the list of
  2274. \code{passes} in the \code{run-tests.rkt} script. Also uncomment the
  2275. call to the \key{compiler-tests} function
  2276. (Appendix~\ref{appendix:utilities}), which tests your complete
  2277. compiler by executing the generated x86 code. Compile the provided
  2278. \key{runtime.c} file to \key{runtime.o} using \key{gcc}. Run the
  2279. script to test your compiler.
  2280. \end{exercise}
  2281. \section{Challenge: Partial Evaluator for \LangVar{}}
  2282. \label{sec:pe-Rvar}
  2283. \index{partial evaluation}
  2284. This section describes optional challenge exercises that involve
  2285. adapting and improving the partial evaluator for \LangInt{} that was
  2286. introduced in Section~\ref{sec:partial-evaluation}.
  2287. \begin{exercise}\label{ex:pe-Rvar}
  2288. \normalfont
  2289. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2290. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  2291. instead of \LangInt{} programs. Recall that \LangVar{} adds \key{let} binding
  2292. and variables to the \LangInt{} language, so you will need to add cases for
  2293. them in the \code{pe-exp} function. Once complete, add the partial
  2294. evaluation pass to the front of your compiler and make sure that your
  2295. compiler still passes all of the tests.
  2296. \end{exercise}
  2297. The next exercise builds on Exercise~\ref{ex:pe-Rvar}.
  2298. \begin{exercise}
  2299. \normalfont
  2300. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2301. \code{pe-add} auxiliary functions with functions that know more about
  2302. arithmetic. For example, your partial evaluator should translate
  2303. \[
  2304. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  2305. \code{(+ 2 (read))}
  2306. \]
  2307. To accomplish this, the \code{pe-exp} function should produce output
  2308. in the form of the $\itm{residual}$ non-terminal of the following
  2309. grammar. The idea is that when processing an addition expression, we
  2310. can always produce either 1) an integer constant, 2) and addition
  2311. expression with an integer constant on the left-hand side but not the
  2312. right-hand side, or 3) or an addition expression in which neither
  2313. subexpression is a constant.
  2314. \[
  2315. \begin{array}{lcl}
  2316. \itm{inert} &::=& \Var \mid \LP\key{read}\RP \mid \LP\key{-} \;\Var\RP
  2317. \mid \LP\key{-} \;\LP\key{read}\RP\RP
  2318. \mid \LP\key{+} \; \itm{inert} \; \itm{inert}\RP\\
  2319. &\mid& \LP\key{let}~\LP\LS\Var~\itm{inert}\RS\RP~ \itm{inert} \RP \\
  2320. \itm{residual} &::=& \Int \mid \LP\key{+}\; \Int\; \itm{inert}\RP \mid \itm{inert}
  2321. \end{array}
  2322. \]
  2323. The \code{pe-add} and \code{pe-neg} functions may assume that their
  2324. inputs are $\itm{residual}$ expressions and they should return
  2325. $\itm{residual}$ expressions. Once the improvements are complete,
  2326. make sure that your compiler still passes all of the tests. After
  2327. all, fast code is useless if it produces incorrect results!
  2328. \end{exercise}
  2329. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2330. \chapter{Register Allocation}
  2331. \label{ch:register-allocation-r1}
  2332. \index{register allocation}
  2333. In Chapter~\ref{ch:int-exp} we learned how to store variables on the
  2334. stack. In this Chapter we learn how to improve the performance of the
  2335. generated code by placing some variables into registers. The CPU can
  2336. access a register in a single cycle, whereas accessing the stack can
  2337. take 10s to 100s of cycles. The program in Figure~\ref{fig:reg-eg}
  2338. serves as a running example. The source program is on the left and the
  2339. output of instruction selection is on the right. The program is almost
  2340. in the x86 assembly language but it still uses variables.
  2341. \begin{figure}
  2342. \begin{minipage}{0.45\textwidth}
  2343. Example \LangVar{} program:
  2344. % s0_28.rkt
  2345. \begin{lstlisting}
  2346. (let ([v 1])
  2347. (let ([w 42])
  2348. (let ([x (+ v 7)])
  2349. (let ([y x])
  2350. (let ([z (+ x w)])
  2351. (+ z (- y)))))))
  2352. \end{lstlisting}
  2353. \end{minipage}
  2354. \begin{minipage}{0.45\textwidth}
  2355. After instruction selection:
  2356. \begin{lstlisting}
  2357. locals-types:
  2358. x : Integer, y : Integer,
  2359. z : Integer, t : Integer,
  2360. v : Integer, w : Integer
  2361. start:
  2362. movq $1, v
  2363. movq $42, w
  2364. movq v, x
  2365. addq $7, x
  2366. movq x, y
  2367. movq x, z
  2368. addq w, z
  2369. movq y, t
  2370. negq t
  2371. movq z, %rax
  2372. addq t, %rax
  2373. jmp conclusion
  2374. \end{lstlisting}
  2375. \end{minipage}
  2376. \caption{A running example for register allocation.}
  2377. \label{fig:reg-eg}
  2378. \end{figure}
  2379. The goal of register allocation is to fit as many variables into
  2380. registers as possible. Some programs have more variables than
  2381. registers so we cannot always map each variable to a different
  2382. register. Fortunately, it is common for different variables to be
  2383. needed during different periods of time during program execution, and
  2384. in such cases several variables can be mapped to the same register.
  2385. Consider variables \code{x} and \code{z} in Figure~\ref{fig:reg-eg}.
  2386. After the variable \code{x} is moved to \code{z} it is no longer
  2387. needed. Variable \code{z}, on the other hand, is used only after this
  2388. point, so \code{x} and \code{z} could share the same register. The
  2389. topic of Section~\ref{sec:liveness-analysis-r1} is how to compute
  2390. where a variable is needed. Once we have that information, we compute
  2391. which variables are needed at the same time, i.e., which ones
  2392. \emph{interfere} with each other, and represent this relation as an
  2393. undirected graph whose vertices are variables and edges indicate when
  2394. two variables interfere (Section~\ref{sec:build-interference}). We
  2395. then model register allocation as a graph coloring problem
  2396. (Section~\ref{sec:graph-coloring}).
  2397. If we run out of registers despite these efforts, we place the
  2398. remaining variables on the stack, similar to what we did in
  2399. Chapter~\ref{ch:int-exp}. It is common to use the verb \emph{spill}
  2400. for assigning a variable to a stack location. The decision to spill a
  2401. variable is handled as part of the graph coloring process
  2402. (Section~\ref{sec:graph-coloring}).
  2403. We make the simplifying assumption that each variable is assigned to
  2404. one location (a register or stack address). A more sophisticated
  2405. approach is to assign a variable to one or more locations in different
  2406. regions of the program. For example, if a variable is used many times
  2407. in short sequence and then only used again after many other
  2408. instructions, it could be more efficient to assign the variable to a
  2409. register during the initial sequence and then move it to the stack for
  2410. the rest of its lifetime. We refer the interested reader to
  2411. \citet{Cooper:2011aa} for more information about that approach.
  2412. % discuss prioritizing variables based on how much they are used.
  2413. \section{Registers and Calling Conventions}
  2414. \label{sec:calling-conventions}
  2415. \index{calling conventions}
  2416. As we perform register allocation, we need to be aware of the
  2417. \emph{calling conventions} \index{calling conventions} that govern how
  2418. functions calls are performed in x86.
  2419. %
  2420. Even though \LangVar{} does not include programmer-defined functions,
  2421. our generated code includes a \code{main} function that is called by
  2422. the operating system and our generated code contains calls to the
  2423. \code{read\_int} function.
  2424. Function calls require coordination between two pieces of code that
  2425. may be written by different programmers or generated by different
  2426. compilers. Here we follow the System V calling conventions that are
  2427. used by the GNU C compiler on Linux and
  2428. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  2429. %
  2430. The calling conventions include rules about how functions share the
  2431. use of registers. In particular, the caller is responsible for freeing
  2432. up some registers prior to the function call for use by the callee.
  2433. These are called the \emph{caller-saved registers}
  2434. \index{caller-saved registers}
  2435. and they are
  2436. \begin{lstlisting}
  2437. rax rcx rdx rsi rdi r8 r9 r10 r11
  2438. \end{lstlisting}
  2439. On the other hand, the callee is responsible for preserving the values
  2440. of the \emph{callee-saved registers}, \index{callee-saved registers}
  2441. which are
  2442. \begin{lstlisting}
  2443. rsp rbp rbx r12 r13 r14 r15
  2444. \end{lstlisting}
  2445. We can think about this caller/callee convention from two points of
  2446. view, the caller view and the callee view:
  2447. \begin{itemize}
  2448. \item The caller should assume that all the caller-saved registers get
  2449. overwritten with arbitrary values by the callee. On the other hand,
  2450. the caller can safely assume that all the callee-saved registers
  2451. contain the same values after the call that they did before the
  2452. call.
  2453. \item The callee can freely use any of the caller-saved registers.
  2454. However, if the callee wants to use a callee-saved register, the
  2455. callee must arrange to put the original value back in the register
  2456. prior to returning to the caller. This can be accomplished by saving
  2457. the value to the stack in the prelude of the function and restoring
  2458. the value in the conclusion of the function.
  2459. \end{itemize}
  2460. In x86, registers are also used for passing arguments to a function
  2461. and for the return value. In particular, the first six arguments to a
  2462. function are passed in the following six registers, in this order.
  2463. \begin{lstlisting}
  2464. rdi rsi rdx rcx r8 r9
  2465. \end{lstlisting}
  2466. If there are more than six arguments, then the convention is to use
  2467. space on the frame of the caller for the rest of the
  2468. arguments. However, in Chapter~\ref{ch:functions} we arrange to never
  2469. need more than six arguments. For now, the only function we care about
  2470. is \code{read\_int} and it takes zero arguments.
  2471. %
  2472. The register \code{rax} is used for the return value of a function.
  2473. The next question is how these calling conventions impact register
  2474. allocation. Consider the \LangVar{} program in
  2475. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  2476. example from the caller point of view and then from the callee point
  2477. of view.
  2478. The program makes two calls to the \code{read} function. Also, the
  2479. variable \code{x} is in-use during the second call to \code{read}, so
  2480. we need to make sure that the value in \code{x} does not get
  2481. accidentally wiped out by the call to \code{read}. One obvious
  2482. approach is to save all the values in caller-saved registers to the
  2483. stack prior to each function call, and restore them after each
  2484. call. That way, if the register allocator chooses to assign \code{x}
  2485. to a caller-saved register, its value will be preserved across the
  2486. call to \code{read}. However, saving and restoring to the stack is
  2487. relatively slow. If \code{x} is not used many times, it may be better
  2488. to assign \code{x} to a stack location in the first place. Or better
  2489. yet, if we can arrange for \code{x} to be placed in a callee-saved
  2490. register, then it won't need to be saved and restored during function
  2491. calls.
  2492. The approach that we recommend for variables that are in-use during a
  2493. function call is to either assign them to callee-saved registers or to
  2494. spill them to the stack. On the other hand, for variables that are not
  2495. in-use during a function call, we try the following alternatives in
  2496. order 1) look for an available caller-saved register (to leave room
  2497. for other variables in the callee-saved register), 2) look for a
  2498. callee-saved register, and 3) spill the variable to the stack.
  2499. It is straightforward to implement this approach in a graph coloring
  2500. register allocator. First, we know which variables are in-use during
  2501. every function call because we compute that information for every
  2502. instruction (Section~\ref{sec:liveness-analysis-r1}). Second, when we
  2503. build the interference graph (Section~\ref{sec:build-interference}),
  2504. we can place an edge between each of these variables and the
  2505. caller-saved registers in the interference graph. This will prevent
  2506. the graph coloring algorithm from assigning those variables to
  2507. caller-saved registers.
  2508. Returning to the example in
  2509. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  2510. generated x86 code on the right-hand side, focusing on the
  2511. \code{start} block. Notice that variable \code{x} is assigned to
  2512. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  2513. place during the second call to \code{read\_int}. Next, notice that
  2514. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  2515. because there are no function calls in the remainder of the block.
  2516. Next we analyze the example from the callee point of view, focusing on
  2517. the prelude and conclusion of the \code{main} function. As usual the
  2518. prelude begins with saving the \code{rbp} register to the stack and
  2519. setting the \code{rbp} to the current stack pointer. We now know why
  2520. it is necessary to save the \code{rbp}: it is a callee-saved register.
  2521. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  2522. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  2523. (\code{x}). The other callee-saved registers are not saved in the
  2524. prelude because they are not used. The prelude subtracts 8 bytes from
  2525. the \code{rsp} to make it 16-byte aligned and then jumps to the
  2526. \code{start} block. Shifting attention to the \code{conclusion}, we
  2527. see that \code{rbx} is restored from the stack with a \code{popq}
  2528. instruction. \index{prelude}\index{conclusion}
  2529. \begin{figure}[tp]
  2530. \begin{minipage}{0.45\textwidth}
  2531. Example \LangVar{} program:
  2532. %s0_14.rkt
  2533. \begin{lstlisting}
  2534. (let ([x (read)])
  2535. (let ([y (read)])
  2536. (+ (+ x y) 42)))
  2537. \end{lstlisting}
  2538. \end{minipage}
  2539. \begin{minipage}{0.45\textwidth}
  2540. Generated x86 assembly:
  2541. \begin{lstlisting}
  2542. start:
  2543. callq read_int
  2544. movq %rax, %rbx
  2545. callq read_int
  2546. movq %rax, %rcx
  2547. addq %rcx, %rbx
  2548. movq %rbx, %rax
  2549. addq $42, %rax
  2550. jmp _conclusion
  2551. .globl main
  2552. main:
  2553. pushq %rbp
  2554. movq %rsp, %rbp
  2555. pushq %rbx
  2556. subq $8, %rsp
  2557. jmp start
  2558. conclusion:
  2559. addq $8, %rsp
  2560. popq %rbx
  2561. popq %rbp
  2562. retq
  2563. \end{lstlisting}
  2564. \end{minipage}
  2565. \caption{An example with function calls.}
  2566. \label{fig:example-calling-conventions}
  2567. \end{figure}
  2568. \clearpage
  2569. \section{Liveness Analysis}
  2570. \label{sec:liveness-analysis-r1}
  2571. \index{liveness analysis}
  2572. The \code{uncover-live} pass performs \emph{liveness analysis}, that
  2573. is, it discovers which variables are in-use in different regions of a
  2574. program.
  2575. %
  2576. A variable or register is \emph{live} at a program point if its
  2577. current value is used at some later point in the program. We
  2578. refer to variables and registers collectively as \emph{locations}.
  2579. %
  2580. Consider the following code fragment in which there are two writes to
  2581. \code{b}. Are \code{a} and \code{b} both live at the same time?
  2582. \begin{center}
  2583. \begin{minipage}{0.96\textwidth}
  2584. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2585. movq $5, a
  2586. movq $30, b
  2587. movq a, c
  2588. movq $10, b
  2589. addq b, c
  2590. \end{lstlisting}
  2591. \end{minipage}
  2592. \end{center}
  2593. The answer is no because \code{a} is live from line 1 to 3 and
  2594. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  2595. line 2 is never used because it is overwritten (line 4) before the
  2596. next read (line 5).
  2597. \begin{wrapfigure}[19]{l}[1.0in]{0.6\textwidth}
  2598. \small
  2599. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  2600. A \emph{set} is an unordered collection of elements without duplicates.
  2601. \index{set}
  2602. \begin{description}
  2603. \item[$\LP\code{set}\,v\,\ldots\RP$] constructs a set containing the specified elements.
  2604. \item[$\LP\code{set-union}\,set_1\,set_2\RP$] returns the union of the two sets.
  2605. \item[$\LP\code{set-subtract}\,set_1\,set_2\RP$] returns the difference of the two sets.
  2606. \item[$\LP\code{set-member?}\,set\,v\RP$] is element $v$ in $set$?
  2607. \item[$\LP\code{set-count}\,set\RP$] how many unique elements are in $set$?
  2608. \item[$\LP\code{set->list}\,set\RP$] converts the set to a list.
  2609. \end{description}
  2610. \end{tcolorbox}
  2611. \end{wrapfigure}
  2612. The live locations can be computed by traversing the instruction
  2613. sequence back to front (i.e., backwards in execution order). Let
  2614. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2615. $L_{\mathsf{after}}(k)$ for the set of live locations after
  2616. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2617. locations before instruction $I_k$. The live locations after an
  2618. instruction are always the same as the live locations before the next
  2619. instruction. \index{live-after} \index{live-before}
  2620. \begin{equation} \label{eq:live-after-before-next}
  2621. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2622. \end{equation}
  2623. To start things off, there are no live locations after the last
  2624. instruction, so
  2625. \begin{equation}\label{eq:live-last-empty}
  2626. L_{\mathsf{after}}(n) = \emptyset
  2627. \end{equation}
  2628. We then apply the following rule repeatedly, traversing the
  2629. instruction sequence back to front.
  2630. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2631. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2632. \end{equation}
  2633. where $W(k)$ are the locations written to by instruction $I_k$ and
  2634. $R(k)$ are the locations read by instruction $I_k$.
  2635. There is a special case for \code{jmp} instructions. The locations
  2636. that are live before a \code{jmp} should be the locations in
  2637. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  2638. maintaining an alist named \code{label->live} that maps each label to
  2639. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  2640. now the only \code{jmp} in a \LangXVar{} program is the one at the
  2641. end, to the conclusion. (For example, see Figure~\ref{fig:reg-eg}.)
  2642. The conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should
  2643. map \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  2644. Let us walk through the above example, applying these formulas
  2645. starting with the instruction on line 5. We collect the answers in
  2646. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  2647. \code{addq b, c} instruction is $\emptyset$ because it is the last
  2648. instruction (formula~\ref{eq:live-last-empty}). The
  2649. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  2650. because it reads from variables \code{b} and \code{c}
  2651. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  2652. \[
  2653. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  2654. \]
  2655. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2656. the live-before set from line 5 to be the live-after set for this
  2657. instruction (formula~\ref{eq:live-after-before-next}).
  2658. \[
  2659. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  2660. \]
  2661. This move instruction writes to \code{b} and does not read from any
  2662. variables, so we have the following live-before set
  2663. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2664. \[
  2665. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  2666. \]
  2667. The live-before for instruction \code{movq a, c}
  2668. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  2669. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2670. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  2671. variable that is not live and does not read from a variable.
  2672. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2673. because it writes to variable \code{a}.
  2674. \begin{figure}[tbp]
  2675. \begin{minipage}{0.45\textwidth}
  2676. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2677. movq $5, a
  2678. movq $30, b
  2679. movq a, c
  2680. movq $10, b
  2681. addq b, c
  2682. \end{lstlisting}
  2683. \end{minipage}
  2684. \vrule\hspace{10pt}
  2685. \begin{minipage}{0.45\textwidth}
  2686. \begin{align*}
  2687. L_{\mathsf{before}}(1)= \emptyset,
  2688. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  2689. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  2690. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  2691. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  2692. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  2693. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  2694. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  2695. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  2696. L_{\mathsf{after}}(5)= \emptyset
  2697. \end{align*}
  2698. \end{minipage}
  2699. \caption{Example output of liveness analysis on a short example.}
  2700. \label{fig:liveness-example-0}
  2701. \end{figure}
  2702. \begin{exercise}\normalfont
  2703. Perform liveness analysis on the running example in
  2704. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  2705. sets for each instruction. Compare your answers to the solution
  2706. shown in Figure~\ref{fig:live-eg}.
  2707. \end{exercise}
  2708. \begin{figure}[tp]
  2709. \hspace{20pt}
  2710. \begin{minipage}{0.45\textwidth}
  2711. \begin{lstlisting}
  2712. |$\{\ttm{rsp}\}$|
  2713. movq $1, v
  2714. |$\{\ttm{v},\ttm{rsp}\}$|
  2715. movq $42, w
  2716. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  2717. movq v, x
  2718. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  2719. addq $7, x
  2720. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  2721. movq x, y
  2722. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  2723. movq x, z
  2724. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  2725. addq w, z
  2726. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  2727. movq y, t
  2728. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  2729. negq t
  2730. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  2731. movq z, %rax
  2732. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  2733. addq t, %rax
  2734. |$\{\ttm{rax},\ttm{rsp}\}$|
  2735. jmp conclusion
  2736. \end{lstlisting}
  2737. \end{minipage}
  2738. \caption{The running example annotated with live-after sets.}
  2739. \label{fig:live-eg}
  2740. \end{figure}
  2741. \begin{exercise}\normalfont
  2742. Implement the \code{uncover-live} pass. Store the sequence of
  2743. live-after sets in the $\itm{info}$ field of the \code{Block}
  2744. structure.
  2745. %
  2746. We recommend creating an auxiliary function that takes a list of
  2747. instructions and an initial live-after set (typically empty) and
  2748. returns the list of live-after sets.
  2749. %
  2750. We also recommend creating auxiliary functions to 1) compute the set
  2751. of locations that appear in an \Arg{}, 2) compute the locations read
  2752. by an instruction (the $R$ function), and 3) the locations written by
  2753. an instruction (the $W$ function). The \code{callq} instruction should
  2754. include all of the caller-saved registers in its write-set $W$ because
  2755. the calling convention says that those registers may be written to
  2756. during the function call. Likewise, the \code{callq} instruction
  2757. should include the appropriate argument-passing registers in its
  2758. read-set $R$, depending on the arity of the function being
  2759. called. (This is why the abstract syntax for \code{callq} includes the
  2760. arity.)
  2761. \end{exercise}
  2762. \section{Building the Interference Graph}
  2763. \label{sec:build-interference}
  2764. \begin{wrapfigure}[27]{r}[1.0in]{0.6\textwidth}
  2765. \small
  2766. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  2767. A \emph{graph} is a collection of vertices and edges where each
  2768. edge connects two vertices. A graph is \emph{directed} if each
  2769. edge points from a source to a target. Otherwise the graph is
  2770. \emph{undirected}.
  2771. \index{graph}\index{directed graph}\index{undirected graph}
  2772. \begin{description}
  2773. %% We currently don't use directed graphs. We instead use
  2774. %% directed multi-graphs. -Jeremy
  2775. %% \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  2776. %% directed graph from a list of edges. Each edge is a list
  2777. %% containing the source and target vertex.
  2778. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  2779. undirected graph from a list of edges. Each edge is represented by
  2780. a list containing two vertices.
  2781. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  2782. inserts a vertex into the graph.
  2783. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  2784. inserts an edge between the two vertices into the graph.
  2785. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  2786. returns a sequence of all the neighbors of the given vertex.
  2787. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  2788. returns a sequence of all the vertices in the graph.
  2789. \end{description}
  2790. \end{tcolorbox}
  2791. \end{wrapfigure}
  2792. Based on the liveness analysis, we know where each location is live.
  2793. However, during register allocation, we need to answer questions of
  2794. the specific form: are locations $u$ and $v$ live at the same time?
  2795. (And therefore cannot be assigned to the same register.) To make this
  2796. question more efficient to answer, we create an explicit data
  2797. structure, an \emph{interference graph}\index{interference graph}. An
  2798. interference graph is an undirected graph that has an edge between two
  2799. locations if they are live at the same time, that is, if they
  2800. interfere with each other.
  2801. An obvious way to compute the interference graph is to look at the set
  2802. of live location between each instruction and add an edge to the graph
  2803. for every pair of variables in the same set. This approach is less
  2804. than ideal for two reasons. First, it can be expensive because it
  2805. takes $O(n^2)$ time to consider at every pair in a set of $n$ live
  2806. locations. Second, in the special case where two locations hold the
  2807. same value (because one was assigned to the other), they can be live
  2808. at the same time without interfering with each other.
  2809. A better way to compute the interference graph is to focus on
  2810. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  2811. must not overwrite something in a live location. So for each
  2812. instruction, we create an edge between the locations being written to
  2813. and the live locations. (Except that one should not create self
  2814. edges.) Note that for the \key{callq} instruction, we consider all of
  2815. the caller-saved registers as being written to, so an edge is added
  2816. between every live variable and every caller-saved register. For
  2817. \key{movq}, we deal with the above-mentioned special case by not
  2818. adding an edge between a live variable $v$ and the destination if $v$
  2819. matches the source. So we have the following two rules.
  2820. \begin{enumerate}
  2821. \item If instruction $I_k$ is a move such as \key{movq} $s$\key{,}
  2822. $d$, then add the edge $(d,v)$ for every $v \in
  2823. L_{\mathsf{after}}(k)$ unless $v = d$ or $v = s$.
  2824. \item For any other instruction $I_k$, for every $d \in W(k)$
  2825. add an edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  2826. %% \item If instruction $I_k$ is an arithmetic instruction such as
  2827. %% \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2828. %% L_{\mathsf{after}}(k)$ unless $v = d$.
  2829. %% \item If instruction $I_k$ is of the form \key{callq}
  2830. %% $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2831. %% register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2832. \end{enumerate}
  2833. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  2834. the above rules to each instruction. We highlight a few of the
  2835. instructions. The first instruction is \lstinline{movq $1, v} and the
  2836. live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies, so \code{v}
  2837. interferes with \code{rsp}.
  2838. %
  2839. The fourth instruction is \lstinline{addq $7, x} and the live-after
  2840. set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so $\ttm{x}$
  2841. interferes with \ttm{w} and \ttm{rsp}.
  2842. %
  2843. The next instruction is \lstinline{movq x, y} and the live-after set
  2844. is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1 applies, so \ttm{y}
  2845. interferes with \ttm{w} and \ttm{rsp} but not \ttm{x} because \ttm{x}
  2846. is the source of the move and therefore \ttm{x} and \ttm{y} hold the
  2847. same value. Figure~\ref{fig:interference-results} lists the
  2848. interference results for all of the instructions and the resulting
  2849. interference graph is shown in Figure~\ref{fig:interfere}.
  2850. \begin{figure}[tbp]
  2851. \begin{quote}
  2852. \begin{tabular}{ll}
  2853. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  2854. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  2855. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  2856. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  2857. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  2858. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  2859. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  2860. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  2861. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  2862. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  2863. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  2864. \lstinline!jmp conclusion!& no interference.
  2865. \end{tabular}
  2866. \end{quote}
  2867. \caption{Interference results for the running example.}
  2868. \label{fig:interference-results}
  2869. \end{figure}
  2870. \begin{figure}[tbp]
  2871. \large
  2872. \[
  2873. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2874. \node (rax) at (0,0) {$\ttm{rax}$};
  2875. \node (rsp) at (9,2) {$\ttm{rsp}$};
  2876. \node (t1) at (0,2) {$\ttm{t}$};
  2877. \node (z) at (3,2) {$\ttm{z}$};
  2878. \node (x) at (6,2) {$\ttm{x}$};
  2879. \node (y) at (3,0) {$\ttm{y}$};
  2880. \node (w) at (6,0) {$\ttm{w}$};
  2881. \node (v) at (9,0) {$\ttm{v}$};
  2882. \draw (t1) to (rax);
  2883. \draw (t1) to (z);
  2884. \draw (z) to (y);
  2885. \draw (z) to (w);
  2886. \draw (x) to (w);
  2887. \draw (y) to (w);
  2888. \draw (v) to (w);
  2889. \draw (v) to (rsp);
  2890. \draw (w) to (rsp);
  2891. \draw (x) to (rsp);
  2892. \draw (y) to (rsp);
  2893. \path[-.,bend left=15] (z) edge node {} (rsp);
  2894. \path[-.,bend left=10] (t1) edge node {} (rsp);
  2895. \draw (rax) to (rsp);
  2896. \end{tikzpicture}
  2897. \]
  2898. \caption{The interference graph of the example program.}
  2899. \label{fig:interfere}
  2900. \end{figure}
  2901. %% Our next concern is to choose a data structure for representing the
  2902. %% interference graph. There are many choices for how to represent a
  2903. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2904. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2905. %% data structure is to study the algorithm that uses the data structure,
  2906. %% determine what operations need to be performed, and then choose the
  2907. %% data structure that provide the most efficient implementations of
  2908. %% those operations. Often times the choice of data structure can have an
  2909. %% effect on the time complexity of the algorithm, as it does here. If
  2910. %% you skim the next section, you will see that the register allocation
  2911. %% algorithm needs to ask the graph for all of its vertices and, given a
  2912. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2913. %% correct choice of graph representation is that of an adjacency
  2914. %% list. There are helper functions in \code{utilities.rkt} for
  2915. %% representing graphs using the adjacency list representation:
  2916. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2917. %% (Appendix~\ref{appendix:utilities}).
  2918. %% %
  2919. %% \margincomment{\footnotesize To do: change to use the
  2920. %% Racket graph library. \\ --Jeremy}
  2921. %% %
  2922. %% In particular, those functions use a hash table to map each vertex to
  2923. %% the set of adjacent vertices, and the sets are represented using
  2924. %% Racket's \key{set}, which is also a hash table.
  2925. \begin{exercise}\normalfont
  2926. Implement the compiler pass named \code{build-interference} according
  2927. to the algorithm suggested above. We recommend using the \code{graph}
  2928. package to create and inspect the interference graph. The output
  2929. graph of this pass should be stored in the $\itm{info}$ field of the
  2930. program, under the key \code{conflicts}.
  2931. \end{exercise}
  2932. \section{Graph Coloring via Sudoku}
  2933. \label{sec:graph-coloring}
  2934. \index{graph coloring}
  2935. \index{Sudoku}
  2936. \index{color}
  2937. We come to the main event, mapping variables to registers and stack
  2938. locations. Variables that interfere with each other must be mapped to
  2939. different locations. In terms of the interference graph, this means
  2940. that adjacent vertices must be mapped to different locations. If we
  2941. think of locations as colors, the register allocation problem becomes
  2942. the graph coloring problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2943. The reader may be more familiar with the graph coloring problem than he
  2944. or she realizes; the popular game of Sudoku is an instance of the
  2945. graph coloring problem. The following describes how to build a graph
  2946. out of an initial Sudoku board.
  2947. \begin{itemize}
  2948. \item There is one vertex in the graph for each Sudoku square.
  2949. \item There is an edge between two vertices if the corresponding squares
  2950. are in the same row, in the same column, or if the squares are in
  2951. the same $3\times 3$ region.
  2952. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2953. \item Based on the initial assignment of numbers to squares in the
  2954. Sudoku board, assign the corresponding colors to the corresponding
  2955. vertices in the graph.
  2956. \end{itemize}
  2957. If you can color the remaining vertices in the graph with the nine
  2958. colors, then you have also solved the corresponding game of Sudoku.
  2959. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2960. the corresponding graph with colored vertices. We map the Sudoku
  2961. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2962. sampling of the vertices (the colored ones) because showing edges for
  2963. all of the vertices would make the graph unreadable.
  2964. \begin{figure}[tbp]
  2965. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2966. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2967. \caption{A Sudoku game board and the corresponding colored graph.}
  2968. \label{fig:sudoku-graph}
  2969. \end{figure}
  2970. It turns out that some techniques for playing Sudoku correspond to
  2971. heuristics used in graph coloring algorithms. For example, one of the
  2972. basic techniques for Sudoku is called Pencil Marks. The idea is to use
  2973. a process of elimination to determine what numbers are no longer
  2974. available for a square and write down those numbers in the square
  2975. (writing very small). For example, if the number $1$ is assigned to a
  2976. square, then write the pencil mark $1$ in all the squares in the same
  2977. row, column, and region.
  2978. %
  2979. The Pencil Marks technique corresponds to the notion of
  2980. \emph{saturation}\index{saturation} due to \cite{Brelaz:1979eu}. The
  2981. saturation of a vertex, in Sudoku terms, is the set of numbers that
  2982. are no longer available. In graph terminology, we have the following
  2983. definition:
  2984. \begin{equation*}
  2985. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  2986. \text{ and } \mathrm{color}(v) = c \}
  2987. \end{equation*}
  2988. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  2989. edge with $u$.
  2990. Using the Pencil Marks technique leads to a simple strategy for
  2991. filling in numbers: if there is a square with only one possible number
  2992. left, then choose that number! But what if there are no squares with
  2993. only one possibility left? One brute-force approach is to try them
  2994. all: choose the first one and if it ultimately leads to a solution,
  2995. great. If not, backtrack and choose the next possibility. One good
  2996. thing about Pencil Marks is that it reduces the degree of branching in
  2997. the search tree. Nevertheless, backtracking can be horribly time
  2998. consuming. One way to reduce the amount of backtracking is to use the
  2999. most-constrained-first heuristic. That is, when choosing a square,
  3000. always choose one with the fewest possibilities left (the vertex with
  3001. the highest saturation). The idea is that choosing highly constrained
  3002. squares earlier rather than later is better because later on there may
  3003. not be any possibilities left in the highly saturated squares.
  3004. However, register allocation is easier than Sudoku because the
  3005. register allocator can map variables to stack locations when the
  3006. registers run out. Thus, it makes sense to replace backtracking with
  3007. greedy search: make the best choice at the time and keep going. We
  3008. still wish to minimize the number of colors needed, so we use the
  3009. most-constrained-first heuristic in the greedy search.
  3010. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  3011. algorithm for register allocation based on saturation and the
  3012. most-constrained-first heuristic. It is roughly equivalent to the
  3013. DSATUR
  3014. algorithm~\citep{Brelaz:1979eu,Gebremedhin:1999fk,Omari:2006uq}. Just
  3015. as in Sudoku, the algorithm represents colors with integers. The
  3016. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  3017. for register allocation. The integers $k$ and larger correspond to
  3018. stack locations. The registers that are not used for register
  3019. allocation, such as \code{rax}, are assigned to negative integers. In
  3020. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  3021. %% One might wonder why we include registers at all in the liveness
  3022. %% analysis and interference graph, for example, we never allocate a
  3023. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  3024. %% leave them out. As we see in Chapter~\ref{ch:tuples}, when we begin
  3025. %% to use register for passing arguments to functions, it will be
  3026. %% necessary for those registers to appear in the interference graph
  3027. %% because those registers will also be assigned to variables, and we
  3028. %% don't want those two uses to encroach on each other. Regarding
  3029. %% registers such as \code{rax} and \code{rsp} that are not used for
  3030. %% variables, we could omit them from the interference graph but that
  3031. %% would require adding special cases to our algorithm, which would
  3032. %% complicate the logic for little gain.
  3033. \begin{figure}[btp]
  3034. \centering
  3035. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  3036. Algorithm: DSATUR
  3037. Input: a graph |$G$|
  3038. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  3039. |$W \gets \mathrm{vertices}(G)$|
  3040. while |$W \neq \emptyset$| do
  3041. pick a vertex |$u$| from |$W$| with the highest saturation,
  3042. breaking ties randomly
  3043. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  3044. |$\mathrm{color}[u] \gets c$|
  3045. |$W \gets W - \{u\}$|
  3046. \end{lstlisting}
  3047. \caption{The saturation-based greedy graph coloring algorithm.}
  3048. \label{fig:satur-algo}
  3049. \end{figure}
  3050. With the DSATUR algorithm in hand, let us return to the running
  3051. example and consider how to color the interference graph in
  3052. Figure~\ref{fig:interfere}.
  3053. %
  3054. We start by assigning the register nodes to their own color. For
  3055. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  3056. assigned $-2$. The variables are not yet colored, so they are
  3057. annotated with a dash. We then update the saturation for vertices that
  3058. are adjacent to a register, obtaining the following annotated
  3059. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  3060. it interferes with both \code{rax} and \code{rsp}.
  3061. \[
  3062. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3063. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  3064. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  3065. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  3066. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  3067. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3068. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3069. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3070. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3071. \draw (t1) to (rax);
  3072. \draw (t1) to (z);
  3073. \draw (z) to (y);
  3074. \draw (z) to (w);
  3075. \draw (x) to (w);
  3076. \draw (y) to (w);
  3077. \draw (v) to (w);
  3078. \draw (v) to (rsp);
  3079. \draw (w) to (rsp);
  3080. \draw (x) to (rsp);
  3081. \draw (y) to (rsp);
  3082. \path[-.,bend left=15] (z) edge node {} (rsp);
  3083. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3084. \draw (rax) to (rsp);
  3085. \end{tikzpicture}
  3086. \]
  3087. The algorithm says to select a maximally saturated vertex. So we pick
  3088. $\ttm{t}$ and color it with the first available integer, which is
  3089. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  3090. and \ttm{rsp} because they interfere with $\ttm{t}$.
  3091. \[
  3092. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3093. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3094. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  3095. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  3096. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  3097. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3098. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3099. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3100. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3101. \draw (t1) to (rax);
  3102. \draw (t1) to (z);
  3103. \draw (z) to (y);
  3104. \draw (z) to (w);
  3105. \draw (x) to (w);
  3106. \draw (y) to (w);
  3107. \draw (v) to (w);
  3108. \draw (v) to (rsp);
  3109. \draw (w) to (rsp);
  3110. \draw (x) to (rsp);
  3111. \draw (y) to (rsp);
  3112. \path[-.,bend left=15] (z) edge node {} (rsp);
  3113. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3114. \draw (rax) to (rsp);
  3115. \end{tikzpicture}
  3116. \]
  3117. We repeat the process, selecting the next maximally saturated vertex,
  3118. which is \code{z}, and color it with the first available number, which
  3119. is $1$. We add $1$ to the saturation for the neighboring vertices
  3120. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  3121. \[
  3122. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3123. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3124. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3125. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3126. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3127. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3128. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3129. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3130. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3131. \draw (t1) to (rax);
  3132. \draw (t1) to (z);
  3133. \draw (z) to (y);
  3134. \draw (z) to (w);
  3135. \draw (x) to (w);
  3136. \draw (y) to (w);
  3137. \draw (v) to (w);
  3138. \draw (v) to (rsp);
  3139. \draw (w) to (rsp);
  3140. \draw (x) to (rsp);
  3141. \draw (y) to (rsp);
  3142. \path[-.,bend left=15] (z) edge node {} (rsp);
  3143. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3144. \draw (rax) to (rsp);
  3145. \end{tikzpicture}
  3146. \]
  3147. The most saturated vertices are now \code{w} and \code{y}. We color
  3148. \code{w} with the first available color, which is $0$.
  3149. \[
  3150. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3151. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3152. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3153. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3154. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3155. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3156. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  3157. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  3158. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  3159. \draw (t1) to (rax);
  3160. \draw (t1) to (z);
  3161. \draw (z) to (y);
  3162. \draw (z) to (w);
  3163. \draw (x) to (w);
  3164. \draw (y) to (w);
  3165. \draw (v) to (w);
  3166. \draw (v) to (rsp);
  3167. \draw (w) to (rsp);
  3168. \draw (x) to (rsp);
  3169. \draw (y) to (rsp);
  3170. \path[-.,bend left=15] (z) edge node {} (rsp);
  3171. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3172. \draw (rax) to (rsp);
  3173. \end{tikzpicture}
  3174. \]
  3175. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  3176. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  3177. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  3178. and \code{z}, whose colors are $0$ and $1$ respectively.
  3179. \[
  3180. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3181. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3182. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3183. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3184. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3185. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3186. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3187. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3188. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  3189. \draw (t1) to (rax);
  3190. \draw (t1) to (z);
  3191. \draw (z) to (y);
  3192. \draw (z) to (w);
  3193. \draw (x) to (w);
  3194. \draw (y) to (w);
  3195. \draw (v) to (w);
  3196. \draw (v) to (rsp);
  3197. \draw (w) to (rsp);
  3198. \draw (x) to (rsp);
  3199. \draw (y) to (rsp);
  3200. \path[-.,bend left=15] (z) edge node {} (rsp);
  3201. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3202. \draw (rax) to (rsp);
  3203. \end{tikzpicture}
  3204. \]
  3205. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  3206. \[
  3207. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3208. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3209. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3210. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3211. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3212. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3213. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3214. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3215. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3216. \draw (t1) to (rax);
  3217. \draw (t1) to (z);
  3218. \draw (z) to (y);
  3219. \draw (z) to (w);
  3220. \draw (x) to (w);
  3221. \draw (y) to (w);
  3222. \draw (v) to (w);
  3223. \draw (v) to (rsp);
  3224. \draw (w) to (rsp);
  3225. \draw (x) to (rsp);
  3226. \draw (y) to (rsp);
  3227. \path[-.,bend left=15] (z) edge node {} (rsp);
  3228. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3229. \draw (rax) to (rsp);
  3230. \end{tikzpicture}
  3231. \]
  3232. In the last step of the algorithm, we color \code{x} with $1$.
  3233. \[
  3234. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3235. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3236. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3237. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3238. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3239. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  3240. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3241. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3242. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3243. \draw (t1) to (rax);
  3244. \draw (t1) to (z);
  3245. \draw (z) to (y);
  3246. \draw (z) to (w);
  3247. \draw (x) to (w);
  3248. \draw (y) to (w);
  3249. \draw (v) to (w);
  3250. \draw (v) to (rsp);
  3251. \draw (w) to (rsp);
  3252. \draw (x) to (rsp);
  3253. \draw (y) to (rsp);
  3254. \path[-.,bend left=15] (z) edge node {} (rsp);
  3255. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3256. \draw (rax) to (rsp);
  3257. \end{tikzpicture}
  3258. \]
  3259. \begin{wrapfigure}[25]{r}[1.0in]{0.6\textwidth}
  3260. \small
  3261. \begin{tcolorbox}[title=Priority Queue]
  3262. A \emph{priority queue} is a collection of items in which the
  3263. removal of items is governed by priority. In a ``min'' queue,
  3264. lower priority items are removed first. An implementation is in
  3265. \code{priority\_queue.rkt} of the support code. \index{priority
  3266. queue} \index{minimum priority queue}
  3267. \begin{description}
  3268. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  3269. priority queue that uses the $\itm{cmp}$ predicate to determine
  3270. whether its first argument has lower or equal priority to its
  3271. second argument.
  3272. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  3273. items in the queue.
  3274. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  3275. the item into the queue and returns a handle for the item in the
  3276. queue.
  3277. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  3278. the lowest priority.
  3279. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  3280. notifies the queue that the priority has decreased for the item
  3281. associated with the given handle.
  3282. \end{description}
  3283. \end{tcolorbox}
  3284. \end{wrapfigure}
  3285. We recommend creating an auxiliary function named \code{color-graph}
  3286. that takes an interference graph and a list of all the variables in
  3287. the program. This function should return a mapping of variables to
  3288. their colors (represented as natural numbers). By creating this helper
  3289. function, you will be able to reuse it in Chapter~\ref{ch:functions}
  3290. when we add support for functions.
  3291. To prioritize the processing of highly saturated nodes inside the
  3292. \code{color-graph} function, we recommend using the priority queue
  3293. data structure (see the side bar on the right). In addition, you will
  3294. need to maintain a mapping from variables to their ``handles'' in the
  3295. priority queue so that you can notify the priority queue when their
  3296. saturation changes.
  3297. With the coloring complete, we finalize the assignment of variables to
  3298. registers and stack locations. We map the first $k$ colors to the $k$
  3299. registers and the rest of the colors to stack locations. Suppose for
  3300. the moment that we have just one register to use for register
  3301. allocation, \key{rcx}. Then we have the following map from colors to
  3302. locations.
  3303. \[
  3304. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  3305. \]
  3306. Composing this mapping with the coloring, we arrive at the following
  3307. assignment of variables to locations.
  3308. \begin{gather*}
  3309. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  3310. \ttm{w} \mapsto \key{\%rcx}, \,
  3311. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  3312. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  3313. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  3314. \ttm{t} \mapsto \key{\%rcx} \}
  3315. \end{gather*}
  3316. Adapt the code from the \code{assign-homes} pass
  3317. (Section~\ref{sec:assign-r1}) to replace the variables with their
  3318. assigned location. Applying the above assignment to our running
  3319. example, on the left, yields the program on the right.
  3320. % why frame size of 32? -JGS
  3321. \begin{center}
  3322. \begin{minipage}{0.3\textwidth}
  3323. \begin{lstlisting}
  3324. movq $1, v
  3325. movq $42, w
  3326. movq v, x
  3327. addq $7, x
  3328. movq x, y
  3329. movq x, z
  3330. addq w, z
  3331. movq y, t
  3332. negq t
  3333. movq z, %rax
  3334. addq t, %rax
  3335. jmp conclusion
  3336. \end{lstlisting}
  3337. \end{minipage}
  3338. $\Rightarrow\qquad$
  3339. \begin{minipage}{0.45\textwidth}
  3340. \begin{lstlisting}
  3341. movq $1, -8(%rbp)
  3342. movq $42, %rcx
  3343. movq -8(%rbp), -8(%rbp)
  3344. addq $7, -8(%rbp)
  3345. movq -8(%rbp), -16(%rbp)
  3346. movq -8(%rbp), -8(%rbp)
  3347. addq %rcx, -8(%rbp)
  3348. movq -16(%rbp), %rcx
  3349. negq %rcx
  3350. movq -8(%rbp), %rax
  3351. addq %rcx, %rax
  3352. jmp conclusion
  3353. \end{lstlisting}
  3354. \end{minipage}
  3355. \end{center}
  3356. \begin{exercise}\normalfont
  3357. %
  3358. Implement the compiler pass \code{allocate-registers}.
  3359. %
  3360. Create five programs that exercise all of the register allocation
  3361. algorithm, including spilling variables to the stack.
  3362. %
  3363. Replace \code{assign-homes} in the list of \code{passes} in the
  3364. \code{run-tests.rkt} script with the three new passes:
  3365. \code{uncover-live}, \code{build-interference}, and
  3366. \code{allocate-registers}.
  3367. %
  3368. Temporarily remove the \code{print-x86} pass from the list of passes
  3369. and the call to \code{compiler-tests}.
  3370. %
  3371. Run the script to test the register allocator.
  3372. \end{exercise}
  3373. \section{Patch Instructions}
  3374. \label{sec:patch-instructions}
  3375. The remaining step in the compilation to x86 is to ensure that the
  3376. instructions have at most one argument that is a memory access.
  3377. In the running example, the instruction \code{movq -8(\%rbp), -16(\%rbp)}
  3378. is problematic. The fix is to first move \code{-8(\%rbp)}
  3379. into \code{rax} and then move \code{rax} into \code{-16(\%rbp)}.
  3380. %
  3381. The two moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  3382. problematic, but they can be fixed by simply deleting them. In
  3383. general, we recommend deleting all the trivial moves whose source and
  3384. destination are the same location.
  3385. %
  3386. The following is the output of \code{patch-instructions} on the
  3387. running example.
  3388. \begin{center}
  3389. \begin{minipage}{0.4\textwidth}
  3390. \begin{lstlisting}
  3391. movq $1, -8(%rbp)
  3392. movq $42, %rcx
  3393. movq -8(%rbp), -8(%rbp)
  3394. addq $7, -8(%rbp)
  3395. movq -8(%rbp), -16(%rbp)
  3396. movq -8(%rbp), -8(%rbp)
  3397. addq %rcx, -8(%rbp)
  3398. movq -16(%rbp), %rcx
  3399. negq %rcx
  3400. movq -8(%rbp), %rax
  3401. addq %rcx, %rax
  3402. jmp conclusion
  3403. \end{lstlisting}
  3404. \end{minipage}
  3405. $\Rightarrow\qquad$
  3406. \begin{minipage}{0.45\textwidth}
  3407. \begin{lstlisting}
  3408. movq $1, -8(%rbp)
  3409. movq $42, %rcx
  3410. addq $7, -8(%rbp)
  3411. movq -8(%rbp), %rax
  3412. movq %rax, -16(%rbp)
  3413. addq %rcx, -8(%rbp)
  3414. movq -16(%rbp), %rcx
  3415. negq %rcx
  3416. movq -8(%rbp), %rax
  3417. addq %rcx, %rax
  3418. jmp conclusion
  3419. \end{lstlisting}
  3420. \end{minipage}
  3421. \end{center}
  3422. \begin{exercise}\normalfont
  3423. %
  3424. Implement the \code{patch-instructions} compiler pass.
  3425. %
  3426. Insert it after \code{allocate-registers} in the list of \code{passes}
  3427. in the \code{run-tests.rkt} script.
  3428. %
  3429. Run the script to test the \code{patch-instructions} pass.
  3430. \end{exercise}
  3431. \section{Print x86}
  3432. \label{sec:print-x86-reg-alloc}
  3433. \index{calling conventions}
  3434. \index{prelude}\index{conclusion}
  3435. Recall that the \code{print-x86} pass generates the prelude and
  3436. conclusion instructions to satisfy the x86 calling conventions
  3437. (Section~\ref{sec:calling-conventions}). With the addition of the
  3438. register allocator, the callee-saved registers used by the register
  3439. allocator must be saved in the prelude and restored in the conclusion.
  3440. In the \code{allocate-registers} pass, add an entry to the \itm{info}
  3441. of \code{X86Program} named \code{used-callee} that stores the set of
  3442. callee-saved registers that were assigned to variables. The
  3443. \code{print-x86} pass can then access this information to decide which
  3444. callee-saved registers need to be saved and restored.
  3445. %
  3446. When calculating the size of the frame to adjust the \code{rsp} in the
  3447. prelude, make sure to take into account the space used for saving the
  3448. callee-saved registers. Also, don't forget that the frame needs to be
  3449. a multiple of 16 bytes!
  3450. An overview of all of the passes involved in register allocation is
  3451. shown in Figure~\ref{fig:reg-alloc-passes}.
  3452. \begin{figure}[tbp]
  3453. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3454. \node (Rvar) at (0,2) {\large \LangVar{}};
  3455. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  3456. \node (Rvar-3) at (6,2) {\large \LangVar{}};
  3457. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  3458. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  3459. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  3460. \node (x86-4) at (9,-2) {\large \LangXASTInt{}};
  3461. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  3462. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  3463. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  3464. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  3465. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvar-3);
  3466. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate-control} (Cvar-1);
  3467. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  3468. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  3469. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  3470. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  3471. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  3472. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  3473. \end{tikzpicture}
  3474. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  3475. \label{fig:reg-alloc-passes}
  3476. \end{figure}
  3477. \begin{exercise}\normalfont
  3478. Update the \code{print-x86} pass as described in this section.
  3479. %
  3480. In the \code{run-tests.rkt} script, reinstate \code{print-x86} in the
  3481. list of passes and the call to \code{compiler-tests}.
  3482. %
  3483. Run the script to test the complete compiler for \LangVar{} that
  3484. performs register allocation.
  3485. \end{exercise}
  3486. \section{Challenge: Move Biasing}
  3487. \label{sec:move-biasing}
  3488. \index{move biasing}
  3489. This section describes an enhancement to the register allocator for
  3490. students looking for an extra challenge or who have a deeper interest
  3491. in register allocation.
  3492. To motivate the need for move biasing we return to the running example
  3493. but this time use all of the general purpose registers. So we have
  3494. the following mapping of color numbers to registers.
  3495. \[
  3496. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi} \}
  3497. \]
  3498. Using the same assignment of variables to color numbers that was
  3499. produced by the register allocator described in the last section, we
  3500. get the following program.
  3501. \begin{center}
  3502. \begin{minipage}{0.3\textwidth}
  3503. \begin{lstlisting}
  3504. movq $1, v
  3505. movq $42, w
  3506. movq v, x
  3507. addq $7, x
  3508. movq x, y
  3509. movq x, z
  3510. addq w, z
  3511. movq y, t
  3512. negq t
  3513. movq z, %rax
  3514. addq t, %rax
  3515. jmp conclusion
  3516. \end{lstlisting}
  3517. \end{minipage}
  3518. $\Rightarrow\qquad$
  3519. \begin{minipage}{0.45\textwidth}
  3520. \begin{lstlisting}
  3521. movq $1, %rdx
  3522. movq $42, %rcx
  3523. movq %rdx, %rdx
  3524. addq $7, %rdx
  3525. movq %rdx, %rsi
  3526. movq %rdx, %rdx
  3527. addq %rcx, %rdx
  3528. movq %rsi, %rcx
  3529. negq %rcx
  3530. movq %rdx, %rax
  3531. addq %rcx, %rax
  3532. jmp conclusion
  3533. \end{lstlisting}
  3534. \end{minipage}
  3535. \end{center}
  3536. In the above output code there are two \key{movq} instructions that
  3537. can be removed because their source and target are the same. However,
  3538. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  3539. register, we could instead remove three \key{movq} instructions. We
  3540. can accomplish this by taking into account which variables appear in
  3541. \key{movq} instructions with which other variables.
  3542. We say that two variables $p$ and $q$ are \emph{move
  3543. related}\index{move related} if they participate together in a
  3544. \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  3545. \key{movq} $q$\key{,} $p$. When the register allocator chooses a color
  3546. for a variable, it should prefer a color that has already been used
  3547. for a move-related variable (assuming that they do not interfere). Of
  3548. course, this preference should not override the preference for
  3549. registers over stack locations. This preference should be used as a
  3550. tie breaker when choosing between registers or when choosing between
  3551. stack locations.
  3552. We recommend representing the move relationships in a graph, similar
  3553. to how we represented interference. The following is the \emph{move
  3554. graph} for our running example.
  3555. \[
  3556. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3557. \node (rax) at (0,0) {$\ttm{rax}$};
  3558. \node (rsp) at (9,2) {$\ttm{rsp}$};
  3559. \node (t) at (0,2) {$\ttm{t}$};
  3560. \node (z) at (3,2) {$\ttm{z}$};
  3561. \node (x) at (6,2) {$\ttm{x}$};
  3562. \node (y) at (3,0) {$\ttm{y}$};
  3563. \node (w) at (6,0) {$\ttm{w}$};
  3564. \node (v) at (9,0) {$\ttm{v}$};
  3565. \draw (v) to (x);
  3566. \draw (x) to (y);
  3567. \draw (x) to (z);
  3568. \draw (y) to (t);
  3569. \end{tikzpicture}
  3570. \]
  3571. Now we replay the graph coloring, pausing to see the coloring of
  3572. \code{y}. Recall the following configuration. The most saturated vertices
  3573. were \code{w} and \code{y}.
  3574. \[
  3575. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3576. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3577. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3578. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3579. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3580. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3581. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3582. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3583. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  3584. \draw (t1) to (rax);
  3585. \draw (t1) to (z);
  3586. \draw (z) to (y);
  3587. \draw (z) to (w);
  3588. \draw (x) to (w);
  3589. \draw (y) to (w);
  3590. \draw (v) to (w);
  3591. \draw (v) to (rsp);
  3592. \draw (w) to (rsp);
  3593. \draw (x) to (rsp);
  3594. \draw (y) to (rsp);
  3595. \path[-.,bend left=15] (z) edge node {} (rsp);
  3596. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3597. \draw (rax) to (rsp);
  3598. \end{tikzpicture}
  3599. \]
  3600. %
  3601. Last time we chose to color \code{w} with $0$. But this time we see
  3602. that \code{w} is not move related to any vertex, but \code{y} is move
  3603. related to \code{t}. So we choose to color \code{y} the same color as
  3604. \code{t}, $0$.
  3605. \[
  3606. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3607. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3608. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3609. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3610. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3611. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3612. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  3613. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  3614. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  3615. \draw (t1) to (rax);
  3616. \draw (t1) to (z);
  3617. \draw (z) to (y);
  3618. \draw (z) to (w);
  3619. \draw (x) to (w);
  3620. \draw (y) to (w);
  3621. \draw (v) to (w);
  3622. \draw (v) to (rsp);
  3623. \draw (w) to (rsp);
  3624. \draw (x) to (rsp);
  3625. \draw (y) to (rsp);
  3626. \path[-.,bend left=15] (z) edge node {} (rsp);
  3627. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3628. \draw (rax) to (rsp);
  3629. \end{tikzpicture}
  3630. \]
  3631. Now \code{w} is the most saturated, so we color it $2$.
  3632. \[
  3633. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3634. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3635. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3636. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3637. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3638. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  3639. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  3640. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  3641. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  3642. \draw (t1) to (rax);
  3643. \draw (t1) to (z);
  3644. \draw (z) to (y);
  3645. \draw (z) to (w);
  3646. \draw (x) to (w);
  3647. \draw (y) to (w);
  3648. \draw (v) to (w);
  3649. \draw (v) to (rsp);
  3650. \draw (w) to (rsp);
  3651. \draw (x) to (rsp);
  3652. \draw (y) to (rsp);
  3653. \path[-.,bend left=15] (z) edge node {} (rsp);
  3654. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3655. \draw (rax) to (rsp);
  3656. \end{tikzpicture}
  3657. \]
  3658. At this point, vertices \code{x} and \code{v} are most saturated, but
  3659. \code{x} is move related to \code{y} and \code{z}, so we color
  3660. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  3661. \[
  3662. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3663. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3664. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3665. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  3666. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3667. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  3668. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  3669. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  3670. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  3671. \draw (t1) to (rax);
  3672. \draw (t) to (z);
  3673. \draw (z) to (y);
  3674. \draw (z) to (w);
  3675. \draw (x) to (w);
  3676. \draw (y) to (w);
  3677. \draw (v) to (w);
  3678. \draw (v) to (rsp);
  3679. \draw (w) to (rsp);
  3680. \draw (x) to (rsp);
  3681. \draw (y) to (rsp);
  3682. \path[-.,bend left=15] (z) edge node {} (rsp);
  3683. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3684. \draw (rax) to (rsp);
  3685. \end{tikzpicture}
  3686. \]
  3687. So we have the following assignment of variables to registers.
  3688. \begin{gather*}
  3689. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  3690. \ttm{w} \mapsto \key{\%rsi}, \,
  3691. \ttm{x} \mapsto \key{\%rcx}, \,
  3692. \ttm{y} \mapsto \key{\%rcx}, \,
  3693. \ttm{z} \mapsto \key{\%rdx}, \,
  3694. \ttm{t} \mapsto \key{\%rcx} \}
  3695. \end{gather*}
  3696. We apply this register assignment to the running example, on the left,
  3697. to obtain the code in the middle. The \code{patch-instructions} then
  3698. removes the three trivial moves to obtain the code on the right.
  3699. \begin{minipage}{0.25\textwidth}
  3700. \begin{lstlisting}
  3701. movq $1, v
  3702. movq $42, w
  3703. movq v, x
  3704. addq $7, x
  3705. movq x, y
  3706. movq x, z
  3707. addq w, z
  3708. movq y, t
  3709. negq t
  3710. movq z, %rax
  3711. addq t, %rax
  3712. jmp conclusion
  3713. \end{lstlisting}
  3714. \end{minipage}
  3715. $\Rightarrow\qquad$
  3716. \begin{minipage}{0.25\textwidth}
  3717. \begin{lstlisting}
  3718. movq $1, %rcx
  3719. movq $42, %rsi
  3720. movq %rcx, %rcx
  3721. addq $7, %rcx
  3722. movq %rcx, %rcx
  3723. movq %rcx, %rdx
  3724. addq %rsi, %rdx
  3725. movq %rcx, %rcx
  3726. negq %rcx
  3727. movq %rdx, %rax
  3728. addq %rcx, %rax
  3729. jmp conclusion
  3730. \end{lstlisting}
  3731. \end{minipage}
  3732. $\Rightarrow\qquad$
  3733. \begin{minipage}{0.25\textwidth}
  3734. \begin{lstlisting}
  3735. movq $1, %rcx
  3736. movq $42, %rsi
  3737. addq $7, %rcx
  3738. movq %rcx, %rdx
  3739. addq %rsi, %rdx
  3740. negq %rcx
  3741. movq %rdx, %rax
  3742. addq %rcx, %rax
  3743. jmp conclusion
  3744. \end{lstlisting}
  3745. \end{minipage}
  3746. \begin{exercise}\normalfont
  3747. Change your implementation of \code{allocate-registers} to take move
  3748. biasing into account. Create two new tests that include at least one
  3749. opportunity for move biasing and visually inspect the output x86
  3750. programs to make sure that your move biasing is working properly. Make
  3751. sure that your compiler still passes all of the tests.
  3752. \end{exercise}
  3753. \margincomment{\footnotesize To do: another neat challenge would be to do
  3754. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3755. %% \subsection{Output of the Running Example}
  3756. %% \label{sec:reg-alloc-output}
  3757. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  3758. the running example (Figure~\ref{fig:reg-eg}) with register allocation
  3759. and move biasing. To demonstrate both the use of registers and the
  3760. stack, we have limited the register allocator to use just two
  3761. registers: \code{rbx} and \code{rcx}. In the prelude\index{prelude}
  3762. of the \code{main} function, we push \code{rbx} onto the stack because
  3763. it is a callee-saved register and it was assigned to variable by the
  3764. register allocator. We subtract \code{8} from the \code{rsp} at the
  3765. end of the prelude to reserve space for the one spilled variable.
  3766. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  3767. Moving on the the \code{start} block, we see how the registers were
  3768. allocated. Variables \code{v}, \code{x}, and \code{y} were assigned to
  3769. \code{rbx} and variable \code{z} was assigned to \code{rcx}. Variable
  3770. \code{w} was spilled to the stack location \code{-16(\%rbp)}. Recall
  3771. that the prelude saved the callee-save register \code{rbx} onto the
  3772. stack. The spilled variables must be placed lower on the stack than
  3773. the saved callee-save registers, so in this case \code{w} is placed at
  3774. \code{-16(\%rbp)}.
  3775. In the \code{conclusion}\index{conclusion}, we undo the work that was
  3776. done in the prelude. We move the stack pointer up by \code{8} bytes
  3777. (the room for spilled variables), then we pop the old values of
  3778. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  3779. \code{retq} to return control to the operating system.
  3780. \begin{figure}[tbp]
  3781. % s0_28.rkt
  3782. % (use-minimal-set-of-registers! #t)
  3783. % and only rbx rcx
  3784. % tmp 0 rbx
  3785. % z 1 rcx
  3786. % y 0 rbx
  3787. % w 2 16(%rbp)
  3788. % v 0 rbx
  3789. % x 0 rbx
  3790. \begin{lstlisting}
  3791. start:
  3792. movq $1, %rbx
  3793. movq $42, -16(%rbp)
  3794. addq $7, %rbx
  3795. movq %rbx, %rcx
  3796. addq -16(%rbp), %rcx
  3797. negq %rbx
  3798. movq %rcx, %rax
  3799. addq %rbx, %rax
  3800. jmp conclusion
  3801. .globl main
  3802. main:
  3803. pushq %rbp
  3804. movq %rsp, %rbp
  3805. pushq %rbx
  3806. subq $8, %rsp
  3807. jmp start
  3808. conclusion:
  3809. addq $8, %rsp
  3810. popq %rbx
  3811. popq %rbp
  3812. retq
  3813. \end{lstlisting}
  3814. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  3815. \label{fig:running-example-x86}
  3816. \end{figure}
  3817. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3818. \chapter{Booleans and Control Flow}
  3819. \label{ch:bool-types}
  3820. \index{Boolean}
  3821. \index{control flow}
  3822. \index{conditional expression}
  3823. The \LangInt{} and \LangVar{} languages only have a single kind of
  3824. value, integers. In this chapter we add a second kind of value, the
  3825. Booleans, to create the \LangIf{} language. The Boolean values
  3826. \emph{true} and \emph{false} are written \key{\#t} and \key{\#f}
  3827. respectively in Racket. The \LangIf{} language includes several
  3828. operations that involve Booleans (\key{and}, \key{not}, \key{eq?},
  3829. \key{<}, etc.) and the conditional \key{if} expression. With the
  3830. addition of \key{if}, programs can have non-trivial control flow which
  3831. impacts \code{explicate-control} and liveness analysis. Also, because
  3832. we now have two kinds of values, we need to handle programs that apply
  3833. an operation to the wrong kind of value, such as \code{(not 1)}.
  3834. There are two language design options for such situations. One option
  3835. is to signal an error and the other is to provide a wider
  3836. interpretation of the operation. The Racket language uses a mixture of
  3837. these two options, depending on the operation and the kind of
  3838. value. For example, the result of \code{(not 1)} in Racket is
  3839. \code{\#f} because Racket treats non-zero integers as if they were
  3840. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  3841. error in Racket because \code{car} expects a pair.
  3842. Typed Racket makes similar design choices as Racket, except much of
  3843. the error detection happens at compile time instead of run time. Typed
  3844. Racket accepts and runs \code{(not 1)}, producing \code{\#f}. But in
  3845. the case of \code{(car 1)}, Typed Racket reports a compile-time error
  3846. because Typed Racket expects the type of the argument to be of the
  3847. form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  3848. The \LangIf{} language performs type checking during compilation like
  3849. Typed Racket. In Chapter~\ref{ch:type-dynamic} we study the
  3850. alternative choice, that is, a dynamically typed language like Racket.
  3851. The \LangIf{} language is a subset of Typed Racket; for some
  3852. operations we are more restrictive, for example, rejecting
  3853. \code{(not 1)}.
  3854. This chapter is organized as follows. We begin by defining the syntax
  3855. and interpreter for the \LangIf{} language
  3856. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  3857. checking and build a type checker for \LangIf{}
  3858. (Section~\ref{sec:type-check-Rif}). To compile \LangIf{} we need to
  3859. enlarge the intermediate language \LangCVar{} into \LangCIf{}
  3860. (Section~\ref{sec:Cif}) and \LangXASTInt{} into \LangXASTIf{}
  3861. (Section~\ref{sec:x86-if}). The remaining sections of this chapter
  3862. discuss how our compiler passes change to accommodate Booleans and
  3863. conditional control flow. There is one new pass, named \code{shrink},
  3864. that translates some operators into others, thereby reducing the
  3865. number of operators that need to be handled in later passes. The
  3866. largest changes occur in \code{explicate-control}, to translate
  3867. \code{if} expressions into control-flow graphs
  3868. (Section~\ref{sec:explicate-control-Rif}). Regarding register
  3869. allocation, the liveness analysis now has multiple basic blocks to
  3870. process and there is the interesting question of how to handle
  3871. conditional jumps.
  3872. \section{The \LangIf{} Language}
  3873. \label{sec:lang-if}
  3874. The concrete syntax of the \LangIf{} language is defined in
  3875. Figure~\ref{fig:Rif-concrete-syntax} and the abstract syntax is defined
  3876. in Figure~\ref{fig:Rif-syntax}. The \LangIf{} language includes all of
  3877. \LangVar{} (shown in gray), the Boolean literals \code{\#t} and
  3878. \code{\#f}, and the conditional \code{if} expression. We expand the
  3879. operators to include
  3880. \begin{enumerate}
  3881. \item subtraction on integers,
  3882. \item the logical operators \key{and}, \key{or} and \key{not},
  3883. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  3884. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  3885. comparing integers.
  3886. \end{enumerate}
  3887. We reorganize the abstract syntax for the primitive operations in
  3888. Figure~\ref{fig:Rif-syntax}, using only one grammar rule for all of
  3889. them. This means that the grammar no longer checks whether the arity
  3890. of an operators matches the number of arguments. That responsibility
  3891. is moved to the type checker for \LangIf{}, which we introduce in
  3892. Section~\ref{sec:type-check-Rif}.
  3893. \begin{figure}[tp]
  3894. \centering
  3895. \fbox{
  3896. \begin{minipage}{0.96\textwidth}
  3897. \[
  3898. \begin{array}{lcl}
  3899. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3900. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3901. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} } \mid \CSUB{\Exp}{\Exp} \\
  3902. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} } \\
  3903. &\mid& \itm{bool}
  3904. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  3905. \mid (\key{not}\;\Exp) \\
  3906. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} \\
  3907. \LangIf{} &::=& \Exp
  3908. \end{array}
  3909. \]
  3910. \end{minipage}
  3911. }
  3912. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  3913. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  3914. \label{fig:Rif-concrete-syntax}
  3915. \end{figure}
  3916. \begin{figure}[tp]
  3917. \centering
  3918. \fbox{
  3919. \begin{minipage}{0.96\textwidth}
  3920. \[
  3921. \begin{array}{lcl}
  3922. \itm{bool} &::=& \code{\#t} \mid \code{\#f} \\
  3923. \itm{cmp} &::= & \code{eq?} \mid \code{<} \mid \code{<=} \mid \code{>} \mid \code{>=} \\
  3924. \itm{op} &::= & \itm{cmp} \mid \code{read} \mid \code{+} \mid \code{-}
  3925. \mid \code{and} \mid \code{or} \mid \code{not} \\
  3926. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  3927. &\mid& \PRIM{\itm{op}}{\Exp\ldots}\\
  3928. &\mid& \BOOL{\itm{bool}} \mid \IF{\Exp}{\Exp}{\Exp} \\
  3929. \LangIf{} &::=& \PROGRAM{\code{'()}}{\Exp}
  3930. \end{array}
  3931. \]
  3932. \end{minipage}
  3933. }
  3934. \caption{The abstract syntax of \LangIf{}.}
  3935. \label{fig:Rif-syntax}
  3936. \end{figure}
  3937. Figure~\ref{fig:interp-Rif} defines the interpreter for \LangIf{},
  3938. which inherits from the interpreter for \LangVar{}
  3939. (Figure~\ref{fig:interp-Rvar}). The literals \code{\#t} and \code{\#f}
  3940. evaluate to the corresponding Boolean values. The conditional
  3941. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  3942. \itm{cnd} and then either evaluates \itm{thn} or \itm{els} depending
  3943. on whether \itm{cnd} produced \code{\#t} or \code{\#f}. The logical
  3944. operations \code{not} and \code{and} behave as you might expect, but
  3945. note that the \code{and} operation is short-circuiting. That is, given
  3946. the expression $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not
  3947. evaluated if $e_1$ evaluates to \code{\#f}.
  3948. With the increase in the number of primitive operations, the
  3949. interpreter would become repetitive without some care. We refactor
  3950. the clause for \code{Prim}, moving the code that differs with each
  3951. operation into the \code{interp-op} method shown in in
  3952. Figure~\ref{fig:interp-op-Rif}. We handle the \code{and} operation
  3953. separately because of its short-circuiting behavior.
  3954. \begin{figure}[tbp]
  3955. \begin{lstlisting}
  3956. (define interp-Rif-class
  3957. (class interp-Rvar-class
  3958. (super-new)
  3959. (define/public (interp-op op) ...)
  3960. (define/override ((interp-exp env) e)
  3961. (define recur (interp-exp env))
  3962. (match e
  3963. [(Bool b) b]
  3964. [(If cnd thn els)
  3965. (match (recur cnd)
  3966. [#t (recur thn)]
  3967. [#f (recur els)])]
  3968. [(Prim 'and (list e1 e2))
  3969. (match (recur e1)
  3970. [#t (match (recur e2) [#t #t] [#f #f])]
  3971. [#f #f])]
  3972. [(Prim op args)
  3973. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  3974. [else ((super interp-exp env) e)]))
  3975. ))
  3976. (define (interp-Rif p)
  3977. (send (new interp-Rif-class) interp-program p))
  3978. \end{lstlisting}
  3979. \caption{Interpreter for the \LangIf{} language. (See
  3980. Figure~\ref{fig:interp-op-Rif} for \code{interp-op}.)}
  3981. \label{fig:interp-Rif}
  3982. \end{figure}
  3983. \begin{figure}[tbp]
  3984. \begin{lstlisting}
  3985. (define/public (interp-op op)
  3986. (match op
  3987. ['+ fx+]
  3988. ['- fx-]
  3989. ['read read-fixnum]
  3990. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  3991. ['or (lambda (v1 v2)
  3992. (cond [(and (boolean? v1) (boolean? v2))
  3993. (or v1 v2)]))]
  3994. ['eq? (lambda (v1 v2)
  3995. (cond [(or (and (fixnum? v1) (fixnum? v2))
  3996. (and (boolean? v1) (boolean? v2))
  3997. (and (vector? v1) (vector? v2)))
  3998. (eq? v1 v2)]))]
  3999. ['< (lambda (v1 v2)
  4000. (cond [(and (fixnum? v1) (fixnum? v2))
  4001. (< v1 v2)]))]
  4002. ['<= (lambda (v1 v2)
  4003. (cond [(and (fixnum? v1) (fixnum? v2))
  4004. (<= v1 v2)]))]
  4005. ['> (lambda (v1 v2)
  4006. (cond [(and (fixnum? v1) (fixnum? v2))
  4007. (> v1 v2)]))]
  4008. ['>= (lambda (v1 v2)
  4009. (cond [(and (fixnum? v1) (fixnum? v2))
  4010. (>= v1 v2)]))]
  4011. [else (error 'interp-op "unknown operator")]))
  4012. \end{lstlisting}
  4013. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  4014. \label{fig:interp-op-Rif}
  4015. \end{figure}
  4016. \section{Type Checking \LangIf{} Programs}
  4017. \label{sec:type-check-Rif}
  4018. \index{type checking}
  4019. \index{semantic analysis}
  4020. It is helpful to think about type checking in two complementary
  4021. ways. A type checker predicts the type of value that will be produced
  4022. by each expression in the program. For \LangIf{}, we have just two types,
  4023. \key{Integer} and \key{Boolean}. So a type checker should predict that
  4024. \begin{lstlisting}
  4025. (+ 10 (- (+ 12 20)))
  4026. \end{lstlisting}
  4027. produces an \key{Integer} while
  4028. \begin{lstlisting}
  4029. (and (not #f) #t)
  4030. \end{lstlisting}
  4031. produces a \key{Boolean}.
  4032. Another way to think about type checking is that it enforces a set of
  4033. rules about which operators can be applied to which kinds of
  4034. values. For example, our type checker for \LangIf{} signals an error
  4035. for the below expression
  4036. \begin{lstlisting}
  4037. (not (+ 10 (- (+ 12 20))))
  4038. \end{lstlisting}
  4039. The subexpression \code{(+ 10 (- (+ 12 20)))} has type \key{Integer}
  4040. but the type checker enforces the rule that the argument of \code{not}
  4041. must be a \key{Boolean}.
  4042. We implement type checking using classes and methods because they
  4043. provide the open recursion needed to reuse code as we extend the type
  4044. checker in later chapters, analogous to the use of classes and methods
  4045. for the interpreters (Section~\ref{sec:extensible-interp}).
  4046. We separate the type checker for the \LangVar{} fragment into its own
  4047. class, shown in Figure~\ref{fig:type-check-Rvar}. The type checker for
  4048. \LangIf{} is shown in Figure~\ref{fig:type-check-Rif} and it inherits
  4049. from the type checker for \LangVar{}. These type checkers are in the
  4050. files \code{type-check-Rvar.rkt} and \code{type-check-Rif.rkt} of the
  4051. support code.
  4052. %
  4053. Each type checker is a structurally recursive function over the AST.
  4054. Given an input expression \code{e}, the type checker either signals an
  4055. error or returns an expression and its type (\key{Integer} or
  4056. \key{Boolean}). It returns an expression because there are situations
  4057. in which we want to change or update the expression.
  4058. Next we discuss the \code{match} clauses in \code{type-check-exp} of
  4059. Figure~\ref{fig:type-check-Rvar}. The type of an integer constant is
  4060. \code{Integer}. To handle variables, the type checker uses the
  4061. environment \code{env} to map variables to types. Consider the clause
  4062. for \key{let}. We type check the initializing expression to obtain
  4063. its type \key{T} and then associate type \code{T} with the variable
  4064. \code{x} in the environment used to type check the body of the
  4065. \key{let}. Thus, when the type checker encounters a use of variable
  4066. \code{x}, it can find its type in the environment. Regarding
  4067. primitive operators, we recursively analyze the arguments and then
  4068. invoke \code{type-check-op} to check whether the argument types are
  4069. allowed.
  4070. Several auxiliary methods are used in the type checker. The method
  4071. \code{operator-types} defines a dictionary that maps the operator
  4072. names to their parameter and return types. The \code{type-equal?}
  4073. method determines whether two types are equal, which for now simply
  4074. dispatches to \code{equal?} (deep equality). The
  4075. \code{check-type-equal?} method triggers an error if the two types are
  4076. not equal. The \code{type-check-op} method looks up the operator in
  4077. the \code{operator-types} dictionary and then checks whether the
  4078. argument types are equal to the parameter types. The result is the
  4079. return type of the operator.
  4080. \begin{figure}[tbp]
  4081. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4082. (define type-check-Rvar-class
  4083. (class object%
  4084. (super-new)
  4085. (define/public (operator-types)
  4086. '((+ . ((Integer Integer) . Integer))
  4087. (- . ((Integer) . Integer))
  4088. (read . (() . Integer))))
  4089. (define/public (type-equal? t1 t2) (equal? t1 t2))
  4090. (define/public (check-type-equal? t1 t2 e)
  4091. (unless (type-equal? t1 t2)
  4092. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  4093. (define/public (type-check-op op arg-types e)
  4094. (match (dict-ref (operator-types) op)
  4095. [`(,param-types . ,return-type)
  4096. (for ([at arg-types] [pt param-types])
  4097. (check-type-equal? at pt e))
  4098. return-type]
  4099. [else (error 'type-check-op "unrecognized ~a" op)]))
  4100. (define/public (type-check-exp env)
  4101. (lambda (e)
  4102. (match e
  4103. [(Int n) (values (Int n) 'Integer)]
  4104. [(Var x) (values (Var x) (dict-ref env x))]
  4105. [(Let x e body)
  4106. (define-values (e^ Te) ((type-check-exp env) e))
  4107. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  4108. (values (Let x e^ b) Tb)]
  4109. [(Prim op es)
  4110. (define-values (new-es ts)
  4111. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  4112. (values (Prim op new-es) (type-check-op op ts e))]
  4113. [else (error 'type-check-exp "couldn't match" e)])))
  4114. (define/public (type-check-program e)
  4115. (match e
  4116. [(Program info body)
  4117. (define-values (body^ Tb) ((type-check-exp '()) body))
  4118. (check-type-equal? Tb 'Integer body)
  4119. (Program info body^)]
  4120. [else (error 'type-check-Rvar "couldn't match ~a" e)]))
  4121. ))
  4122. (define (type-check-Rvar p)
  4123. (send (new type-check-Rvar-class) type-check-program p))
  4124. \end{lstlisting}
  4125. \caption{Type checker for the \LangVar{} language.}
  4126. \label{fig:type-check-Rvar}
  4127. \end{figure}
  4128. \begin{figure}[tbp]
  4129. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4130. (define type-check-Rif-class
  4131. (class type-check-Rvar-class
  4132. (super-new)
  4133. (inherit check-type-equal?)
  4134. (define/override (operator-types)
  4135. (append '((- . ((Integer Integer) . Integer))
  4136. (and . ((Boolean Boolean) . Boolean))
  4137. (or . ((Boolean Boolean) . Boolean))
  4138. (< . ((Integer Integer) . Boolean))
  4139. (<= . ((Integer Integer) . Boolean))
  4140. (> . ((Integer Integer) . Boolean))
  4141. (>= . ((Integer Integer) . Boolean))
  4142. (not . ((Boolean) . Boolean))
  4143. )
  4144. (super operator-types)))
  4145. (define/override (type-check-exp env)
  4146. (lambda (e)
  4147. (match e
  4148. [(Prim 'eq? (list e1 e2))
  4149. (define-values (e1^ T1) ((type-check-exp env) e1))
  4150. (define-values (e2^ T2) ((type-check-exp env) e2))
  4151. (check-type-equal? T1 T2 e)
  4152. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  4153. [(Bool b) (values (Bool b) 'Boolean)]
  4154. [(If cnd thn els)
  4155. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  4156. (define-values (thn^ Tt) ((type-check-exp env) thn))
  4157. (define-values (els^ Te) ((type-check-exp env) els))
  4158. (check-type-equal? Tc 'Boolean e)
  4159. (check-type-equal? Tt Te e)
  4160. (values (If cnd^ thn^ els^) Te)]
  4161. [else ((super type-check-exp env) e)])))
  4162. ))
  4163. (define (type-check-Rif p)
  4164. (send (new type-check-Rif-class) type-check-program p))
  4165. \end{lstlisting}
  4166. \caption{Type checker for the \LangIf{} language.}
  4167. \label{fig:type-check-Rif}
  4168. \end{figure}
  4169. Next we discuss the type checker for \LangIf{} in
  4170. Figure~\ref{fig:type-check-Rif}. The operator \code{eq?} requires the
  4171. two arguments to have the same type. The type of a Boolean constant is
  4172. \code{Boolean}. The condition of an \code{if} must be of
  4173. \code{Boolean} type and the two branches must have the same type. The
  4174. \code{operator-types} function adds dictionary entries for the other
  4175. new operators.
  4176. \begin{exercise}\normalfont
  4177. Create 10 new test programs in \LangIf{}. Half of the programs should
  4178. have a type error. For those programs, create an empty file with the
  4179. same base name but with file extension \code{.tyerr}. For example, if
  4180. the test \code{cond\_test\_14.rkt} is expected to error, then create
  4181. an empty file named \code{cond\_test\_14.tyerr}. This indicates to
  4182. \code{interp-tests} and \code{compiler-tests} that a type error is
  4183. expected. The other half of the test programs should not have type
  4184. errors.
  4185. In the \code{run-tests.rkt} script, change the second argument of
  4186. \code{interp-tests} and \code{compiler-tests} to
  4187. \code{type-check-Rif}, which causes the type checker to run prior to
  4188. the compiler passes. Temporarily change the \code{passes} to an empty
  4189. list and run the script, thereby checking that the new test programs
  4190. either type check or not as intended.
  4191. \end{exercise}
  4192. \section{The \LangCIf{} Intermediate Language}
  4193. \label{sec:Cif}
  4194. Figure~\ref{fig:c1-syntax} defines the abstract syntax of the
  4195. \LangCIf{} intermediate language. (The concrete syntax is in the
  4196. Appendix, Figure~\ref{fig:c1-concrete-syntax}.) Compared to
  4197. \LangCVar{}, the \LangCIf{} language adds logical and comparison
  4198. operators to the \Exp{} non-terminal and the literals \key{\#t} and
  4199. \key{\#f} to the \Arg{} non-terminal.
  4200. Regarding control flow, \LangCIf{} adds \key{goto} and \code{if}
  4201. statements to the \Tail{} non-terminal. The condition of an \code{if}
  4202. statement is a comparison operation and the branches are \code{goto}
  4203. statements, making it straightforward to compile \code{if} statements
  4204. to x86.
  4205. \begin{figure}[tp]
  4206. \fbox{
  4207. \begin{minipage}{0.96\textwidth}
  4208. \small
  4209. \[
  4210. \begin{array}{lcl}
  4211. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  4212. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  4213. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  4214. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4215. &\mid& \UNIOP{\key{'not}}{\Atm}
  4216. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  4217. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  4218. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  4219. \mid \GOTO{\itm{label}} \\
  4220. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  4221. \LangCIf{} & ::= & \gray{\CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}}
  4222. \end{array}
  4223. \]
  4224. \end{minipage}
  4225. }
  4226. \caption{The abstract syntax of \LangCIf{}, an extension of \LangCVar{}
  4227. (Figure~\ref{fig:c0-syntax}).}
  4228. \label{fig:c1-syntax}
  4229. \end{figure}
  4230. \section{The \LangXASTIf{} Language}
  4231. \label{sec:x86-if}
  4232. \index{x86} To implement the new logical operations, the comparison
  4233. operations, and the \key{if} expression, we need to delve further into
  4234. the x86 language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1}
  4235. define the concrete and abstract syntax for the \LangXASTIf{} subset
  4236. of x86, which includes instructions for logical operations,
  4237. comparisons, and conditional jumps.
  4238. One challenge is that x86 does not provide an instruction that
  4239. directly implements logical negation (\code{not} in \LangIf{} and
  4240. \LangCIf{}). However, the \code{xorq} instruction can be used to
  4241. encode \code{not}. The \key{xorq} instruction takes two arguments,
  4242. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  4243. bit of its arguments, and writes the results into its second argument.
  4244. Recall the truth table for exclusive-or:
  4245. \begin{center}
  4246. \begin{tabular}{l|cc}
  4247. & 0 & 1 \\ \hline
  4248. 0 & 0 & 1 \\
  4249. 1 & 1 & 0
  4250. \end{tabular}
  4251. \end{center}
  4252. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  4253. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  4254. for the bit $1$, the result is the opposite of the second bit. Thus,
  4255. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  4256. the first argument:
  4257. \[
  4258. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  4259. \qquad\Rightarrow\qquad
  4260. \begin{array}{l}
  4261. \key{movq}~ \Arg\key{,} \Var\\
  4262. \key{xorq}~ \key{\$1,} \Var
  4263. \end{array}
  4264. \]
  4265. \begin{figure}[tp]
  4266. \fbox{
  4267. \begin{minipage}{0.96\textwidth}
  4268. \[
  4269. \begin{array}{lcl}
  4270. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  4271. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4272. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} } \mid \key{\%}\itm{bytereg}\\
  4273. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4274. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \mid
  4275. \key{subq} \; \Arg\key{,} \Arg \mid
  4276. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid } \\
  4277. && \gray{ \key{callq} \; \itm{label} \mid
  4278. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} } \\
  4279. && \gray{ \itm{label}\key{:}\; \Instr }
  4280. \mid \key{xorq}~\Arg\key{,}~\Arg
  4281. \mid \key{cmpq}~\Arg\key{,}~\Arg \mid \\
  4282. && \key{set}cc~\Arg
  4283. \mid \key{movzbq}~\Arg\key{,}~\Arg
  4284. \mid \key{j}cc~\itm{label}
  4285. \\
  4286. \LangXIf{} &::= & \gray{ \key{.globl main} }\\
  4287. & & \gray{ \key{main:} \; \Instr\ldots }
  4288. \end{array}
  4289. \]
  4290. \end{minipage}
  4291. }
  4292. \caption{The concrete syntax of \LangXIf{} (extends \LangXASTInt{} of Figure~\ref{fig:x86-int-concrete}).}
  4293. \label{fig:x86-1-concrete}
  4294. \end{figure}
  4295. \begin{figure}[tp]
  4296. \fbox{
  4297. \begin{minipage}{0.98\textwidth}
  4298. \small
  4299. \[
  4300. \begin{array}{lcl}
  4301. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  4302. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  4303. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}}
  4304. \mid \BYTEREG{\itm{bytereg}} \\
  4305. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  4306. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  4307. \mid \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  4308. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  4309. \mid \UNIINSTR{\code{negq}}{\Arg} } \\
  4310. &\mid& \gray{ \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  4311. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  4312. &\mid& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  4313. \mid \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  4314. &\mid& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  4315. \mid \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  4316. &\mid& \JMPIF{\itm{cc}}{\itm{label}} \\
  4317. \Block &::= & \gray{\BLOCK{\itm{info}}{\LP\Instr\ldots\RP}} \\
  4318. \LangXASTIf{} &::= & \gray{\XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}}
  4319. \end{array}
  4320. \]
  4321. \end{minipage}
  4322. }
  4323. \caption{The abstract syntax of \LangXASTIf{} (extends \LangXASTInt{} of Figure~\ref{fig:x86-int-ast}).}
  4324. \label{fig:x86-1}
  4325. \end{figure}
  4326. Next we consider the x86 instructions that are relevant for compiling
  4327. the comparison operations. The \key{cmpq} instruction compares its two
  4328. arguments to determine whether one argument is less than, equal, or
  4329. greater than the other argument. The \key{cmpq} instruction is unusual
  4330. regarding the order of its arguments and where the result is
  4331. placed. The argument order is backwards: if you want to test whether
  4332. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  4333. \key{cmpq} is placed in the special EFLAGS register. This register
  4334. cannot be accessed directly but it can be queried by a number of
  4335. instructions, including the \key{set} instruction. The instruction
  4336. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  4337. depending on whether the comparison comes out according to the
  4338. condition code \itm{cc} (\key{e} for equal, \key{l} for less, \key{le}
  4339. for less-or-equal, \key{g} for greater, \key{ge} for
  4340. greater-or-equal). The \key{set} instruction has an annoying quirk in
  4341. that its destination argument must be single byte register, such as
  4342. \code{al} (L for lower bits) or \code{ah} (H for higher bits), which
  4343. are part of the \code{rax} register. Thankfully, the \key{movzbq}
  4344. instruction can be used to move from a single byte register to a
  4345. normal 64-bit register. The abstract syntax for the \code{set}
  4346. instruction differs from the concrete syntax in that it separates the
  4347. instruction name from the condition code.
  4348. The x86 instruction for conditional jump is relevant to the
  4349. compilation of \key{if} expressions. The instruction
  4350. $\key{j}\itm{cc}~\itm{label}$ updates the program counter to point to
  4351. the instruction after \itm{label} depending on whether the result in
  4352. the EFLAGS register matches the condition code \itm{cc}, otherwise the
  4353. jump instruction falls through to the next instruction. Like the
  4354. abstract syntax for \code{set}, the abstract syntax for conditional
  4355. jump separates the instruction name from the condition code. For
  4356. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  4357. the conditional jump instruction relies on the EFLAGS register, it is
  4358. common for it to be immediately preceded by a \key{cmpq} instruction
  4359. to set the EFLAGS register.
  4360. \section{Shrink the \LangIf{} Language}
  4361. \label{sec:shrink-Rif}
  4362. The \LangIf{} language includes several operators that are easily
  4363. expressible with other operators. For example, subtraction is
  4364. expressible using addition and negation.
  4365. \[
  4366. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  4367. \]
  4368. Several of the comparison operations are expressible using less-than
  4369. and logical negation.
  4370. \[
  4371. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  4372. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  4373. \]
  4374. The \key{let} is needed in the above translation to ensure that
  4375. expression $e_1$ is evaluated before $e_2$.
  4376. By performing these translations in the front-end of the compiler, the
  4377. later passes of the compiler do not need to deal with these operators,
  4378. making the passes shorter.
  4379. %% On the other hand, sometimes
  4380. %% these translations make it more difficult to generate the most
  4381. %% efficient code with respect to the number of instructions. However,
  4382. %% these differences typically do not affect the number of accesses to
  4383. %% memory, which is the primary factor that determines execution time on
  4384. %% modern computer architectures.
  4385. \begin{exercise}\normalfont
  4386. Implement the pass \code{shrink} to remove subtraction, \key{and},
  4387. \key{or}, \key{<=}, \key{>}, and \key{>=} from the language by
  4388. translating them to other constructs in \LangIf{}.
  4389. %
  4390. Create six test programs that involve these operators.
  4391. %
  4392. In the \code{run-tests.rkt} script, add the following entry for
  4393. \code{shrink} to the list of passes (it should be the only pass at
  4394. this point).
  4395. \begin{lstlisting}
  4396. (list "shrink" shrink interp-Rif type-check-Rif)
  4397. \end{lstlisting}
  4398. This instructs \code{interp-tests} to run the intepreter
  4399. \code{interp-Rif} and the type checker \code{type-check-Rif} on the
  4400. output of \code{shrink}.
  4401. %
  4402. Run the script to test the \code{shrink} pass on all the test
  4403. programs.
  4404. \end{exercise}
  4405. \section{Remove Complex Operands}
  4406. \label{sec:remove-complex-opera-Rif}
  4407. The output language for this pass is \LangIfANF{}
  4408. (Figure~\ref{fig:Rif-anf-syntax}), the administrative normal form of
  4409. \LangIf{}. The \code{Bool} form is an atomic expressions but
  4410. \code{If} is not. All three sub-expressions of an \code{If} are
  4411. allowed to be complex expressions but the operands of \code{not} and
  4412. the comparisons must be atoms.
  4413. Add cases for \code{Bool} and \code{If} to the \code{rco-exp} and
  4414. \code{rco-atom} functions according to whether the output needs to be
  4415. \Exp{} or \Atm{} as specified in the grammar for \LangIfANF{}.
  4416. Regarding \code{If}, it is particularly important to \textbf{not}
  4417. replace its condition with a temporary variable because that would
  4418. interfere with the generation of high-quality output in the
  4419. \code{explicate-control} pass.
  4420. \begin{figure}[tp]
  4421. \centering
  4422. \fbox{
  4423. \begin{minipage}{0.96\textwidth}
  4424. \[
  4425. \begin{array}{rcl}
  4426. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} } \mid \BOOL{\itm{bool}}\\
  4427. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  4428. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4429. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  4430. &\mid& \UNIOP{\key{'not}}{\Atm} \\
  4431. &\mid& \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4432. R^{\dagger}_2 &::=& \PROGRAM{\code{'()}}{\Exp}
  4433. \end{array}
  4434. \]
  4435. \end{minipage}
  4436. }
  4437. \caption{\LangIfANF{} is \LangIf{} in administrative normal form (ANF).}
  4438. \label{fig:Rif-anf-syntax}
  4439. \end{figure}
  4440. \section{Explicate Control}
  4441. \label{sec:explicate-control-Rif}
  4442. Recall that the purpose of \code{explicate-control} is to make the
  4443. order of evaluation explicit in the syntax of the program. With the
  4444. addition of \key{if} this get more interesting.
  4445. As a motivating example, consider the following program that has an
  4446. \key{if} expression nested in the predicate of another \key{if}.
  4447. % s1_41.rkt
  4448. \begin{center}
  4449. \begin{minipage}{0.96\textwidth}
  4450. \begin{lstlisting}
  4451. (let ([x (read)])
  4452. (let ([y (read)])
  4453. (if (if (< x 1) (eq? x 0) (eq? x 2))
  4454. (+ y 2)
  4455. (+ y 10))))
  4456. \end{lstlisting}
  4457. \end{minipage}
  4458. \end{center}
  4459. %
  4460. The naive way to compile \key{if} and the comparison would be to
  4461. handle each of them in isolation, regardless of their context. Each
  4462. comparison would be translated into a \key{cmpq} instruction followed
  4463. by a couple instructions to move the result from the EFLAGS register
  4464. into a general purpose register or stack location. Each \key{if} would
  4465. be translated into a \key{cmpq} instruction followed by a conditional
  4466. jump. The generated code for the inner \key{if} in the above example
  4467. would be as follows.
  4468. \begin{center}
  4469. \begin{minipage}{0.96\textwidth}
  4470. \begin{lstlisting}
  4471. ...
  4472. cmpq $1, x ;; (< x 1)
  4473. setl %al
  4474. movzbq %al, tmp
  4475. cmpq $1, tmp ;; (if ...)
  4476. je then_branch_1
  4477. jmp else_branch_1
  4478. ...
  4479. \end{lstlisting}
  4480. \end{minipage}
  4481. \end{center}
  4482. However, if we take context into account we can do better and reduce
  4483. the use of \key{cmpq} instructions for accessing the EFLAG register.
  4484. Our goal will be compile \key{if} expressions so that the relevant
  4485. comparison instruction appears directly before the conditional jump.
  4486. For example, we want to generate the following code for the inner
  4487. \code{if}.
  4488. \begin{center}
  4489. \begin{minipage}{0.96\textwidth}
  4490. \begin{lstlisting}
  4491. ...
  4492. cmpq $1, x
  4493. je then_branch_1
  4494. jmp else_branch_1
  4495. ...
  4496. \end{lstlisting}
  4497. \end{minipage}
  4498. \end{center}
  4499. One way to achieve this is to reorganize the code at the level of
  4500. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  4501. the following code.
  4502. \begin{center}
  4503. \begin{minipage}{0.96\textwidth}
  4504. \begin{lstlisting}
  4505. (let ([x (read)])
  4506. (let ([y (read)])
  4507. (if (< x 1)
  4508. (if (eq? x 0)
  4509. (+ y 2)
  4510. (+ y 10))
  4511. (if (eq? x 2)
  4512. (+ y 2)
  4513. (+ y 10)))))
  4514. \end{lstlisting}
  4515. \end{minipage}
  4516. \end{center}
  4517. Unfortunately, this approach duplicates the two branches from the
  4518. outer \code{if} and a compiler must never duplicate code!
  4519. We need a way to perform the above transformation but without
  4520. duplicating code. That is, we need a way for different parts of a
  4521. program to refer to the same piece of code. At the level of x86
  4522. assembly this is straightforward because we can label the code for
  4523. each branch and insert jumps in all the places that need to execute
  4524. the branch. In our intermediate language, we need to move away from
  4525. abstract syntax \emph{trees} and instead use \emph{graphs}. In
  4526. particular, we use a standard program representation called a
  4527. \emph{control flow graph} (CFG), due to Frances Elizabeth
  4528. \citet{Allen:1970uq}. \index{control-flow graph} Each vertex is a
  4529. labeled sequence of code, called a \emph{basic block}, and each edge
  4530. represents a jump to another block. The \key{CProgram} construct of
  4531. \LangCVar{} and \LangCIf{} contains a control flow graph represented
  4532. as an alist mapping labels to basic blocks. Each basic block is
  4533. represented by the $\Tail$ non-terminal.
  4534. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  4535. \code{remove-complex-opera*} pass and then the
  4536. \code{explicate-control} pass on the example program. We walk through
  4537. the output program and then discuss the algorithm.
  4538. %
  4539. Following the order of evaluation in the output of
  4540. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  4541. and then the comparison \lstinline{(< x 1)} in the predicate of the
  4542. inner \key{if}. In the output of \code{explicate-control}, in the
  4543. block labeled \code{start}, is two assignment statements followed by a
  4544. \code{if} statement that branches to \code{block40} or
  4545. \code{block41}. The blocks associated with those labels contain the
  4546. translations of the code \lstinline{(eq? x 0)} and \lstinline{(eq? x 2)},
  4547. respectively. In particular, we start \code{block40} with the
  4548. comparison \lstinline{(eq? x 0)} and then branch to \code{block38} or
  4549. \code{block39}, the two branches of the outer \key{if}, i.e.,
  4550. \lstinline{(+ y 2)} and \lstinline{(+ y 10)}. The story for
  4551. \code{block41} is similar.
  4552. \begin{figure}[tbp]
  4553. \begin{tabular}{lll}
  4554. \begin{minipage}{0.4\textwidth}
  4555. % s1_41.rkt
  4556. \begin{lstlisting}
  4557. (let ([x (read)])
  4558. (let ([y (read)])
  4559. (if (if (< x 1)
  4560. (eq? x 0)
  4561. (eq? x 2))
  4562. (+ y 2)
  4563. (+ y 10))))
  4564. \end{lstlisting}
  4565. \hspace{40pt}$\Downarrow$
  4566. \begin{lstlisting}
  4567. (let ([x (read)])
  4568. (let ([y (read)])
  4569. (if (if (< x 1)
  4570. (eq? x 0)
  4571. (eq? x 2))
  4572. (+ y 2)
  4573. (+ y 10))))
  4574. \end{lstlisting}
  4575. \end{minipage}
  4576. &
  4577. $\Rightarrow$
  4578. &
  4579. \begin{minipage}{0.55\textwidth}
  4580. \begin{lstlisting}
  4581. start:
  4582. x = (read);
  4583. y = (read);
  4584. if (< x 1) goto block40;
  4585. else goto block41;
  4586. block40:
  4587. if (eq? x 0) goto block38;
  4588. else goto block39;
  4589. block41:
  4590. if (eq? x 2) goto block38;
  4591. else goto block39;
  4592. block38:
  4593. return (+ y 2);
  4594. block39:
  4595. return (+ y 10);
  4596. \end{lstlisting}
  4597. \end{minipage}
  4598. \end{tabular}
  4599. \caption{Translation from \LangIf{} to \LangCIf{}
  4600. via the \code{explicate-control}.}
  4601. \label{fig:explicate-control-s1-38}
  4602. \end{figure}
  4603. %% The nice thing about the output of \code{explicate-control} is that
  4604. %% there are no unnecessary comparisons and every comparison is part of a
  4605. %% conditional jump.
  4606. %% The down-side of this output is that it includes
  4607. %% trivial blocks, such as the blocks labeled \code{block92} through
  4608. %% \code{block95}, that only jump to another block. We discuss a solution
  4609. %% to this problem in Section~\ref{sec:opt-jumps}.
  4610. Recall that in Section~\ref{sec:explicate-control-r1} we implement
  4611. \code{explicate-control} for \LangVar{} using two mutually recursive
  4612. functions, \code{explicate-tail} and \code{explicate-assign}. The
  4613. former function translates expressions in tail position whereas the
  4614. later function translates expressions on the right-hand-side of a
  4615. \key{let}. With the addition of \key{if} expression in \LangIf{} we
  4616. have a new kind of position to deal with: the predicate position of
  4617. the \key{if}. We need another function, \code{explicate-pred}, that
  4618. takes an \LangIf{} expression and two blocks for the then-branch and
  4619. else-branch. The output of \code{explicate-pred} is a block.
  4620. %
  4621. %% Note that the three explicate functions need to construct a
  4622. %% control-flow graph, which we recommend they do via updates to a global
  4623. %% variable.
  4624. %
  4625. In the following paragraphs we discuss specific cases in the
  4626. \code{explicate-pred} function as well as additions to the
  4627. \code{explicate-tail} and \code{explicate-assign} functions.
  4628. The function \code{explicate-pred} will need a case for every
  4629. expression that can have type \code{Boolean}. We detail a few cases
  4630. here and leave the rest for the reader. The input to this function is
  4631. an expression and two blocks, $B_1$ and $B_2$, for the two branches of
  4632. the enclosing \key{if}. Suppose the expression is the Boolean
  4633. \code{\#t}. Then we can perform a kind of partial evaluation
  4634. \index{partial evaluation} and translate it to the ``then'' branch
  4635. $B_1$. Likewise, we translate \code{\#f} to the ``else`` branch $B_2$.
  4636. \[
  4637. \key{\#t} \quad\Rightarrow\quad B_1,
  4638. \qquad\qquad\qquad
  4639. \key{\#f} \quad\Rightarrow\quad B_2
  4640. \]
  4641. These two cases demonstrate that we sometimes discard one of the
  4642. blocks that are input to \code{explicate-pred}. We want the blocks
  4643. that we actually use to appear in the resulting control-flow graph,
  4644. but not the discarded blocks. We return to this issue later.
  4645. The case for \key{if} in \code{explicate-pred} is particularly
  4646. illuminating because it deals with the challenges we discussed above
  4647. regarding the example of the nested \key{if} expressions. The
  4648. ``then'' and ``else'' branches of the current \key{if} inherit their
  4649. context from the current one, that is, predicate context. So we
  4650. recursively apply \code{explicate-pred} to the ``then'' and ``else''
  4651. branches. For both of those recursive calls, we pass the blocks $B_1$
  4652. and $B_2$. Thus, $B_1$ may get used twice, once inside each recursive
  4653. call, and likewise for $B_2$. As discussed above, to avoid duplicating
  4654. code, we need to add these blocks to the control-flow graph so that we
  4655. can instead refer to them by name and execute them with a
  4656. \key{goto}. However, as we saw in the cases above for \key{\#t} and
  4657. \key{\#f}, the blocks $B_1$ or $B_2$ may not get used at all and we
  4658. don't want to prematurely add them to the control-flow graph if they
  4659. end up being discarded.
  4660. The solution to this conundrum is to use \emph{lazy
  4661. evaluation}\index{lazy evaluation} \citep{Friedman:1976aa} to delay
  4662. adding the blocks to the control-flow graph until the points where we
  4663. know they will be used. Racket provides support for lazy evaluation
  4664. with the
  4665. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  4666. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  4667. \index{delay} creates a \emph{promise}\index{promise} in which the
  4668. evaluation of the expressions is postponed. When \key{(force}
  4669. $p$\key{)}\index{force} is applied to a promise $p$ for the first
  4670. time, the expressions $e_1 \ldots e_n$ are evaluated and the result of
  4671. $e_n$ is cached in the promise and returned. If \code{force} is
  4672. applied again to the same promise, then the cached result is returned.
  4673. We use lazy evaluation for the input and output blocks of the
  4674. functions \code{explicate-pred} and \code{explicate-assign} and for
  4675. the output block of \code{explicate-tail}. So instead of taking and
  4676. returning blocks, they take and return promised blocks. Furthermore,
  4677. when we come to a situation in which we a block might be used more
  4678. than once, as in the case for \code{if} above, we transform the
  4679. promise into a new promise that will add the block to the control-flow
  4680. graph and return a \code{goto}. The following auxiliary function
  4681. accomplishes this task. It begins with \code{delay} to create a
  4682. promise. When forced, this promise will force the input block. If that
  4683. block is already a \code{goto} (because it was already added to the
  4684. control-flow graph), then we return that \code{goto}. Otherwise we add
  4685. the block to the control-flow graph with another auxiliary function
  4686. named \code{add-node} that returns the new label, and then return the
  4687. \code{goto}.
  4688. \begin{lstlisting}
  4689. (define (block->goto block)
  4690. (delay
  4691. (define b (force block))
  4692. (match b
  4693. [(Goto label) (Goto label)]
  4694. [else (Goto (add-node b))]
  4695. )))
  4696. \end{lstlisting}
  4697. Getting back to the case for \code{if} in \code{explicate-pred}, we
  4698. make the recursive calls to \code{explicate-pred} on the ``then'' and
  4699. ``else'' branches with the arguments \code{(block->goto} $B_1$\code{)}
  4700. and \code{(block->goto} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  4701. results from the two recursive calls. We complete the case for
  4702. \code{if} by recursively apply \code{explicate-pred} to the condition
  4703. of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  4704. the result $B_5$.
  4705. \[
  4706. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  4707. \quad\Rightarrow\quad
  4708. B_5
  4709. \]
  4710. Next, consider the case for a less-than comparison in
  4711. \code{explicate-pred}. We translate it to an \code{if} statement,
  4712. whose two branches are required to be \code{goto}'s. So we apply
  4713. \code{block->goto} to $B_1$ and $B_2$ to obtain two promised goto's,
  4714. which we can \code{force} to obtain the two actual goto's $G_1$ and
  4715. $G_2$. The translation of the less-than comparison is as follows.
  4716. \[
  4717. (\key{<}~e_1~e_2) \quad\Rightarrow\quad
  4718. \begin{array}{l}
  4719. \key{if}~(\key{<}~e_1~e_2) \; G_1\\
  4720. \key{else} \; G_2
  4721. \end{array}
  4722. \]
  4723. The \code{explicate-tail} function needs to be updated to use lazy
  4724. evaluation and it needs an additional case for \key{if}. Each of the
  4725. cases that return an AST node need use \code{delay} to instead return
  4726. a promise of an AST node. Recall that \code{explicate-tail} has an
  4727. accumulator parameter that is a block, which now becomes a promise of
  4728. a block, which we refer to as $B_0$.
  4729. In the case for \code{if} in \code{explicate-tail}, the two branches
  4730. inherit the current context, so they are in tail position. Thus, the
  4731. recursive calls on the ``then'' and ``else'' branch should be calls to
  4732. \code{explicate-tail}.
  4733. %
  4734. We need to pass $B_0$ as the accumulator argument for both of these
  4735. recursive calls, but we need to be careful not to duplicate $B_0$.
  4736. Thus, we first apply \code{block->goto} to $B_0$ so that it gets added
  4737. to the control-flow graph and obtain a promised goto $G_0$.
  4738. %
  4739. Let $B_1$ be the result of \code{explicate-tail} on the ``then''
  4740. branch and $G_0$ and let $B_2$ be the result of \code{explicate-tail}
  4741. on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  4742. \code{explicate-pred} to the condition of the \key{if}, $B_1$, and
  4743. $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  4744. \[
  4745. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  4746. \]
  4747. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  4748. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  4749. %% should not be confused with the labels for the blocks that appear in
  4750. %% the generated code. We initially construct unlabeled blocks; we only
  4751. %% attach labels to blocks when we add them to the control-flow graph, as
  4752. %% we see in the next case.
  4753. Next consider the case for \key{if} in the \code{explicate-assign}
  4754. function. The context of the \key{if} is an assignment to some
  4755. variable $x$ and then the control continues to some promised block
  4756. $B_1$. The code that we generate for both the ``then'' and ``else''
  4757. branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  4758. apply \code{block->goto} to it and obtain a promised goto $G_1$. The
  4759. branches of the \key{if} inherit the current context, so they are in
  4760. assignment positions. Let $B_2$ be the result of applying
  4761. \code{explicate-assign} to the ``then'' branch, variable $x$, and
  4762. $G_1$. Let $B_3$ be the result of applying \code{explicate-assign} to
  4763. the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  4764. the result of applying \code{explicate-pred} to the predicate
  4765. $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  4766. translates to the promise $B_4$.
  4767. \[
  4768. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  4769. \]
  4770. This completes the description of \code{explicate-control} for \LangIf{}.
  4771. The way in which the \code{shrink} pass transforms logical operations
  4772. such as \code{and} and \code{or} can impact the quality of code
  4773. generated by \code{explicate-control}. For example, consider the
  4774. following program.
  4775. % s1_21.rkt
  4776. \begin{lstlisting}
  4777. (if (and (eq? (read) 0) (eq? (read) 1))
  4778. 0
  4779. 42)
  4780. \end{lstlisting}
  4781. The \code{and} operation should transform into something that the
  4782. \code{explicate-pred} function can still analyze and descend through to
  4783. reach the underlying \code{eq?} conditions. Ideally, your
  4784. \code{explicate-control} pass should generate code similar to the
  4785. following for the above program.
  4786. \begin{center}
  4787. \begin{lstlisting}
  4788. start:
  4789. tmp1 = (read);
  4790. if (eq? tmp1 0)
  4791. goto block40;
  4792. else
  4793. goto block39;
  4794. block40:
  4795. tmp2 = (read);
  4796. if (eq? tmp2 1)
  4797. goto block38;
  4798. else
  4799. goto block39;
  4800. block38:
  4801. return 0;
  4802. block39:
  4803. return 42;
  4804. \end{lstlisting}
  4805. \end{center}
  4806. \begin{exercise}\normalfont
  4807. Implement the pass \code{explicate-control} by adding the cases for
  4808. \key{if} to the functions for tail and assignment contexts, and
  4809. implement \code{explicate-pred} for predicate contexts. Create test
  4810. cases that exercise all of the new cases in the code for this pass.
  4811. \end{exercise}
  4812. \section{Select Instructions}
  4813. \label{sec:select-Rif}
  4814. \index{instruction selection}
  4815. Recall that the \code{select-instructions} pass lowers from our
  4816. $C$-like intermediate representation to the pseudo-x86 language, which
  4817. is suitable for conducting register allocation. The pass is
  4818. implemented using three auxiliary functions, one for each of the
  4819. non-terminals $\Atm$, $\Stmt$, and $\Tail$.
  4820. For $\Atm$, we have new cases for the Booleans. We take the usual
  4821. approach of encoding them as integers, with true as 1 and false as 0.
  4822. \[
  4823. \key{\#t} \Rightarrow \key{1}
  4824. \qquad
  4825. \key{\#f} \Rightarrow \key{0}
  4826. \]
  4827. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  4828. be implemented in terms of \code{xorq} as we discussed at the
  4829. beginning of this section. Given an assignment
  4830. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  4831. if the left-hand side $\itm{var}$ is
  4832. the same as $\Atm$, then just the \code{xorq} suffices.
  4833. \[
  4834. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  4835. \quad\Rightarrow\quad
  4836. \key{xorq}~\key{\$}1\key{,}~\Var
  4837. \]
  4838. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  4839. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  4840. x86. Then we have
  4841. \[
  4842. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  4843. \quad\Rightarrow\quad
  4844. \begin{array}{l}
  4845. \key{movq}~\Arg\key{,}~\Var\\
  4846. \key{xorq}~\key{\$}1\key{,}~\Var
  4847. \end{array}
  4848. \]
  4849. Next consider the cases for \code{eq?} and less-than comparison.
  4850. Translating these operations to x86 is slightly involved due to the
  4851. unusual nature of the \key{cmpq} instruction discussed above. We
  4852. recommend translating an assignment from \code{eq?} into the following
  4853. sequence of three instructions. \\
  4854. \begin{tabular}{lll}
  4855. \begin{minipage}{0.4\textwidth}
  4856. \begin{lstlisting}
  4857. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  4858. \end{lstlisting}
  4859. \end{minipage}
  4860. &
  4861. $\Rightarrow$
  4862. &
  4863. \begin{minipage}{0.4\textwidth}
  4864. \begin{lstlisting}
  4865. cmpq |$\Arg_2$|, |$\Arg_1$|
  4866. sete %al
  4867. movzbq %al, |$\Var$|
  4868. \end{lstlisting}
  4869. \end{minipage}
  4870. \end{tabular} \\
  4871. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  4872. and conditional \key{goto}. Both are straightforward to handle. A
  4873. \key{goto} becomes a jump instruction.
  4874. \[
  4875. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  4876. \]
  4877. A conditional \key{goto} becomes a compare instruction followed
  4878. by a conditional jump (for ``then'') and the fall-through is
  4879. to a regular jump (for ``else'').\\
  4880. \begin{tabular}{lll}
  4881. \begin{minipage}{0.4\textwidth}
  4882. \begin{lstlisting}
  4883. if (eq? |$\Atm_1$| |$\Atm_2$|)
  4884. goto |$\ell_1$|;
  4885. else
  4886. goto |$\ell_2$|;
  4887. \end{lstlisting}
  4888. \end{minipage}
  4889. &
  4890. $\Rightarrow$
  4891. &
  4892. \begin{minipage}{0.4\textwidth}
  4893. \begin{lstlisting}
  4894. cmpq |$\Arg_2$|, |$\Arg_1$|
  4895. je |$\ell_1$|
  4896. jmp |$\ell_2$|
  4897. \end{lstlisting}
  4898. \end{minipage}
  4899. \end{tabular} \\
  4900. \begin{exercise}\normalfont
  4901. Expand your \code{select-instructions} pass to handle the new features
  4902. of the \LangIf{} language. Test the pass on all the examples you have
  4903. created and make sure that you have some test programs that use the
  4904. \code{eq?} and \code{<} operators, creating some if necessary. Test
  4905. the output using the \code{interp-x86} interpreter
  4906. (Appendix~\ref{appendix:interp}).
  4907. \end{exercise}
  4908. \section{Register Allocation}
  4909. \label{sec:register-allocation-Rif}
  4910. \index{register allocation}
  4911. The changes required for \LangIf{} affect liveness analysis, building the
  4912. interference graph, and assigning homes, but the graph coloring
  4913. algorithm itself does not change.
  4914. \subsection{Liveness Analysis}
  4915. \label{sec:liveness-analysis-Rif}
  4916. \index{liveness analysis}
  4917. Recall that for \LangVar{} we implemented liveness analysis for a single
  4918. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  4919. addition of \key{if} expressions to \LangIf{}, \code{explicate-control}
  4920. produces many basic blocks arranged in a control-flow graph. We
  4921. recommend that you create a new auxiliary function named
  4922. \code{uncover-live-CFG} that applies liveness analysis to a
  4923. control-flow graph.
  4924. The first question we need to consider is: what order should we
  4925. process the basic blocks in the control-flow graph? To perform
  4926. liveness analysis on a basic block, we need to know its live-after
  4927. set. If a basic block has no successor blocks (i.e. no out-edges in
  4928. the control flow graph), then it has an empty live-after set and we
  4929. can immediately apply liveness analysis to it. If a basic block has
  4930. some successors, then we need to complete liveness analysis on those
  4931. blocks first. Thankfully, the control flow graph does not contain any
  4932. cycles because \LangIf{} does not include loops. (In
  4933. Chapter~\ref{ch:loop} we add loops and study how to handle cycles in
  4934. the control-flow graph.)
  4935. %
  4936. Returning to the question of what order should we process the basic
  4937. blocks, the answer is reverse topological order. We recommend using
  4938. the \code{tsort} (topological sort) and \code{transpose} functions of
  4939. the Racket \code{graph} package to obtain this ordering.
  4940. \index{topological order}
  4941. \index{topological sort}
  4942. The next question is how to analyze the jump instructions. In
  4943. Section~\ref{sec:liveness-analysis-r1} we recommended that you
  4944. maintain an alist named \code{label->live} that maps each label to the
  4945. set of live locations at the beginning of the associated block. Now
  4946. that we have many basic blocks, the alist needs to be extended as we
  4947. process the blocks. In particular, after performing liveness analysis
  4948. on a block, we can take the live-before set for its first instruction
  4949. and associate that with the block's label in the alist.
  4950. %
  4951. As discussed in Section~\ref{sec:liveness-analysis-r1}, the
  4952. live-before set for a $\JMP{\itm{label}}$ instruction is given by the
  4953. mapping for $\itm{label}$ in \code{label->live}.
  4954. Now for $x86_1$ we also have the conditional jump
  4955. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. This one is
  4956. particularly interesting because during compilation we do not know, in
  4957. general, which way a conditional jump will go, so we do not know
  4958. whether to use the live-before set for the following instruction or
  4959. the live-before set for $\itm{label}$. The solution to this challenge
  4960. is based on the observation that there is no harm to the correctness
  4961. of the compiler if we classify more locations as live than the ones
  4962. that are truly live during a particular execution of the
  4963. instruction. Thus, we can take the union of the live-before sets from
  4964. the following instruction and from the mapping fro $\itm{label}$ in
  4965. \code{label->live}.
  4966. The helper functions for computing the variables in an instruction's
  4967. argument and for computing the variables read-from ($R$) or written-to
  4968. ($W$) by an instruction need to be updated to handle the new kinds of
  4969. arguments and instructions in \LangXASTIf{}.
  4970. \subsection{Build Interference}
  4971. \label{sec:build-interference-Rif}
  4972. Many of the new instructions in \LangXASTIf{} can be handled in the same way
  4973. as the instructions in \LangXASTInt{}. Thus, if your code was already quite
  4974. general, it will not need to be changed to handle the new
  4975. instructions. If you code is not general enough, I recommend that you
  4976. change your code to be more general. For example, you can factor out
  4977. the computing of the the read and write sets for each kind of
  4978. instruction into two auxiliary functions.
  4979. Note that the \key{movzbq} instruction requires some special care,
  4980. just like the \key{movq} instruction. See rule number 3 in
  4981. Section~\ref{sec:build-interference}.
  4982. %% \subsection{Assign Homes}
  4983. %% \label{sec:assign-homes-Rif}
  4984. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  4985. %% to be updated to handle the \key{if} statement, simply by recursively
  4986. %% processing the child nodes. Hopefully your code already handles the
  4987. %% other new instructions, but if not, you can generalize your code.
  4988. \begin{exercise}\normalfont
  4989. Update the \code{register-allocation} pass so that it works for \LangIf{}
  4990. and test your compiler using your previously created programs on the
  4991. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4992. \end{exercise}
  4993. \section{Patch Instructions}
  4994. The second argument of the \key{cmpq} instruction must not be an
  4995. immediate value (such as an integer). So if you are comparing two
  4996. immediates, we recommend inserting a \key{movq} instruction to put the
  4997. second argument in \key{rax}. Also, recall that instructions may have
  4998. at most one memory reference.
  4999. %
  5000. The second argument of the \key{movzbq} must be a register.
  5001. %
  5002. There are no special restrictions on the x86 instructions \key{JmpIf}
  5003. and \key{Jmp}.
  5004. \begin{exercise}\normalfont
  5005. Update \code{patch-instructions} to handle the new x86 instructions.
  5006. Test your compiler using your previously created programs on the
  5007. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  5008. \end{exercise}
  5009. \begin{figure}[tbp]
  5010. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5011. \node (Rif) at (0,2) {\large \LangIf{}};
  5012. \node (Rif-2) at (3,2) {\large \LangIf{}};
  5013. \node (Rif-3) at (6,2) {\large \LangIf{}};
  5014. \node (Rif-4) at (9,2) {\large \LangIf{}};
  5015. \node (Rif-5) at (12,2) {\large \LangIf{}};
  5016. \node (C1-1) at (3,0) {\large \LangCIf{}};
  5017. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  5018. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  5019. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  5020. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  5021. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  5022. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  5023. \path[->,bend left=15] (Rif) edge [above] node {\ttfamily\footnotesize type-check} (Rif-2);
  5024. \path[->,bend left=15] (Rif-2) edge [above] node {\ttfamily\footnotesize shrink} (Rif-3);
  5025. \path[->,bend left=15] (Rif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Rif-4);
  5026. \path[->,bend left=15] (Rif-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rif-5);
  5027. \path[->,bend left=15] (Rif-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C1-1);
  5028. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select-instructions} (x86-2);
  5029. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  5030. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  5031. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  5032. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  5033. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86 } (x86-5);
  5034. \end{tikzpicture}
  5035. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  5036. \label{fig:Rif-passes}
  5037. \end{figure}
  5038. Figure~\ref{fig:Rif-passes} lists all the passes needed for the
  5039. compilation of \LangIf{}.
  5040. \section{An Example Translation}
  5041. Figure~\ref{fig:if-example-x86} shows a simple example program in
  5042. \LangIf{} translated to x86, showing the results of
  5043. \code{explicate-control}, \code{select-instructions}, and the final
  5044. x86 assembly code.
  5045. \begin{figure}[tbp]
  5046. \begin{tabular}{lll}
  5047. \begin{minipage}{0.5\textwidth}
  5048. % s1_20.rkt
  5049. \begin{lstlisting}
  5050. (if (eq? (read) 1) 42 0)
  5051. \end{lstlisting}
  5052. $\Downarrow$
  5053. \begin{lstlisting}
  5054. start:
  5055. tmp7951 = (read);
  5056. if (eq? tmp7951 1) then
  5057. goto block7952;
  5058. else
  5059. goto block7953;
  5060. block7952:
  5061. return 42;
  5062. block7953:
  5063. return 0;
  5064. \end{lstlisting}
  5065. $\Downarrow$
  5066. \begin{lstlisting}
  5067. start:
  5068. callq read_int
  5069. movq %rax, tmp7951
  5070. cmpq $1, tmp7951
  5071. je block7952
  5072. jmp block7953
  5073. block7953:
  5074. movq $0, %rax
  5075. jmp conclusion
  5076. block7952:
  5077. movq $42, %rax
  5078. jmp conclusion
  5079. \end{lstlisting}
  5080. \end{minipage}
  5081. &
  5082. $\Rightarrow\qquad$
  5083. \begin{minipage}{0.4\textwidth}
  5084. \begin{lstlisting}
  5085. start:
  5086. callq read_int
  5087. movq %rax, %rcx
  5088. cmpq $1, %rcx
  5089. je block7952
  5090. jmp block7953
  5091. block7953:
  5092. movq $0, %rax
  5093. jmp conclusion
  5094. block7952:
  5095. movq $42, %rax
  5096. jmp conclusion
  5097. .globl main
  5098. main:
  5099. pushq %rbp
  5100. movq %rsp, %rbp
  5101. pushq %r13
  5102. pushq %r12
  5103. pushq %rbx
  5104. pushq %r14
  5105. subq $0, %rsp
  5106. jmp start
  5107. conclusion:
  5108. addq $0, %rsp
  5109. popq %r14
  5110. popq %rbx
  5111. popq %r12
  5112. popq %r13
  5113. popq %rbp
  5114. retq
  5115. \end{lstlisting}
  5116. \end{minipage}
  5117. \end{tabular}
  5118. \caption{Example compilation of an \key{if} expression to x86.}
  5119. \label{fig:if-example-x86}
  5120. \end{figure}
  5121. \section{Challenge: Remove Jumps}
  5122. \label{sec:opt-jumps}
  5123. %% Recall that in the example output of \code{explicate-control} in
  5124. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  5125. %% \code{block60} are trivial blocks, they do nothing but jump to another
  5126. %% block. The first goal of this challenge assignment is to remove those
  5127. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  5128. %% \code{explicate-control} on the left and shows the result of bypassing
  5129. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  5130. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  5131. %% \code{block55}. The optimized code on the right of
  5132. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  5133. %% \code{then} branch jumping directly to \code{block55}. The story is
  5134. %% similar for the \code{else} branch, as well as for the two branches in
  5135. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  5136. %% have been optimized in this way, there are no longer any jumps to
  5137. %% blocks \code{block57} through \code{block60}, so they can be removed.
  5138. %% \begin{figure}[tbp]
  5139. %% \begin{tabular}{lll}
  5140. %% \begin{minipage}{0.4\textwidth}
  5141. %% \begin{lstlisting}
  5142. %% block62:
  5143. %% tmp54 = (read);
  5144. %% if (eq? tmp54 2) then
  5145. %% goto block59;
  5146. %% else
  5147. %% goto block60;
  5148. %% block61:
  5149. %% tmp53 = (read);
  5150. %% if (eq? tmp53 0) then
  5151. %% goto block57;
  5152. %% else
  5153. %% goto block58;
  5154. %% block60:
  5155. %% goto block56;
  5156. %% block59:
  5157. %% goto block55;
  5158. %% block58:
  5159. %% goto block56;
  5160. %% block57:
  5161. %% goto block55;
  5162. %% block56:
  5163. %% return (+ 700 77);
  5164. %% block55:
  5165. %% return (+ 10 32);
  5166. %% start:
  5167. %% tmp52 = (read);
  5168. %% if (eq? tmp52 1) then
  5169. %% goto block61;
  5170. %% else
  5171. %% goto block62;
  5172. %% \end{lstlisting}
  5173. %% \end{minipage}
  5174. %% &
  5175. %% $\Rightarrow$
  5176. %% &
  5177. %% \begin{minipage}{0.55\textwidth}
  5178. %% \begin{lstlisting}
  5179. %% block62:
  5180. %% tmp54 = (read);
  5181. %% if (eq? tmp54 2) then
  5182. %% goto block55;
  5183. %% else
  5184. %% goto block56;
  5185. %% block61:
  5186. %% tmp53 = (read);
  5187. %% if (eq? tmp53 0) then
  5188. %% goto block55;
  5189. %% else
  5190. %% goto block56;
  5191. %% block56:
  5192. %% return (+ 700 77);
  5193. %% block55:
  5194. %% return (+ 10 32);
  5195. %% start:
  5196. %% tmp52 = (read);
  5197. %% if (eq? tmp52 1) then
  5198. %% goto block61;
  5199. %% else
  5200. %% goto block62;
  5201. %% \end{lstlisting}
  5202. %% \end{minipage}
  5203. %% \end{tabular}
  5204. %% \caption{Optimize jumps by removing trivial blocks.}
  5205. %% \label{fig:optimize-jumps}
  5206. %% \end{figure}
  5207. %% The name of this pass is \code{optimize-jumps}. We recommend
  5208. %% implementing this pass in two phases. The first phrase builds a hash
  5209. %% table that maps labels to possibly improved labels. The second phase
  5210. %% changes the target of each \code{goto} to use the improved label. If
  5211. %% the label is for a trivial block, then the hash table should map the
  5212. %% label to the first non-trivial block that can be reached from this
  5213. %% label by jumping through trivial blocks. If the label is for a
  5214. %% non-trivial block, then the hash table should map the label to itself;
  5215. %% we do not want to change jumps to non-trivial blocks.
  5216. %% The first phase can be accomplished by constructing an empty hash
  5217. %% table, call it \code{short-cut}, and then iterating over the control
  5218. %% flow graph. Each time you encouter a block that is just a \code{goto},
  5219. %% then update the hash table, mapping the block's source to the target
  5220. %% of the \code{goto}. Also, the hash table may already have mapped some
  5221. %% labels to the block's source, to you must iterate through the hash
  5222. %% table and update all of those so that they instead map to the target
  5223. %% of the \code{goto}.
  5224. %% For the second phase, we recommend iterating through the $\Tail$ of
  5225. %% each block in the program, updating the target of every \code{goto}
  5226. %% according to the mapping in \code{short-cut}.
  5227. %% \begin{exercise}\normalfont
  5228. %% Implement the \code{optimize-jumps} pass as a transformation from
  5229. %% \LangCIf{} to \LangCIf{}, coming after the \code{explicate-control} pass.
  5230. %% Check that \code{optimize-jumps} removes trivial blocks in a few
  5231. %% example programs. Then check that your compiler still passes all of
  5232. %% your tests.
  5233. %% \end{exercise}
  5234. There is an opportunity for optimizing jumps that is apparent in the
  5235. example of Figure~\ref{fig:if-example-x86}. The \code{start} block end
  5236. with a jump to \code{block7953} and there are no other jumps to
  5237. \code{block7953} in the rest of the program. In this situation we can
  5238. avoid the runtime overhead of this jump by merging \code{block7953}
  5239. into the preceding block, in this case the \code{start} block.
  5240. Figure~\ref{fig:remove-jumps} shows the output of
  5241. \code{select-instructions} on the left and the result of this
  5242. optimization on the right.
  5243. \begin{figure}[tbp]
  5244. \begin{tabular}{lll}
  5245. \begin{minipage}{0.5\textwidth}
  5246. % s1_20.rkt
  5247. \begin{lstlisting}
  5248. start:
  5249. callq read_int
  5250. movq %rax, tmp7951
  5251. cmpq $1, tmp7951
  5252. je block7952
  5253. jmp block7953
  5254. block7953:
  5255. movq $0, %rax
  5256. jmp conclusion
  5257. block7952:
  5258. movq $42, %rax
  5259. jmp conclusion
  5260. \end{lstlisting}
  5261. \end{minipage}
  5262. &
  5263. $\Rightarrow\qquad$
  5264. \begin{minipage}{0.4\textwidth}
  5265. \begin{lstlisting}
  5266. start:
  5267. callq read_int
  5268. movq %rax, tmp7951
  5269. cmpq $1, tmp7951
  5270. je block7952
  5271. movq $0, %rax
  5272. jmp conclusion
  5273. block7952:
  5274. movq $42, %rax
  5275. jmp conclusion
  5276. \end{lstlisting}
  5277. \end{minipage}
  5278. \end{tabular}
  5279. \caption{Merging basic blocks by removing unnecessary jumps.}
  5280. \label{fig:remove-jumps}
  5281. \end{figure}
  5282. \begin{exercise}\normalfont
  5283. Implement a pass named \code{remove-jumps} that merges basic blocks
  5284. into their preceding basic block, when there is only one preceding
  5285. block. The pass should translate from pseudo $x86_1$ to pseudo
  5286. $x86_1$ and it should come immediately after
  5287. \code{select-instructions}. Check that \code{remove-jumps}
  5288. accomplishes the goal of merging basic blocks on several test
  5289. programs and check that your compiler passes all of your tests.
  5290. \end{exercise}
  5291. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5292. \chapter{Tuples and Garbage Collection}
  5293. \label{ch:tuples}
  5294. \index{tuple}
  5295. \index{vector}
  5296. \margincomment{\scriptsize To do: challenge assignments: mark-and-sweep,
  5297. add simple structures. \\ --Jeremy}
  5298. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  5299. things to discuss in this chapter. \\ --Jeremy}
  5300. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  5301. all the IR grammars are spelled out! \\ --Jeremy}
  5302. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  5303. but keep type annotations on vector creation and local variables, function
  5304. parameters, etc. \\ --Jeremy}
  5305. \margincomment{\scriptsize Be more explicit about how to deal with
  5306. the root stack. \\ --Jeremy}
  5307. In this chapter we study the implementation of mutable tuples (called
  5308. ``vectors'' in Racket). This language feature is the first to use the
  5309. computer's \emph{heap}\index{heap} because the lifetime of a Racket tuple is
  5310. indefinite, that is, a tuple lives forever from the programmer's
  5311. viewpoint. Of course, from an implementer's viewpoint, it is important
  5312. to reclaim the space associated with a tuple when it is no longer
  5313. needed, which is why we also study \emph{garbage collection}
  5314. \emph{garbage collection}
  5315. techniques in this chapter.
  5316. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  5317. interpreter and type checker. The \LangVec{} language extends the \LangIf{}
  5318. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  5319. \code{void} value. The reason for including the later is that the
  5320. \code{vector-set!} operation returns a value of type
  5321. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  5322. called the \code{Unit} type in the programming languages
  5323. literature. Racket's \code{Void} type is inhabited by a single value
  5324. \code{void} which corresponds to \code{unit} or \code{()} in the
  5325. literature~\citep{Pierce:2002hj}.}.
  5326. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  5327. copying live objects back and forth between two halves of the
  5328. heap. The garbage collector requires coordination with the compiler so
  5329. that it can see all of the \emph{root} pointers, that is, pointers in
  5330. registers or on the procedure call stack.
  5331. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  5332. discuss all the necessary changes and additions to the compiler
  5333. passes, including a new compiler pass named \code{expose-allocation}.
  5334. \section{The \LangVec{} Language}
  5335. \label{sec:r3}
  5336. Figure~\ref{fig:Rvec-concrete-syntax} defines the concrete syntax for
  5337. \LangVec{} and Figure~\ref{fig:Rvec-syntax} defines the abstract syntax. The
  5338. \LangVec{} language includes three new forms: \code{vector} for creating a
  5339. tuple, \code{vector-ref} for reading an element of a tuple, and
  5340. \code{vector-set!} for writing to an element of a tuple. The program
  5341. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  5342. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  5343. the 3-tuple, demonstrating that tuples are first-class values. The
  5344. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  5345. of the \key{if} is taken. The element at index $0$ of \code{t} is
  5346. \code{40}, to which we add \code{2}, the element at index $0$ of the
  5347. 1-tuple. So the result of the program is \code{42}.
  5348. \begin{figure}[tbp]
  5349. \centering
  5350. \fbox{
  5351. \begin{minipage}{0.96\textwidth}
  5352. \[
  5353. \begin{array}{lcl}
  5354. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  5355. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \key{Void}\\
  5356. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  5357. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  5358. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  5359. \mid \LP\key{and}\;\Exp\;\Exp\RP
  5360. \mid \LP\key{or}\;\Exp\;\Exp\RP
  5361. \mid \LP\key{not}\;\Exp\RP } \\
  5362. &\mid& \gray{ \LP\itm{cmp}\;\Exp\;\Exp\RP
  5363. \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  5364. &\mid& \LP\key{vector}\;\Exp\ldots\RP
  5365. \mid \LP\key{vector-length}\;\Exp\RP \\
  5366. &\mid& \LP\key{vector-ref}\;\Exp\;\Int\RP
  5367. \mid \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP \\
  5368. &\mid& \LP\key{void}\RP \mid \LP\key{has-type}~\Exp~\Type\RP\\
  5369. \LangVec{} &::=& \Exp
  5370. \end{array}
  5371. \]
  5372. \end{minipage}
  5373. }
  5374. \caption{The concrete syntax of \LangVec{}, extending \LangIf{}
  5375. (Figure~\ref{fig:Rif-concrete-syntax}).}
  5376. \label{fig:Rvec-concrete-syntax}
  5377. \end{figure}
  5378. \begin{figure}[tbp]
  5379. \begin{lstlisting}
  5380. (let ([t (vector 40 #t (vector 2))])
  5381. (if (vector-ref t 1)
  5382. (+ (vector-ref t 0)
  5383. (vector-ref (vector-ref t 2) 0))
  5384. 44))
  5385. \end{lstlisting}
  5386. \caption{Example program that creates tuples and reads from them.}
  5387. \label{fig:vector-eg}
  5388. \end{figure}
  5389. \begin{figure}[tp]
  5390. \centering
  5391. \fbox{
  5392. \begin{minipage}{0.96\textwidth}
  5393. \[
  5394. \begin{array}{lcl}
  5395. \itm{op} &::=& \ldots \mid \code{vector} \mid \code{vector-length} \\
  5396. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  5397. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots}
  5398. \mid \BOOL{\itm{bool}}
  5399. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  5400. &\mid& \VECREF{\Exp}{\INT{\Int}}\\
  5401. &\mid& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  5402. &\mid& \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP \\
  5403. \LangVec{} &::=& \PROGRAM{\key{'()}}{\Exp}
  5404. \end{array}
  5405. \]
  5406. \end{minipage}
  5407. }
  5408. \caption{The abstract syntax of \LangVec{}.}
  5409. \label{fig:Rvec-syntax}
  5410. \end{figure}
  5411. \index{allocate}
  5412. \index{heap allocate}
  5413. Tuples are our first encounter with heap-allocated data, which raises
  5414. several interesting issues. First, variable binding performs a
  5415. shallow-copy when dealing with tuples, which means that different
  5416. variables can refer to the same tuple, that is, different variables
  5417. can be \emph{aliases} for the same entity. Consider the following
  5418. example in which both \code{t1} and \code{t2} refer to the same tuple.
  5419. Thus, the mutation through \code{t2} is visible when referencing the
  5420. tuple from \code{t1}, so the result of this program is \code{42}.
  5421. \index{alias}\index{mutation}
  5422. \begin{center}
  5423. \begin{minipage}{0.96\textwidth}
  5424. \begin{lstlisting}
  5425. (let ([t1 (vector 3 7)])
  5426. (let ([t2 t1])
  5427. (let ([_ (vector-set! t2 0 42)])
  5428. (vector-ref t1 0))))
  5429. \end{lstlisting}
  5430. \end{minipage}
  5431. \end{center}
  5432. The next issue concerns the lifetime of tuples. Of course, they are
  5433. created by the \code{vector} form, but when does their lifetime end?
  5434. Notice that \LangVec{} does not include an operation for deleting
  5435. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  5436. of static scoping. For example, the following program returns
  5437. \code{42} even though the variable \code{w} goes out of scope prior to
  5438. the \code{vector-ref} that reads from the vector it was bound to.
  5439. \begin{center}
  5440. \begin{minipage}{0.96\textwidth}
  5441. \begin{lstlisting}
  5442. (let ([v (vector (vector 44))])
  5443. (let ([x (let ([w (vector 42)])
  5444. (let ([_ (vector-set! v 0 w)])
  5445. 0))])
  5446. (+ x (vector-ref (vector-ref v 0) 0))))
  5447. \end{lstlisting}
  5448. \end{minipage}
  5449. \end{center}
  5450. From the perspective of programmer-observable behavior, tuples live
  5451. forever. Of course, if they really lived forever, then many programs
  5452. would run out of memory.\footnote{The \LangVec{} language does not have
  5453. looping or recursive functions, so it is nigh impossible to write a
  5454. program in \LangVec{} that will run out of memory. However, we add
  5455. recursive functions in the next Chapter!} A Racket implementation
  5456. must therefore perform automatic garbage collection.
  5457. Figure~\ref{fig:interp-Rvec} shows the definitional interpreter for the
  5458. \LangVec{} language. We define the \code{vector}, \code{vector-length},
  5459. \code{vector-ref}, and \code{vector-set!} operations for \LangVec{} in
  5460. terms of the corresponding operations in Racket. One subtle point is
  5461. that the \code{vector-set!} operation returns the \code{\#<void>}
  5462. value. The \code{\#<void>} value can be passed around just like other
  5463. values inside an \LangVec{} program and a \code{\#<void>} value can be
  5464. compared for equality with another \code{\#<void>} value. However,
  5465. there are no other operations specific to the the \code{\#<void>}
  5466. value in \LangVec{}. In contrast, Racket defines the \code{void?} predicate
  5467. that returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  5468. otherwise.
  5469. \begin{figure}[tbp]
  5470. \begin{lstlisting}
  5471. (define interp-Rvec-class
  5472. (class interp-Rif-class
  5473. (super-new)
  5474. (define/override (interp-op op)
  5475. (match op
  5476. ['eq? (lambda (v1 v2)
  5477. (cond [(or (and (fixnum? v1) (fixnum? v2))
  5478. (and (boolean? v1) (boolean? v2))
  5479. (and (vector? v1) (vector? v2))
  5480. (and (void? v1) (void? v2)))
  5481. (eq? v1 v2)]))]
  5482. ['vector vector]
  5483. ['vector-length vector-length]
  5484. ['vector-ref vector-ref]
  5485. ['vector-set! vector-set!]
  5486. [else (super interp-op op)]
  5487. ))
  5488. (define/override ((interp-exp env) e)
  5489. (define recur (interp-exp env))
  5490. (match e
  5491. [(HasType e t) (recur e)]
  5492. [(Void) (void)]
  5493. [else ((super interp-exp env) e)]
  5494. ))
  5495. ))
  5496. (define (interp-Rvec p)
  5497. (send (new interp-Rvec-class) interp-program p))
  5498. \end{lstlisting}
  5499. \caption{Interpreter for the \LangVec{} language.}
  5500. \label{fig:interp-Rvec}
  5501. \end{figure}
  5502. Figure~\ref{fig:type-check-Rvec} shows the type checker for \LangVec{}, which
  5503. deserves some explanation. When allocating a vector, we need to know
  5504. which elements of the vector are pointers (i.e. are also vectors). We
  5505. can obtain this information during type checking. The type checker in
  5506. Figure~\ref{fig:type-check-Rvec} not only computes the type of an
  5507. expression, it also wraps every \key{vector} creation with the form
  5508. $(\key{HasType}~e~T)$, where $T$ is the vector's type.
  5509. %
  5510. To create the s-expression for the \code{Vector} type in
  5511. Figure~\ref{fig:type-check-Rvec}, we use the
  5512. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  5513. operator} \code{,@} to insert the list \code{t*} without its usual
  5514. start and end parentheses. \index{unquote-slicing}
  5515. \begin{figure}[tp]
  5516. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5517. (define type-check-Rvec-class
  5518. (class type-check-Rif-class
  5519. (super-new)
  5520. (inherit check-type-equal?)
  5521. (define/override (type-check-exp env)
  5522. (lambda (e)
  5523. (define recur (type-check-exp env))
  5524. (match e
  5525. [(Void) (values (Void) 'Void)]
  5526. [(Prim 'vector es)
  5527. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  5528. (define t `(Vector ,@t*))
  5529. (values (HasType (Prim 'vector e*) t) t)]
  5530. [(Prim 'vector-ref (list e1 (Int i)))
  5531. (define-values (e1^ t) (recur e1))
  5532. (match t
  5533. [`(Vector ,ts ...)
  5534. (unless (and (0 . <= . i) (i . < . (length ts)))
  5535. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  5536. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  5537. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  5538. [(Prim 'vector-set! (list e1 (Int i) arg) )
  5539. (define-values (e-vec t-vec) (recur e1))
  5540. (define-values (e-arg^ t-arg) (recur arg))
  5541. (match t-vec
  5542. [`(Vector ,ts ...)
  5543. (unless (and (0 . <= . i) (i . < . (length ts)))
  5544. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  5545. (check-type-equal? (list-ref ts i) t-arg e)
  5546. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  5547. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  5548. [(Prim 'vector-length (list e))
  5549. (define-values (e^ t) (recur e))
  5550. (match t
  5551. [`(Vector ,ts ...)
  5552. (values (Prim 'vector-length (list e^)) 'Integer)]
  5553. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  5554. [(Prim 'eq? (list arg1 arg2))
  5555. (define-values (e1 t1) (recur arg1))
  5556. (define-values (e2 t2) (recur arg2))
  5557. (match* (t1 t2)
  5558. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  5559. [(other wise) (check-type-equal? t1 t2 e)])
  5560. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  5561. [(HasType (Prim 'vector es) t)
  5562. ((type-check-exp env) (Prim 'vector es))]
  5563. [(HasType e1 t)
  5564. (define-values (e1^ t^) (recur e1))
  5565. (check-type-equal? t t^ e)
  5566. (values (HasType e1^ t) t)]
  5567. [else ((super type-check-exp env) e)]
  5568. )))
  5569. ))
  5570. (define (type-check-Rvec p)
  5571. (send (new type-check-Rvec-class) type-check-program p))
  5572. \end{lstlisting}
  5573. \caption{Type checker for the \LangVec{} language.}
  5574. \label{fig:type-check-Rvec}
  5575. \end{figure}
  5576. \section{Garbage Collection}
  5577. \label{sec:GC}
  5578. Here we study a relatively simple algorithm for garbage collection
  5579. that is the basis of state-of-the-art garbage
  5580. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  5581. particular, we describe a two-space copying
  5582. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  5583. perform the
  5584. copy~\citep{Cheney:1970aa}.
  5585. \index{copying collector}
  5586. \index{two-space copying collector}
  5587. Figure~\ref{fig:copying-collector} gives a
  5588. coarse-grained depiction of what happens in a two-space collector,
  5589. showing two time steps, prior to garbage collection (on the top) and
  5590. after garbage collection (on the bottom). In a two-space collector,
  5591. the heap is divided into two parts named the FromSpace and the
  5592. ToSpace. Initially, all allocations go to the FromSpace until there is
  5593. not enough room for the next allocation request. At that point, the
  5594. garbage collector goes to work to make more room.
  5595. \index{ToSpace}
  5596. \index{FromSpace}
  5597. The garbage collector must be careful not to reclaim tuples that will
  5598. be used by the program in the future. Of course, it is impossible in
  5599. general to predict what a program will do, but we can over approximate
  5600. the will-be-used tuples by preserving all tuples that could be
  5601. accessed by \emph{any} program given the current computer state. A
  5602. program could access any tuple whose address is in a register or on
  5603. the procedure call stack. These addresses are called the \emph{root
  5604. set}\index{root set}. In addition, a program could access any tuple that is
  5605. transitively reachable from the root set. Thus, it is safe for the
  5606. garbage collector to reclaim the tuples that are not reachable in this
  5607. way.
  5608. So the goal of the garbage collector is twofold:
  5609. \begin{enumerate}
  5610. \item preserve all tuple that are reachable from the root set via a
  5611. path of pointers, that is, the \emph{live} tuples, and
  5612. \item reclaim the memory of everything else, that is, the
  5613. \emph{garbage}.
  5614. \end{enumerate}
  5615. A copying collector accomplishes this by copying all of the live
  5616. objects from the FromSpace into the ToSpace and then performs a sleight
  5617. of hand, treating the ToSpace as the new FromSpace and the old
  5618. FromSpace as the new ToSpace. In the example of
  5619. Figure~\ref{fig:copying-collector}, there are three pointers in the
  5620. root set, one in a register and two on the stack. All of the live
  5621. objects have been copied to the ToSpace (the right-hand side of
  5622. Figure~\ref{fig:copying-collector}) in a way that preserves the
  5623. pointer relationships. For example, the pointer in the register still
  5624. points to a 2-tuple whose first element is a 3-tuple and whose second
  5625. element is a 2-tuple. There are four tuples that are not reachable
  5626. from the root set and therefore do not get copied into the ToSpace.
  5627. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  5628. created by a well-typed program in \LangVec{} because it contains a
  5629. cycle. However, creating cycles will be possible once we get to \LangAny{}.
  5630. We design the garbage collector to deal with cycles to begin with so
  5631. we will not need to revisit this issue.
  5632. \begin{figure}[tbp]
  5633. \centering
  5634. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  5635. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  5636. \caption{A copying collector in action.}
  5637. \label{fig:copying-collector}
  5638. \end{figure}
  5639. There are many alternatives to copying collectors (and their bigger
  5640. siblings, the generational collectors) when its comes to garbage
  5641. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  5642. reference counting~\citep{Collins:1960aa}. The strengths of copying
  5643. collectors are that allocation is fast (just a comparison and pointer
  5644. increment), there is no fragmentation, cyclic garbage is collected,
  5645. and the time complexity of collection only depends on the amount of
  5646. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  5647. main disadvantages of a two-space copying collector is that it uses a
  5648. lot of space and takes a long time to perform the copy, though these
  5649. problems are ameliorated in generational collectors. Racket and
  5650. Scheme programs tend to allocate many small objects and generate a lot
  5651. of garbage, so copying and generational collectors are a good fit.
  5652. Garbage collection is an active research topic, especially concurrent
  5653. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  5654. developing new techniques and revisiting old
  5655. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  5656. meet every year at the International Symposium on Memory Management to
  5657. present these findings.
  5658. \subsection{Graph Copying via Cheney's Algorithm}
  5659. \label{sec:cheney}
  5660. \index{Cheney's algorithm}
  5661. Let us take a closer look at the copying of the live objects. The
  5662. allocated objects and pointers can be viewed as a graph and we need to
  5663. copy the part of the graph that is reachable from the root set. To
  5664. make sure we copy all of the reachable vertices in the graph, we need
  5665. an exhaustive graph traversal algorithm, such as depth-first search or
  5666. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  5667. such algorithms take into account the possibility of cycles by marking
  5668. which vertices have already been visited, so as to ensure termination
  5669. of the algorithm. These search algorithms also use a data structure
  5670. such as a stack or queue as a to-do list to keep track of the vertices
  5671. that need to be visited. We use breadth-first search and a trick
  5672. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  5673. and copying tuples into the ToSpace.
  5674. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  5675. copy progresses. The queue is represented by a chunk of contiguous
  5676. memory at the beginning of the ToSpace, using two pointers to track
  5677. the front and the back of the queue. The algorithm starts by copying
  5678. all tuples that are immediately reachable from the root set into the
  5679. ToSpace to form the initial queue. When we copy a tuple, we mark the
  5680. old tuple to indicate that it has been visited. We discuss how this
  5681. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  5682. pointers inside the copied tuples in the queue still point back to the
  5683. FromSpace. Once the initial queue has been created, the algorithm
  5684. enters a loop in which it repeatedly processes the tuple at the front
  5685. of the queue and pops it off the queue. To process a tuple, the
  5686. algorithm copies all the tuple that are directly reachable from it to
  5687. the ToSpace, placing them at the back of the queue. The algorithm then
  5688. updates the pointers in the popped tuple so they point to the newly
  5689. copied tuples.
  5690. \begin{figure}[tbp]
  5691. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  5692. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  5693. \label{fig:cheney}
  5694. \end{figure}
  5695. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  5696. tuple whose second element is $42$ to the back of the queue. The other
  5697. pointer goes to a tuple that has already been copied, so we do not
  5698. need to copy it again, but we do need to update the pointer to the new
  5699. location. This can be accomplished by storing a \emph{forwarding
  5700. pointer} to the new location in the old tuple, back when we initially
  5701. copied the tuple into the ToSpace. This completes one step of the
  5702. algorithm. The algorithm continues in this way until the front of the
  5703. queue is empty, that is, until the front catches up with the back.
  5704. \subsection{Data Representation}
  5705. \label{sec:data-rep-gc}
  5706. The garbage collector places some requirements on the data
  5707. representations used by our compiler. First, the garbage collector
  5708. needs to distinguish between pointers and other kinds of data. There
  5709. are several ways to accomplish this.
  5710. \begin{enumerate}
  5711. \item Attached a tag to each object that identifies what type of
  5712. object it is~\citep{McCarthy:1960dz}.
  5713. \item Store different types of objects in different
  5714. regions~\citep{Steele:1977ab}.
  5715. \item Use type information from the program to either generate
  5716. type-specific code for collecting or to generate tables that can
  5717. guide the
  5718. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  5719. \end{enumerate}
  5720. Dynamically typed languages, such as Lisp, need to tag objects
  5721. anyways, so option 1 is a natural choice for those languages.
  5722. However, \LangVec{} is a statically typed language, so it would be
  5723. unfortunate to require tags on every object, especially small and
  5724. pervasive objects like integers and Booleans. Option 3 is the
  5725. best-performing choice for statically typed languages, but comes with
  5726. a relatively high implementation complexity. To keep this chapter
  5727. within a 2-week time budget, we recommend a combination of options 1
  5728. and 2, using separate strategies for the stack and the heap.
  5729. Regarding the stack, we recommend using a separate stack for pointers,
  5730. which we call a \emph{root stack}\index{root stack} (a.k.a. ``shadow
  5731. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  5732. is, when a local variable needs to be spilled and is of type
  5733. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  5734. stack instead of the normal procedure call stack. Furthermore, we
  5735. always spill vector-typed variables if they are live during a call to
  5736. the collector, thereby ensuring that no pointers are in registers
  5737. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  5738. example from Figure~\ref{fig:copying-collector} and contrasts it with
  5739. the data layout using a root stack. The root stack contains the two
  5740. pointers from the regular stack and also the pointer in the second
  5741. register.
  5742. \begin{figure}[tbp]
  5743. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  5744. \caption{Maintaining a root stack to facilitate garbage collection.}
  5745. \label{fig:shadow-stack}
  5746. \end{figure}
  5747. The problem of distinguishing between pointers and other kinds of data
  5748. also arises inside of each tuple on the heap. We solve this problem by
  5749. attaching a tag, an extra 64-bits, to each
  5750. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  5751. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  5752. that we have drawn the bits in a big-endian way, from right-to-left,
  5753. with bit location 0 (the least significant bit) on the far right,
  5754. which corresponds to the direction of the x86 shifting instructions
  5755. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  5756. is dedicated to specifying which elements of the tuple are pointers,
  5757. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  5758. indicates there is a pointer and a 0 bit indicates some other kind of
  5759. data. The pointer mask starts at bit location 7. We have limited
  5760. tuples to a maximum size of 50 elements, so we just need 50 bits for
  5761. the pointer mask. The tag also contains two other pieces of
  5762. information. The length of the tuple (number of elements) is stored in
  5763. bits location 1 through 6. Finally, the bit at location 0 indicates
  5764. whether the tuple has yet to be copied to the ToSpace. If the bit has
  5765. value 1, then this tuple has not yet been copied. If the bit has
  5766. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  5767. of a pointer are always zero anyways because our tuples are 8-byte
  5768. aligned.)
  5769. \begin{figure}[tbp]
  5770. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  5771. \caption{Representation of tuples in the heap.}
  5772. \label{fig:tuple-rep}
  5773. \end{figure}
  5774. \subsection{Implementation of the Garbage Collector}
  5775. \label{sec:organize-gz}
  5776. \index{prelude}
  5777. An implementation of the copying collector is provided in the
  5778. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  5779. interface to the garbage collector that is used by the compiler. The
  5780. \code{initialize} function creates the FromSpace, ToSpace, and root
  5781. stack and should be called in the prelude of the \code{main}
  5782. function. The arguments of \code{initialize} are the root stack size
  5783. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  5784. good choice for both. The \code{initialize} function puts the address
  5785. of the beginning of the FromSpace into the global variable
  5786. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  5787. the address that is 1-past the last element of the FromSpace. (We use
  5788. half-open intervals to represent chunks of
  5789. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  5790. points to the first element of the root stack.
  5791. As long as there is room left in the FromSpace, your generated code
  5792. can allocate tuples simply by moving the \code{free\_ptr} forward.
  5793. %
  5794. The amount of room left in FromSpace is the difference between the
  5795. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  5796. function should be called when there is not enough room left in the
  5797. FromSpace for the next allocation. The \code{collect} function takes
  5798. a pointer to the current top of the root stack (one past the last item
  5799. that was pushed) and the number of bytes that need to be
  5800. allocated. The \code{collect} function performs the copying collection
  5801. and leaves the heap in a state such that the next allocation will
  5802. succeed.
  5803. \begin{figure}[tbp]
  5804. \begin{lstlisting}
  5805. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  5806. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  5807. int64_t* free_ptr;
  5808. int64_t* fromspace_begin;
  5809. int64_t* fromspace_end;
  5810. int64_t** rootstack_begin;
  5811. \end{lstlisting}
  5812. \caption{The compiler's interface to the garbage collector.}
  5813. \label{fig:gc-header}
  5814. \end{figure}
  5815. %% \begin{exercise}
  5816. %% In the file \code{runtime.c} you will find the implementation of
  5817. %% \code{initialize} and a partial implementation of \code{collect}.
  5818. %% The \code{collect} function calls another function, \code{cheney},
  5819. %% to perform the actual copy, and that function is left to the reader
  5820. %% to implement. The following is the prototype for \code{cheney}.
  5821. %% \begin{lstlisting}
  5822. %% static void cheney(int64_t** rootstack_ptr);
  5823. %% \end{lstlisting}
  5824. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  5825. %% rootstack (which is an array of pointers). The \code{cheney} function
  5826. %% also communicates with \code{collect} through the global
  5827. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  5828. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  5829. %% the ToSpace:
  5830. %% \begin{lstlisting}
  5831. %% static int64_t* tospace_begin;
  5832. %% static int64_t* tospace_end;
  5833. %% \end{lstlisting}
  5834. %% The job of the \code{cheney} function is to copy all the live
  5835. %% objects (reachable from the root stack) into the ToSpace, update
  5836. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  5837. %% update the root stack so that it points to the objects in the
  5838. %% ToSpace, and finally to swap the global pointers for the FromSpace
  5839. %% and ToSpace.
  5840. %% \end{exercise}
  5841. %% \section{Compiler Passes}
  5842. %% \label{sec:code-generation-gc}
  5843. The introduction of garbage collection has a non-trivial impact on our
  5844. compiler passes. We introduce a new compiler pass named
  5845. \code{expose-allocation}. We make
  5846. significant changes to \code{select-instructions},
  5847. \code{build-interference}, \code{allocate-registers}, and
  5848. \code{print-x86} and make minor changes in several more passes. The
  5849. following program will serve as our running example. It creates two
  5850. tuples, one nested inside the other. Both tuples have length one. The
  5851. program accesses the element in the inner tuple tuple via two vector
  5852. references.
  5853. % tests/s2_17.rkt
  5854. \begin{lstlisting}
  5855. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  5856. \end{lstlisting}
  5857. \section{Shrink}
  5858. \label{sec:shrink-Rvec}
  5859. Recall that the \code{shrink} pass translates the primitives operators
  5860. into a smaller set of primitives. Because this pass comes after type
  5861. checking, but before the passes that require the type information in
  5862. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  5863. to wrap \code{HasType} around each AST node that it generates.
  5864. \section{Expose Allocation}
  5865. \label{sec:expose-allocation}
  5866. The pass \code{expose-allocation} lowers the \code{vector} creation
  5867. form into a conditional call to the collector followed by the
  5868. allocation. We choose to place the \code{expose-allocation} pass
  5869. before \code{remove-complex-opera*} because the code generated by
  5870. \code{expose-allocation} contains complex operands. We also place
  5871. \code{expose-allocation} before \code{explicate-control} because
  5872. \code{expose-allocation} introduces new variables using \code{let},
  5873. but \code{let} is gone after \code{explicate-control}.
  5874. The output of \code{expose-allocation} is a language \LangAlloc{} that
  5875. extends \LangVec{} with the three new forms that we use in the translation
  5876. of the \code{vector} form.
  5877. \[
  5878. \begin{array}{lcl}
  5879. \Exp &::=& \cdots
  5880. \mid (\key{collect} \,\itm{int})
  5881. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  5882. \mid (\key{global-value} \,\itm{name})
  5883. \end{array}
  5884. \]
  5885. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  5886. $n$ bytes. It will become a call to the \code{collect} function in
  5887. \code{runtime.c} in \code{select-instructions}. The
  5888. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  5889. \index{allocate}
  5890. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  5891. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  5892. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  5893. a global variable, such as \code{free\_ptr}.
  5894. In the following, we show the transformation for the \code{vector}
  5895. form into 1) a sequence of let-bindings for the initializing
  5896. expressions, 2) a conditional call to \code{collect}, 3) a call to
  5897. \code{allocate}, and 4) the initialization of the vector. In the
  5898. following, \itm{len} refers to the length of the vector and
  5899. \itm{bytes} is how many total bytes need to be allocated for the
  5900. vector, which is 8 for the tag plus \itm{len} times 8.
  5901. \begin{lstlisting}
  5902. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  5903. |$\Longrightarrow$|
  5904. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  5905. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  5906. (global-value fromspace_end))
  5907. (void)
  5908. (collect |\itm{bytes}|))])
  5909. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  5910. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  5911. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  5912. |$v$|) ... )))) ...)
  5913. \end{lstlisting}
  5914. In the above, we suppressed all of the \code{has-type} forms in the
  5915. output for the sake of readability. The placement of the initializing
  5916. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  5917. sequence of \code{vector-set!} is important, as those expressions may
  5918. trigger garbage collection and we cannot have an allocated but
  5919. uninitialized tuple on the heap during a collection.
  5920. Figure~\ref{fig:expose-alloc-output} shows the output of the
  5921. \code{expose-allocation} pass on our running example.
  5922. \begin{figure}[tbp]
  5923. % tests/s2_17.rkt
  5924. \begin{lstlisting}
  5925. (vector-ref
  5926. (vector-ref
  5927. (let ([vecinit7976
  5928. (let ([vecinit7972 42])
  5929. (let ([collectret7974
  5930. (if (< (+ (global-value free_ptr) 16)
  5931. (global-value fromspace_end))
  5932. (void)
  5933. (collect 16)
  5934. )])
  5935. (let ([alloc7971 (allocate 1 (Vector Integer))])
  5936. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  5937. alloc7971)
  5938. )
  5939. )
  5940. )
  5941. ])
  5942. (let ([collectret7978
  5943. (if (< (+ (global-value free_ptr) 16)
  5944. (global-value fromspace_end))
  5945. (void)
  5946. (collect 16)
  5947. )])
  5948. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  5949. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  5950. alloc7975)
  5951. )
  5952. )
  5953. )
  5954. 0)
  5955. 0)
  5956. \end{lstlisting}
  5957. \caption{Output of the \code{expose-allocation} pass, minus
  5958. all of the \code{has-type} forms.}
  5959. \label{fig:expose-alloc-output}
  5960. \end{figure}
  5961. \section{Remove Complex Operands}
  5962. \label{sec:remove-complex-opera-Rvec}
  5963. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  5964. should all be treated as complex operands.
  5965. %% A new case for
  5966. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  5967. %% handled carefully to prevent the \code{Prim} node from being separated
  5968. %% from its enclosing \code{HasType}.
  5969. Figure~\ref{fig:Rvec-anf-syntax}
  5970. shows the grammar for the output language \LangVecANF{} of this
  5971. pass, which is \LangVec{} in administrative normal form.
  5972. \begin{figure}[tp]
  5973. \centering
  5974. \fbox{
  5975. \begin{minipage}{0.96\textwidth}
  5976. \small
  5977. \[
  5978. \begin{array}{rcl}
  5979. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }
  5980. \mid \VOID{} \\
  5981. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  5982. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  5983. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  5984. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  5985. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  5986. &\mid& \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  5987. \mid \LP\key{GlobalValue}~\Var\RP\\
  5988. % &\mid& \LP\key{HasType}~\Exp~\Type\RP \\
  5989. R^{\dagger}_3 &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  5990. \end{array}
  5991. \]
  5992. \end{minipage}
  5993. }
  5994. \caption{\LangVecANF{} is \LangVec{} in administrative normal form (ANF).}
  5995. \label{fig:Rvec-anf-syntax}
  5996. \end{figure}
  5997. \section{Explicate Control and the \LangCVec{} language}
  5998. \label{sec:explicate-control-r3}
  5999. \begin{figure}[tp]
  6000. \fbox{
  6001. \begin{minipage}{0.96\textwidth}
  6002. \small
  6003. \[
  6004. \begin{array}{lcl}
  6005. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  6006. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  6007. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  6008. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  6009. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  6010. &\mid& \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  6011. &\mid& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  6012. &\mid& \LP\key{Prim}~\key{'vector-set!}\,\LP\Atm\,\INT{\Int}\,\Atm\RP\RP\\
  6013. &\mid& \LP\key{GlobalValue} \,\Var\RP \mid \LP\key{Void}\RP\\
  6014. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  6015. \mid \LP\key{Collect} \,\itm{int}\RP \\
  6016. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  6017. \mid \GOTO{\itm{label}} } \\
  6018. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  6019. \LangCVec{} & ::= & \gray{ \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }
  6020. \end{array}
  6021. \]
  6022. \end{minipage}
  6023. }
  6024. \caption{The abstract syntax of \LangCVec{}, extending \LangCIf{}
  6025. (Figure~\ref{fig:c1-syntax}).}
  6026. \label{fig:c2-syntax}
  6027. \end{figure}
  6028. The output of \code{explicate-control} is a program in the
  6029. intermediate language \LangCVec{}, whose abstract syntax is defined in
  6030. Figure~\ref{fig:c2-syntax}. (The concrete syntax is defined in
  6031. Figure~\ref{fig:c2-concrete-syntax} of the Appendix.) The new forms
  6032. of \LangCVec{} include the \key{allocate}, \key{vector-ref}, and
  6033. \key{vector-set!}, and \key{global-value} expressions and the
  6034. \code{collect} statement. The \code{explicate-control} pass can treat
  6035. these new forms much like the other expression forms that we've
  6036. already encoutered.
  6037. \section{Select Instructions and the \LangXASTGlobal{} Language}
  6038. \label{sec:select-instructions-gc}
  6039. \index{instruction selection}
  6040. %% void (rep as zero)
  6041. %% allocate
  6042. %% collect (callq collect)
  6043. %% vector-ref
  6044. %% vector-set!
  6045. %% global (postpone)
  6046. In this pass we generate x86 code for most of the new operations that
  6047. were needed to compile tuples, including \code{Allocate},
  6048. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  6049. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  6050. the later has a different concrete syntax (see
  6051. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  6052. \index{x86}
  6053. The \code{vector-ref} and \code{vector-set!} forms translate into
  6054. \code{movq} instructions. (The plus one in the offset is to get past
  6055. the tag at the beginning of the tuple representation.)
  6056. \begin{lstlisting}
  6057. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  6058. |$\Longrightarrow$|
  6059. movq |$\itm{vec}'$|, %r11
  6060. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  6061. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  6062. |$\Longrightarrow$|
  6063. movq |$\itm{vec}'$|, %r11
  6064. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  6065. movq $0, |$\itm{lhs'}$|
  6066. \end{lstlisting}
  6067. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  6068. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  6069. register \code{r11} ensures that offset expression
  6070. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  6071. removing \code{r11} from consideration by the register allocating.
  6072. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  6073. \code{rax}. Then the generated code for \code{vector-set!} would be
  6074. \begin{lstlisting}
  6075. movq |$\itm{vec}'$|, %rax
  6076. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  6077. movq $0, |$\itm{lhs}'$|
  6078. \end{lstlisting}
  6079. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  6080. \code{patch-instructions} would insert a move through \code{rax}
  6081. as follows.
  6082. \begin{lstlisting}
  6083. movq |$\itm{vec}'$|, %rax
  6084. movq |$\itm{arg}'$|, %rax
  6085. movq %rax, |$8(n+1)$|(%rax)
  6086. movq $0, |$\itm{lhs}'$|
  6087. \end{lstlisting}
  6088. But the above sequence of instructions does not work because we're
  6089. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  6090. $\itm{arg}'$) at the same time!
  6091. We compile the \code{allocate} form to operations on the
  6092. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  6093. is the next free address in the FromSpace, so we copy it into
  6094. \code{r11} and then move it forward by enough space for the tuple
  6095. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  6096. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  6097. initialize the \itm{tag} and finally copy the address in \code{r11} to
  6098. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  6099. tag is organized. We recommend using the Racket operations
  6100. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  6101. during compilation. The type annotation in the \code{vector} form is
  6102. used to determine the pointer mask region of the tag.
  6103. \begin{lstlisting}
  6104. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  6105. |$\Longrightarrow$|
  6106. movq free_ptr(%rip), %r11
  6107. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  6108. movq $|$\itm{tag}$|, 0(%r11)
  6109. movq %r11, |$\itm{lhs}'$|
  6110. \end{lstlisting}
  6111. The \code{collect} form is compiled to a call to the \code{collect}
  6112. function in the runtime. The arguments to \code{collect} are 1) the
  6113. top of the root stack and 2) the number of bytes that need to be
  6114. allocated. We use another dedicated register, \code{r15}, to
  6115. store the pointer to the top of the root stack. So \code{r15} is not
  6116. available for use by the register allocator.
  6117. \begin{lstlisting}
  6118. (collect |$\itm{bytes}$|)
  6119. |$\Longrightarrow$|
  6120. movq %r15, %rdi
  6121. movq $|\itm{bytes}|, %rsi
  6122. callq collect
  6123. \end{lstlisting}
  6124. \begin{figure}[tp]
  6125. \fbox{
  6126. \begin{minipage}{0.96\textwidth}
  6127. \[
  6128. \begin{array}{lcl}
  6129. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)} \\
  6130. \LangXGlobal{} &::= & \gray{ \key{.globl main} }\\
  6131. & & \gray{ \key{main:} \; \Instr\ldots }
  6132. \end{array}
  6133. \]
  6134. \end{minipage}
  6135. }
  6136. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXASTIf{} of Figure~\ref{fig:x86-1-concrete}).}
  6137. \label{fig:x86-2-concrete}
  6138. \end{figure}
  6139. \begin{figure}[tp]
  6140. \fbox{
  6141. \begin{minipage}{0.96\textwidth}
  6142. \small
  6143. \[
  6144. \begin{array}{lcl}
  6145. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  6146. \mid \BYTEREG{\Reg}} \\
  6147. &\mid& (\key{Global}~\Var) \\
  6148. \LangXASTGlobal{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  6149. \end{array}
  6150. \]
  6151. \end{minipage}
  6152. }
  6153. \caption{The abstract syntax of \LangXASTGlobal{} (extends \LangXASTIf{} of Figure~\ref{fig:x86-1}).}
  6154. \label{fig:x86-2}
  6155. \end{figure}
  6156. The concrete and abstract syntax of the \LangXASTGlobal{} language is
  6157. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  6158. differs from \LangXASTIf{} just in the addition of the form for global
  6159. variables.
  6160. %
  6161. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  6162. \code{select-instructions} pass on the running example.
  6163. \begin{figure}[tbp]
  6164. \centering
  6165. % tests/s2_17.rkt
  6166. \begin{minipage}[t]{0.5\textwidth}
  6167. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6168. block35:
  6169. movq free_ptr(%rip), alloc9024
  6170. addq $16, free_ptr(%rip)
  6171. movq alloc9024, %r11
  6172. movq $131, 0(%r11)
  6173. movq alloc9024, %r11
  6174. movq vecinit9025, 8(%r11)
  6175. movq $0, initret9026
  6176. movq alloc9024, %r11
  6177. movq 8(%r11), tmp9034
  6178. movq tmp9034, %r11
  6179. movq 8(%r11), %rax
  6180. jmp conclusion
  6181. block36:
  6182. movq $0, collectret9027
  6183. jmp block35
  6184. block38:
  6185. movq free_ptr(%rip), alloc9020
  6186. addq $16, free_ptr(%rip)
  6187. movq alloc9020, %r11
  6188. movq $3, 0(%r11)
  6189. movq alloc9020, %r11
  6190. movq vecinit9021, 8(%r11)
  6191. movq $0, initret9022
  6192. movq alloc9020, vecinit9025
  6193. movq free_ptr(%rip), tmp9031
  6194. movq tmp9031, tmp9032
  6195. addq $16, tmp9032
  6196. movq fromspace_end(%rip), tmp9033
  6197. cmpq tmp9033, tmp9032
  6198. jl block36
  6199. jmp block37
  6200. block37:
  6201. movq %r15, %rdi
  6202. movq $16, %rsi
  6203. callq 'collect
  6204. jmp block35
  6205. block39:
  6206. movq $0, collectret9023
  6207. jmp block38
  6208. \end{lstlisting}
  6209. \end{minipage}
  6210. \begin{minipage}[t]{0.45\textwidth}
  6211. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6212. start:
  6213. movq $42, vecinit9021
  6214. movq free_ptr(%rip), tmp9028
  6215. movq tmp9028, tmp9029
  6216. addq $16, tmp9029
  6217. movq fromspace_end(%rip), tmp9030
  6218. cmpq tmp9030, tmp9029
  6219. jl block39
  6220. jmp block40
  6221. block40:
  6222. movq %r15, %rdi
  6223. movq $16, %rsi
  6224. callq 'collect
  6225. jmp block38
  6226. \end{lstlisting}
  6227. \end{minipage}
  6228. \caption{Output of the \code{select-instructions} pass.}
  6229. \label{fig:select-instr-output-gc}
  6230. \end{figure}
  6231. \clearpage
  6232. \section{Register Allocation}
  6233. \label{sec:reg-alloc-gc}
  6234. \index{register allocation}
  6235. As discussed earlier in this chapter, the garbage collector needs to
  6236. access all the pointers in the root set, that is, all variables that
  6237. are vectors. It will be the responsibility of the register allocator
  6238. to make sure that:
  6239. \begin{enumerate}
  6240. \item the root stack is used for spilling vector-typed variables, and
  6241. \item if a vector-typed variable is live during a call to the
  6242. collector, it must be spilled to ensure it is visible to the
  6243. collector.
  6244. \end{enumerate}
  6245. The later responsibility can be handled during construction of the
  6246. interference graph, by adding interference edges between the call-live
  6247. vector-typed variables and all the callee-saved registers. (They
  6248. already interfere with the caller-saved registers.) The type
  6249. information for variables is in the \code{Program} form, so we
  6250. recommend adding another parameter to the \code{build-interference}
  6251. function to communicate this alist.
  6252. The spilling of vector-typed variables to the root stack can be
  6253. handled after graph coloring, when choosing how to assign the colors
  6254. (integers) to registers and stack locations. The \code{Program} output
  6255. of this pass changes to also record the number of spills to the root
  6256. stack.
  6257. % build-interference
  6258. %
  6259. % callq
  6260. % extra parameter for var->type assoc. list
  6261. % update 'program' and 'if'
  6262. % allocate-registers
  6263. % allocate spilled vectors to the rootstack
  6264. % don't change color-graph
  6265. \section{Print x86}
  6266. \label{sec:print-x86-gc}
  6267. \index{prelude}\index{conclusion}
  6268. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  6269. \code{print-x86} pass on the running example. In the prelude and
  6270. conclusion of the \code{main} function, we treat the root stack very
  6271. much like the regular stack in that we move the root stack pointer
  6272. (\code{r15}) to make room for the spills to the root stack, except
  6273. that the root stack grows up instead of down. For the running
  6274. example, there was just one spill so we increment \code{r15} by 8
  6275. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  6276. One issue that deserves special care is that there may be a call to
  6277. \code{collect} prior to the initializing assignments for all the
  6278. variables in the root stack. We do not want the garbage collector to
  6279. accidentally think that some uninitialized variable is a pointer that
  6280. needs to be followed. Thus, we zero-out all locations on the root
  6281. stack in the prelude of \code{main}. In
  6282. Figure~\ref{fig:print-x86-output-gc}, the instruction
  6283. %
  6284. \lstinline{movq $0, (%r15)}
  6285. %
  6286. accomplishes this task. The garbage collector tests each root to see
  6287. if it is null prior to dereferencing it.
  6288. \begin{figure}[htbp]
  6289. \begin{minipage}[t]{0.5\textwidth}
  6290. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6291. block35:
  6292. movq free_ptr(%rip), %rcx
  6293. addq $16, free_ptr(%rip)
  6294. movq %rcx, %r11
  6295. movq $131, 0(%r11)
  6296. movq %rcx, %r11
  6297. movq -8(%r15), %rax
  6298. movq %rax, 8(%r11)
  6299. movq $0, %rdx
  6300. movq %rcx, %r11
  6301. movq 8(%r11), %rcx
  6302. movq %rcx, %r11
  6303. movq 8(%r11), %rax
  6304. jmp conclusion
  6305. block36:
  6306. movq $0, %rcx
  6307. jmp block35
  6308. block38:
  6309. movq free_ptr(%rip), %rcx
  6310. addq $16, free_ptr(%rip)
  6311. movq %rcx, %r11
  6312. movq $3, 0(%r11)
  6313. movq %rcx, %r11
  6314. movq %rbx, 8(%r11)
  6315. movq $0, %rdx
  6316. movq %rcx, -8(%r15)
  6317. movq free_ptr(%rip), %rcx
  6318. addq $16, %rcx
  6319. movq fromspace_end(%rip), %rdx
  6320. cmpq %rdx, %rcx
  6321. jl block36
  6322. movq %r15, %rdi
  6323. movq $16, %rsi
  6324. callq collect
  6325. jmp block35
  6326. block39:
  6327. movq $0, %rcx
  6328. jmp block38
  6329. \end{lstlisting}
  6330. \end{minipage}
  6331. \begin{minipage}[t]{0.45\textwidth}
  6332. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6333. start:
  6334. movq $42, %rbx
  6335. movq free_ptr(%rip), %rdx
  6336. addq $16, %rdx
  6337. movq fromspace_end(%rip), %rcx
  6338. cmpq %rcx, %rdx
  6339. jl block39
  6340. movq %r15, %rdi
  6341. movq $16, %rsi
  6342. callq collect
  6343. jmp block38
  6344. .globl main
  6345. main:
  6346. pushq %rbp
  6347. movq %rsp, %rbp
  6348. pushq %r13
  6349. pushq %r12
  6350. pushq %rbx
  6351. pushq %r14
  6352. subq $0, %rsp
  6353. movq $16384, %rdi
  6354. movq $16384, %rsi
  6355. callq initialize
  6356. movq rootstack_begin(%rip), %r15
  6357. movq $0, (%r15)
  6358. addq $8, %r15
  6359. jmp start
  6360. conclusion:
  6361. subq $8, %r15
  6362. addq $0, %rsp
  6363. popq %r14
  6364. popq %rbx
  6365. popq %r12
  6366. popq %r13
  6367. popq %rbp
  6368. retq
  6369. \end{lstlisting}
  6370. \end{minipage}
  6371. \caption{Output of the \code{print-x86} pass.}
  6372. \label{fig:print-x86-output-gc}
  6373. \end{figure}
  6374. \begin{figure}[p]
  6375. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6376. \node (Rvec) at (0,2) {\large \LangVec{}};
  6377. \node (Rvec-2) at (3,2) {\large \LangVec{}};
  6378. \node (Rvec-3) at (6,2) {\large \LangVec{}};
  6379. \node (Rvec-4) at (9,2) {\large \LangVec{}};
  6380. \node (Rvec-5) at (12,2) {\large \LangAlloc{}};
  6381. \node (C2-4) at (3,0) {\large \LangCVec{}};
  6382. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  6383. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  6384. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  6385. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  6386. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  6387. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  6388. %\path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize type-check} (Rvec-2);
  6389. \path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize shrink} (Rvec-2);
  6390. \path[->,bend left=15] (Rvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Rvec-3);
  6391. \path[->,bend left=15] (Rvec-3) edge [above] node {\ttfamily\footnotesize expose-alloc.} (Rvec-4);
  6392. \path[->,bend left=15] (Rvec-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvec-5);
  6393. \path[->,bend left=20] (Rvec-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-4);
  6394. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select-instr.} (x86-2);
  6395. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6396. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  6397. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  6398. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  6399. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  6400. \end{tikzpicture}
  6401. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  6402. \label{fig:Rvec-passes}
  6403. \end{figure}
  6404. Figure~\ref{fig:Rvec-passes} gives an overview of all the passes needed
  6405. for the compilation of \LangVec{}.
  6406. \section{Challenge: Simple Structures}
  6407. \label{sec:simple-structures}
  6408. \index{struct}
  6409. \index{structure}
  6410. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  6411. $R^s_3$, which extends $R^3$ with support for simple structures.
  6412. Recall that a \code{struct} in Typed Racket is a user-defined data
  6413. type that contains named fields and that is heap allocated, similar to
  6414. a vector. The following is an example of a structure definition, in
  6415. this case the definition of a \code{point} type.
  6416. \begin{lstlisting}
  6417. (struct point ([x : Integer] [y : Integer]) #:mutable)
  6418. \end{lstlisting}
  6419. \begin{figure}[tbp]
  6420. \centering
  6421. \fbox{
  6422. \begin{minipage}{0.96\textwidth}
  6423. \[
  6424. \begin{array}{lcl}
  6425. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6426. \mid (\key{Vector}\;\Type \ldots) \mid \key{Void} } \mid \Var \\
  6427. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6428. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  6429. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  6430. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6431. \mid (\key{and}\;\Exp\;\Exp)
  6432. \mid (\key{or}\;\Exp\;\Exp)
  6433. \mid (\key{not}\;\Exp) } \\
  6434. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  6435. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  6436. &\mid& \gray{ (\key{vector}\;\Exp \ldots)
  6437. \mid (\key{vector-ref}\;\Exp\;\Int) } \\
  6438. &\mid& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  6439. &\mid& \gray{ (\key{void}) } \mid (\Var\;\Exp \ldots)\\
  6440. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  6441. R^s_3 &::=& \Def \ldots \; \Exp
  6442. \end{array}
  6443. \]
  6444. \end{minipage}
  6445. }
  6446. \caption{The concrete syntax of $R^s_3$, extending \LangVec{}
  6447. (Figure~\ref{fig:Rvec-concrete-syntax}).}
  6448. \label{fig:r3s-concrete-syntax}
  6449. \end{figure}
  6450. An instance of a structure is created using function call syntax, with
  6451. the name of the structure in the function position:
  6452. \begin{lstlisting}
  6453. (point 7 12)
  6454. \end{lstlisting}
  6455. Function-call syntax is also used to read the value in a field of a
  6456. structure. The function name is formed by the structure name, a dash,
  6457. and the field name. The following example uses \code{point-x} and
  6458. \code{point-y} to access the \code{x} and \code{y} fields of two point
  6459. instances.
  6460. \begin{center}
  6461. \begin{lstlisting}
  6462. (let ([pt1 (point 7 12)])
  6463. (let ([pt2 (point 4 3)])
  6464. (+ (- (point-x pt1) (point-x pt2))
  6465. (- (point-y pt1) (point-y pt2)))))
  6466. \end{lstlisting}
  6467. \end{center}
  6468. Similarly, to write to a field of a structure, use its set function,
  6469. whose name starts with \code{set-}, followed by the structure name,
  6470. then a dash, then the field name, and concluded with an exclamation
  6471. mark. The following example uses \code{set-point-x!} to change the
  6472. \code{x} field from \code{7} to \code{42}.
  6473. \begin{center}
  6474. \begin{lstlisting}
  6475. (let ([pt (point 7 12)])
  6476. (let ([_ (set-point-x! pt 42)])
  6477. (point-x pt)))
  6478. \end{lstlisting}
  6479. \end{center}
  6480. \begin{exercise}\normalfont
  6481. Extend your compiler with support for simple structures, compiling
  6482. $R^s_3$ to x86 assembly code. Create five new test cases that use
  6483. structures and test your compiler.
  6484. \end{exercise}
  6485. \section{Challenge: Generational Collection}
  6486. The copying collector described in Section~\ref{sec:GC} can incur
  6487. significant runtime overhead because the call to \code{collect} takes
  6488. time proportional to all of the live data. One way to reduce this
  6489. overhead is to reduce how much data is inspected in each call to
  6490. \code{collect}. In particular, researchers have observed that recently
  6491. allocated data is more likely to become garbage then data that has
  6492. survived one or more previous calls to \code{collect}. This insight
  6493. motivated the creation of \emph{generational garbage collectors}
  6494. \index{generational garbage collector} that
  6495. 1) segregates data according to its age into two or more generations,
  6496. 2) allocates less space for younger generations, so collecting them is
  6497. faster, and more space for the older generations, and 3) performs
  6498. collection on the younger generations more frequently then for older
  6499. generations~\citep{Wilson:1992fk}.
  6500. For this challenge assignment, the goal is to adapt the copying
  6501. collector implemented in \code{runtime.c} to use two generations, one
  6502. for young data and one for old data. Each generation consists of a
  6503. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  6504. \code{collect} function to use the two generations.
  6505. \begin{enumerate}
  6506. \item Copy the young generation's FromSpace to its ToSpace then switch
  6507. the role of the ToSpace and FromSpace
  6508. \item If there is enough space for the requested number of bytes in
  6509. the young FromSpace, then return from \code{collect}.
  6510. \item If there is not enough space in the young FromSpace for the
  6511. requested bytes, then move the data from the young generation to the
  6512. old one with the following steps:
  6513. \begin{enumerate}
  6514. \item If there is enough room in the old FromSpace, copy the young
  6515. FromSpace to the old FromSpace and then return.
  6516. \item If there is not enough room in the old FromSpace, then collect
  6517. the old generation by copying the old FromSpace to the old ToSpace
  6518. and swap the roles of the old FromSpace and ToSpace.
  6519. \item If there is enough room now, copy the young FromSpace to the
  6520. old FromSpace and return. Otherwise, allocate a larger FromSpace
  6521. and ToSpace for the old generation. Copy the young FromSpace and
  6522. the old FromSpace into the larger FromSpace for the old
  6523. generation and then return.
  6524. \end{enumerate}
  6525. \end{enumerate}
  6526. We recommend that you generalize the \code{cheney} function so that it
  6527. can be used for all the copies mentioned above: between the young
  6528. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  6529. between the young FromSpace and old FromSpace. This can be
  6530. accomplished by adding parameters to \code{cheney} that replace its
  6531. use of the global variables \code{fromspace\_begin},
  6532. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  6533. Note that the collection of the young generation does not traverse the
  6534. old generation. This introduces a potential problem: there may be
  6535. young data that is only reachable through pointers in the old
  6536. generation. If these pointers are not taken into account, the
  6537. collector could throw away young data that is live! One solution,
  6538. called \emph{pointer recording}, is to maintain a set of all the
  6539. pointers from the old generation into the new generation and consider
  6540. this set as part of the root set. To maintain this set, the compiler
  6541. must insert extra instructions around every \code{vector-set!}. If the
  6542. vector being modified is in the old generation, and if the value being
  6543. written is a pointer into the new generation, than that pointer must
  6544. be added to the set. Also, if the value being overwritten was a
  6545. pointer into the new generation, then that pointer should be removed
  6546. from the set.
  6547. \begin{exercise}\normalfont
  6548. Adapt the \code{collect} function in \code{runtime.c} to implement
  6549. generational garbage collection, as outlined in this section.
  6550. Update the code generation for \code{vector-set!} to implement
  6551. pointer recording. Make sure that your new compiler and runtime
  6552. passes your test suite.
  6553. \end{exercise}
  6554. % TODO: challenge, implement homogeneous vectors
  6555. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6556. \chapter{Functions}
  6557. \label{ch:functions}
  6558. \index{function}
  6559. This chapter studies the compilation of functions similar to those
  6560. found in the C language. This corresponds to a subset of Typed Racket
  6561. in which only top-level function definitions are allowed. This kind of
  6562. function is an important stepping stone to implementing
  6563. lexically-scoped functions, that is, \key{lambda} abstractions, which
  6564. is the topic of Chapter~\ref{ch:lambdas}.
  6565. \section{The \LangFun{} Language}
  6566. The concrete and abstract syntax for function definitions and function
  6567. application is shown in Figures~\ref{fig:Rfun-concrete-syntax} and
  6568. \ref{fig:Rfun-syntax}, where we define the \LangFun{} language. Programs in
  6569. \LangFun{} begin with zero or more function definitions. The function
  6570. names from these definitions are in-scope for the entire program,
  6571. including all other function definitions (so the ordering of function
  6572. definitions does not matter). The concrete syntax for function
  6573. application\index{function application} is $(\Exp \; \Exp \ldots)$
  6574. where the first expression must
  6575. evaluate to a function and the rest are the arguments.
  6576. The abstract syntax for function application is
  6577. $\APPLY{\Exp}{\Exp\ldots}$.
  6578. %% The syntax for function application does not include an explicit
  6579. %% keyword, which is error prone when using \code{match}. To alleviate
  6580. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  6581. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  6582. Functions are first-class in the sense that a function pointer
  6583. \index{function pointer} is data and can be stored in memory or passed
  6584. as a parameter to another function. Thus, we introduce a function
  6585. type, written
  6586. \begin{lstlisting}
  6587. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  6588. \end{lstlisting}
  6589. for a function whose $n$ parameters have the types $\Type_1$ through
  6590. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  6591. these functions (with respect to Racket functions) is that they are
  6592. not lexically scoped. That is, the only external entities that can be
  6593. referenced from inside a function body are other globally-defined
  6594. functions. The syntax of \LangFun{} prevents functions from being nested
  6595. inside each other.
  6596. \begin{figure}[tp]
  6597. \centering
  6598. \fbox{
  6599. \begin{minipage}{0.96\textwidth}
  6600. \small
  6601. \[
  6602. \begin{array}{lcl}
  6603. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  6604. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void} } \mid (\Type \ldots \; \key{->}\; \Type) \\
  6605. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6606. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  6607. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  6608. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6609. \mid (\key{and}\;\Exp\;\Exp)
  6610. \mid (\key{or}\;\Exp\;\Exp)
  6611. \mid (\key{not}\;\Exp)} \\
  6612. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  6613. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  6614. (\key{vector-ref}\;\Exp\;\Int)} \\
  6615. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  6616. \mid \LP\key{has-type}~\Exp~\Type\RP } \\
  6617. &\mid& \LP\Exp \; \Exp \ldots\RP \\
  6618. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  6619. \LangFun{} &::=& \Def \ldots \; \Exp
  6620. \end{array}
  6621. \]
  6622. \end{minipage}
  6623. }
  6624. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-concrete-syntax}).}
  6625. \label{fig:Rfun-concrete-syntax}
  6626. \end{figure}
  6627. \begin{figure}[tp]
  6628. \centering
  6629. \fbox{
  6630. \begin{minipage}{0.96\textwidth}
  6631. \small
  6632. \[
  6633. \begin{array}{lcl}
  6634. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6635. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  6636. &\mid& \gray{ \BOOL{\itm{bool}}
  6637. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6638. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP }
  6639. \mid \APPLY{\Exp}{\Exp\ldots}\\
  6640. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}\\
  6641. \LangFun{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  6642. \end{array}
  6643. \]
  6644. \end{minipage}
  6645. }
  6646. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-syntax}).}
  6647. \label{fig:Rfun-syntax}
  6648. \end{figure}
  6649. The program in Figure~\ref{fig:Rfun-function-example} is a
  6650. representative example of defining and using functions in \LangFun{}. We
  6651. define a function \code{map-vec} that applies some other function
  6652. \code{f} to both elements of a vector and returns a new
  6653. vector containing the results. We also define a function \code{add1}.
  6654. The program applies
  6655. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  6656. \code{(vector 1 42)}, from which we return the \code{42}.
  6657. \begin{figure}[tbp]
  6658. \begin{lstlisting}
  6659. (define (map-vec [f : (Integer -> Integer)]
  6660. [v : (Vector Integer Integer)])
  6661. : (Vector Integer Integer)
  6662. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  6663. (define (add1 [x : Integer]) : Integer
  6664. (+ x 1))
  6665. (vector-ref (map-vec add1 (vector 0 41)) 1)
  6666. \end{lstlisting}
  6667. \caption{Example of using functions in \LangFun{}.}
  6668. \label{fig:Rfun-function-example}
  6669. \end{figure}
  6670. The definitional interpreter for \LangFun{} is in
  6671. Figure~\ref{fig:interp-Rfun}. The case for the \code{ProgramDefsExp} form is
  6672. responsible for setting up the mutual recursion between the top-level
  6673. function definitions. We use the classic back-patching \index{back-patching}
  6674. approach that uses mutable variables and makes two passes over the function
  6675. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  6676. top-level environment using a mutable cons cell for each function
  6677. definition. Note that the \code{lambda} value for each function is
  6678. incomplete; it does not yet include the environment. Once the
  6679. top-level environment is constructed, we then iterate over it and
  6680. update the \code{lambda} values to use the top-level environment.
  6681. \begin{figure}[tp]
  6682. \begin{lstlisting}
  6683. (define interp-Rfun-class
  6684. (class interp-Rvec-class
  6685. (super-new)
  6686. (define/override ((interp-exp env) e)
  6687. (define recur (interp-exp env))
  6688. (match e
  6689. [(Var x) (unbox (dict-ref env x))]
  6690. [(Let x e body)
  6691. (define new-env (dict-set env x (box (recur e))))
  6692. ((interp-exp new-env) body)]
  6693. [(Apply fun args)
  6694. (define fun-val (recur fun))
  6695. (define arg-vals (for/list ([e args]) (recur e)))
  6696. (match fun-val
  6697. [`(function (,xs ...) ,body ,fun-env)
  6698. (define params-args (for/list ([x xs] [arg arg-vals])
  6699. (cons x (box arg))))
  6700. (define new-env (append params-args fun-env))
  6701. ((interp-exp new-env) body)]
  6702. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  6703. [else ((super interp-exp env) e)]
  6704. ))
  6705. (define/public (interp-def d)
  6706. (match d
  6707. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  6708. (cons f (box `(function ,xs ,body ())))]))
  6709. (define/override (interp-program p)
  6710. (match p
  6711. [(ProgramDefsExp info ds body)
  6712. (let ([top-level (for/list ([d ds]) (interp-def d))])
  6713. (for/list ([f (in-dict-values top-level)])
  6714. (set-box! f (match (unbox f)
  6715. [`(function ,xs ,body ())
  6716. `(function ,xs ,body ,top-level)])))
  6717. ((interp-exp top-level) body))]))
  6718. ))
  6719. (define (interp-Rfun p)
  6720. (send (new interp-Rfun-class) interp-program p))
  6721. \end{lstlisting}
  6722. \caption{Interpreter for the \LangFun{} language.}
  6723. \label{fig:interp-Rfun}
  6724. \end{figure}
  6725. \margincomment{TODO: explain type checker}
  6726. The type checker for \LangFun{} is is in Figure~\ref{fig:type-check-Rfun}.
  6727. \begin{figure}[tp]
  6728. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6729. (define type-check-Rfun-class
  6730. (class type-check-Rvec-class
  6731. (super-new)
  6732. (inherit check-type-equal?)
  6733. (define/public (type-check-apply env e es)
  6734. (define-values (e^ ty) ((type-check-exp env) e))
  6735. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  6736. ((type-check-exp env) e)))
  6737. (match ty
  6738. [`(,ty^* ... -> ,rt)
  6739. (for ([arg-ty ty*] [param-ty ty^*])
  6740. (check-type-equal? arg-ty param-ty (Apply e es)))
  6741. (values e^ e* rt)]))
  6742. (define/override (type-check-exp env)
  6743. (lambda (e)
  6744. (match e
  6745. [(FunRef f)
  6746. (values (FunRef f) (dict-ref env f))]
  6747. [(Apply e es)
  6748. (define-values (e^ es^ rt) (type-check-apply env e es))
  6749. (values (Apply e^ es^) rt)]
  6750. [(Call e es)
  6751. (define-values (e^ es^ rt) (type-check-apply env e es))
  6752. (values (Call e^ es^) rt)]
  6753. [else ((super type-check-exp env) e)])))
  6754. (define/public (type-check-def env)
  6755. (lambda (e)
  6756. (match e
  6757. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  6758. (define new-env (append (map cons xs ps) env))
  6759. (define-values (body^ ty^) ((type-check-exp new-env) body))
  6760. (check-type-equal? ty^ rt body)
  6761. (Def f p:t* rt info body^)])))
  6762. (define/public (fun-def-type d)
  6763. (match d
  6764. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  6765. (define/override (type-check-program e)
  6766. (match e
  6767. [(ProgramDefsExp info ds body)
  6768. (define new-env (for/list ([d ds])
  6769. (cons (Def-name d) (fun-def-type d))))
  6770. (define ds^ (for/list ([d ds]) ((type-check-def new-env) d)))
  6771. (define-values (body^ ty) ((type-check-exp new-env) body))
  6772. (check-type-equal? ty 'Integer body)
  6773. (ProgramDefsExp info ds^ body^)]))))
  6774. (define (type-check-Rfun p)
  6775. (send (new type-check-Rfun-class) type-check-program p))
  6776. \end{lstlisting}
  6777. \caption{Type checker for the \LangFun{} language.}
  6778. \label{fig:type-check-Rfun}
  6779. \end{figure}
  6780. \section{Functions in x86}
  6781. \label{sec:fun-x86}
  6782. \margincomment{\tiny Make sure callee-saved registers are discussed
  6783. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  6784. \margincomment{\tiny Talk about the return address on the
  6785. stack and what callq and retq does.\\ --Jeremy }
  6786. The x86 architecture provides a few features to support the
  6787. implementation of functions. We have already seen that x86 provides
  6788. labels so that one can refer to the location of an instruction, as is
  6789. needed for jump instructions. Labels can also be used to mark the
  6790. beginning of the instructions for a function. Going further, we can
  6791. obtain the address of a label by using the \key{leaq} instruction and
  6792. PC-relative addressing. For example, the following puts the
  6793. address of the \code{add1} label into the \code{rbx} register.
  6794. \begin{lstlisting}
  6795. leaq add1(%rip), %rbx
  6796. \end{lstlisting}
  6797. The instruction pointer register \key{rip} (aka. the program counter
  6798. \index{program counter}) always points to the next instruction to be
  6799. executed. When combined with an label, as in \code{add1(\%rip)}, the
  6800. linker computes the distance $d$ between the address of \code{add1}
  6801. and where the \code{rip} would be at that moment and then changes
  6802. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  6803. the address of \code{add1}.
  6804. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  6805. jump to a function whose location is given by a label. To support
  6806. function calls in this chapter we instead will be jumping to a
  6807. function whose location is given by an address in a register, that is,
  6808. we need to make an \emph{indirect function call}. The x86 syntax for
  6809. this is a \code{callq} instruction but with an asterisk before the
  6810. register name.\index{indirect function call}
  6811. \begin{lstlisting}
  6812. callq *%rbx
  6813. \end{lstlisting}
  6814. \subsection{Calling Conventions}
  6815. \index{calling conventions}
  6816. The \code{callq} instruction provides partial support for implementing
  6817. functions: it pushes the return address on the stack and it jumps to
  6818. the target. However, \code{callq} does not handle
  6819. \begin{enumerate}
  6820. \item parameter passing,
  6821. \item pushing frames on the procedure call stack and popping them off,
  6822. or
  6823. \item determining how registers are shared by different functions.
  6824. \end{enumerate}
  6825. Regarding (1) parameter passing, recall that the following six
  6826. registers are used to pass arguments to a function, in this order.
  6827. \begin{lstlisting}
  6828. rdi rsi rdx rcx r8 r9
  6829. \end{lstlisting}
  6830. If there are
  6831. more than six arguments, then the convention is to use space on the
  6832. frame of the caller for the rest of the arguments. However, to ease
  6833. the implementation of efficient tail calls
  6834. (Section~\ref{sec:tail-call}), we arrange to never need more than six
  6835. arguments.
  6836. %
  6837. Also recall that the register \code{rax} is for the return value of
  6838. the function.
  6839. \index{prelude}\index{conclusion}
  6840. Regarding (2) frames \index{frame} and the procedure call stack,
  6841. \index{procedure call stack} recall from Section~\ref{sec:x86} that
  6842. the stack grows down, with each function call using a chunk of space
  6843. called a frame. The caller sets the stack pointer, register
  6844. \code{rsp}, to the last data item in its frame. The callee must not
  6845. change anything in the caller's frame, that is, anything that is at or
  6846. above the stack pointer. The callee is free to use locations that are
  6847. below the stack pointer.
  6848. Recall that we are storing variables of vector type on the root stack.
  6849. So the prelude needs to move the root stack pointer \code{r15} up and
  6850. the conclusion needs to move the root stack pointer back down. Also,
  6851. the prelude must initialize to \code{0} this frame's slots in the root
  6852. stack to signal to the garbage collector that those slots do not yet
  6853. contain a pointer to a vector. Otherwise the garbage collector will
  6854. interpret the garbage bits in those slots as memory addresses and try
  6855. to traverse them, causing serious mayhem!
  6856. Regarding (3) the sharing of registers between different functions,
  6857. recall from Section~\ref{sec:calling-conventions} that the registers
  6858. are divided into two groups, the caller-saved registers and the
  6859. callee-saved registers. The caller should assume that all the
  6860. caller-saved registers get overwritten with arbitrary values by the
  6861. callee. That is why we recommend in
  6862. Section~\ref{sec:calling-conventions} that variables that are live
  6863. during a function call should not be assigned to caller-saved
  6864. registers.
  6865. On the flip side, if the callee wants to use a callee-saved register,
  6866. the callee must save the contents of those registers on their stack
  6867. frame and then put them back prior to returning to the caller. That
  6868. is why we recommended in Section~\ref{sec:calling-conventions} that if
  6869. the register allocator assigns a variable to a callee-saved register,
  6870. then the prelude of the \code{main} function must save that register
  6871. to the stack and the conclusion of \code{main} must restore it. This
  6872. recommendation now generalizes to all functions.
  6873. Also recall that the base pointer, register \code{rbp}, is used as a
  6874. point-of-reference within a frame, so that each local variable can be
  6875. accessed at a fixed offset from the base pointer
  6876. (Section~\ref{sec:x86}).
  6877. %
  6878. Figure~\ref{fig:call-frames} shows the general layout of the caller
  6879. and callee frames.
  6880. \begin{figure}[tbp]
  6881. \centering
  6882. \begin{tabular}{r|r|l|l} \hline
  6883. Caller View & Callee View & Contents & Frame \\ \hline
  6884. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  6885. 0(\key{\%rbp}) & & old \key{rbp} \\
  6886. -8(\key{\%rbp}) & & callee-saved $1$ \\
  6887. \ldots & & \ldots \\
  6888. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  6889. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  6890. \ldots & & \ldots \\
  6891. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  6892. %% & & \\
  6893. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  6894. %% & \ldots & \ldots \\
  6895. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  6896. \hline
  6897. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  6898. & 0(\key{\%rbp}) & old \key{rbp} \\
  6899. & -8(\key{\%rbp}) & callee-saved $1$ \\
  6900. & \ldots & \ldots \\
  6901. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  6902. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  6903. & \ldots & \ldots \\
  6904. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  6905. \end{tabular}
  6906. \caption{Memory layout of caller and callee frames.}
  6907. \label{fig:call-frames}
  6908. \end{figure}
  6909. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  6910. %% local variables and for storing the values of callee-saved registers
  6911. %% (we shall refer to all of these collectively as ``locals''), and that
  6912. %% at the beginning of a function we move the stack pointer \code{rsp}
  6913. %% down to make room for them.
  6914. %% We recommend storing the local variables
  6915. %% first and then the callee-saved registers, so that the local variables
  6916. %% can be accessed using \code{rbp} the same as before the addition of
  6917. %% functions.
  6918. %% To make additional room for passing arguments, we shall
  6919. %% move the stack pointer even further down. We count how many stack
  6920. %% arguments are needed for each function call that occurs inside the
  6921. %% body of the function and find their maximum. Adding this number to the
  6922. %% number of locals gives us how much the \code{rsp} should be moved at
  6923. %% the beginning of the function. In preparation for a function call, we
  6924. %% offset from \code{rsp} to set up the stack arguments. We put the first
  6925. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  6926. %% so on.
  6927. %% Upon calling the function, the stack arguments are retrieved by the
  6928. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  6929. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  6930. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  6931. %% the layout of the caller and callee frames. Notice how important it is
  6932. %% that we correctly compute the maximum number of arguments needed for
  6933. %% function calls; if that number is too small then the arguments and
  6934. %% local variables will smash into each other!
  6935. \subsection{Efficient Tail Calls}
  6936. \label{sec:tail-call}
  6937. In general, the amount of stack space used by a program is determined
  6938. by the longest chain of nested function calls. That is, if function
  6939. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  6940. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  6941. $n$ can grow quite large in the case of recursive or mutually
  6942. recursive functions. However, in some cases we can arrange to use only
  6943. constant space, i.e. $O(1)$, instead of $O(n)$.
  6944. If a function call is the last action in a function body, then that
  6945. call is said to be a \emph{tail call}\index{tail call}.
  6946. For example, in the following
  6947. program, the recursive call to \code{tail-sum} is a tail call.
  6948. \begin{center}
  6949. \begin{lstlisting}
  6950. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  6951. (if (eq? n 0)
  6952. r
  6953. (tail-sum (- n 1) (+ n r))))
  6954. (+ (tail-sum 5 0) 27)
  6955. \end{lstlisting}
  6956. \end{center}
  6957. At a tail call, the frame of the caller is no longer needed, so we
  6958. can pop the caller's frame before making the tail call. With this
  6959. approach, a recursive function that only makes tail calls will only
  6960. use $O(1)$ stack space. Functional languages like Racket typically
  6961. rely heavily on recursive functions, so they typically guarantee that
  6962. all tail calls will be optimized in this way.
  6963. \index{frame}
  6964. However, some care is needed with regards to argument passing in tail
  6965. calls. As mentioned above, for arguments beyond the sixth, the
  6966. convention is to use space in the caller's frame for passing
  6967. arguments. But for a tail call we pop the caller's frame and can no
  6968. longer use it. Another alternative is to use space in the callee's
  6969. frame for passing arguments. However, this option is also problematic
  6970. because the caller and callee's frame overlap in memory. As we begin
  6971. to copy the arguments from their sources in the caller's frame, the
  6972. target locations in the callee's frame might overlap with the sources
  6973. for later arguments! We solve this problem by not using the stack for
  6974. passing more than six arguments but instead using the heap, as we
  6975. describe in the Section~\ref{sec:limit-functions-r4}.
  6976. As mentioned above, for a tail call we pop the caller's frame prior to
  6977. making the tail call. The instructions for popping a frame are the
  6978. instructions that we usually place in the conclusion of a
  6979. function. Thus, we also need to place such code immediately before
  6980. each tail call. These instructions include restoring the callee-saved
  6981. registers, so it is good that the argument passing registers are all
  6982. caller-saved registers.
  6983. One last note regarding which instruction to use to make the tail
  6984. call. When the callee is finished, it should not return to the current
  6985. function, but it should return to the function that called the current
  6986. one. Thus, the return address that is already on the stack is the
  6987. right one, and we should not use \key{callq} to make the tail call, as
  6988. that would unnecessarily overwrite the return address. Instead we can
  6989. simply use the \key{jmp} instruction. Like the indirect function call,
  6990. we write an \emph{indirect jump}\index{indirect jump} with a register
  6991. prefixed with an asterisk. We recommend using \code{rax} to hold the
  6992. jump target because the preceding conclusion overwrites just about
  6993. everything else.
  6994. \begin{lstlisting}
  6995. jmp *%rax
  6996. \end{lstlisting}
  6997. \section{Shrink \LangFun{}}
  6998. \label{sec:shrink-r4}
  6999. The \code{shrink} pass performs a minor modification to ease the
  7000. later passes. This pass introduces an explicit \code{main} function
  7001. and changes the top \code{ProgramDefsExp} form to
  7002. \code{ProgramDefs} as follows.
  7003. \begin{lstlisting}
  7004. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  7005. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  7006. \end{lstlisting}
  7007. where $\itm{mainDef}$ is
  7008. \begin{lstlisting}
  7009. (Def 'main '() 'Integer '() |$\Exp'$|)
  7010. \end{lstlisting}
  7011. \section{Reveal Functions and the \LangFunRef{} language}
  7012. \label{sec:reveal-functions-r4}
  7013. The syntax of \LangFun{} is inconvenient for purposes of compilation in one
  7014. respect: it conflates the use of function names and local
  7015. variables. This is a problem because we need to compile the use of a
  7016. function name differently than the use of a local variable; we need to
  7017. use \code{leaq} to convert the function name (a label in x86) to an
  7018. address in a register. Thus, it is a good idea to create a new pass
  7019. that changes function references from just a symbol $f$ to
  7020. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  7021. output language, \LangFunRef{}, is defined in Figure~\ref{fig:f1-syntax}.
  7022. The concrete syntax for a function reference is $\CFUNREF{f}$.
  7023. \begin{figure}[tp]
  7024. \centering
  7025. \fbox{
  7026. \begin{minipage}{0.96\textwidth}
  7027. \[
  7028. \begin{array}{lcl}
  7029. \Exp &::=& \ldots \mid \FUNREF{\Var}\\
  7030. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7031. \LangFunRef{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  7032. \end{array}
  7033. \]
  7034. \end{minipage}
  7035. }
  7036. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  7037. (Figure~\ref{fig:Rfun-syntax}).}
  7038. \label{fig:f1-syntax}
  7039. \end{figure}
  7040. %% Distinguishing between calls in tail position and non-tail position
  7041. %% requires the pass to have some notion of context. We recommend using
  7042. %% two mutually recursive functions, one for processing expressions in
  7043. %% tail position and another for the rest.
  7044. Placing this pass after \code{uniquify} will make sure that there are
  7045. no local variables and functions that share the same name. On the
  7046. other hand, \code{reveal-functions} needs to come before the
  7047. \code{explicate-control} pass because that pass helps us compile
  7048. \code{FunRef} forms into assignment statements.
  7049. \section{Limit Functions}
  7050. \label{sec:limit-functions-r4}
  7051. Recall that we wish to limit the number of function parameters to six
  7052. so that we do not need to use the stack for argument passing, which
  7053. makes it easier to implement efficient tail calls. However, because
  7054. the input language \LangFun{} supports arbitrary numbers of function
  7055. arguments, we have some work to do!
  7056. This pass transforms functions and function calls that involve more
  7057. than six arguments to pass the first five arguments as usual, but it
  7058. packs the rest of the arguments into a vector and passes it as the
  7059. sixth argument.
  7060. Each function definition with too many parameters is transformed as
  7061. follows.
  7062. \begin{lstlisting}
  7063. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  7064. |$\Rightarrow$|
  7065. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  7066. \end{lstlisting}
  7067. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  7068. the occurrences of the later parameters with vector references.
  7069. \begin{lstlisting}
  7070. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  7071. \end{lstlisting}
  7072. For function calls with too many arguments, the \code{limit-functions}
  7073. pass transforms them in the following way.
  7074. \begin{tabular}{lll}
  7075. \begin{minipage}{0.2\textwidth}
  7076. \begin{lstlisting}
  7077. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  7078. \end{lstlisting}
  7079. \end{minipage}
  7080. &
  7081. $\Rightarrow$
  7082. &
  7083. \begin{minipage}{0.4\textwidth}
  7084. \begin{lstlisting}
  7085. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  7086. \end{lstlisting}
  7087. \end{minipage}
  7088. \end{tabular}
  7089. \section{Remove Complex Operands}
  7090. \label{sec:rco-r4}
  7091. The primary decisions to make for this pass is whether to classify
  7092. \code{FunRef} and \code{Apply} as either atomic or complex
  7093. expressions. Recall that a simple expression will eventually end up as
  7094. just an immediate argument of an x86 instruction. Function
  7095. application will be translated to a sequence of instructions, so
  7096. \code{Apply} must be classified as complex expression.
  7097. On the other hand, the arguments of \code{Apply} should be
  7098. atomic expressions.
  7099. %
  7100. Regarding \code{FunRef}, as discussed above, the function label needs
  7101. to be converted to an address using the \code{leaq} instruction. Thus,
  7102. even though \code{FunRef} seems rather simple, it needs to be
  7103. classified as a complex expression so that we generate an assignment
  7104. statement with a left-hand side that can serve as the target of the
  7105. \code{leaq}. Figure~\ref{fig:Rfun-anf-syntax} defines the
  7106. output language \LangFunANF{} of this pass.
  7107. \begin{figure}[tp]
  7108. \centering
  7109. \fbox{
  7110. \begin{minipage}{0.96\textwidth}
  7111. \small
  7112. \[
  7113. \begin{array}{rcl}
  7114. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  7115. \mid \VOID{} } \\
  7116. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  7117. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  7118. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  7119. &\mid& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  7120. &\mid& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} }\\
  7121. &\mid& \gray{ \LP\key{Collect}~\Int\RP \mid \LP\key{Allocate}~\Int~\Type\RP
  7122. \mid \LP\key{GlobalValue}~\Var\RP }\\
  7123. &\mid& \FUNREF{\Var} \mid \APPLY{\Atm}{\Atm\ldots}\\
  7124. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7125. R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  7126. \end{array}
  7127. \]
  7128. \end{minipage}
  7129. }
  7130. \caption{\LangFunANF{} is \LangFun{} in administrative normal form (ANF).}
  7131. \label{fig:Rfun-anf-syntax}
  7132. \end{figure}
  7133. \section{Explicate Control and the \LangCFun{} language}
  7134. \label{sec:explicate-control-r4}
  7135. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  7136. output of \key{explicate-control}. (The concrete syntax is given in
  7137. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.) The auxiliary
  7138. functions for assignment and tail contexts should be updated with
  7139. cases for \code{Apply} and \code{FunRef} and the function for
  7140. predicate context should be updated for \code{Apply} but not
  7141. \code{FunRef}. (A \code{FunRef} can't be a Boolean.) In assignment
  7142. and predicate contexts, \code{Apply} becomes \code{Call}, whereas in
  7143. tail position \code{Apply} becomes \code{TailCall}. We recommend
  7144. defining a new auxiliary function for processing function definitions.
  7145. This code is similar to the case for \code{Program} in \LangVec{}. The
  7146. top-level \code{explicate-control} function that handles the
  7147. \code{ProgramDefs} form of \LangFun{} can then apply this new function to
  7148. all the function definitions.
  7149. \begin{figure}[tp]
  7150. \fbox{
  7151. \begin{minipage}{0.96\textwidth}
  7152. \small
  7153. \[
  7154. \begin{array}{lcl}
  7155. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  7156. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  7157. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  7158. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  7159. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  7160. &\mid& \gray{ \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP } \\
  7161. &\mid& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  7162. &\mid& \gray{ \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP }\\
  7163. &\mid& \gray{ \LP\key{GlobalValue} \,\Var\RP \mid \LP\key{Void}\RP }\\
  7164. &\mid& \FUNREF{\itm{label}} \mid \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  7165. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  7166. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  7167. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  7168. \mid \GOTO{\itm{label}} } \\
  7169. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  7170. &\mid& \TAILCALL{\Atm}{\Atm\ldots} \\
  7171. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  7172. \LangCFun{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  7173. \end{array}
  7174. \]
  7175. \end{minipage}
  7176. }
  7177. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  7178. \label{fig:c3-syntax}
  7179. \end{figure}
  7180. \section{Select Instructions and the \LangXIndCall{} Language}
  7181. \label{sec:select-r4}
  7182. \index{instruction selection}
  7183. The output of select instructions is a program in the \LangXIndCall{}
  7184. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  7185. \index{x86}
  7186. \begin{figure}[tp]
  7187. \fbox{
  7188. \begin{minipage}{0.96\textwidth}
  7189. \small
  7190. \[
  7191. \begin{array}{lcl}
  7192. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)}
  7193. \mid \LP\key{fun-ref}\; \itm{label}\RP\\
  7194. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  7195. \Instr &::=& \ldots
  7196. \mid \key{callq}\;\key{*}\Arg \mid \key{tailjmp}\;\Arg
  7197. \mid \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  7198. \Block &::= & \Instr\ldots \\
  7199. \Def &::= & \LP\key{define} \; \LP\itm{label}\RP \;\LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\RP\\
  7200. \LangXIndCall{} &::= & \Def\ldots
  7201. \end{array}
  7202. \]
  7203. \end{minipage}
  7204. }
  7205. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  7206. \label{fig:x86-3-concrete}
  7207. \end{figure}
  7208. \begin{figure}[tp]
  7209. \fbox{
  7210. \begin{minipage}{0.96\textwidth}
  7211. \small
  7212. \[
  7213. \begin{array}{lcl}
  7214. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  7215. \mid \BYTEREG{\Reg} } \\
  7216. &\mid& \gray{ (\key{Global}~\Var) } \mid \FUNREF{\itm{label}} \\
  7217. \Instr &::=& \ldots \mid \INDCALLQ{\Arg}{\itm{int}}
  7218. \mid \TAILJMP{\Arg}{\itm{int}}\\
  7219. &\mid& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  7220. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  7221. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  7222. \LangXIndCall{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  7223. \end{array}
  7224. \]
  7225. \end{minipage}
  7226. }
  7227. \caption{The abstract syntax of \LangXIndCall{} (extends \LangXASTGlobal{} of Figure~\ref{fig:x86-2}).}
  7228. \label{fig:x86-3}
  7229. \end{figure}
  7230. An assignment of a function reference to a variable becomes a
  7231. load-effective-address instruction as follows: \\
  7232. \begin{tabular}{lcl}
  7233. \begin{minipage}{0.35\textwidth}
  7234. \begin{lstlisting}
  7235. |$\itm{lhs}$| = (fun-ref |$f$|);
  7236. \end{lstlisting}
  7237. \end{minipage}
  7238. &
  7239. $\Rightarrow$\qquad\qquad
  7240. &
  7241. \begin{minipage}{0.3\textwidth}
  7242. \begin{lstlisting}
  7243. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  7244. \end{lstlisting}
  7245. \end{minipage}
  7246. \end{tabular} \\
  7247. Regarding function definitions, we need to remove the parameters and
  7248. instead perform parameter passing using the conventions discussed in
  7249. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  7250. registers. We recommend turning the parameters into local variables
  7251. and generating instructions at the beginning of the function to move
  7252. from the argument passing registers to these local variables.
  7253. \begin{lstlisting}
  7254. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  7255. |$\Rightarrow$|
  7256. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  7257. \end{lstlisting}
  7258. The $G'$ control-flow graph is the same as $G$ except that the
  7259. \code{start} block is modified to add the instructions for moving from
  7260. the argument registers to the parameter variables. So the \code{start}
  7261. block of $G$ shown on the left is changed to the code on the right.
  7262. \begin{center}
  7263. \begin{minipage}{0.3\textwidth}
  7264. \begin{lstlisting}
  7265. start:
  7266. |$\itm{instr}_1$|
  7267. |$\vdots$|
  7268. |$\itm{instr}_n$|
  7269. \end{lstlisting}
  7270. \end{minipage}
  7271. $\Rightarrow$
  7272. \begin{minipage}{0.3\textwidth}
  7273. \begin{lstlisting}
  7274. start:
  7275. movq %rdi, |$x_1$|
  7276. movq %rsi, |$x_2$|
  7277. |$\vdots$|
  7278. |$\itm{instr}_1$|
  7279. |$\vdots$|
  7280. |$\itm{instr}_n$|
  7281. \end{lstlisting}
  7282. \end{minipage}
  7283. \end{center}
  7284. By changing the parameters to local variables, we are giving the
  7285. register allocator control over which registers or stack locations to
  7286. use for them. If you implemented the move-biasing challenge
  7287. (Section~\ref{sec:move-biasing}), the register allocator will try to
  7288. assign the parameter variables to the corresponding argument register,
  7289. in which case the \code{patch-instructions} pass will remove the
  7290. \code{movq} instruction. This happens in the example translation in
  7291. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  7292. the \code{add} function.
  7293. %
  7294. Also, note that the register allocator will perform liveness analysis
  7295. on this sequence of move instructions and build the interference
  7296. graph. So, for example, $x_1$ will be marked as interfering with
  7297. \code{rsi} and that will prevent the assignment of $x_1$ to
  7298. \code{rsi}, which is good, because that would overwrite the argument
  7299. that needs to move into $x_2$.
  7300. Next, consider the compilation of function calls. In the mirror image
  7301. of handling the parameters of function definitions, the arguments need
  7302. to be moved to the argument passing registers. The function call
  7303. itself is performed with an indirect function call. The return value
  7304. from the function is stored in \code{rax}, so it needs to be moved
  7305. into the \itm{lhs}.
  7306. \begin{lstlisting}
  7307. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  7308. |$\Rightarrow$|
  7309. movq |$\itm{arg}_1$|, %rdi
  7310. movq |$\itm{arg}_2$|, %rsi
  7311. |$\vdots$|
  7312. callq *|\itm{fun}|
  7313. movq %rax, |\itm{lhs}|
  7314. \end{lstlisting}
  7315. The \code{IndirectCallq} AST node includes an integer for the arity of
  7316. the function, i.e., the number of parameters. That information is
  7317. useful in the \code{uncover-live} pass for determining which
  7318. argument-passing registers are potentially read during the call.
  7319. For tail calls, the parameter passing is the same as non-tail calls:
  7320. generate instructions to move the arguments into to the argument
  7321. passing registers. After that we need to pop the frame from the
  7322. procedure call stack. However, we do not yet know how big the frame
  7323. is; that gets determined during register allocation. So instead of
  7324. generating those instructions here, we invent a new instruction that
  7325. means ``pop the frame and then do an indirect jump'', which we name
  7326. \code{TailJmp}. The abstract syntax for this instruction includes an
  7327. argument that specifies where to jump and an integer that represents
  7328. the arity of the function being called.
  7329. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  7330. using the label \code{start} for the initial block of a program, and
  7331. in Section~\ref{sec:select-r1} we recommended labeling the conclusion
  7332. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  7333. can be compiled to an assignment to \code{rax} followed by a jump to
  7334. \code{conclusion}. With the addition of function definitions, we will
  7335. have a starting block and conclusion for each function, but their
  7336. labels need to be unique. We recommend prepending the function's name
  7337. to \code{start} and \code{conclusion}, respectively, to obtain unique
  7338. labels. (Alternatively, one could \code{gensym} labels for the start
  7339. and conclusion and store them in the $\itm{info}$ field of the
  7340. function definition.)
  7341. \section{Register Allocation}
  7342. \label{sec:register-allocation-r4}
  7343. \subsection{Liveness Analysis}
  7344. \label{sec:liveness-analysis-r4}
  7345. \index{liveness analysis}
  7346. %% The rest of the passes need only minor modifications to handle the new
  7347. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  7348. %% \code{leaq}.
  7349. The \code{IndirectCallq} instruction should be treated like
  7350. \code{Callq} regarding its written locations $W$, in that they should
  7351. include all the caller-saved registers. Recall that the reason for
  7352. that is to force call-live variables to be assigned to callee-saved
  7353. registers or to be spilled to the stack.
  7354. Regarding the set of read locations $R$ the arity field of
  7355. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  7356. argument-passing registers should be considered as read by those
  7357. instructions.
  7358. \subsection{Build Interference Graph}
  7359. \label{sec:build-interference-r4}
  7360. With the addition of function definitions, we compute an interference
  7361. graph for each function (not just one for the whole program).
  7362. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  7363. spill vector-typed variables that are live during a call to the
  7364. \code{collect}. With the addition of functions to our language, we
  7365. need to revisit this issue. Many functions perform allocation and
  7366. therefore have calls to the collector inside of them. Thus, we should
  7367. not only spill a vector-typed variable when it is live during a call
  7368. to \code{collect}, but we should spill the variable if it is live
  7369. during any function call. Thus, in the \code{build-interference} pass,
  7370. we recommend adding interference edges between call-live vector-typed
  7371. variables and the callee-saved registers (in addition to the usual
  7372. addition of edges between call-live variables and the caller-saved
  7373. registers).
  7374. \subsection{Allocate Registers}
  7375. The primary change to the \code{allocate-registers} pass is adding an
  7376. auxiliary function for handling definitions (the \Def{} non-terminal
  7377. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  7378. logic is the same as described in
  7379. Chapter~\ref{ch:register-allocation-r1}, except now register
  7380. allocation is performed many times, once for each function definition,
  7381. instead of just once for the whole program.
  7382. \section{Patch Instructions}
  7383. In \code{patch-instructions}, you should deal with the x86
  7384. idiosyncrasy that the destination argument of \code{leaq} must be a
  7385. register. Additionally, you should ensure that the argument of
  7386. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  7387. code generation more convenient, because we trample many registers
  7388. before the tail call (as explained in the next section).
  7389. \section{Print x86}
  7390. For the \code{print-x86} pass, the cases for \code{FunRef} and
  7391. \code{IndirectCallq} are straightforward: output their concrete
  7392. syntax.
  7393. \begin{lstlisting}
  7394. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  7395. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  7396. \end{lstlisting}
  7397. The \code{TailJmp} node requires a bit work. A straightforward
  7398. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  7399. before the jump we need to pop the current frame. This sequence of
  7400. instructions is the same as the code for the conclusion of a function,
  7401. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  7402. Regarding function definitions, you will need to generate a prelude
  7403. and conclusion for each one. This code is similar to the prelude and
  7404. conclusion that you generated for the \code{main} function in
  7405. Chapter~\ref{ch:tuples}. To review, the prelude of every function
  7406. should carry out the following steps.
  7407. \begin{enumerate}
  7408. \item Start with \code{.global} and \code{.align} directives followed
  7409. by the label for the function. (See Figure~\ref{fig:add-fun} for an
  7410. example.)
  7411. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  7412. pointer.
  7413. \item Push to the stack all of the callee-saved registers that were
  7414. used for register allocation.
  7415. \item Move the stack pointer \code{rsp} down by the size of the stack
  7416. frame for this function, which depends on the number of regular
  7417. spills. (Aligned to 16 bytes.)
  7418. \item Move the root stack pointer \code{r15} up by the size of the
  7419. root-stack frame for this function, which depends on the number of
  7420. spilled vectors. \label{root-stack-init}
  7421. \item Initialize to zero all of the entries in the root-stack frame.
  7422. \item Jump to the start block.
  7423. \end{enumerate}
  7424. The prelude of the \code{main} function has one additional task: call
  7425. the \code{initialize} function to set up the garbage collector and
  7426. move the value of the global \code{rootstack\_begin} in
  7427. \code{r15}. This should happen before step \ref{root-stack-init}
  7428. above, which depends on \code{r15}.
  7429. The conclusion of every function should do the following.
  7430. \begin{enumerate}
  7431. \item Move the stack pointer back up by the size of the stack frame
  7432. for this function.
  7433. \item Restore the callee-saved registers by popping them from the
  7434. stack.
  7435. \item Move the root stack pointer back down by the size of the
  7436. root-stack frame for this function.
  7437. \item Restore \code{rbp} by popping it from the stack.
  7438. \item Return to the caller with the \code{retq} instruction.
  7439. \end{enumerate}
  7440. \begin{exercise}\normalfont
  7441. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  7442. Create 5 new programs that use functions, including examples that pass
  7443. functions and return functions from other functions, recursive
  7444. functions, functions that create vectors, and functions that make tail
  7445. calls. Test your compiler on these new programs and all of your
  7446. previously created test programs.
  7447. \end{exercise}
  7448. \begin{figure}[tbp]
  7449. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7450. \node (Rfun) at (0,2) {\large \LangFun{}};
  7451. \node (Rfun-1) at (3,2) {\large \LangFun{}};
  7452. \node (Rfun-2) at (6,2) {\large \LangFun{}};
  7453. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  7454. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  7455. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  7456. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  7457. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  7458. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  7459. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  7460. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  7461. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  7462. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  7463. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  7464. \path[->,bend left=15] (Rfun) edge [above] node
  7465. {\ttfamily\footnotesize shrink} (Rfun-1);
  7466. \path[->,bend left=15] (Rfun-1) edge [above] node
  7467. {\ttfamily\footnotesize uniquify} (Rfun-2);
  7468. \path[->,bend left=15] (Rfun-2) edge [right] node
  7469. {\ttfamily\footnotesize ~~reveal-functions} (F1-1);
  7470. \path[->,bend left=15] (F1-1) edge [below] node
  7471. {\ttfamily\footnotesize limit-functions} (F1-2);
  7472. \path[->,bend right=15] (F1-2) edge [above] node
  7473. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  7474. \path[->,bend right=15] (F1-3) edge [above] node
  7475. {\ttfamily\footnotesize remove-complex.} (F1-4);
  7476. \path[->,bend left=15] (F1-4) edge [right] node
  7477. {\ttfamily\footnotesize explicate-control} (C3-2);
  7478. \path[->,bend right=15] (C3-2) edge [left] node
  7479. {\ttfamily\footnotesize select-instr.} (x86-2);
  7480. \path[->,bend left=15] (x86-2) edge [left] node
  7481. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  7482. \path[->,bend right=15] (x86-2-1) edge [below] node
  7483. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  7484. \path[->,bend right=15] (x86-2-2) edge [left] node
  7485. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7486. \path[->,bend left=15] (x86-3) edge [above] node
  7487. {\ttfamily\footnotesize patch-instr.} (x86-4);
  7488. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  7489. \end{tikzpicture}
  7490. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  7491. \label{fig:Rfun-passes}
  7492. \end{figure}
  7493. Figure~\ref{fig:Rfun-passes} gives an overview of the passes for
  7494. compiling \LangFun{} to x86.
  7495. \section{An Example Translation}
  7496. \label{sec:functions-example}
  7497. Figure~\ref{fig:add-fun} shows an example translation of a simple
  7498. function in \LangFun{} to x86. The figure also includes the results of the
  7499. \code{explicate-control} and \code{select-instructions} passes.
  7500. \begin{figure}[htbp]
  7501. \begin{tabular}{ll}
  7502. \begin{minipage}{0.5\textwidth}
  7503. % s3_2.rkt
  7504. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7505. (define (add [x : Integer] [y : Integer])
  7506. : Integer
  7507. (+ x y))
  7508. (add 40 2)
  7509. \end{lstlisting}
  7510. $\Downarrow$
  7511. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7512. (define (add86 [x87 : Integer]
  7513. [y88 : Integer]) : Integer
  7514. add86start:
  7515. return (+ x87 y88);
  7516. )
  7517. (define (main) : Integer ()
  7518. mainstart:
  7519. tmp89 = (fun-ref add86);
  7520. (tail-call tmp89 40 2)
  7521. )
  7522. \end{lstlisting}
  7523. \end{minipage}
  7524. &
  7525. $\Rightarrow$
  7526. \begin{minipage}{0.5\textwidth}
  7527. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7528. (define (add86) : Integer
  7529. add86start:
  7530. movq %rdi, x87
  7531. movq %rsi, y88
  7532. movq x87, %rax
  7533. addq y88, %rax
  7534. jmp add11389conclusion
  7535. )
  7536. (define (main) : Integer
  7537. mainstart:
  7538. leaq (fun-ref add86), tmp89
  7539. movq $40, %rdi
  7540. movq $2, %rsi
  7541. tail-jmp tmp89
  7542. )
  7543. \end{lstlisting}
  7544. $\Downarrow$
  7545. \end{minipage}
  7546. \end{tabular}
  7547. \begin{tabular}{ll}
  7548. \begin{minipage}{0.3\textwidth}
  7549. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7550. .globl add86
  7551. .align 16
  7552. add86:
  7553. pushq %rbp
  7554. movq %rsp, %rbp
  7555. jmp add86start
  7556. add86start:
  7557. movq %rdi, %rax
  7558. addq %rsi, %rax
  7559. jmp add86conclusion
  7560. add86conclusion:
  7561. popq %rbp
  7562. retq
  7563. \end{lstlisting}
  7564. \end{minipage}
  7565. &
  7566. \begin{minipage}{0.5\textwidth}
  7567. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7568. .globl main
  7569. .align 16
  7570. main:
  7571. pushq %rbp
  7572. movq %rsp, %rbp
  7573. movq $16384, %rdi
  7574. movq $16384, %rsi
  7575. callq initialize
  7576. movq rootstack_begin(%rip), %r15
  7577. jmp mainstart
  7578. mainstart:
  7579. leaq add86(%rip), %rcx
  7580. movq $40, %rdi
  7581. movq $2, %rsi
  7582. movq %rcx, %rax
  7583. popq %rbp
  7584. jmp *%rax
  7585. mainconclusion:
  7586. popq %rbp
  7587. retq
  7588. \end{lstlisting}
  7589. \end{minipage}
  7590. \end{tabular}
  7591. \caption{Example compilation of a simple function to x86.}
  7592. \label{fig:add-fun}
  7593. \end{figure}
  7594. % Challenge idea: inlining! (simple version)
  7595. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7596. \chapter{Lexically Scoped Functions}
  7597. \label{ch:lambdas}
  7598. \index{lambda}
  7599. \index{lexical scoping}
  7600. This chapter studies lexically scoped functions as they appear in
  7601. functional languages such as Racket. By lexical scoping we mean that a
  7602. function's body may refer to variables whose binding site is outside
  7603. of the function, in an enclosing scope.
  7604. %
  7605. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  7606. \LangLam{}, which extends \LangFun{} with anonymous functions using the
  7607. \key{lambda} form. The body of the \key{lambda}, refers to three
  7608. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  7609. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  7610. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  7611. parameter of function \code{f}. The \key{lambda} is returned from the
  7612. function \code{f}. The main expression of the program includes two
  7613. calls to \code{f} with different arguments for \code{x}, first
  7614. \code{5} then \code{3}. The functions returned from \code{f} are bound
  7615. to variables \code{g} and \code{h}. Even though these two functions
  7616. were created by the same \code{lambda}, they are really different
  7617. functions because they use different values for \code{x}. Applying
  7618. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  7619. \code{15} produces \code{22}. The result of this program is \code{42}.
  7620. \begin{figure}[btp]
  7621. % s4_6.rkt
  7622. \begin{lstlisting}
  7623. (define (f [x : Integer]) : (Integer -> Integer)
  7624. (let ([y 4])
  7625. (lambda: ([z : Integer]) : Integer
  7626. (+ x (+ y z)))))
  7627. (let ([g (f 5)])
  7628. (let ([h (f 3)])
  7629. (+ (g 11) (h 15))))
  7630. \end{lstlisting}
  7631. \caption{Example of a lexically scoped function.}
  7632. \label{fig:lexical-scoping}
  7633. \end{figure}
  7634. The approach that we take for implementing lexically scoped
  7635. functions is to compile them into top-level function definitions,
  7636. translating from \LangLam{} into \LangFun{}. However, the compiler will need to
  7637. provide special treatment for variable occurrences such as \code{x}
  7638. and \code{y} in the body of the \code{lambda} of
  7639. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function may not
  7640. refer to variables defined outside of it. To identify such variable
  7641. occurrences, we review the standard notion of free variable.
  7642. \begin{definition}
  7643. A variable is \emph{free in expression} $e$ if the variable occurs
  7644. inside $e$ but does not have an enclosing binding in $e$.\index{free
  7645. variable}
  7646. \end{definition}
  7647. For example, in the expression \code{(+ x (+ y z))} the variables
  7648. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  7649. only \code{x} and \code{y} are free in the following expression
  7650. because \code{z} is bound by the \code{lambda}.
  7651. \begin{lstlisting}
  7652. (lambda: ([z : Integer]) : Integer
  7653. (+ x (+ y z)))
  7654. \end{lstlisting}
  7655. So the free variables of a \code{lambda} are the ones that will need
  7656. special treatment. We need to arrange for some way to transport, at
  7657. runtime, the values of those variables from the point where the
  7658. \code{lambda} was created to the point where the \code{lambda} is
  7659. applied. An efficient solution to the problem, due to
  7660. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  7661. free variables together with the function pointer for the lambda's
  7662. code, an arrangement called a \emph{flat closure} (which we shorten to
  7663. just ``closure''). \index{closure}\index{flat closure} Fortunately,
  7664. we have all the ingredients to make closures, Chapter~\ref{ch:tuples}
  7665. gave us vectors and Chapter~\ref{ch:functions} gave us function
  7666. pointers. The function pointer resides at index $0$ and the
  7667. values for the free variables will fill in the rest of the vector.
  7668. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  7669. how closures work. It's a three-step dance. The program first calls
  7670. function \code{f}, which creates a closure for the \code{lambda}. The
  7671. closure is a vector whose first element is a pointer to the top-level
  7672. function that we will generate for the \code{lambda}, the second
  7673. element is the value of \code{x}, which is \code{5}, and the third
  7674. element is \code{4}, the value of \code{y}. The closure does not
  7675. contain an element for \code{z} because \code{z} is not a free
  7676. variable of the \code{lambda}. Creating the closure is step 1 of the
  7677. dance. The closure is returned from \code{f} and bound to \code{g}, as
  7678. shown in Figure~\ref{fig:closures}.
  7679. %
  7680. The second call to \code{f} creates another closure, this time with
  7681. \code{3} in the second slot (for \code{x}). This closure is also
  7682. returned from \code{f} but bound to \code{h}, which is also shown in
  7683. Figure~\ref{fig:closures}.
  7684. \begin{figure}[tbp]
  7685. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  7686. \caption{Example closure representation for the \key{lambda}'s
  7687. in Figure~\ref{fig:lexical-scoping}.}
  7688. \label{fig:closures}
  7689. \end{figure}
  7690. Continuing with the example, consider the application of \code{g} to
  7691. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  7692. obtain the function pointer in the first element of the closure and
  7693. call it, passing in the closure itself and then the regular arguments,
  7694. in this case \code{11}. This technique for applying a closure is step
  7695. 2 of the dance.
  7696. %
  7697. But doesn't this \code{lambda} only take 1 argument, for parameter
  7698. \code{z}? The third and final step of the dance is generating a
  7699. top-level function for a \code{lambda}. We add an additional
  7700. parameter for the closure and we insert a \code{let} at the beginning
  7701. of the function for each free variable, to bind those variables to the
  7702. appropriate elements from the closure parameter.
  7703. %
  7704. This three-step dance is known as \emph{closure conversion}. We
  7705. discuss the details of closure conversion in
  7706. Section~\ref{sec:closure-conversion} and the code generated from the
  7707. example in Section~\ref{sec:example-lambda}. But first we define the
  7708. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  7709. \section{The \LangLam{} Language}
  7710. \label{sec:r5}
  7711. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  7712. functions and lexical scoping, is defined in
  7713. Figures~\ref{fig:Rlam-concrete-syntax} and ~\ref{fig:Rlam-syntax}. It adds
  7714. the \key{lambda} form to the grammar for \LangFun{}, which already has
  7715. syntax for function application.
  7716. \begin{figure}[tp]
  7717. \centering
  7718. \fbox{
  7719. \begin{minipage}{0.96\textwidth}
  7720. \small
  7721. \[
  7722. \begin{array}{lcl}
  7723. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7724. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}
  7725. \mid (\Type\ldots \; \key{->}\; \Type)} \\
  7726. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  7727. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  7728. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  7729. &\mid& \gray{\key{\#t} \mid \key{\#f}
  7730. \mid (\key{and}\;\Exp\;\Exp)
  7731. \mid (\key{or}\;\Exp\;\Exp)
  7732. \mid (\key{not}\;\Exp) } \\
  7733. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  7734. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  7735. (\key{vector-ref}\;\Exp\;\Int)} \\
  7736. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  7737. \mid (\Exp \; \Exp\ldots) } \\
  7738. &\mid& \LP \key{procedure-arity}~\Exp\RP \\
  7739. &\mid& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  7740. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  7741. \LangLam{} &::=& \gray{\Def\ldots \; \Exp}
  7742. \end{array}
  7743. \]
  7744. \end{minipage}
  7745. }
  7746. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-concrete-syntax})
  7747. with \key{lambda}.}
  7748. \label{fig:Rlam-concrete-syntax}
  7749. \end{figure}
  7750. \begin{figure}[tp]
  7751. \centering
  7752. \fbox{
  7753. \begin{minipage}{0.96\textwidth}
  7754. \small
  7755. \[
  7756. \begin{array}{lcl}
  7757. \itm{op} &::=& \ldots \mid \code{procedure-arity} \\
  7758. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  7759. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  7760. &\mid& \gray{ \BOOL{\itm{bool}}
  7761. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  7762. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  7763. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  7764. &\mid& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  7765. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  7766. \LangLam{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  7767. \end{array}
  7768. \]
  7769. \end{minipage}
  7770. }
  7771. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-syntax}).}
  7772. \label{fig:Rlam-syntax}
  7773. \end{figure}
  7774. \index{interpreter}
  7775. \label{sec:interp-Rlambda}
  7776. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  7777. \LangLam{}. The clause for \key{lambda} saves the current environment
  7778. inside the returned \key{lambda}. Then the clause for \key{Apply} uses
  7779. the environment from the \key{lambda}, the \code{lam-env}, when
  7780. interpreting the body of the \key{lambda}. The \code{lam-env}
  7781. environment is extended with the mapping of parameters to argument
  7782. values.
  7783. \begin{figure}[tbp]
  7784. \begin{lstlisting}
  7785. (define interp-Rlambda-class
  7786. (class interp-Rfun-class
  7787. (super-new)
  7788. (define/override (interp-op op)
  7789. (match op
  7790. ['procedure-arity
  7791. (lambda (v)
  7792. (match v
  7793. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  7794. [else (error 'interp-op "expected a function, not ~a" v)]))]
  7795. [else (super interp-op op)]))
  7796. (define/override ((interp-exp env) e)
  7797. (define recur (interp-exp env))
  7798. (match e
  7799. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  7800. `(function ,xs ,body ,env)]
  7801. [else ((super interp-exp env) e)]))
  7802. ))
  7803. (define (interp-Rlambda p)
  7804. (send (new interp-Rlambda-class) interp-program p))
  7805. \end{lstlisting}
  7806. \caption{Interpreter for \LangLam{}.}
  7807. \label{fig:interp-Rlambda}
  7808. \end{figure}
  7809. \label{sec:type-check-r5}
  7810. \index{type checking}
  7811. Figure~\ref{fig:type-check-Rlambda} shows how to type check the new
  7812. \key{lambda} form. The body of the \key{lambda} is checked in an
  7813. environment that includes the current environment (because it is
  7814. lexically scoped) and also includes the \key{lambda}'s parameters. We
  7815. require the body's type to match the declared return type.
  7816. \begin{figure}[tbp]
  7817. \begin{lstlisting}
  7818. (define (type-check-Rlambda env)
  7819. (lambda (e)
  7820. (match e
  7821. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  7822. (define-values (new-body bodyT)
  7823. ((type-check-exp (append (map cons xs Ts) env)) body))
  7824. (define ty `(,@Ts -> ,rT))
  7825. (cond
  7826. [(equal? rT bodyT)
  7827. (values (HasType (Lambda params rT new-body) ty) ty)]
  7828. [else
  7829. (error "mismatch in return type" bodyT rT)])]
  7830. ...
  7831. )))
  7832. \end{lstlisting}
  7833. \caption{Type checking the \key{lambda}'s in \LangLam{}.}
  7834. \label{fig:type-check-Rlambda}
  7835. \end{figure}
  7836. \section{Reveal Functions and the $F_2$ language}
  7837. \label{sec:reveal-functions-r5}
  7838. To support the \code{procedure-arity} operator we need to communicate
  7839. the arity of a function to the point of closure creation. We can
  7840. accomplish this by replacing the $\FUNREF{\Var}$ struct with one that
  7841. has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$. The
  7842. output of this pass is the language $F_2$, whose syntax is defined in
  7843. Figure~\ref{fig:f2-syntax}.
  7844. \begin{figure}[tp]
  7845. \centering
  7846. \fbox{
  7847. \begin{minipage}{0.96\textwidth}
  7848. \[
  7849. \begin{array}{lcl}
  7850. \Exp &::=& \ldots \mid \FUNREFARITY{\Var}{\Int}\\
  7851. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7852. F_2 &::=& \gray{\PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}}
  7853. \end{array}
  7854. \]
  7855. \end{minipage}
  7856. }
  7857. \caption{The abstract syntax $F_2$, an extension of \LangLam{}
  7858. (Figure~\ref{fig:Rlam-syntax}).}
  7859. \label{fig:f2-syntax}
  7860. \end{figure}
  7861. \section{Closure Conversion}
  7862. \label{sec:closure-conversion}
  7863. \index{closure conversion}
  7864. The compiling of lexically-scoped functions into top-level function
  7865. definitions is accomplished in the pass \code{convert-to-closures}
  7866. that comes after \code{reveal-functions} and before
  7867. \code{limit-functions}.
  7868. As usual, we implement the pass as a recursive function over the
  7869. AST. All of the action is in the clauses for \key{Lambda} and
  7870. \key{Apply}. We transform a \key{Lambda} expression into an expression
  7871. that creates a closure, that is, a vector whose first element is a
  7872. function pointer and the rest of the elements are the free variables
  7873. of the \key{Lambda}. We use the struct \code{Closure} here instead of
  7874. using \code{vector} so that we can distinguish closures from vectors
  7875. in Section~\ref{sec:optimize-closures} and to record the arity. In
  7876. the generated code below, the \itm{name} is a unique symbol generated
  7877. to identify the function and the \itm{arity} is the number of
  7878. parameters (the length of \itm{ps}).
  7879. \begin{lstlisting}
  7880. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  7881. |$\Rightarrow$|
  7882. (Closure |\itm{arity}| (cons (FunRef |\itm{name}|) |\itm{fvs}|))
  7883. \end{lstlisting}
  7884. In addition to transforming each \key{Lambda} into a \key{Closure}, we
  7885. create a top-level function definition for each \key{Lambda}, as
  7886. shown below.\\
  7887. \begin{minipage}{0.8\textwidth}
  7888. \begin{lstlisting}
  7889. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  7890. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  7891. ...
  7892. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  7893. |\itm{body'}|)...))
  7894. \end{lstlisting}
  7895. \end{minipage}\\
  7896. The \code{clos} parameter refers to the closure. Translate the type
  7897. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  7898. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The types
  7899. $\itm{fvts}$ are the types of the free variables in the lambda and the
  7900. underscore \code{\_} is a dummy type that we use because it is rather
  7901. difficult to give a type to the function in the closure's
  7902. type.\footnote{To give an accurate type to a closure, we would need to
  7903. add existential types to the type checker~\citep{Minamide:1996ys}.}
  7904. The dummy type is considered to be equal to any other type during type
  7905. checking. The sequence of \key{Let} forms bind the free variables to
  7906. their values obtained from the closure.
  7907. Closure conversion turns functions into vectors, so the type
  7908. annotations in the program must also be translated. We recommend
  7909. defining a auxiliary recursive function for this purpose. Function
  7910. types should be translated as follows.
  7911. \begin{lstlisting}
  7912. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  7913. |$\Rightarrow$|
  7914. (Vector ((Vector _) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  7915. \end{lstlisting}
  7916. The above type says that the first thing in the vector is a function
  7917. pointer. The first parameter of the function pointer is a vector (a
  7918. closure) and the rest of the parameters are the ones from the original
  7919. function, with types $T'_1, \ldots, T'_n$. The \code{Vector} type for
  7920. the closure omits the types of the free variables because 1) those
  7921. types are not available in this context and 2) we do not need them in
  7922. the code that is generated for function application.
  7923. We transform function application into code that retrieves the
  7924. function pointer from the closure and then calls the function, passing
  7925. in the closure as the first argument. We bind $e'$ to a temporary
  7926. variable to avoid code duplication.
  7927. \begin{lstlisting}
  7928. (Apply |$e$| |\itm{es}|)
  7929. |$\Rightarrow$|
  7930. (Let |\itm{tmp}| |$e'$|
  7931. (Apply (Prim 'vector-ref (list (Var |\itm{tmp}|) (Int 0))) (cons |\itm{tmp}| |\itm{es'}|)))
  7932. \end{lstlisting}
  7933. There is also the question of what to do with references top-level
  7934. function definitions. To maintain a uniform translation of function
  7935. application, we turn function references into closures.
  7936. \begin{tabular}{lll}
  7937. \begin{minipage}{0.3\textwidth}
  7938. \begin{lstlisting}
  7939. (FunRefArity |$f$| |$n$|)
  7940. \end{lstlisting}
  7941. \end{minipage}
  7942. &
  7943. $\Rightarrow$
  7944. &
  7945. \begin{minipage}{0.5\textwidth}
  7946. \begin{lstlisting}
  7947. (Closure |$n$| (FunRef |$f$|) '())
  7948. \end{lstlisting}
  7949. \end{minipage}
  7950. \end{tabular} \\
  7951. %
  7952. The top-level function definitions need to be updated as well to take
  7953. an extra closure parameter.
  7954. \section{An Example Translation}
  7955. \label{sec:example-lambda}
  7956. Figure~\ref{fig:lexical-functions-example} shows the result of
  7957. \code{reveal-functions} and \code{convert-to-closures} for the example
  7958. program demonstrating lexical scoping that we discussed at the
  7959. beginning of this chapter.
  7960. \begin{figure}[tbp]
  7961. \begin{minipage}{0.8\textwidth}
  7962. % tests/lambda_test_6.rkt
  7963. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7964. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  7965. (let ([y8 4])
  7966. (lambda: ([z9 : Integer]) : Integer
  7967. (+ x7 (+ y8 z9)))))
  7968. (define (main) : Integer
  7969. (let ([g0 ((fun-ref-arity f6 1) 5)])
  7970. (let ([h1 ((fun-ref-arity f6 1) 3)])
  7971. (+ (g0 11) (h1 15)))))
  7972. \end{lstlisting}
  7973. $\Rightarrow$
  7974. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7975. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  7976. (let ([y8 4])
  7977. (closure 1 (list (fun-ref lambda2) x7 y8))))
  7978. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  7979. (let ([x7 (vector-ref fvs3 1)])
  7980. (let ([y8 (vector-ref fvs3 2)])
  7981. (+ x7 (+ y8 z9)))))
  7982. (define (main) : Integer
  7983. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6)))])
  7984. ((vector-ref clos5 0) clos5 5))])
  7985. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6)))])
  7986. ((vector-ref clos6 0) clos6 3))])
  7987. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  7988. \end{lstlisting}
  7989. \end{minipage}
  7990. \caption{Example of closure conversion.}
  7991. \label{fig:lexical-functions-example}
  7992. \end{figure}
  7993. \begin{exercise}\normalfont
  7994. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  7995. Create 5 new programs that use \key{lambda} functions and make use of
  7996. lexical scoping. Test your compiler on these new programs and all of
  7997. your previously created test programs.
  7998. \end{exercise}
  7999. \section{Expose Allocation}
  8000. \label{sec:expose-allocation-r5}
  8001. Compile the $\CLOSURE{\itm{arity}}{\LP\Exp\ldots\RP}$ form into code
  8002. that allocates and initializes a vector, similar to the translation of
  8003. the \code{vector} operator in Section~\ref{sec:expose-allocation}.
  8004. The only difference is replacing the use of
  8005. \ALLOC{\itm{len}}{\itm{type}} with
  8006. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  8007. \section{Explicate Control and \LangCLam{}}
  8008. \label{sec:explicate-r5}
  8009. The output language of \code{explicate-control} is \LangCLam{} whose
  8010. abstract syntax is defined in Figure~\ref{fig:c4-syntax}. The only
  8011. difference with respect to \LangCFun{} is the addition of the
  8012. \code{AllocateClosure} form to the grammar for $\Exp$. The handling
  8013. of \code{AllocateClosure} in the \code{explicate-control} pass is
  8014. similar to the handling of other expressions such as primitive
  8015. operators.
  8016. \begin{figure}[tp]
  8017. \fbox{
  8018. \begin{minipage}{0.96\textwidth}
  8019. \small
  8020. \[
  8021. \begin{array}{lcl}
  8022. \Exp &::= & \ldots
  8023. \mid \ALLOCCLOS{\Int}{\Type}{\Int} \\
  8024. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  8025. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  8026. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  8027. \mid \GOTO{\itm{label}} } \\
  8028. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  8029. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  8030. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  8031. \LangCLam{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  8032. \end{array}
  8033. \]
  8034. \end{minipage}
  8035. }
  8036. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  8037. \label{fig:c4-syntax}
  8038. \end{figure}
  8039. \section{Select Instructions}
  8040. \label{sec:select-instructions-Rlambda}
  8041. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  8042. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  8043. (Section~\ref{sec:select-instructions-gc}). The only difference is
  8044. that you should place the \itm{arity} in the tag that is stored at
  8045. position $0$ of the vector. Recall that in
  8046. Section~\ref{sec:select-instructions-gc} we used the first $56$ bits
  8047. of the 64-bit tag, but that the rest were unused. So the arity goes
  8048. into the tag in bit positions $57$ through $63$.
  8049. Compile the \code{procedure-arity} operator into a sequence of
  8050. instructions that access the tag from position $0$ of the vector and
  8051. shift it by $57$ bits to the right.
  8052. \begin{figure}[p]
  8053. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8054. \node (Rfun) at (0,2) {\large \LangFun{}};
  8055. \node (Rfun-2) at (3,2) {\large \LangFun{}};
  8056. \node (Rfun-3) at (6,2) {\large \LangFun{}};
  8057. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  8058. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  8059. \node (F1-3) at (6,0) {\large $F_1$};
  8060. \node (F1-4) at (3,0) {\large $F_1$};
  8061. \node (F1-5) at (0,0) {\large $F_1$};
  8062. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  8063. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  8064. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  8065. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  8066. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  8067. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  8068. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  8069. \path[->,bend left=15] (Rfun) edge [above] node
  8070. {\ttfamily\footnotesize shrink} (Rfun-2);
  8071. \path[->,bend left=15] (Rfun-2) edge [above] node
  8072. {\ttfamily\footnotesize uniquify} (Rfun-3);
  8073. \path[->,bend left=15] (Rfun-3) edge [right] node
  8074. {\ttfamily\footnotesize reveal-functions} (F1-1);
  8075. \path[->,bend left=15] (F1-1) edge [below] node
  8076. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  8077. \path[->,bend right=15] (F1-2) edge [above] node
  8078. {\ttfamily\footnotesize limit-fun.} (F1-3);
  8079. \path[->,bend right=15] (F1-3) edge [above] node
  8080. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  8081. \path[->,bend right=15] (F1-4) edge [above] node
  8082. {\ttfamily\footnotesize remove-complex.} (F1-5);
  8083. \path[->,bend right=15] (F1-5) edge [right] node
  8084. {\ttfamily\footnotesize explicate-control} (C3-2);
  8085. \path[->,bend left=15] (C3-2) edge [left] node
  8086. {\ttfamily\footnotesize select-instr.} (x86-2);
  8087. \path[->,bend right=15] (x86-2) edge [left] node
  8088. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  8089. \path[->,bend right=15] (x86-2-1) edge [below] node
  8090. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  8091. \path[->,bend right=15] (x86-2-2) edge [left] node
  8092. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  8093. \path[->,bend left=15] (x86-3) edge [above] node
  8094. {\ttfamily\footnotesize patch-instr.} (x86-4);
  8095. \path[->,bend left=15] (x86-4) edge [right] node
  8096. {\ttfamily\footnotesize print-x86} (x86-5);
  8097. \end{tikzpicture}
  8098. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  8099. functions.}
  8100. \label{fig:Rlambda-passes}
  8101. \end{figure}
  8102. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  8103. for the compilation of \LangLam{}.
  8104. \clearpage
  8105. \section{Challenge: Optimize Closures}
  8106. \label{sec:optimize-closures}
  8107. In this chapter we compiled lexically-scoped functions into a
  8108. relatively efficient representation: flat closures. However, even this
  8109. representation comes with some overhead. For example, consider the
  8110. following program with a function \code{tail-sum} that does not have
  8111. any free variables and where all the uses of \code{tail-sum} are in
  8112. applications where we know that only \code{tail-sum} is being applied
  8113. (and not any other functions).
  8114. \begin{center}
  8115. \begin{minipage}{0.95\textwidth}
  8116. \begin{lstlisting}
  8117. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  8118. (if (eq? n 0)
  8119. r
  8120. (tail-sum (- n 1) (+ n r))))
  8121. (+ (tail-sum 5 0) 27)
  8122. \end{lstlisting}
  8123. \end{minipage}
  8124. \end{center}
  8125. As described in this chapter, we uniformly apply closure conversion to
  8126. all functions, obtaining the following output for this program.
  8127. \begin{center}
  8128. \begin{minipage}{0.95\textwidth}
  8129. \begin{lstlisting}
  8130. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [r3 : Integer]) : Integer
  8131. (if (eq? n2 0)
  8132. r3
  8133. (let ([clos4 (closure (list (fun-ref tail_sum1)))])
  8134. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 r3)))))
  8135. (define (main) : Integer
  8136. (+ (let ([clos6 (closure (list (fun-ref tail_sum1)))])
  8137. ((vector-ref clos6 0) clos6 5 0)) 27))
  8138. \end{lstlisting}
  8139. \end{minipage}
  8140. \end{center}
  8141. In the previous Chapter, there would be no allocation in the program
  8142. and the calls to \code{tail-sum} would be direct calls. In contrast,
  8143. the above program allocates memory for each \code{closure} and the
  8144. calls to \code{tail-sum} are indirect. These two differences incur
  8145. considerable overhead in a program such as this one, where the
  8146. allocations and indirect calls occur inside a tight loop.
  8147. One might think that this problem is trivial to solve: can't we just
  8148. recognize calls of the form \code{((fun-ref $f$) $e_1 \ldots e_n$)}
  8149. and compile them to direct calls \code{((fun-ref $f$) $e'_1 \ldots
  8150. e'_n$)} instead of treating it like a call to a closure? We would
  8151. also drop the \code{fvs5} parameter of \code{tail\_sum1}.
  8152. %
  8153. However, this problem is not so trivial because a global function may
  8154. ``escape'' and become involved in applications that also involve
  8155. closures. Consider the following example in which the application
  8156. \code{(f 41)} needs to be compiled into a closure application, because
  8157. the \code{lambda} may get bound to \code{f}, but the \code{add1}
  8158. function might also get bound to \code{f}.
  8159. \begin{lstlisting}
  8160. (define (add1 [x : Integer]) : Integer
  8161. (+ x 1))
  8162. (let ([y (read)])
  8163. (let ([f (if (eq? (read) 0)
  8164. add1
  8165. (lambda: ([x : Integer]) : Integer (- x y)))])
  8166. (f 41)))
  8167. \end{lstlisting}
  8168. If a global function name is used in any way other than as the
  8169. operator in a direct call, then we say that the function
  8170. \emph{escapes}. If a global function does not escape, then we do not
  8171. need to perform closure conversion on the function.
  8172. \begin{exercise}\normalfont
  8173. Implement an auxiliary function for detecting which global
  8174. functions escape. Using that function, implement an improved version
  8175. of closure conversion that does not apply closure conversion to
  8176. global functions that do not escape but instead compiles them as
  8177. regular functions. Create several new test cases that check whether
  8178. you properly detect whether global functions escape or not.
  8179. \end{exercise}
  8180. So far we have reduced the overhead of calling global functions, but
  8181. it would also be nice to reduce the overhead of calling a
  8182. \code{lambda} when we can determine at compile time which
  8183. \code{lambda} will be called. We refer to such calls as \emph{known
  8184. calls}. Consider the following example in which a \code{lambda} is
  8185. bound to \code{f} and then applied.
  8186. \begin{lstlisting}
  8187. (let ([y (read)])
  8188. (let ([f (lambda: ([x : Integer]) : Integer
  8189. (+ x y))])
  8190. (f 21)))
  8191. \end{lstlisting}
  8192. Closure conversion compiles \code{(f 21)} into an indirect call:
  8193. \begin{lstlisting}
  8194. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  8195. (let ([y2 (vector-ref fvs6 1)])
  8196. (+ x3 y2)))
  8197. (define (main) : Integer
  8198. (let ([y2 (read)])
  8199. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  8200. ((vector-ref f4 0) f4 21))))
  8201. \end{lstlisting}
  8202. but we can instead compile the application \code{(f 21)} into a direct call
  8203. to \code{lambda5}:
  8204. \begin{lstlisting}
  8205. (define (main) : Integer
  8206. (let ([y2 (read)])
  8207. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  8208. ((fun-ref lambda5) f4 21))))
  8209. \end{lstlisting}
  8210. The problem of determining which lambda will be called from a
  8211. particular application is quite challenging in general and the topic
  8212. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  8213. following exercise we recommend that you compile an application to a
  8214. direct call when the operator is a variable and the variable is
  8215. \code{let}-bound to a closure. This can be accomplished by maintaining
  8216. an environment mapping \code{let}-bound variables to function names.
  8217. Extend the environment whenever you encounter a closure on the
  8218. right-hand side of a \code{let}, mapping the \code{let}-bound variable
  8219. to the name of the global function for the closure. This pass should
  8220. come after closure conversion.
  8221. \begin{exercise}\normalfont
  8222. Implement a compiler pass, named \code{optimize-known-calls}, that
  8223. compiles known calls into direct calls. Verify that your compiler is
  8224. successful in this regard on several example programs.
  8225. \end{exercise}
  8226. These exercises only scratches the surface of optimizing of
  8227. closures. A good next step for the interested reader is to look at the
  8228. work of \citet{Keep:2012ab}.
  8229. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8230. \chapter{Dynamic Typing}
  8231. \label{ch:type-dynamic}
  8232. \index{dynamic typing}
  8233. In this chapter we discuss the compilation of \LangDyn{}, a dynamically
  8234. typed language that is a subset of Racket. This is in contrast to the
  8235. previous chapters, which have studied the compilation of Typed
  8236. Racket. In dynamically typed languages such as \LangDyn{}, a given
  8237. expression may produce a value of a different type each time it is
  8238. executed. Consider the following example with a conditional \code{if}
  8239. expression that may return a Boolean or an integer depending on the
  8240. input to the program.
  8241. % part of dynamic_test_25.rkt
  8242. \begin{lstlisting}
  8243. (not (if (eq? (read) 1) #f 0))
  8244. \end{lstlisting}
  8245. Languages that allow expressions to produce different kinds of values
  8246. are called \emph{polymorphic}, a word composed of the Greek roots
  8247. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  8248. are several kinds of polymorphism in programming languages, such as
  8249. subtype polymorphism and parametric
  8250. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  8251. study in this chapter does not have a special name but it is the kind
  8252. that arises in dynamically typed languages.
  8253. Another characteristic of dynamically typed languages is that
  8254. primitive operations, such as \code{not}, are often defined to operate
  8255. on many different types of values. In fact, in Racket, the \code{not}
  8256. operator produces a result for any kind of value: given \code{\#f} it
  8257. returns \code{\#t} and given anything else it returns \code{\#f}.
  8258. Furthermore, even when primitive operations restrict their inputs to
  8259. values of a certain type, this restriction is enforced at runtime
  8260. instead of during compilation. For example, the following vector
  8261. reference results in a run-time contract violation because the index
  8262. must be in integer, not a Boolean such as \code{\#t}.
  8263. \begin{lstlisting}
  8264. (vector-ref (vector 42) #t)
  8265. \end{lstlisting}
  8266. \begin{figure}[tp]
  8267. \centering
  8268. \fbox{
  8269. \begin{minipage}{0.97\textwidth}
  8270. \[
  8271. \begin{array}{rcl}
  8272. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  8273. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp}
  8274. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} \\
  8275. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  8276. &\mid& \key{\#t} \mid \key{\#f}
  8277. \mid \CBINOP{\key{and}}{\Exp}{\Exp}
  8278. \mid \CBINOP{\key{or}}{\Exp}{\Exp}
  8279. \mid \CUNIOP{\key{not}}{\Exp} \\
  8280. &\mid& \LP\itm{cmp}\;\Exp\;\Exp\RP \mid \CIF{\Exp}{\Exp}{\Exp} \\
  8281. &\mid& \LP\key{vector}\;\Exp\ldots\RP \mid
  8282. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  8283. &\mid& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \mid \LP\key{void}\RP \\
  8284. &\mid& \LP\Exp \; \Exp\ldots\RP
  8285. \mid \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  8286. & \mid & \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP\\
  8287. & \mid & \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \mid \LP\key{void?}\;\Exp\RP \\
  8288. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  8289. \LangDyn{} &::=& \Def\ldots\; \Exp
  8290. \end{array}
  8291. \]
  8292. \end{minipage}
  8293. }
  8294. \caption{Syntax of \LangDyn{}, an untyped language (a subset of Racket).}
  8295. \label{fig:r7-concrete-syntax}
  8296. \end{figure}
  8297. \begin{figure}[tp]
  8298. \centering
  8299. \fbox{
  8300. \begin{minipage}{0.96\textwidth}
  8301. \small
  8302. \[
  8303. \begin{array}{lcl}
  8304. \Exp &::=& \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  8305. &\mid& \PRIM{\itm{op}}{\Exp\ldots} \\
  8306. &\mid& \BOOL{\itm{bool}}
  8307. \mid \IF{\Exp}{\Exp}{\Exp} \\
  8308. &\mid& \VOID{} \mid \APPLY{\Exp}{\Exp\ldots} \\
  8309. &\mid& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  8310. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  8311. \LangDyn{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  8312. \end{array}
  8313. \]
  8314. \end{minipage}
  8315. }
  8316. \caption{The abstract syntax of \LangDyn{}.}
  8317. \label{fig:r7-syntax}
  8318. \end{figure}
  8319. The concrete and abstract syntax of \LangDyn{}, our subset of Racket, is
  8320. defined in Figures~\ref{fig:r7-concrete-syntax} and
  8321. \ref{fig:r7-syntax}.
  8322. %
  8323. There is no type checker for \LangDyn{} because it is not a statically
  8324. typed language (it's dynamically typed!).
  8325. The definitional interpreter for \LangDyn{} is presented in
  8326. Figure~\ref{fig:interp-Rdyn} and its auxiliary functions are defined in
  8327. Figure~\ref{fig:interp-Rdyn-aux}. Consider the match clause for
  8328. \code{(Int n)}. Instead of simply returning the integer \code{n} (as
  8329. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Rvar}), the
  8330. interpreter for \LangDyn{} creates a \emph{tagged value}\index{tagged
  8331. value} that combines an underlying value with a tag that identifies
  8332. what kind of value it is. We define the following struct
  8333. to represented tagged values.
  8334. \begin{lstlisting}
  8335. (struct Tagged (value tag) #:transparent)
  8336. \end{lstlisting}
  8337. The tags are \code{Integer}, \code{Boolean}, \code{Void},
  8338. \code{Vector}, and \code{Procedure}. Tags are closely related to types
  8339. but don't always capture all the information that a type does. For
  8340. example, a vector of type \code{(Vector Any Any)} is tagged with
  8341. \code{Vector} and a procedure of type \code{(Any Any -> Any)}
  8342. is tagged with \code{Procedure}.
  8343. Next consider the match clause for \code{vector-ref}. The
  8344. \code{check-tag} auxiliary function (Figure~\ref{fig:interp-Rdyn-aux})
  8345. is used to ensure that the first argument is a vector and the second
  8346. is an integer. If they are not, a \code{trapped-error} is raised.
  8347. Recall from Section~\ref{sec:interp-Rint} that when a definition
  8348. interpreter raises a \code{trapped-error} error, the compiled code
  8349. must also signal an error by exiting with return code \code{255}. A
  8350. \code{trapped-error} is also raised if the index is not less than
  8351. length of the vector.
  8352. \begin{figure}[tbp]
  8353. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8354. (define ((interp-Rdyn-exp env) ast)
  8355. (define recur (interp-Rdyn-exp env))
  8356. (match ast
  8357. [(Var x) (lookup x env)]
  8358. [(Int n) (Tagged n 'Integer)]
  8359. [(Bool b) (Tagged b 'Boolean)]
  8360. [(Lambda xs rt body)
  8361. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  8362. [(Prim 'vector es)
  8363. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  8364. [(Prim 'vector-ref (list e1 e2))
  8365. (define vec (recur e1)) (define i (recur e2))
  8366. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  8367. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  8368. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  8369. (vector-ref (Tagged-value vec) (Tagged-value i))]
  8370. [(Prim 'vector-set! (list e1 e2 e3))
  8371. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  8372. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  8373. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  8374. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  8375. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  8376. (Tagged (void) 'Void)]
  8377. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  8378. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  8379. [(Prim 'or (list e1 e2))
  8380. (define v1 (recur e1))
  8381. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  8382. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  8383. [(Prim op (list e1))
  8384. #:when (set-member? type-predicates op)
  8385. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  8386. [(Prim op es)
  8387. (define args (map recur es))
  8388. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  8389. (unless (for/or ([expected-tags (op-tags op)])
  8390. (equal? expected-tags tags))
  8391. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  8392. (tag-value
  8393. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  8394. [(If q t f)
  8395. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  8396. [(Apply f es)
  8397. (define new-f (recur f)) (define args (map recur es))
  8398. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  8399. (match f-val
  8400. [`(function ,xs ,body ,lam-env)
  8401. (unless (eq? (length xs) (length args))
  8402. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  8403. (define new-env (append (map cons xs args) lam-env))
  8404. ((interp-Rdyn-exp new-env) body)]
  8405. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  8406. \end{lstlisting}
  8407. \caption{Interpreter for the \LangDyn{} language.}
  8408. \label{fig:interp-Rdyn}
  8409. \end{figure}
  8410. \begin{figure}[tbp]
  8411. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8412. (define (interp-op op)
  8413. (match op
  8414. ['+ fx+]
  8415. ['- fx-]
  8416. ['read read-fixnum]
  8417. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  8418. ['< (lambda (v1 v2)
  8419. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  8420. ['<= (lambda (v1 v2)
  8421. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  8422. ['> (lambda (v1 v2)
  8423. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  8424. ['>= (lambda (v1 v2)
  8425. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  8426. ['boolean? boolean?]
  8427. ['integer? fixnum?]
  8428. ['void? void?]
  8429. ['vector? vector?]
  8430. ['vector-length vector-length]
  8431. ['procedure? (match-lambda
  8432. [`(functions ,xs ,body ,env) #t] [else #f])]
  8433. [else (error 'interp-op "unknown operator" op)]))
  8434. (define (op-tags op)
  8435. (match op
  8436. ['+ '((Integer Integer))]
  8437. ['- '((Integer Integer) (Integer))]
  8438. ['read '(())]
  8439. ['not '((Boolean))]
  8440. ['< '((Integer Integer))]
  8441. ['<= '((Integer Integer))]
  8442. ['> '((Integer Integer))]
  8443. ['>= '((Integer Integer))]
  8444. ['vector-length '((Vector))]))
  8445. (define type-predicates
  8446. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  8447. (define (tag-value v)
  8448. (cond [(boolean? v) (Tagged v 'Boolean)]
  8449. [(fixnum? v) (Tagged v 'Integer)]
  8450. [(procedure? v) (Tagged v 'Procedure)]
  8451. [(vector? v) (Tagged v 'Vector)]
  8452. [(void? v) (Tagged v 'Void)]
  8453. [else (error 'tag-value "unidentified value ~a" v)]))
  8454. (define (check-tag val expected ast)
  8455. (define tag (Tagged-tag val))
  8456. (unless (eq? tag expected)
  8457. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  8458. \end{lstlisting}
  8459. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  8460. \label{fig:interp-Rdyn-aux}
  8461. \end{figure}
  8462. \clearpage
  8463. \section{Representation of Tagged Values}
  8464. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  8465. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  8466. values at the bit level. Because almost every operation in \LangDyn{}
  8467. involves manipulating tagged values, the representation must be
  8468. efficient. Recall that all of our values are 64 bits. We shall steal
  8469. the 3 right-most bits to encode the tag. We use $001$ to identify
  8470. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  8471. and $101$ for the void value. We define the following auxiliary
  8472. function for mapping types to tag codes.
  8473. \begin{align*}
  8474. \itm{tagof}(\key{Integer}) &= 001 \\
  8475. \itm{tagof}(\key{Boolean}) &= 100 \\
  8476. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  8477. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  8478. \itm{tagof}(\key{Void}) &= 101
  8479. \end{align*}
  8480. This stealing of 3 bits comes at some price: our integers are reduced
  8481. to ranging from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  8482. affect vectors and procedures because those values are addresses, and
  8483. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  8484. they are always $000$. Thus, we do not lose information by overwriting
  8485. the rightmost 3 bits with the tag and we can simply zero-out the tag
  8486. to recover the original address.
  8487. To make tagged values into first-class entities, we can give them a
  8488. type, called \code{Any}, and define operations such as \code{Inject}
  8489. and \code{Project} for creating and using them, yielding the \LangAny{}
  8490. intermediate language. We describe how to compile \LangDyn{} to \LangAny{} in
  8491. Section~\ref{sec:compile-r7} but first we describe the \LangAny{} language
  8492. in greater detail.
  8493. \section{The \LangAny{} Language}
  8494. \label{sec:r6-lang}
  8495. \begin{figure}[tp]
  8496. \centering
  8497. \fbox{
  8498. \begin{minipage}{0.96\textwidth}
  8499. \small
  8500. \[
  8501. \begin{array}{lcl}
  8502. \Type &::= & \ldots \mid \key{Any} \\
  8503. \itm{op} &::= & \ldots \mid \code{any-vector-length}
  8504. \mid \code{any-vector-ref} \mid \code{any-vector-set!}\\
  8505. &\mid& \code{boolean?} \mid \code{integer?} \mid \code{vector?}
  8506. \mid \code{procedure?} \mid \code{void?} \\
  8507. \Exp &::=& \ldots
  8508. \mid \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  8509. &\mid& \INJECT{\Exp}{\FType} \mid \PROJECT{\Exp}{\FType} \\
  8510. \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  8511. \LangAny{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  8512. \end{array}
  8513. \]
  8514. \end{minipage}
  8515. }
  8516. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Rlam-syntax}).}
  8517. \label{fig:r6-syntax}
  8518. \end{figure}
  8519. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:r6-syntax}.
  8520. (The concrete syntax of \LangAny{} is in the Appendix,
  8521. Figure~\ref{fig:r6-concrete-syntax}.) The $\INJECT{e}{T}$ form
  8522. converts the value produced by expression $e$ of type $T$ into a
  8523. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  8524. produced by expression $e$ into a value of type $T$ or else halts the
  8525. program if the type tag is not equivalent to $T$.
  8526. %
  8527. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  8528. restricted to a flat type $\FType$, which simplifies the
  8529. implementation and corresponds with what is needed for compiling \LangDyn{}.
  8530. The \code{any-vector} operators adapt the vector operations so that
  8531. they can be applied to a value of type \code{Any}. They also
  8532. generalize the vector operations in that the index is not restricted
  8533. to be a literal integer in the grammar but is allowed to be any
  8534. expression.
  8535. The type predicates such as \key{boolean?} expect their argument to
  8536. produce a tagged value; they return \key{\#t} if the tag corresponds
  8537. to the predicate and they return \key{\#f} otherwise.
  8538. The type checker for \LangAny{} is shown in
  8539. Figures~\ref{fig:type-check-Rany-part-1} and
  8540. \ref{fig:type-check-Rany-part-2} and uses the auxiliary functions in
  8541. Figure~\ref{fig:type-check-Rany-aux}.
  8542. %
  8543. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Rany} and the
  8544. auxiliary functions \code{apply-inject} and \code{apply-project} are
  8545. in Figure~\ref{fig:apply-project}.
  8546. \begin{figure}[btp]
  8547. \begin{lstlisting}[basicstyle=\ttfamily\small]
  8548. (define type-check-Rany-class
  8549. (class type-check-Rlambda-class
  8550. (super-new)
  8551. (inherit check-type-equal?)
  8552. (define/override (type-check-exp env)
  8553. (lambda (e)
  8554. (define recur (type-check-exp env))
  8555. (match e
  8556. [(Inject e1 ty)
  8557. (unless (flat-ty? ty)
  8558. (error 'type-check "may only inject from flat type, not ~a" ty))
  8559. (define-values (new-e1 e-ty) (recur e1))
  8560. (check-type-equal? e-ty ty e)
  8561. (values (Inject new-e1 ty) 'Any)]
  8562. [(Project e1 ty)
  8563. (unless (flat-ty? ty)
  8564. (error 'type-check "may only project to flat type, not ~a" ty))
  8565. (define-values (new-e1 e-ty) (recur e1))
  8566. (check-type-equal? e-ty 'Any e)
  8567. (values (Project new-e1 ty) ty)]
  8568. [(Prim 'any-vector-length (list e1))
  8569. (define-values (e1^ t1) (recur e1))
  8570. (check-type-equal? t1 'Any e)
  8571. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  8572. [(Prim 'any-vector-ref (list e1 e2))
  8573. (define-values (e1^ t1) (recur e1))
  8574. (define-values (e2^ t2) (recur e2))
  8575. (check-type-equal? t1 'Any e)
  8576. (check-type-equal? t2 'Integer e)
  8577. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  8578. [(Prim 'any-vector-set! (list e1 e2 e3))
  8579. (define-values (e1^ t1) (recur e1))
  8580. (define-values (e2^ t2) (recur e2))
  8581. (define-values (e3^ t3) (recur e3))
  8582. (check-type-equal? t1 'Any e)
  8583. (check-type-equal? t2 'Integer e)
  8584. (check-type-equal? t3 'Any e)
  8585. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  8586. \end{lstlisting}
  8587. \caption{Type checker for the \LangAny{} language, part 1.}
  8588. \label{fig:type-check-Rany-part-1}
  8589. \end{figure}
  8590. \begin{figure}[btp]
  8591. \begin{lstlisting}[basicstyle=\ttfamily\small]
  8592. [(ValueOf e ty)
  8593. (define-values (new-e e-ty) (recur e))
  8594. (values (ValueOf new-e ty) ty)]
  8595. [(Prim pred (list e1))
  8596. #:when (set-member? (type-predicates) pred)
  8597. (define-values (new-e1 e-ty) (recur e1))
  8598. (check-type-equal? e-ty 'Any e)
  8599. (values (Prim pred (list new-e1)) 'Boolean)]
  8600. [(If cnd thn els)
  8601. (define-values (cnd^ Tc) (recur cnd))
  8602. (define-values (thn^ Tt) (recur thn))
  8603. (define-values (els^ Te) (recur els))
  8604. (check-type-equal? Tc 'Boolean cnd)
  8605. (check-type-equal? Tt Te e)
  8606. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  8607. [(Exit) (values (Exit) '_)]
  8608. [(Prim 'eq? (list arg1 arg2))
  8609. (define-values (e1 t1) (recur arg1))
  8610. (define-values (e2 t2) (recur arg2))
  8611. (match* (t1 t2)
  8612. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  8613. [(other wise) (check-type-equal? t1 t2 e)])
  8614. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  8615. [else ((super type-check-exp env) e)])))
  8616. ))
  8617. \end{lstlisting}
  8618. \caption{Type checker for the \LangAny{} language, part 2.}
  8619. \label{fig:type-check-Rany-part-2}
  8620. \end{figure}
  8621. \begin{figure}[tbp]
  8622. \begin{lstlisting}
  8623. (define/override (operator-types)
  8624. (append
  8625. '((integer? . ((Any) . Boolean))
  8626. (vector? . ((Any) . Boolean))
  8627. (procedure? . ((Any) . Boolean))
  8628. (void? . ((Any) . Boolean))
  8629. (tag-of-any . ((Any) . Integer))
  8630. (make-any . ((_ Integer) . Any))
  8631. )
  8632. (super operator-types)))
  8633. (define/public (type-predicates)
  8634. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  8635. (define/public (combine-types t1 t2)
  8636. (match (list t1 t2)
  8637. [(list '_ t2) t2]
  8638. [(list t1 '_) t1]
  8639. [(list `(Vector ,ts1 ...)
  8640. `(Vector ,ts2 ...))
  8641. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  8642. (combine-types t1 t2)))]
  8643. [(list `(,ts1 ... -> ,rt1)
  8644. `(,ts2 ... -> ,rt2))
  8645. `(,@(for/list ([t1 ts1] [t2 ts2])
  8646. (combine-types t1 t2))
  8647. -> ,(combine-types rt1 rt2))]
  8648. [else t1]))
  8649. (define/public (flat-ty? ty)
  8650. (match ty
  8651. [(or `Integer `Boolean '_ `Void) #t]
  8652. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  8653. [`(,ts ... -> ,rt)
  8654. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  8655. [else #f]))
  8656. \end{lstlisting}
  8657. \caption{Auxiliary methods for type checking \LangAny{}.}
  8658. \label{fig:type-check-Rany-aux}
  8659. \end{figure}
  8660. \begin{figure}[btp]
  8661. \begin{lstlisting}
  8662. (define interp-Rany-class
  8663. (class interp-Rlambda-class
  8664. (super-new)
  8665. (define/override (interp-op op)
  8666. (match op
  8667. ['boolean? (match-lambda
  8668. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  8669. [else #f])]
  8670. ['integer? (match-lambda
  8671. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  8672. [else #f])]
  8673. ['vector? (match-lambda
  8674. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  8675. [else #f])]
  8676. ['procedure? (match-lambda
  8677. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  8678. [else #f])]
  8679. ['eq? (match-lambda*
  8680. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  8681. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  8682. [ls (apply (super interp-op op) ls)])]
  8683. ['any-vector-ref (lambda (v i)
  8684. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  8685. ['any-vector-set! (lambda (v i a)
  8686. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  8687. ['any-vector-length (lambda (v)
  8688. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  8689. [else (super interp-op op)]))
  8690. (define/override ((interp-exp env) e)
  8691. (define recur (interp-exp env))
  8692. (match e
  8693. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  8694. [(Project e ty2) (apply-project (recur e) ty2)]
  8695. [else ((super interp-exp env) e)]))
  8696. ))
  8697. (define (interp-Rany p)
  8698. (send (new interp-Rany-class) interp-program p))
  8699. \end{lstlisting}
  8700. \caption{Interpreter for \LangAny{}.}
  8701. \label{fig:interp-Rany}
  8702. \end{figure}
  8703. \begin{figure}[tbp]
  8704. \begin{lstlisting}
  8705. (define/public (apply-inject v tg) (Tagged v tg))
  8706. (define/public (apply-project v ty2)
  8707. (define tag2 (any-tag ty2))
  8708. (match v
  8709. [(Tagged v1 tag1)
  8710. (cond
  8711. [(eq? tag1 tag2)
  8712. (match ty2
  8713. [`(Vector ,ts ...)
  8714. (define l1 ((interp-op 'vector-length) v1))
  8715. (cond
  8716. [(eq? l1 (length ts)) v1]
  8717. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  8718. l1 (length ts))])]
  8719. [`(,ts ... -> ,rt)
  8720. (match v1
  8721. [`(function ,xs ,body ,env)
  8722. (cond [(eq? (length xs) (length ts)) v1]
  8723. [else
  8724. (error 'apply-project "arity mismatch ~a != ~a"
  8725. (length xs) (length ts))])]
  8726. [else (error 'apply-project "expected function not ~a" v1)])]
  8727. [else v1])]
  8728. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  8729. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  8730. \end{lstlisting}
  8731. \caption{Auxiliary functions for injection and projection.}
  8732. \label{fig:apply-project}
  8733. \end{figure}
  8734. \clearpage
  8735. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  8736. \label{sec:compile-r7}
  8737. The \code{cast-insert} pass compiles from \LangDyn{} to \LangAny{}.
  8738. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  8739. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  8740. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  8741. an expression $e'$ in \LangAny{} that has type \key{Any}. For example, the
  8742. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  8743. the Boolean \code{\#t}, which must be injected to produce an
  8744. expression of type \key{Any}.
  8745. %
  8746. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  8747. addition, is representative of compilation for many primitive
  8748. operations: the arguments have type \key{Any} and must be projected to
  8749. \key{Integer} before the addition can be performed.
  8750. The compilation of \key{lambda} (third row of
  8751. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  8752. produce type annotations: we simply use \key{Any}.
  8753. %
  8754. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  8755. has to account for some differences in behavior between \LangDyn{} and
  8756. \LangAny{}. The \LangDyn{} language is more permissive than \LangAny{} regarding what
  8757. kind of values can be used in various places. For example, the
  8758. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  8759. the arguments need not be of the same type (in that case the
  8760. result is \code{\#f}).
  8761. \begin{figure}[btp]
  8762. \centering
  8763. \begin{tabular}{|lll|} \hline
  8764. \begin{minipage}{0.27\textwidth}
  8765. \begin{lstlisting}
  8766. #t
  8767. \end{lstlisting}
  8768. \end{minipage}
  8769. &
  8770. $\Rightarrow$
  8771. &
  8772. \begin{minipage}{0.65\textwidth}
  8773. \begin{lstlisting}
  8774. (inject #t Boolean)
  8775. \end{lstlisting}
  8776. \end{minipage}
  8777. \\[2ex]\hline
  8778. \begin{minipage}{0.27\textwidth}
  8779. \begin{lstlisting}
  8780. (+ |$e_1$| |$e_2$|)
  8781. \end{lstlisting}
  8782. \end{minipage}
  8783. &
  8784. $\Rightarrow$
  8785. &
  8786. \begin{minipage}{0.65\textwidth}
  8787. \begin{lstlisting}
  8788. (inject
  8789. (+ (project |$e'_1$| Integer)
  8790. (project |$e'_2$| Integer))
  8791. Integer)
  8792. \end{lstlisting}
  8793. \end{minipage}
  8794. \\[2ex]\hline
  8795. \begin{minipage}{0.27\textwidth}
  8796. \begin{lstlisting}
  8797. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  8798. \end{lstlisting}
  8799. \end{minipage}
  8800. &
  8801. $\Rightarrow$
  8802. &
  8803. \begin{minipage}{0.65\textwidth}
  8804. \begin{lstlisting}
  8805. (inject
  8806. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  8807. (Any|$\ldots$|Any -> Any))
  8808. \end{lstlisting}
  8809. \end{minipage}
  8810. \\[2ex]\hline
  8811. \begin{minipage}{0.27\textwidth}
  8812. \begin{lstlisting}
  8813. (|$e_0$| |$e_1 \ldots e_n$|)
  8814. \end{lstlisting}
  8815. \end{minipage}
  8816. &
  8817. $\Rightarrow$
  8818. &
  8819. \begin{minipage}{0.65\textwidth}
  8820. \begin{lstlisting}
  8821. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  8822. \end{lstlisting}
  8823. \end{minipage}
  8824. \\[2ex]\hline
  8825. \begin{minipage}{0.27\textwidth}
  8826. \begin{lstlisting}
  8827. (vector-ref |$e_1$| |$e_2$|)
  8828. \end{lstlisting}
  8829. \end{minipage}
  8830. &
  8831. $\Rightarrow$
  8832. &
  8833. \begin{minipage}{0.65\textwidth}
  8834. \begin{lstlisting}
  8835. (any-vector-ref |$e_1'$| |$e_2'$|)
  8836. \end{lstlisting}
  8837. \end{minipage}
  8838. \\[2ex]\hline
  8839. \begin{minipage}{0.27\textwidth}
  8840. \begin{lstlisting}
  8841. (if |$e_1$| |$e_2$| |$e_3$|)
  8842. \end{lstlisting}
  8843. \end{minipage}
  8844. &
  8845. $\Rightarrow$
  8846. &
  8847. \begin{minipage}{0.65\textwidth}
  8848. \begin{lstlisting}
  8849. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  8850. \end{lstlisting}
  8851. \end{minipage}
  8852. \\[2ex]\hline
  8853. \begin{minipage}{0.27\textwidth}
  8854. \begin{lstlisting}
  8855. (eq? |$e_1$| |$e_2$|)
  8856. \end{lstlisting}
  8857. \end{minipage}
  8858. &
  8859. $\Rightarrow$
  8860. &
  8861. \begin{minipage}{0.65\textwidth}
  8862. \begin{lstlisting}
  8863. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  8864. \end{lstlisting}
  8865. \end{minipage}
  8866. \\[2ex]\hline
  8867. \begin{minipage}{0.27\textwidth}
  8868. \begin{lstlisting}
  8869. (not |$e_1$|)
  8870. \end{lstlisting}
  8871. \end{minipage}
  8872. &
  8873. $\Rightarrow$
  8874. &
  8875. \begin{minipage}{0.65\textwidth}
  8876. \begin{lstlisting}
  8877. (if (eq? |$e'_1$| (inject #f Boolean))
  8878. (inject #t Boolean) (inject #f Boolean))
  8879. \end{lstlisting}
  8880. \end{minipage}
  8881. \\[2ex]\hline
  8882. \end{tabular}
  8883. \caption{Cast Insertion}
  8884. \label{fig:compile-r7-r6}
  8885. \end{figure}
  8886. \section{Reveal Casts}
  8887. \label{sec:reveal-casts-r6}
  8888. % TODO: define R'_6
  8889. In the \code{reveal-casts} pass we recommend compiling \code{project}
  8890. into an \code{if} expression that checks whether the value's tag
  8891. matches the target type; if it does, the value is converted to a value
  8892. of the target type by removing the tag; if it does not, the program
  8893. exits. To perform these actions we need a new primitive operation,
  8894. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  8895. The \code{tag-of-any} operation retrieves the type tag from a tagged
  8896. value of type \code{Any}. The \code{ValueOf} form retrieves the
  8897. underlying value from a tagged value. The \code{ValueOf} form
  8898. includes the type for the underlying value which is used by the type
  8899. checker. Finally, the \code{Exit} form ends the execution of the
  8900. program.
  8901. If the target type of the projection is \code{Boolean} or
  8902. \code{Integer}, then \code{Project} can be translated as follows.
  8903. \begin{center}
  8904. \begin{minipage}{1.0\textwidth}
  8905. \begin{lstlisting}
  8906. (Project |$e$| |$\FType$|)
  8907. |$\Rightarrow$|
  8908. (Let |$\itm{tmp}$| |$e'$|
  8909. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  8910. (Int |$\itm{tagof}(\FType)$|)))
  8911. (ValueOf |$\itm{tmp}$| |$\FType$|)
  8912. (Exit)))
  8913. \end{lstlisting}
  8914. \end{minipage}
  8915. \end{center}
  8916. If the target type of the projection is a vector or function type,
  8917. then there is a bit more work to do. For vectors, check that the
  8918. length of the vector type matches the length of the vector (using the
  8919. \code{vector-length} primitive). For functions, check that the number
  8920. of parameters in the function type matches the function's arity (using
  8921. \code{procedure-arity}).
  8922. Regarding \code{inject}, we recommend compiling it to a slightly
  8923. lower-level primitive operation named \code{make-any}. This operation
  8924. takes a tag instead of a type.
  8925. \begin{center}
  8926. \begin{minipage}{1.0\textwidth}
  8927. \begin{lstlisting}
  8928. (Inject |$e$| |$\FType$|)
  8929. |$\Rightarrow$|
  8930. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  8931. \end{lstlisting}
  8932. \end{minipage}
  8933. \end{center}
  8934. The type predicates (\code{boolean?}, etc.) can be translated into
  8935. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  8936. translation of \code{Project}.
  8937. The \code{any-vector-ref} and \code{any-vector-set!} operations
  8938. combine the projection action with the vector operation. Also, the
  8939. read and write operations allow arbitrary expressions for the index so
  8940. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany-part-1})
  8941. cannot guarantee that the index is within bounds. Thus, we insert code
  8942. to perform bounds checking at runtime. The translation for
  8943. \code{any-vector-ref} is as follows and the other two operations are
  8944. translated in a similar way.
  8945. \begin{lstlisting}
  8946. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  8947. |$\Rightarrow$|
  8948. (Let |$v$| |$e'_1$|
  8949. (Let |$i$| |$e'_2$|
  8950. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  8951. (If (Prim '< (list (Var |$i$|)
  8952. (Prim 'any-vector-length (list (Var |$v$|)))))
  8953. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  8954. (Exit))))
  8955. \end{lstlisting}
  8956. \section{Remove Complex Operands}
  8957. \label{sec:rco-r6}
  8958. The \code{ValueOf} and \code{Exit} forms are both complex expressions.
  8959. The subexpression of \code{ValueOf} must be atomic.
  8960. \section{Explicate Control and \LangCAny{}}
  8961. \label{sec:explicate-r6}
  8962. The output of \code{explicate-control} is the \LangCAny{} language whose
  8963. syntax is defined in Figure~\ref{fig:c5-syntax}. The \code{ValueOf}
  8964. form that we added to \LangAny{} remains an expression and the \code{Exit}
  8965. expression becomes a $\Tail$. Also, note that the index argument of
  8966. \code{vector-ref} and \code{vector-set!} is an $\Atm$ instead
  8967. of an integer, as in \LangCVec{} (Figure~\ref{fig:c2-syntax}).
  8968. \begin{figure}[tp]
  8969. \fbox{
  8970. \begin{minipage}{0.96\textwidth}
  8971. \small
  8972. \[
  8973. \begin{array}{lcl}
  8974. \Exp &::= & \ldots
  8975. \mid \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  8976. &\mid& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  8977. &\mid& \VALUEOF{\Exp}{\FType} \\
  8978. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  8979. \mid \LP\key{Collect} \,\itm{int}\RP }\\
  8980. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  8981. \mid \GOTO{\itm{label}} } \\
  8982. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  8983. &\mid& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  8984. \mid \LP\key{Exit}\RP \\
  8985. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  8986. \LangCLam{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  8987. \end{array}
  8988. \]
  8989. \end{minipage}
  8990. }
  8991. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  8992. \label{fig:c5-syntax}
  8993. \end{figure}
  8994. \section{Select Instructions}
  8995. \label{sec:select-r6}
  8996. In the \code{select-instructions} pass we translate the primitive
  8997. operations on the \code{Any} type to x86 instructions that involve
  8998. manipulating the 3 tag bits of the tagged value.
  8999. \paragraph{Make-any}
  9000. We recommend compiling the \key{make-any} primitive as follows if the
  9001. tag is for \key{Integer} or \key{Boolean}. The \key{salq} instruction
  9002. shifts the destination to the left by the number of bits specified its
  9003. source argument (in this case $3$, the length of the tag) and it
  9004. preserves the sign of the integer. We use the \key{orq} instruction to
  9005. combine the tag and the value to form the tagged value. \\
  9006. \begin{lstlisting}
  9007. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  9008. |$\Rightarrow$|
  9009. movq |$e'$|, |\itm{lhs'}|
  9010. salq $3, |\itm{lhs'}|
  9011. orq $|$\itm{tag}$|, |\itm{lhs'}|
  9012. \end{lstlisting}
  9013. The instruction selection for vectors and procedures is different
  9014. because their is no need to shift them to the left. The rightmost 3
  9015. bits are already zeros as described at the beginning of this
  9016. chapter. So we just combine the value and the tag using \key{orq}. \\
  9017. \begin{lstlisting}
  9018. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  9019. |$\Rightarrow$|
  9020. movq |$e'$|, |\itm{lhs'}|
  9021. orq $|$\itm{tag}$|, |\itm{lhs'}|
  9022. \end{lstlisting}
  9023. \paragraph{Tag-of-any}
  9024. Recall that the \code{tag-of-any} operation extracts the type tag from
  9025. a value of type \code{Any}. The type tag is the bottom three bits, so
  9026. we obtain the tag by taking the bitwise-and of the value with $111$
  9027. ($7$ in decimal).
  9028. \begin{lstlisting}
  9029. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  9030. |$\Rightarrow$|
  9031. movq |$e'$|, |\itm{lhs'}|
  9032. andq $7, |\itm{lhs'}|
  9033. \end{lstlisting}
  9034. \paragraph{ValueOf}
  9035. Like \key{make-any}, the instructions for \key{ValueOf} are different
  9036. depending on whether the type $T$ is a pointer (vector or procedure)
  9037. or not (Integer or Boolean). The following shows the instruction
  9038. selection for Integer and Boolean. We produce an untagged value by
  9039. shifting it to the right by 3 bits.
  9040. \begin{lstlisting}
  9041. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  9042. |$\Rightarrow$|
  9043. movq |$e'$|, |\itm{lhs'}|
  9044. sarq $3, |\itm{lhs'}|
  9045. \end{lstlisting}
  9046. %
  9047. In the case for vectors and procedures, there is no need to
  9048. shift. Instead we just need to zero-out the rightmost 3 bits. We
  9049. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  9050. decimal) and apply \code{bitwise-not} to obtain $\ldots 11111000$ (-8
  9051. in decimal) which we \code{movq} into the destination $\itm{lhs}$. We
  9052. then apply \code{andq} with the tagged value to get the desired
  9053. result. \\
  9054. \begin{lstlisting}
  9055. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  9056. |$\Rightarrow$|
  9057. movq $|$-8$|, |\itm{lhs'}|
  9058. andq |$e'$|, |\itm{lhs'}|
  9059. \end{lstlisting}
  9060. %% \paragraph{Type Predicates} We leave it to the reader to
  9061. %% devise a sequence of instructions to implement the type predicates
  9062. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  9063. \paragraph{Any-vector-length}
  9064. \begin{lstlisting}
  9065. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$a_1$|)))
  9066. |$\Longrightarrow$|
  9067. movq |$\neg 111$|, %r11
  9068. andq |$a_1'$|, %r11
  9069. movq 0(%r11), %r11
  9070. andq $126, %r11
  9071. sarq $1, %r11
  9072. movq %r11, |$\itm{lhs'}$|
  9073. \end{lstlisting}
  9074. \paragraph{Any-vector-ref}
  9075. The index may be an arbitrary atom so instead of computing the offset
  9076. at compile time, instructions need to be generated to compute the
  9077. offset at runtime as follows. Note the use of the new instruction
  9078. \code{imulq}.
  9079. \begin{center}
  9080. \begin{minipage}{0.96\textwidth}
  9081. \begin{lstlisting}
  9082. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$a_1$| |$a_2$|)))
  9083. |$\Longrightarrow$|
  9084. movq |$\neg 111$|, %r11
  9085. andq |$a_1'$|, %r11
  9086. movq |$a_2'$|, %rax
  9087. addq $1, %rax
  9088. imulq $8, %rax
  9089. addq %rax, %r11
  9090. movq 0(%r11) |$\itm{lhs'}$|
  9091. \end{lstlisting}
  9092. \end{minipage}
  9093. \end{center}
  9094. \paragraph{Any-vector-set!}
  9095. The code generation for \code{any-vector-set!} is similar to the other
  9096. \code{any-vector} operations.
  9097. \section{Register Allocation for \LangAny{}}
  9098. \label{sec:register-allocation-r6}
  9099. \index{register allocation}
  9100. There is an interesting interaction between tagged values and garbage
  9101. collection that has an impact on register allocation. A variable of
  9102. type \code{Any} might refer to a vector and therefore it might be a
  9103. root that needs to be inspected and copied during garbage
  9104. collection. Thus, we need to treat variables of type \code{Any} in a
  9105. similar way to variables of type \code{Vector} for purposes of
  9106. register allocation. In particular,
  9107. \begin{itemize}
  9108. \item If a variable of type \code{Any} is live during a function call,
  9109. then it must be spilled. This can be accomplished by changing
  9110. \code{build-interference} to mark all variables of type \code{Any}
  9111. that are live after a \code{callq} as interfering with all the
  9112. registers.
  9113. \item If a variable of type \code{Any} is spilled, it must be spilled
  9114. to the root stack instead of the normal procedure call stack.
  9115. \end{itemize}
  9116. Another concern regarding the root stack is that the garbage collector
  9117. needs to differentiate between (1) plain old pointers to tuples, (2) a
  9118. tagged value that points to a tuple, and (3) a tagged value that is
  9119. not a tuple. We enable this differentiation by choosing not to use the
  9120. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  9121. reserved for identifying plain old pointers to tuples. That way, if
  9122. one of the first three bits is set, then we have a tagged value and
  9123. inspecting the tag can differentiation between vectors ($010$) and the
  9124. other kinds of values.
  9125. \begin{exercise}\normalfont
  9126. Expand your compiler to handle \LangAny{} as discussed in the last few
  9127. sections. Create 5 new programs that use the \code{Any} type and the
  9128. new operations (\code{inject}, \code{project}, \code{boolean?},
  9129. etc.). Test your compiler on these new programs and all of your
  9130. previously created test programs.
  9131. \end{exercise}
  9132. \begin{exercise}\normalfont
  9133. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  9134. Create tests for \LangDyn{} by adapting ten of your previous test programs
  9135. by removing type annotations. Add 5 more tests programs that
  9136. specifically rely on the language being dynamically typed. That is,
  9137. they should not be legal programs in a statically typed language, but
  9138. nevertheless, they should be valid \LangDyn{} programs that run to
  9139. completion without error.
  9140. \end{exercise}
  9141. \begin{figure}[p]
  9142. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9143. \node (Rfun) at (0,4) {\large \LangDyn{}};
  9144. \node (Rfun-2) at (3,4) {\large \LangDyn{}};
  9145. \node (Rfun-3) at (6,4) {\large \LangDyn{}};
  9146. \node (Rfun-4) at (9,4) {\large \LangDynFunRef{}};
  9147. \node (Rfun-5) at (9,2) {\large \LangAnyFunRef{}};
  9148. \node (Rfun-6) at (12,2) {\large \LangAnyFunRef{}};
  9149. \node (Rfun-7) at (12,0) {\large \LangAnyFunRef{}};
  9150. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  9151. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  9152. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  9153. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  9154. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  9155. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  9156. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  9157. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  9158. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  9159. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  9160. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  9161. \path[->,bend left=15] (Rfun) edge [above] node
  9162. {\ttfamily\footnotesize shrink} (Rfun-2);
  9163. \path[->,bend left=15] (Rfun-2) edge [above] node
  9164. {\ttfamily\footnotesize uniquify} (Rfun-3);
  9165. \path[->,bend left=15] (Rfun-3) edge [above] node
  9166. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  9167. \path[->,bend right=15] (Rfun-4) edge [left] node
  9168. {\ttfamily\footnotesize cast-insert} (Rfun-5);
  9169. \path[->,bend left=15] (Rfun-5) edge [above] node
  9170. {\ttfamily\footnotesize check-bounds} (Rfun-6);
  9171. \path[->,bend left=15] (Rfun-6) edge [left] node
  9172. {\ttfamily\footnotesize reveal-casts} (Rfun-7);
  9173. \path[->,bend left=15] (Rfun-7) edge [below] node
  9174. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  9175. \path[->,bend right=15] (F1-2) edge [above] node
  9176. {\ttfamily\footnotesize limit-fun.} (F1-3);
  9177. \path[->,bend right=15] (F1-3) edge [above] node
  9178. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9179. \path[->,bend right=15] (F1-4) edge [above] node
  9180. {\ttfamily\footnotesize remove-complex.} (F1-5);
  9181. \path[->,bend right=15] (F1-5) edge [right] node
  9182. {\ttfamily\footnotesize explicate-control} (C3-2);
  9183. \path[->,bend left=15] (C3-2) edge [left] node
  9184. {\ttfamily\footnotesize select-instr.} (x86-2);
  9185. \path[->,bend right=15] (x86-2) edge [left] node
  9186. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  9187. \path[->,bend right=15] (x86-2-1) edge [below] node
  9188. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  9189. \path[->,bend right=15] (x86-2-2) edge [left] node
  9190. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  9191. \path[->,bend left=15] (x86-3) edge [above] node
  9192. {\ttfamily\footnotesize patch-instr.} (x86-4);
  9193. \path[->,bend left=15] (x86-4) edge [right] node
  9194. {\ttfamily\footnotesize print-x86} (x86-5);
  9195. \end{tikzpicture}
  9196. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  9197. \label{fig:Rdyn-passes}
  9198. \end{figure}
  9199. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  9200. for the compilation of \LangDyn{}.
  9201. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9202. \chapter{Loops and Assignment}
  9203. \label{ch:loop}
  9204. % TODO: define R'_8
  9205. % TODO: multi-graph
  9206. In this chapter we study two features that are the hallmarks of
  9207. imperative programming languages: loops and assignments to local
  9208. variables. The following example demonstrates these new features by
  9209. computing the sum of the first five positive integers.
  9210. % similar to loop_test_1.rkt
  9211. \begin{lstlisting}
  9212. (let ([sum 0])
  9213. (let ([i 5])
  9214. (begin
  9215. (while (> i 0)
  9216. (begin
  9217. (set! sum (+ sum i))
  9218. (set! i (- i 1))))
  9219. sum)))
  9220. \end{lstlisting}
  9221. The \code{while} loop consists of a condition and a body.
  9222. %
  9223. The \code{set!} consists of a variable and a right-hand-side expression.
  9224. %
  9225. The primary purpose of both the \code{while} loop and \code{set!} is
  9226. to cause side effects, so it is convenient to also include in a
  9227. language feature for sequencing side effects: the \code{begin}
  9228. expression. It consists of one or more subexpressions that are
  9229. evaluated left-to-right.
  9230. \section{The \LangLoop{} Language}
  9231. \begin{figure}[tp]
  9232. \centering
  9233. \fbox{
  9234. \begin{minipage}{0.96\textwidth}
  9235. \small
  9236. \[
  9237. \begin{array}{lcl}
  9238. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  9239. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  9240. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  9241. &\mid& \gray{\key{\#t} \mid \key{\#f}
  9242. \mid (\key{and}\;\Exp\;\Exp)
  9243. \mid (\key{or}\;\Exp\;\Exp)
  9244. \mid (\key{not}\;\Exp) } \\
  9245. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  9246. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  9247. (\key{vector-ref}\;\Exp\;\Int)} \\
  9248. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  9249. \mid (\Exp \; \Exp\ldots) } \\
  9250. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP
  9251. \mid \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  9252. &\mid& \CSETBANG{\Var}{\Exp}
  9253. \mid \CBEGIN{\Exp\ldots}{\Exp}
  9254. \mid \CWHILE{\Exp}{\Exp} \\
  9255. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  9256. \LangLoop{} &::=& \gray{\Def\ldots \; \Exp}
  9257. \end{array}
  9258. \]
  9259. \end{minipage}
  9260. }
  9261. \caption{The concrete syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:r6-concrete-syntax}).}
  9262. \label{fig:r8-concrete-syntax}
  9263. \end{figure}
  9264. \begin{figure}[tp]
  9265. \centering
  9266. \fbox{
  9267. \begin{minipage}{0.96\textwidth}
  9268. \small
  9269. \[
  9270. \begin{array}{lcl}
  9271. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  9272. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  9273. &\mid& \gray{ \BOOL{\itm{bool}}
  9274. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  9275. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  9276. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  9277. &\mid& \gray{ \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp} }\\
  9278. &\mid& \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  9279. \mid \WHILE{\Exp}{\Exp} \\
  9280. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  9281. \LangLoop{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  9282. \end{array}
  9283. \]
  9284. \end{minipage}
  9285. }
  9286. \caption{The abstract syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:r6-syntax}).}
  9287. \label{fig:r8-syntax}
  9288. \end{figure}
  9289. The concrete syntax of \LangLoop{} is defined in
  9290. Figure~\ref{fig:r8-concrete-syntax} and its abstract syntax is defined
  9291. in Figure~\ref{fig:r8-syntax}.
  9292. %
  9293. The definitional interpreter for \LangLoop{} is shown in
  9294. Figure~\ref{fig:interp-Rwhile}. We add three new cases for \code{SetBang},
  9295. \code{WhileLoop}, and \code{Begin} and we make changes to the cases
  9296. for \code{Var}, \code{Let}, and \code{Apply} regarding variables. To
  9297. support assignment to variables and to make their lifetimes indefinite
  9298. (see the second example in Section~\ref{sec:assignment-scoping}), we
  9299. box the value that is bound to each variable (in \code{Let}) and
  9300. function parameter (in \code{Apply}). The case for \code{Var} unboxes
  9301. the value.
  9302. %
  9303. Now to discuss the new cases. For \code{SetBang}, we lookup the
  9304. variable in the environment to obtain a boxed value and then we change
  9305. it using \code{set-box!} to the result of evaluating the right-hand
  9306. side. The result value of a \code{SetBang} is \code{void}.
  9307. %
  9308. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  9309. if the result is true, 2) evaluate the body.
  9310. The result value of a \code{while} loop is also \code{void}.
  9311. %
  9312. Finally, the $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  9313. subexpressions \itm{es} for their effects and then evaluates
  9314. and returns the result from \itm{body}.
  9315. \begin{figure}[tbp]
  9316. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9317. (define interp-Rwhile-class
  9318. (class interp-Rany-class
  9319. (super-new)
  9320. (define/override ((interp-exp env) e)
  9321. (define recur (interp-exp env))
  9322. (match e
  9323. [(SetBang x rhs)
  9324. (set-box! (lookup x env) (recur rhs))]
  9325. [(WhileLoop cnd body)
  9326. (define (loop)
  9327. (cond [(recur cnd) (recur body) (loop)]
  9328. [else (void)]))
  9329. (loop)]
  9330. [(Begin es body)
  9331. (for ([e es]) (recur e))
  9332. (recur body)]
  9333. [else ((super interp-exp env) e)]))
  9334. ))
  9335. (define (interp-Rwhile p)
  9336. (send (new interp-Rwhile-class) interp-program p))
  9337. \end{lstlisting}
  9338. \caption{Interpreter for \LangLoop{}.}
  9339. \label{fig:interp-Rwhile}
  9340. \end{figure}
  9341. The type checker for \LangLoop{} is define in
  9342. Figure~\ref{fig:type-check-Rwhile}. For \code{SetBang}, the type of the
  9343. variable and the right-hand-side must agree. The result type is
  9344. \code{Void}. For the \code{WhileLoop}, the condition must be a
  9345. \code{Boolean}. The result type is also \code{Void}. For
  9346. \code{Begin}, the result type is the type of its last subexpression.
  9347. \begin{figure}[tbp]
  9348. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9349. (define type-check-Rwhile-class
  9350. (class type-check-Rany-class
  9351. (super-new)
  9352. (inherit check-type-equal?)
  9353. (define/override (type-check-exp env)
  9354. (lambda (e)
  9355. (define recur (type-check-exp env))
  9356. (match e
  9357. [(SetBang x rhs)
  9358. (define-values (rhs^ rhsT) (recur rhs))
  9359. (define varT (dict-ref env x))
  9360. (check-type-equal? rhsT varT e)
  9361. (values (SetBang x rhs^) 'Void)]
  9362. [(WhileLoop cnd body)
  9363. (define-values (cnd^ Tc) (recur cnd))
  9364. (check-type-equal? Tc 'Boolean e)
  9365. (define-values (body^ Tbody) ((type-check-exp env) body))
  9366. (values (WhileLoop cnd^ body^) 'Void)]
  9367. [(Begin es body)
  9368. (define-values (es^ ts)
  9369. (for/lists (l1 l2) ([e es]) (recur e)))
  9370. (define-values (body^ Tbody) (recur body))
  9371. (values (Begin es^ body^) Tbody)]
  9372. [else ((super type-check-exp env) e)])))
  9373. ))
  9374. (define (type-check-Rwhile p)
  9375. (send (new type-check-Rwhile-class) type-check-program p))
  9376. \end{lstlisting}
  9377. \caption{Type checking \key{SetBang}, \key{WhileLoop},
  9378. and \code{Begin} in \LangLoop{}.}
  9379. \label{fig:type-check-Rwhile}
  9380. \end{figure}
  9381. At first glance, the translation of these language features to x86
  9382. seems straightforward because the \LangCFun{} intermediate language already
  9383. supports all of the ingredients that we need: assignment, \code{goto},
  9384. conditional branching, and sequencing. However, there are two
  9385. complications that arise which we discuss in the next two
  9386. sections. After that we introduce one new compiler pass and the
  9387. changes necessary to the existing passes.
  9388. \section{Assignment and Lexically Scoped Functions}
  9389. \label{sec:assignment-scoping}
  9390. The addition of assignment raises a problem with our approach to
  9391. implementing lexically-scoped functions. Consider the following
  9392. example in which function \code{f} has a free variable \code{x} that
  9393. is changed after \code{f} is created but before the call to \code{f}.
  9394. % loop_test_11.rkt
  9395. \begin{lstlisting}
  9396. (let ([x 0])
  9397. (let ([y 0])
  9398. (let ([z 20])
  9399. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  9400. (begin
  9401. (set! x 10)
  9402. (set! y 12)
  9403. (f y))))))
  9404. \end{lstlisting}
  9405. The correct output for this example is \code{42} because the call to
  9406. \code{f} is required to use the current value of \code{x} (which is
  9407. \code{10}). Unfortunately, the closure conversion pass
  9408. (Section~\ref{sec:closure-conversion}) generates code for the
  9409. \code{lambda} that copies the old value of \code{x} into a
  9410. closure. Thus, if we naively add support for assignment to our current
  9411. compiler, the output of this program would be \code{32}.
  9412. A first attempt at solving this problem would be to save a pointer to
  9413. \code{x} in the closure and change the occurrences of \code{x} inside
  9414. the lambda to dereference the pointer. Of course, this would require
  9415. assigning \code{x} to the stack and not to a register. However, the
  9416. problem goes a bit deeper. Consider the following example in which we
  9417. create a counter abstraction by creating a pair of functions that
  9418. share the free variable \code{x}.
  9419. % similar to loop_test_10.rkt
  9420. \begin{lstlisting}
  9421. (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  9422. (vector
  9423. (lambda: () : Integer x)
  9424. (lambda: () : Void (set! x (+ 1 x)))))
  9425. (let ([counter (f 0)])
  9426. (let ([get (vector-ref counter 0)])
  9427. (let ([inc (vector-ref counter 1)])
  9428. (begin
  9429. (inc)
  9430. (get)))))
  9431. \end{lstlisting}
  9432. In this example, the lifetime of \code{x} extends beyond the lifetime
  9433. of the call to \code{f}. Thus, if we were to store \code{x} on the
  9434. stack frame for the call to \code{f}, it would be gone by the time we
  9435. call \code{inc} and \code{get}, leaving us with dangling pointers for
  9436. \code{x}. This example demonstrates that when a variable occurs free
  9437. inside a \code{lambda}, its lifetime becomes indefinite. Thus, the
  9438. value of the variable needs to live on the heap. The verb ``box'' is
  9439. often used for allocating a single value on the heap, producing a
  9440. pointer, and ``unbox'' for dereferencing the pointer.
  9441. We recommend solving these problems by ``boxing'' the local variables
  9442. that are in the intersection of 1) variables that appear on the
  9443. left-hand-side of a \code{set!} and 2) variables that occur free
  9444. inside a \code{lambda}. We shall introduce a new pass named
  9445. \code{convert-assignments} in Section~\ref{sec:convert-assignments} to
  9446. perform this translation. But before diving into the compiler passes,
  9447. we one more problem to discuss.
  9448. \section{Cyclic Control Flow and Dataflow Analysis}
  9449. \label{sec:dataflow-analysis}
  9450. Up until this point the control-flow graphs generated in
  9451. \code{explicate-control} were guaranteed to be acyclic. However, each
  9452. \code{while} loop introduces a cycle in the control-flow graph.
  9453. But does that matter?
  9454. %
  9455. Indeed it does. Recall that for register allocation, the compiler
  9456. performs liveness analysis to determine which variables can share the
  9457. same register. In Section~\ref{sec:liveness-analysis-Rif} we analyze
  9458. the control-flow graph in reverse topological order, but topological
  9459. order is only well-defined for acyclic graphs.
  9460. Let us return to the example of computing the sum of the first five
  9461. positive integers. Here is the program after instruction selection but
  9462. before register allocation.
  9463. \begin{center}
  9464. \begin{minipage}{0.45\textwidth}
  9465. \begin{lstlisting}
  9466. (define (main) : Integer
  9467. mainstart:
  9468. movq $0, sum1
  9469. movq $5, i2
  9470. jmp block5
  9471. block5:
  9472. movq i2, tmp3
  9473. cmpq tmp3, $0
  9474. jl block7
  9475. jmp block8
  9476. \end{lstlisting}
  9477. \end{minipage}
  9478. \begin{minipage}{0.45\textwidth}
  9479. \begin{lstlisting}
  9480. block7:
  9481. addq i2, sum1
  9482. movq $1, tmp4
  9483. negq tmp4
  9484. addq tmp4, i2
  9485. jmp block5
  9486. block8:
  9487. movq $27, %rax
  9488. addq sum1, %rax
  9489. jmp mainconclusion
  9490. )
  9491. \end{lstlisting}
  9492. \end{minipage}
  9493. \end{center}
  9494. Recall that liveness analysis works backwards, starting at the end
  9495. of each function. For this example we could start with \code{block8}
  9496. because we know what is live at the beginning of the conclusion,
  9497. just \code{rax} and \code{rsp}. So the live-before set
  9498. for \code{block8} is $\{\ttm{rsp},\ttm{sum1}\}$.
  9499. %
  9500. Next we might try to analyze \code{block5} or \code{block7}, but
  9501. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9502. we are stuck.
  9503. The way out of this impasse comes from the realization that one can
  9504. perform liveness analysis starting with an empty live-after set to
  9505. compute an under-approximation of the live-before set. By
  9506. \emph{under-approximation}, we mean that the set only contains
  9507. variables that are really live, but it may be missing some. Next, the
  9508. under-approximations for each block can be improved by 1) updating the
  9509. live-after set for each block using the approximate live-before sets
  9510. from the other blocks and 2) perform liveness analysis again on each
  9511. block. In fact, by iterating this process, the under-approximations
  9512. eventually become the correct solutions!
  9513. %
  9514. This approach of iteratively analyzing a control-flow graph is
  9515. applicable to many static analysis problems and goes by the name
  9516. \emph{dataflow analysis}\index{dataflow analysis}. It was invented by
  9517. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  9518. Washington.
  9519. Let us apply this approach to the above example. We use the empty set
  9520. for the initial live-before set for each block. Let $m_0$ be the
  9521. following mapping from label names to sets of locations (variables and
  9522. registers).
  9523. \begin{center}
  9524. \begin{lstlisting}
  9525. mainstart: {}
  9526. block5: {}
  9527. block7: {}
  9528. block8: {}
  9529. \end{lstlisting}
  9530. \end{center}
  9531. Using the above live-before approximations, we determine the
  9532. live-after for each block and then apply liveness analysis to each
  9533. block. This produces our next approximation $m_1$ of the live-before
  9534. sets.
  9535. \begin{center}
  9536. \begin{lstlisting}
  9537. mainstart: {}
  9538. block5: {i2}
  9539. block7: {i2, sum1}
  9540. block8: {rsp, sum1}
  9541. \end{lstlisting}
  9542. \end{center}
  9543. For the second round, the live-after for \code{mainstart} is the
  9544. current live-before for \code{block5}, which is \code{\{i2\}}. So the
  9545. liveness analysis for \code{mainstart} computes the empty set. The
  9546. live-after for \code{block5} is the union of the live-before sets for
  9547. \code{block7} and \code{block8}, which is \code{\{i2 , rsp, sum1\}}.
  9548. So the liveness analysis for \code{block5} computes \code{\{i2 , rsp,
  9549. sum1\}}. The live-after for \code{block7} is the live-before for
  9550. \code{block5} (from the previous iteration), which is \code{\{i2\}}.
  9551. So the liveness analysis for \code{block7} remains \code{\{i2,
  9552. sum1\}}. Together these yield the following approximation $m_2$ of
  9553. the live-before sets.
  9554. \begin{center}
  9555. \begin{lstlisting}
  9556. mainstart: {}
  9557. block5: {i2, rsp, sum1}
  9558. block7: {i2, sum1}
  9559. block8: {rsp, sum1}
  9560. \end{lstlisting}
  9561. \end{center}
  9562. In the preceding iteration, only \code{block5} changed, so we can
  9563. limit our attention to \code{mainstart} and \code{block7}, the two
  9564. blocks that jump to \code{block5}. As a result, the live-before sets
  9565. for \code{mainstart} and \code{block7} are updated to include
  9566. \code{rsp}, yielding the following approximation $m_3$.
  9567. \begin{center}
  9568. \begin{lstlisting}
  9569. mainstart: {rsp}
  9570. block5: {i2, rsp, sum1}
  9571. block7: {i2, rsp, sum1}
  9572. block8: {rsp, sum1}
  9573. \end{lstlisting}
  9574. \end{center}
  9575. Because \code{block7} changed, we analyze \code{block5} once more, but
  9576. its live-before set remains \code{\{ i2, rsp, sum1 \}}. At this point
  9577. our approximations have converged, so $m_3$ is the solution.
  9578. This iteration process is guaranteed to converge to a solution by the
  9579. Kleene Fixed-Point Theorem, a general theorem about functions on
  9580. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9581. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9582. elements, a least element $\bot$ (pronounced bottom), and a join
  9583. operator $\sqcup$.\index{lattice}\index{bottom}\index{partial
  9584. ordering}\index{join}\footnote{Technically speaking, we will be
  9585. working with join semi-lattices.} When two elements are ordered $m_i
  9586. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  9587. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  9588. approximation than $m_i$. The bottom element $\bot$ represents the
  9589. complete lack of information, i.e., the worst approximation. The join
  9590. operator takes two lattice elements and combines their information,
  9591. i.e., it produces the least upper bound of the two.\index{least upper
  9592. bound}
  9593. A dataflow analysis typically involves two lattices: one lattice to
  9594. represent abstract states and another lattice that aggregates the
  9595. abstract states of all the blocks in the control-flow graph. For
  9596. liveness analysis, an abstract state is a set of locations. We form
  9597. the lattice $L$ by taking its elements to be sets of locations, the
  9598. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9599. set, and the join operator to be set union.
  9600. %
  9601. We form a second lattice $M$ by taking its elements to be mappings
  9602. from the block labels to sets of locations (elements of $L$). We
  9603. order the mappings point-wise, using the ordering of $L$. So given any
  9604. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9605. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9606. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9607. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  9608. We can think of one iteration of liveness analysis as being a function
  9609. $f$ on the lattice $M$. It takes a mapping as input and computes a new
  9610. mapping.
  9611. \[
  9612. f(m_i) = m_{i+1}
  9613. \]
  9614. Next let us think for a moment about what a final solution $m_s$
  9615. should look like. If we perform liveness analysis using the solution
  9616. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9617. solution should be a \emph{fixed point} of the function $f$.\index{fixed point}
  9618. \[
  9619. f(m_s) = m_s
  9620. \]
  9621. Furthermore, the solution should only include locations that are
  9622. forced to be there by performing liveness analysis on the program, so
  9623. the solution should be the \emph{least} fixed point.\index{least fixed point}
  9624. The Kleene Fixed-Point Theorem states that if a function $f$ is
  9625. monotone (better inputs produce better outputs), then the least fixed
  9626. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9627. chain} obtained by starting at $\bot$ and iterating $f$ as
  9628. follows.\index{Kleene Fixed-Point Theorem}
  9629. \[
  9630. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9631. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9632. \]
  9633. When a lattice contains only finitely-long ascending chains, then
  9634. every Kleene chain tops out at some fixed point after a number of
  9635. iterations of $f$. So that fixed point is also a least upper
  9636. bound of the chain.
  9637. \[
  9638. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9639. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9640. \]
  9641. The liveness analysis is indeed a monotone function and the lattice
  9642. $M$ only has finitely-long ascending chains because there are only a
  9643. finite number of variables and blocks in the program. Thus we are
  9644. guaranteed that iteratively applying liveness analysis to all blocks
  9645. in the program will eventually produce the least fixed point solution.
  9646. Next let us consider dataflow analysis in general and discuss the
  9647. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  9648. %
  9649. The algorithm has four parameters: the control-flow graph \code{G}, a
  9650. function \code{transfer} that applies the analysis to one block, the
  9651. \code{bottom} and \code{join} operator for the lattice of abstract
  9652. states. The algorithm begins by creating the bottom mapping,
  9653. represented by a hash table. It then pushes all of the nodes in the
  9654. control-flow graph onto the work list (a queue). The algorithm repeats
  9655. the \code{while} loop as long as there are items in the work list. In
  9656. each iteration, a node is popped from the work list and processed. The
  9657. \code{input} for the node is computed by taking the join of the
  9658. abstract states of all the predecessor nodes. The \code{transfer}
  9659. function is then applied to obtain the \code{output} abstract
  9660. state. If the output differs from the previous state for this block,
  9661. the mapping for this block is updated and its successor nodes are
  9662. pushed onto the work list.
  9663. \begin{figure}[tb]
  9664. \begin{lstlisting}
  9665. (define (analyze-dataflow G transfer bottom join)
  9666. (define mapping (make-hash))
  9667. (for ([v (in-vertices G)])
  9668. (dict-set! mapping v bottom))
  9669. (define worklist (make-queue))
  9670. (for ([v (in-vertices G)])
  9671. (enqueue! worklist v))
  9672. (define trans-G (transpose G))
  9673. (while (not (queue-empty? worklist))
  9674. (define node (dequeue! worklist))
  9675. (define input (for/fold ([state bottom])
  9676. ([pred (in-neighbors trans-G node)])
  9677. (join state (dict-ref mapping pred))))
  9678. (define output (transfer node input))
  9679. (cond [(not (equal? output (dict-ref mapping node)))
  9680. (dict-set! mapping node output)
  9681. (for ([v (in-neighbors G node)])
  9682. (enqueue! worklist v))]))
  9683. mapping)
  9684. \end{lstlisting}
  9685. \caption{Generic work list algorithm for dataflow analysis}
  9686. \label{fig:generic-dataflow}
  9687. \end{figure}
  9688. Having discussed the two complications that arise from adding support
  9689. for assignment and loops, we turn to discussing the one new compiler
  9690. pass and the significant changes to existing passes.
  9691. \section{Convert Assignments}
  9692. \label{sec:convert-assignments}
  9693. Recall that in Section~\ref{sec:assignment-scoping} we learned that
  9694. the combination of assignments and lexically-scoped functions requires
  9695. that we box those variables that are both assigned-to and that appear
  9696. free inside a \code{lambda}. The purpose of the
  9697. \code{convert-assignments} pass is to carry out that transformation.
  9698. We recommend placing this pass after \code{uniquify} but before
  9699. \code{reveal-functions}.
  9700. Consider again the first example from
  9701. Section~\ref{sec:assignment-scoping}:
  9702. \begin{lstlisting}
  9703. (let ([x 0])
  9704. (let ([y 0])
  9705. (let ([z 20])
  9706. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  9707. (begin
  9708. (set! x 10)
  9709. (set! y 12)
  9710. (f y))))))
  9711. \end{lstlisting}
  9712. The variables \code{x} and \code{y} are assigned-to. The variables
  9713. \code{x} and \code{z} occur free inside the \code{lambda}. Thus,
  9714. variable \code{x} needs to be boxed but not \code{y} and \code{z}.
  9715. The boxing of \code{x} consists of three transformations: initialize
  9716. \code{x} with a vector, replace reads from \code{x} with
  9717. \code{vector-ref}'s, and replace each \code{set!} on \code{x} with a
  9718. \code{vector-set!}. The output of \code{convert-assignments} for this
  9719. example is as follows.
  9720. \begin{lstlisting}
  9721. (define (main) : Integer
  9722. (let ([x0 (vector 0)])
  9723. (let ([y1 0])
  9724. (let ([z2 20])
  9725. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  9726. (+ a3 (+ (vector-ref x0 0) z2)))])
  9727. (begin
  9728. (vector-set! x0 0 10)
  9729. (set! y1 12)
  9730. (f4 y1)))))))
  9731. \end{lstlisting}
  9732. \paragraph{Assigned \& Free}
  9733. We recommend defining an auxiliary function named
  9734. \code{assigned\&free} that takes an expression and simultaneously
  9735. computes 1) a set of assigned variables $A$, 2) a set $F$ of variables
  9736. that occur free within lambda's, and 3) a new version of the
  9737. expression that records which bound variables occurred in the
  9738. intersection of $A$ and $F$. You can use the struct
  9739. \code{AssignedFree} to do this. Consider the case for
  9740. $\LET{x}{\itm{rhs}}{\itm{body}}$. Suppose the the recursive call on
  9741. $\itm{rhs}$ produces $\itm{rhs}'$, $A_r$, and $F_r$ and the recursive
  9742. call on the $\itm{body}$ produces $\itm{body}'$, $A_b$, and $F_b$. If
  9743. $x$ is in $A_b\cap F_b$, then transforms the \code{Let} as follows.
  9744. \begin{lstlisting}
  9745. (Let |$x$| |$rhs$| |$body$|)
  9746. |$\Rightarrow$|
  9747. (Let (AssignedFree |$x$|) |$rhs'$| |$body'$|)
  9748. \end{lstlisting}
  9749. If $x$ is not in $A_b\cap F_b$ then omit the use of \code{AssignedFree}.
  9750. The set of assigned variables for this \code{Let} is
  9751. $A_r \cup (A_b - \{x\})$
  9752. and the set of variables free in lambda's is
  9753. $F_r \cup (F_b - \{x\})$.
  9754. The case for $\SETBANG{x}{\itm{rhs}}$ is straightforward but
  9755. important. Recursively process \itm{rhs} to obtain \itm{rhs'}, $A_r$,
  9756. and $F_r$. The result is $\SETBANG{x}{\itm{rhs'}}$, $\{x\} \cup A_r$,
  9757. and $F_r$.
  9758. The case for $\LAMBDA{\itm{params}}{T}{\itm{body}}$ is a bit more
  9759. involved. Let \itm{body'}, $A_b$, and $F_b$ be the result of
  9760. recursively processing \itm{body}. Wrap each of parameter that occurs
  9761. in $A_b \cap F_b$ with \code{AssignedFree} to produce \itm{params'}.
  9762. Let $P$ be the set of parameter names in \itm{params}. The result is
  9763. $\LAMBDA{\itm{params'}}{T}{\itm{body'}}$, $A_b - P$, and $(F_b \cup
  9764. \mathrm{FV}(\itm{body})) - P$, where $\mathrm{FV}$ computes the free
  9765. variables of an expression (see Chapter~\ref{ch:lambdas}).
  9766. \paragraph{Convert Assignments}
  9767. Next we discuss the \code{convert-assignment} pass with its auxiliary
  9768. functions for expressions and definitions. The function for
  9769. expressions, \code{cnvt-assign-exp}, should take an expression and a
  9770. set of assigned-and-free variables (obtained from the result of
  9771. \code{assigned\&free}. In the case for $\VAR{x}$, if $x$ is
  9772. assigned-and-free, then unbox it by translating $\VAR{x}$ to a
  9773. \code{vector-ref}.
  9774. \begin{lstlisting}
  9775. (Var |$x$|)
  9776. |$\Rightarrow$|
  9777. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  9778. \end{lstlisting}
  9779. %
  9780. In the case for $\LET{\LP\code{AssignedFree}\,
  9781. x\RP}{\itm{rhs}}{\itm{body}}$, recursively process \itm{rhs} to
  9782. obtain \itm{rhs'}. Next, recursively process \itm{body} to obtain
  9783. \itm{body'} but with $x$ added to the set of assigned-and-free
  9784. variables. Translate the let-expression as follows to bind $x$ to a
  9785. boxed value.
  9786. \begin{lstlisting}
  9787. (Let (AssignedFree |$x$|) |$rhs$| |$body$|)
  9788. |$\Rightarrow$|
  9789. (Let |$x$| (Prim 'vector (list |$rhs'$|)) |$body'$|)
  9790. \end{lstlisting}
  9791. %
  9792. In the case for $\SETBANG{x}{\itm{rhs}}$, recursively process
  9793. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in the assigned-and-free
  9794. variables, translate the \code{set!} into a \code{vector-set!}
  9795. as follows.
  9796. \begin{lstlisting}
  9797. (SetBang |$x$| |$\itm{rhs}$|)
  9798. |$\Rightarrow$|
  9799. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  9800. \end{lstlisting}
  9801. %
  9802. The case for \code{Lambda} is non-trivial, but it is similar to the
  9803. case for function definitions, which we discuss next.
  9804. The auxiliary function for definitions, \code{cnvt-assign-def},
  9805. applies assignment conversion to function definitions.
  9806. We translate a function definition as follows.
  9807. \begin{lstlisting}
  9808. (Def |$f$| |$\itm{params}$| |$T$| |$\itm{info}$| |$\itm{body_1}$|)
  9809. |$\Rightarrow$|
  9810. (Def |$f$| |$\itm{params'}$| |$T$| |$\itm{info}$| |$\itm{body_4}$|)
  9811. \end{lstlisting}
  9812. So it remains to explain \itm{params'} and $\itm{body}_4$.
  9813. Let \itm{body_2}, $A_b$, and $F_b$ be the result of
  9814. \code{assigned\&free} on $\itm{body_1}$.
  9815. Let $P$ be the parameter names in \itm{params}.
  9816. We then apply \code{cnvt-assign-exp} to $\itm{body_2}$ to
  9817. obtain \itm{body_3}, passing $A_b \cap F_b \cap P$
  9818. as the set of assigned-and-free variables.
  9819. Finally, we obtain \itm{body_4} by wrapping \itm{body_3}
  9820. in a sequence of let-expressions that box the parameters
  9821. that are in $A_b \cap F_b$.
  9822. %
  9823. Regarding \itm{params'}, change the names of the parameters that are
  9824. in $A_b \cap F_b$ to maintain uniqueness (and so the let-bound
  9825. variables can retain the original names). Recall the second example in
  9826. Section~\ref{sec:assignment-scoping} involving a counter
  9827. abstraction. The following is the output of assignment version for
  9828. function \code{f}.
  9829. \begin{lstlisting}
  9830. (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  9831. (vector
  9832. (lambda: () : Integer x1)
  9833. (lambda: () : Void (set! x1 (+ 1 x1)))))
  9834. |$\Rightarrow$|
  9835. (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  9836. (let ([x1 (vector param_x1)])
  9837. (vector (lambda: () : Integer (vector-ref x1 0))
  9838. (lambda: () : Void
  9839. (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  9840. \end{lstlisting}
  9841. \section{Remove Complex Operands}
  9842. \label{sec:rco-loop}
  9843. The three new language forms, \code{while}, \code{set!}, and
  9844. \code{begin} are all complex expressions and their subexpressions are
  9845. allowed to be complex. Figure~\ref{fig:Rfun-anf-syntax} defines the
  9846. output language \LangFunANF{} of this pass.
  9847. \begin{figure}[tp]
  9848. \centering
  9849. \fbox{
  9850. \begin{minipage}{0.96\textwidth}
  9851. \small
  9852. \[
  9853. \begin{array}{rcl}
  9854. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}}
  9855. \mid \VOID{} } \\
  9856. \Exp &::=& \ldots \mid \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  9857. &\mid& \WHILE{\Exp}{\Exp} \mid \SETBANG{\Var}{\Exp}
  9858. \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  9859. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  9860. R^{\dagger}_8 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  9861. \end{array}
  9862. \]
  9863. \end{minipage}
  9864. }
  9865. \caption{\LangLoopANF{} is \LangLoop{} in administrative normal form (ANF).}
  9866. \label{fig:r8-anf-syntax}
  9867. \end{figure}
  9868. As usual, when a complex expression appears in a grammar position that
  9869. needs to be atomic, such as the argument of a primitive operator, we
  9870. must introduce a temporary variable and bind it to the complex
  9871. expression. This approach applies, unchanged, to handle the new
  9872. language forms. For example, in the following code there are two
  9873. \code{begin} expressions appearing as arguments to \code{+}. The
  9874. output of \code{rco-exp} is shown below, in which the \code{begin}
  9875. expressions have been bound to temporary variables. Recall that
  9876. \code{let} expressions in \LangLoopANF{} are allowed to have
  9877. arbitrary expressions in their right-hand-side expression, so it is
  9878. fine to place \code{begin} there.
  9879. \begin{lstlisting}
  9880. (let ([x0 10])
  9881. (let ([y1 0])
  9882. (+ (+ (begin (set! y1 (read)) x0)
  9883. (begin (set! x0 (read)) y1))
  9884. x0)))
  9885. |$\Rightarrow$|
  9886. (let ([x0 10])
  9887. (let ([y1 0])
  9888. (let ([tmp2 (begin (set! y1 (read)) x0)])
  9889. (let ([tmp3 (begin (set! x0 (read)) y1)])
  9890. (let ([tmp4 (+ tmp2 tmp3)])
  9891. (+ tmp4 x0))))))
  9892. \end{lstlisting}
  9893. \section{Explicate Control and \LangCLoop{}}
  9894. \label{sec:explicate-loop}
  9895. Recall that in the \code{explicate-control} pass we define one helper
  9896. function for each kind of position in the program. For the \LangVar{}
  9897. language of integers and variables we needed kinds of positions:
  9898. assignment and tail. The \code{if} expressions of \LangIf{} introduced
  9899. predicate positions. For \LangLoop{}, the \code{begin} expression introduces
  9900. yet another kind of position: effect position. Except for the last
  9901. subexpression, the subexpressions inside a \code{begin} are evaluated
  9902. only for their effect. Their result values are discarded. We can
  9903. generate better code by taking this fact into account.
  9904. The output language of \code{explicate-control} is \LangCLoop{}
  9905. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  9906. \LangCLam{}. The only syntactic difference is that \code{Call},
  9907. \code{vector-set!}, and \code{read} may also appear as statements.
  9908. The most significant difference between \LangCLam{} and \LangCLoop{}
  9909. is that the control-flow graphs of the later may contain cycles.
  9910. \begin{figure}[tp]
  9911. \fbox{
  9912. \begin{minipage}{0.96\textwidth}
  9913. \small
  9914. \[
  9915. \begin{array}{lcl}
  9916. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  9917. \mid \LP\key{Collect} \,\itm{int}\RP } \\
  9918. &\mid& \CALL{\Atm}{\LP\Atm\ldots\RP} \mid \READ{}\\
  9919. &\mid& \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP \\
  9920. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  9921. \LangCLoop{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  9922. \end{array}
  9923. \]
  9924. \end{minipage}
  9925. }
  9926. \caption{The abstract syntax of \LangCLoop{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  9927. \label{fig:c7-syntax}
  9928. \end{figure}
  9929. The new auxiliary function \code{explicate-effect} takes an expression
  9930. (in an effect position) and a promise of a continuation block. The
  9931. function returns a promise for a $\Tail$ that includes the generated
  9932. code for the input expression followed by the continuation block. If
  9933. the expression is obviously pure, that is, never causes side effects,
  9934. then the expression can be removed, so the result is just the
  9935. continuation block.
  9936. %
  9937. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  9938. case. First, you will need a fresh label $\itm{loop}$ for the top of
  9939. the loop. Recursively process the \itm{body} (in effect position)
  9940. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  9941. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  9942. \itm{body'} as the then-branch and the continuation block as the
  9943. else-branch. The result should be added to the control-flow graph with
  9944. the label \itm{loop}. The result for the whole \code{while} loop is a
  9945. \code{goto} to the \itm{loop} label. Note that the loop should only be
  9946. added to the control-flow graph if the loop is indeed used, which can
  9947. be accomplished using \code{delay}.
  9948. The auxiliary functions for tail, assignment, and predicate positions
  9949. need to be updated. The three new language forms, \code{while},
  9950. \code{set!}, and \code{begin}, can appear in assignment and tail
  9951. positions. Only \code{begin} may appear in predicate positions; the
  9952. other two have result type \code{Void}.
  9953. \section{Select Instructions}
  9954. \label{sec:select-instructions-loop}
  9955. Only three small additions are needed in the
  9956. \code{select-instructions} pass to handle the changes to \LangCLoop{}. That
  9957. is, \code{Call}, \code{read}, and \code{vector-set!} may now appear as
  9958. stand-alone statements instead of only appearing on the right-hand
  9959. side of an assignment statement. The code generation is nearly
  9960. identical; just leave off the instruction for moving the result into
  9961. the left-hand side.
  9962. \section{Register Allocation}
  9963. \label{sec:register-allocation-loop}
  9964. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  9965. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  9966. which complicates the liveness analysis needed for register
  9967. allocation.
  9968. \subsection{Liveness Analysis}
  9969. \label{sec:liveness-analysis-r8}
  9970. We recommend using the generic \code{analyze-dataflow} function that
  9971. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  9972. perform liveness analysis, replacing the code in
  9973. \code{uncover-live-CFG} that processed the basic blocks in topological
  9974. order (Section~\ref{sec:liveness-analysis-Rif}).
  9975. The \code{analyze-dataflow} function has four parameters.
  9976. \begin{enumerate}
  9977. \item The first parameter \code{G} should be a directed graph from the
  9978. \code{racket/graph} package (see the sidebar in
  9979. Section~\ref{sec:build-interference}) that represents the
  9980. control-flow graph.
  9981. \item The second parameter \code{transfer} is a function that applies
  9982. liveness analysis to a basic block. It takes two parameters: the
  9983. label for the block to analyze and the live-after set for that
  9984. block. The transfer function should return the live-before set for
  9985. the block. Also, as a side-effect, it should update the block's
  9986. $\itm{info}$ with the liveness information for each instruction. To
  9987. implement the \code{transfer} function, you should be able to reuse
  9988. the code you already have for analyzing basic blocks.
  9989. \item The third and fourth parameters of \code{analyze-dataflow} are
  9990. \code{bottom} and \code{join} for the lattice of abstract states,
  9991. i.e. sets of locations. The bottom of the lattice is the empty set
  9992. \code{(set)} and the join operator is \code{set-union}.
  9993. \end{enumerate}
  9994. \begin{figure}[p]
  9995. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9996. \node (Rfun) at (0,2) {\large \LangLoop{}};
  9997. \node (Rfun-2) at (3,2) {\large \LangLoop{}};
  9998. \node (Rfun-3) at (6,2) {\large \LangLoop{}};
  9999. \node (Rfun-4) at (9,2) {\large \LangLoopFunRef{}};
  10000. \node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  10001. \node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  10002. \node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  10003. \node (F1-4) at (3,0) {\large \LangLoopAlloc{}};
  10004. \node (F1-5) at (0,0) {\large \LangLoopAlloc{}};
  10005. \node (C3-2) at (3,-2) {\large \LangCLoop{}};
  10006. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  10007. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  10008. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  10009. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  10010. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  10011. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  10012. %% \path[->,bend left=15] (Rfun) edge [above] node
  10013. %% {\ttfamily\footnotesize type-check} (Rfun-2);
  10014. \path[->,bend left=15] (Rfun) edge [above] node
  10015. {\ttfamily\footnotesize shrink} (Rfun-2);
  10016. \path[->,bend left=15] (Rfun-2) edge [above] node
  10017. {\ttfamily\footnotesize uniquify} (Rfun-3);
  10018. \path[->,bend left=15] (Rfun-3) edge [above] node
  10019. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  10020. \path[->,bend left=15] (Rfun-4) edge [right] node
  10021. {\ttfamily\footnotesize convert-assignments} (F1-1);
  10022. \path[->,bend left=15] (F1-1) edge [below] node
  10023. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  10024. \path[->,bend right=15] (F1-2) edge [above] node
  10025. {\ttfamily\footnotesize limit-fun.} (F1-3);
  10026. \path[->,bend right=15] (F1-3) edge [above] node
  10027. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  10028. \path[->,bend right=15] (F1-4) edge [above] node
  10029. {\ttfamily\footnotesize remove-complex.} (F1-5);
  10030. \path[->,bend right=15] (F1-5) edge [right] node
  10031. {\ttfamily\footnotesize explicate-control} (C3-2);
  10032. \path[->,bend left=15] (C3-2) edge [left] node
  10033. {\ttfamily\footnotesize select-instr.} (x86-2);
  10034. \path[->,bend right=15] (x86-2) edge [left] node
  10035. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  10036. \path[->,bend right=15] (x86-2-1) edge [below] node
  10037. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  10038. \path[->,bend right=15] (x86-2-2) edge [left] node
  10039. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  10040. \path[->,bend left=15] (x86-3) edge [above] node
  10041. {\ttfamily\footnotesize patch-instr.} (x86-4);
  10042. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  10043. \end{tikzpicture}
  10044. \caption{Diagram of the passes for \LangLoop{} (loops and assignment).}
  10045. \label{fig:Rwhile-passes}
  10046. \end{figure}
  10047. Figure~\ref{fig:Rwhile-passes} provides an overview of all the passes needed
  10048. for the compilation of \LangLoop{}.
  10049. % TODO: challenge assignment
  10050. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10051. \chapter{Gradual Typing}
  10052. \label{ch:gradual-typing}
  10053. \index{gradual typing}
  10054. This chapter studies a language, \LangGrad{}, in which the programmer
  10055. can choose between static and dynamic type checking in different parts
  10056. of a program, thereby mixing the statically typed \LangLoop{} language
  10057. with the dynamically typed \LangDyn{}. There are several approaches to
  10058. mixing static and dynamic typing, including multi-language
  10059. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  10060. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  10061. we focus on \emph{gradual typing}\index{gradual typing}, in which the
  10062. programmer controls the amount of static versus dynamic checking by
  10063. adding or removing type annotations on parameters and
  10064. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  10065. %
  10066. The concrete syntax of \LangGrad{} is defined in
  10067. Figure~\ref{fig:r9-concrete-syntax} and its abstract syntax is defined
  10068. in Figure~\ref{fig:r9-syntax}. The main syntactic difference between
  10069. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  10070. non-terminals that make type annotations optional. The return types
  10071. are not optional in the abstract syntax; the parser fills in
  10072. \code{Any} when the return type is not specified in the concrete
  10073. syntax.
  10074. \begin{figure}[tp]
  10075. \centering
  10076. \fbox{
  10077. \begin{minipage}{0.96\textwidth}
  10078. \small
  10079. \[
  10080. \begin{array}{lcl}
  10081. \itm{param} &::=& \Var \mid \LS\Var \key{:} \Type\RS \\
  10082. \itm{ret} &::=& \epsilon \mid \key{:} \Type \\
  10083. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  10084. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  10085. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  10086. &\mid& \gray{\key{\#t} \mid \key{\#f}
  10087. \mid (\key{and}\;\Exp\;\Exp)
  10088. \mid (\key{or}\;\Exp\;\Exp)
  10089. \mid (\key{not}\;\Exp) } \\
  10090. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  10091. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  10092. (\key{vector-ref}\;\Exp\;\Int)} \\
  10093. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  10094. \mid (\Exp \; \Exp\ldots) } \\
  10095. &\mid& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  10096. \mid \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  10097. &\mid& \gray{ \CSETBANG{\Var}{\Exp}
  10098. \mid \CBEGIN{\Exp\ldots}{\Exp}
  10099. \mid \CWHILE{\Exp}{\Exp} } \\
  10100. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  10101. \LangGrad{} &::=& \gray{\Def\ldots \; \Exp}
  10102. \end{array}
  10103. \]
  10104. \end{minipage}
  10105. }
  10106. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:r8-concrete-syntax}).}
  10107. \label{fig:r9-concrete-syntax}
  10108. \end{figure}
  10109. \begin{figure}[tp]
  10110. \centering
  10111. \fbox{
  10112. \begin{minipage}{0.96\textwidth}
  10113. \small
  10114. \[
  10115. \begin{array}{lcl}
  10116. \itm{param} &::=& \Var \mid \LS\Var \key{:} \Type\RS \\
  10117. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  10118. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  10119. &\mid& \gray{ \BOOL{\itm{bool}}
  10120. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  10121. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  10122. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  10123. &\mid& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  10124. &\mid& \gray{ \SETBANG{\Var}{\Exp} \mid \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  10125. &\mid& \gray{ \WHILE{\Exp}{\Exp} } \\
  10126. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  10127. \LangGrad{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  10128. \end{array}
  10129. \]
  10130. \end{minipage}
  10131. }
  10132. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:r8-syntax}).}
  10133. \label{fig:r9-syntax}
  10134. \end{figure}
  10135. Both the type checker and the interpreter for \LangGrad{} require some
  10136. interesting changes to enable gradual typing, which we discuss in the
  10137. next two sections in the context of the \code{map-vec} example from
  10138. Chapter~\ref{ch:functions}. In Figure~\ref{fig:gradual-map-vec} we
  10139. revised the \code{map-vec} example, omitting the type annotations from
  10140. the \code{add1} function.
  10141. \begin{figure}[btp]
  10142. % gradual_test_9.rkt
  10143. \begin{lstlisting}
  10144. (define (map-vec [f : (Integer -> Integer)]
  10145. [v : (Vector Integer Integer)])
  10146. : (Vector Integer Integer)
  10147. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10148. (define (add1 x) (+ x 1))
  10149. (vector-ref (map-vec add1 (vector 0 41)) 1)
  10150. \end{lstlisting}
  10151. \caption{A partially-typed version of the \code{map-vec} example.}
  10152. \label{fig:gradual-map-vec}
  10153. \end{figure}
  10154. \section{Type Checking \LangGrad{}, Casts, and \LangCast{}}
  10155. \label{sec:gradual-type-check}
  10156. The type checker for \LangGrad{} uses the \code{Any} type for missing
  10157. parameter and return types. For example, the \code{x} parameter of
  10158. \code{add1} in Figure~\ref{fig:gradual-map-vec} is given the type
  10159. \code{Any} and the return type of \code{add1} is \code{Any}. Next
  10160. consider the \code{+} operator inside \code{add1}. It expects both
  10161. arguments to have type \code{Integer}, but its first argument \code{x}
  10162. has type \code{Any}. In a gradually typed language, such differences
  10163. are allowed so long as the types are \emph{consistent}, that is, they
  10164. are equal except in places where there is an \code{Any} type. The type
  10165. \code{Any} is consistent with every other type.
  10166. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  10167. \begin{figure}[tbp]
  10168. \begin{lstlisting}
  10169. (define/public (consistent? t1 t2)
  10170. (match* (t1 t2)
  10171. [('Integer 'Integer) #t]
  10172. [('Boolean 'Boolean) #t]
  10173. [('Void 'Void) #t]
  10174. [('Any t2) #t]
  10175. [(t1 'Any) #t]
  10176. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10177. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  10178. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10179. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  10180. (consistent? rt1 rt2))]
  10181. [(other wise) #f]))
  10182. \end{lstlisting}
  10183. \caption{The consistency predicate on types, a method in
  10184. \code{type-check-gradual-class}.}
  10185. \label{fig:consistent}
  10186. \end{figure}
  10187. Returning to the \code{map-vec} example of
  10188. Figure~\ref{fig:gradual-map-vec}, the \code{add1} function has type
  10189. \code{(Any -> Any)} but parameter \code{f} of \code{map-vec} has type
  10190. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  10191. because the two types are consistent. In particular, \code{->} is
  10192. equal to \code{->} and because \code{Any} is consistent with
  10193. \code{Integer}.
  10194. Next consider a program with an error, such as applying the
  10195. \code{map-vec} to a function that sometimes returns a Boolean, as
  10196. shown in Figure~\ref{fig:map-vec-maybe-add1}. The type checker for
  10197. \LangGrad{} accepts this program because the type of \code{maybe-add1} is
  10198. consistent with the type of parameter \code{f} of \code{map-vec}, that
  10199. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  10200. Integer)}. One might say that a gradual type checker is optimistic
  10201. in that it accepts programs that might execute without a runtime type
  10202. error.
  10203. %
  10204. Unfortunately, running this program with input \code{1} triggers an
  10205. error when the \code{maybe-add1} function returns \code{\#t}. \LangGrad{}
  10206. performs checking at runtime to ensure the integrity of the static
  10207. types, such as the \code{(Integer -> Integer)} annotation on parameter
  10208. \code{f} of \code{map-vec}. This runtime checking is carried out by a
  10209. new \code{Cast} form that is inserted by the type checker. Thus, the
  10210. output of the type checker is a program in the \LangCast{} language, which
  10211. adds \code{Cast} to \LangLoop{}, as shown in
  10212. Figure~\ref{fig:r9-prime-syntax}.
  10213. \begin{figure}[tp]
  10214. \centering
  10215. \fbox{
  10216. \begin{minipage}{0.96\textwidth}
  10217. \small
  10218. \[
  10219. \begin{array}{lcl}
  10220. \Exp &::=& \ldots \mid \CAST{\Exp}{\Type}{\Type} \\
  10221. \LangCast{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  10222. \end{array}
  10223. \]
  10224. \end{minipage}
  10225. }
  10226. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:r8-syntax}).}
  10227. \label{fig:r9-prime-syntax}
  10228. \end{figure}
  10229. \begin{figure}[tbp]
  10230. \begin{lstlisting}
  10231. (define (map-vec [f : (Integer -> Integer)]
  10232. [v : (Vector Integer Integer)])
  10233. : (Vector Integer Integer)
  10234. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10235. (define (add1 x) (+ x 1))
  10236. (define (true) #t)
  10237. (define (maybe-add1 x) (if (eq? 0 (read)) (add1 x) (true)))
  10238. (vector-ref (map-vec maybe-add1 (vector 0 41)) 0)
  10239. \end{lstlisting}
  10240. \caption{A variant of the \code{map-vec} example with an error.}
  10241. \label{fig:map-vec-maybe-add1}
  10242. \end{figure}
  10243. Figure~\ref{fig:map-vec-cast} shows the output of the type checker for
  10244. \code{map-vec} and \code{maybe-add1}. The idea is that \code{Cast} is
  10245. inserted every time the type checker sees two types that are
  10246. consistent but not equal. In the \code{add1} function, \code{x} is
  10247. cast to \code{Integer} and the result of the \code{+} is cast to
  10248. \code{Any}. In the call to \code{map-vec}, the \code{add1} argument
  10249. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  10250. \begin{figure}[btp]
  10251. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10252. (define (map-vec [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  10253. : (Vector Integer Integer)
  10254. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10255. (define (add1 [x : Any]) : Any
  10256. (cast (+ (cast x Any Integer) 1) Integer Any))
  10257. (define (true) : Any (cast #t Boolean Any))
  10258. (define (maybe-add1 [x : Any]) : Any
  10259. (if (eq? 0 (read)) (add1 x) (true)))
  10260. (vector-ref (map-vec (cast maybe-add1 (Any -> Any) (Integer -> Integer))
  10261. (vector 0 41)) 0)
  10262. \end{lstlisting}
  10263. \caption{Output of type checking \code{map-vec}
  10264. and \code{maybe-add1}.}
  10265. \label{fig:map-vec-cast}
  10266. \end{figure}
  10267. The type checker for \LangGrad{} is defined in
  10268. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  10269. and \ref{fig:type-check-Rgradual-3}.
  10270. \begin{figure}[tbp]
  10271. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10272. (define type-check-gradual-class
  10273. (class type-check-Rwhile-class
  10274. (super-new)
  10275. (inherit operator-types type-predicates)
  10276. (define/override (type-check-exp env)
  10277. (lambda (e)
  10278. (define recur (type-check-exp env))
  10279. (match e
  10280. [(Prim 'vector-length (list e1))
  10281. (define-values (e1^ t) (recur e1))
  10282. (match t
  10283. [`(Vector ,ts ...)
  10284. (values (Prim 'vector-length (list e1^)) 'Integer)]
  10285. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  10286. [(Prim 'vector-ref (list e1 e2))
  10287. (define-values (e1^ t1) (recur e1))
  10288. (define-values (e2^ t2) (recur e2))
  10289. (check-consistent? t2 'Integer e)
  10290. (match t1
  10291. [`(Vector ,ts ...)
  10292. (match e2^
  10293. [(Int i)
  10294. (unless (and (0 . <= . i) (i . < . (length ts)))
  10295. (error 'type-check "invalid index ~a in ~a" i e))
  10296. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10297. [else (define e1^^ (make-cast e1^ t1 'Any))
  10298. (define e2^^ (make-cast e2^ t2 'Integer))
  10299. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  10300. ['Any
  10301. (define e2^^ (make-cast e2^ t2 'Integer))
  10302. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  10303. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  10304. [(Prim 'vector-set! (list e1 e2 e3) )
  10305. (define-values (e1^ t1) (recur e1))
  10306. (define-values (e2^ t2) (recur e2))
  10307. (define-values (e3^ t3) (recur e3))
  10308. (check-consistent? t2 'Integer e)
  10309. (match t1
  10310. [`(Vector ,ts ...)
  10311. (match e2^
  10312. [(Int i)
  10313. (unless (and (0 . <= . i) (i . < . (length ts)))
  10314. (error 'type-check "invalid index ~a in ~a" i e))
  10315. (check-consistent? (list-ref ts i) t3 e)
  10316. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  10317. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  10318. [else
  10319. (define e1^^ (make-cast e1^ t1 'Any))
  10320. (define e2^^ (make-cast e2^ t2 'Integer))
  10321. (define e3^^ (make-cast e3^ t3 'Any))
  10322. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  10323. ['Any
  10324. (define e2^^ (make-cast e2^ t2 'Integer))
  10325. (define e3^^ (make-cast e3^ t3 'Any))
  10326. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  10327. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  10328. \end{lstlisting}
  10329. \caption{Type checker for the \LangGrad{} language, part 1.}
  10330. \label{fig:type-check-Rgradual-1}
  10331. \end{figure}
  10332. \begin{figure}[tbp]
  10333. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10334. [(Prim 'eq? (list e1 e2))
  10335. (define-values (e1^ t1) (recur e1))
  10336. (define-values (e2^ t2) (recur e2))
  10337. (check-consistent? t1 t2 e)
  10338. (define T (meet t1 t2))
  10339. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  10340. 'Boolean)]
  10341. [(Prim 'not (list e1))
  10342. (define-values (e1^ t1) (recur e1))
  10343. (match t1
  10344. ['Any
  10345. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  10346. (Bool #t) (Bool #f)))]
  10347. [else
  10348. (define-values (t-ret new-es^)
  10349. (type-check-op 'not (list t1) (list e1^) e))
  10350. (values (Prim 'not new-es^) t-ret)])]
  10351. [(Prim 'and (list e1 e2))
  10352. (recur (If e1 e2 (Bool #f)))]
  10353. [(Prim 'or (list e1 e2))
  10354. (define tmp (gensym 'tmp))
  10355. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  10356. [(Prim op es)
  10357. #:when (not (set-member? explicit-prim-ops op))
  10358. (define-values (new-es ts)
  10359. (for/lists (exprs types) ([e es])
  10360. (recur e)))
  10361. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  10362. (values (Prim op new-es^) t-ret)]
  10363. [(If e1 e2 e3)
  10364. (define-values (e1^ T1) (recur e1))
  10365. (define-values (e2^ T2) (recur e2))
  10366. (define-values (e3^ T3) (recur e3))
  10367. (check-consistent? T2 T3 e)
  10368. (match T1
  10369. ['Boolean
  10370. (define Tif (join T2 T3))
  10371. (values (If e1^ (make-cast e2^ T2 Tif)
  10372. (make-cast e3^ T3 Tif)) Tif)]
  10373. ['Any
  10374. (define Tif (meet T2 T3))
  10375. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  10376. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  10377. Tif)]
  10378. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  10379. [(HasType e1 T)
  10380. (define-values (e1^ T1) (recur e1))
  10381. (check-consistent? T1 T)
  10382. (values (make-cast e1^ T1 T) T)]
  10383. [(SetBang x e1)
  10384. (define-values (e1^ T1) (recur e1))
  10385. (define varT (dict-ref env x))
  10386. (check-consistent? T1 varT e)
  10387. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  10388. [(WhileLoop e1 e2)
  10389. (define-values (e1^ T1) (recur e1))
  10390. (check-consistent? T1 'Boolean e)
  10391. (define-values (e2^ T2) ((type-check-exp env) e2))
  10392. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  10393. \end{lstlisting}
  10394. \caption{Type checker for the \LangGrad{} language, part 2.}
  10395. \label{fig:type-check-Rgradual-2}
  10396. \end{figure}
  10397. \begin{figure}[tbp]
  10398. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10399. [(Apply e1 e2s)
  10400. (define-values (e1^ T1) (recur e1))
  10401. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  10402. (match T1
  10403. [`(,T1ps ... -> ,T1rt)
  10404. (for ([T2 T2s] [Tp T1ps])
  10405. (check-consistent? T2 Tp e))
  10406. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  10407. (make-cast e2 src tgt)))
  10408. (values (Apply e1^ e2s^^) T1rt)]
  10409. [`Any
  10410. (define e1^^ (make-cast e1^ 'Any
  10411. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  10412. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  10413. (make-cast e2 src 'Any)))
  10414. (values (Apply e1^^ e2s^^) 'Any)]
  10415. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  10416. [(Lambda params Tr e1)
  10417. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  10418. (match p
  10419. [`[,x : ,T] (values x T)]
  10420. [(? symbol? x) (values x 'Any)])))
  10421. (define-values (e1^ T1)
  10422. ((type-check-exp (append (map cons xs Ts) env)) e1))
  10423. (check-consistent? Tr T1 e)
  10424. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  10425. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  10426. [else ((super type-check-exp env) e)]
  10427. )))
  10428. \end{lstlisting}
  10429. \caption{Type checker for the \LangGrad{} language, part 3.}
  10430. \label{fig:type-check-Rgradual-3}
  10431. \end{figure}
  10432. \begin{figure}[tbp]
  10433. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10434. (define/public (join t1 t2)
  10435. (match* (t1 t2)
  10436. [('Integer 'Integer) 'Integer]
  10437. [('Boolean 'Boolean) 'Boolean]
  10438. [('Void 'Void) 'Void]
  10439. [('Any t2) t2]
  10440. [(t1 'Any) t1]
  10441. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10442. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  10443. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10444. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  10445. -> ,(join rt1 rt2))]))
  10446. (define/public (meet t1 t2)
  10447. (match* (t1 t2)
  10448. [('Integer 'Integer) 'Integer]
  10449. [('Boolean 'Boolean) 'Boolean]
  10450. [('Void 'Void) 'Void]
  10451. [('Any t2) 'Any]
  10452. [(t1 'Any) 'Any]
  10453. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10454. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  10455. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10456. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  10457. -> ,(meet rt1 rt2))]))
  10458. (define/public (make-cast e src tgt)
  10459. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  10460. (define/public (check-consistent? t1 t2 e)
  10461. (unless (consistent? t1 t2)
  10462. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  10463. (define/override (type-check-op op arg-types args e)
  10464. (match (dict-ref (operator-types) op)
  10465. [`(,param-types . ,return-type)
  10466. (for ([at arg-types] [pt param-types])
  10467. (check-consistent? at pt e))
  10468. (values return-type
  10469. (for/list ([e args] [s arg-types] [t param-types])
  10470. (make-cast e s t)))]
  10471. [else (error 'type-check-op "unrecognized ~a" op)]))
  10472. (define explicit-prim-ops
  10473. (set-union
  10474. (type-predicates)
  10475. (set 'procedure-arity 'eq?
  10476. 'vector 'vector-length 'vector-ref 'vector-set!
  10477. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  10478. (define/override (fun-def-type d)
  10479. (match d
  10480. [(Def f params rt info body)
  10481. (define ps
  10482. (for/list ([p params])
  10483. (match p
  10484. [`[,x : ,T] T]
  10485. [(? symbol?) 'Any]
  10486. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  10487. `(,@ps -> ,rt)]
  10488. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  10489. \end{lstlisting}
  10490. \caption{Auxiliary functions for type checking \LangGrad{}.}
  10491. \label{fig:type-check-Rgradual-aux}
  10492. \end{figure}
  10493. \clearpage
  10494. \section{Interpreting \LangCast{}}
  10495. \label{sec:interp-casts}
  10496. The runtime behavior of first-order casts is straightforward, that is,
  10497. casts involving simple types such as \code{Integer} and
  10498. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  10499. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  10500. puts the integer into a tagged value
  10501. (Figure~\ref{fig:interp-Rany}). Similarly, a cast from \code{Any} to
  10502. \code{Integer} is accomplished with the \code{Project} operator, that
  10503. is, by checking the value's tag and either retrieving the underlying
  10504. integer or signaling an error if it the tag is not the one for
  10505. integers (Figure~\ref{fig:apply-project}).
  10506. %
  10507. Things get more interesting for higher-order casts, that is, casts
  10508. involving function or vector types.
  10509. Consider the cast of the function \code{maybe-add1} from \code{(Any ->
  10510. Any)} to \code{(Integer -> Integer)}. When a function flows through
  10511. this cast at runtime, we can't know in general whether the function
  10512. will always return an integer.\footnote{Predicting the return value of
  10513. a function is equivalent to the halting problem, which is
  10514. undecidable.} The \LangCast{} interpreter therefore delays the checking
  10515. of the cast until the function is applied. This is accomplished by
  10516. wrapping \code{maybe-add1} in a new function that casts its parameter
  10517. from \code{Integer} to \code{Any}, applies \code{maybe-add1}, and then
  10518. casts the return value from \code{Any} to \code{Integer}.
  10519. Turning our attention to casts involving vector types, we consider the
  10520. example in Figure~\ref{fig:map-vec-bang} that defines a
  10521. partially-typed version of \code{map-vec} whose parameter \code{v} has
  10522. type \code{(Vector Any Any)} and that updates \code{v} in place
  10523. instead of returning a new vector. So we name this function
  10524. \code{map-vec!}. We apply \code{map-vec!} to a vector of integers, so
  10525. the type checker inserts a cast from \code{(Vector Integer Integer)}
  10526. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  10527. cast between vector types would be a build a new vector whose elements
  10528. are the result of casting each of the original elements to the
  10529. appropriate target type. However, this approach is only valid for
  10530. immutable vectors; and our vectors are mutable. In the example of
  10531. Figure~\ref{fig:map-vec-bang}, if the cast created a new vector, then
  10532. the updates inside of \code{map-vec!} would happen to the new vector
  10533. and not the original one.
  10534. \begin{figure}[tbp]
  10535. % gradual_test_11.rkt
  10536. \begin{lstlisting}
  10537. (define (map-vec! [f : (Any -> Any)]
  10538. [v : (Vector Any Any)]) : Void
  10539. (begin
  10540. (vector-set! v 0 (f (vector-ref v 0)))
  10541. (vector-set! v 1 (f (vector-ref v 1)))))
  10542. (define (add1 x) (+ x 1))
  10543. (let ([v (vector 0 41)])
  10544. (begin (map-vec! add1 v) (vector-ref v 1)))
  10545. \end{lstlisting}
  10546. \caption{An example involving casts on vectors.}
  10547. \label{fig:map-vec-bang}
  10548. \end{figure}
  10549. Instead the interpreter needs to create a new kind of value, a
  10550. \emph{vector proxy}, that intercepts every vector operation. On a
  10551. read, the proxy reads from the underlying vector and then applies a
  10552. cast to the resulting value. On a write, the proxy casts the argument
  10553. value and then performs the write to the underlying vector. For the
  10554. first \code{(vector-ref v 0)} in \code{map-vec!}, the proxy casts
  10555. \code{0} from \code{Integer} to \code{Any}. For the first
  10556. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  10557. to \code{Integer}.
  10558. The final category of cast that we need to consider are casts between
  10559. the \code{Any} type and either a function or a vector
  10560. type. Figure~\ref{fig:map-vec-any} shows a variant of \code{map-vec!}
  10561. in which parameter \code{v} does not have a type annotation, so it is
  10562. given type \code{Any}. In the call to \code{map-vec!}, the vector has
  10563. type \code{(Vector Integer Integer)} so the type checker inserts a
  10564. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  10565. thought is to use \code{Inject}, but that doesn't work because
  10566. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  10567. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  10568. to \code{Any}.
  10569. \begin{figure}[tbp]
  10570. \begin{lstlisting}
  10571. (define (map-vec! [f : (Any -> Any)] v) : Void
  10572. (begin
  10573. (vector-set! v 0 (f (vector-ref v 0)))
  10574. (vector-set! v 1 (f (vector-ref v 1)))))
  10575. (define (add1 x) (+ x 1))
  10576. (let ([v (vector 0 41)])
  10577. (begin (map-vec! add1 v) (vector-ref v 1)))
  10578. \end{lstlisting}
  10579. \caption{Casting a vector to \code{Any}.}
  10580. \label{fig:map-vec-any}
  10581. \end{figure}
  10582. The \LangCast{} interpreter uses an auxiliary function named
  10583. \code{apply-cast} to cast a value from a source type to a target type,
  10584. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  10585. of the kinds of casts that we've discussed in this section.
  10586. \begin{figure}[tbp]
  10587. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10588. (define/public (apply-cast v s t)
  10589. (match* (s t)
  10590. [(t1 t2) #:when (equal? t1 t2) v]
  10591. [('Any t2)
  10592. (match t2
  10593. [`(,ts ... -> ,rt)
  10594. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  10595. (define v^ (apply-project v any->any))
  10596. (apply-cast v^ any->any `(,@ts -> ,rt))]
  10597. [`(Vector ,ts ...)
  10598. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  10599. (define v^ (apply-project v vec-any))
  10600. (apply-cast v^ vec-any `(Vector ,@ts))]
  10601. [else (apply-project v t2)])]
  10602. [(t1 'Any)
  10603. (match t1
  10604. [`(,ts ... -> ,rt)
  10605. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  10606. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  10607. (apply-inject v^ (any-tag any->any))]
  10608. [`(Vector ,ts ...)
  10609. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  10610. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  10611. (apply-inject v^ (any-tag vec-any))]
  10612. [else (apply-inject v (any-tag t1))])]
  10613. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  10614. (define x (gensym 'x))
  10615. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  10616. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  10617. (define cast-writes
  10618. (for/list ([t1 ts1] [t2 ts2])
  10619. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  10620. `(vector-proxy ,(vector v (apply vector cast-reads)
  10621. (apply vector cast-writes)))]
  10622. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  10623. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  10624. `(function ,xs ,(Cast
  10625. (Apply (Value v)
  10626. (for/list ([x xs][t1 ts1][t2 ts2])
  10627. (Cast (Var x) t2 t1)))
  10628. rt1 rt2) ())]
  10629. ))
  10630. \end{lstlisting}
  10631. \caption{The \code{apply-cast} auxiliary method.}
  10632. \label{fig:apply-cast}
  10633. \end{figure}
  10634. The interpreter for \LangCast{} is defined in
  10635. Figure~\ref{fig:interp-Rcast}, with the case for \code{Cast}
  10636. dispatching to \code{apply-cast}. To handle the addition of vector
  10637. proxies, we update the vector primitives in \code{interp-op} using the
  10638. functions in Figure~\ref{fig:guarded-vector}.
  10639. \begin{figure}[tbp]
  10640. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10641. (define interp-Rcast-class
  10642. (class interp-Rwhile-class
  10643. (super-new)
  10644. (inherit apply-fun apply-inject apply-project)
  10645. (define/override (interp-op op)
  10646. (match op
  10647. ['vector-length guarded-vector-length]
  10648. ['vector-ref guarded-vector-ref]
  10649. ['vector-set! guarded-vector-set!]
  10650. ['any-vector-ref (lambda (v i)
  10651. (match v [`(tagged ,v^ ,tg)
  10652. (guarded-vector-ref v^ i)]))]
  10653. ['any-vector-set! (lambda (v i a)
  10654. (match v [`(tagged ,v^ ,tg)
  10655. (guarded-vector-set! v^ i a)]))]
  10656. ['any-vector-length (lambda (v)
  10657. (match v [`(tagged ,v^ ,tg)
  10658. (guarded-vector-length v^)]))]
  10659. [else (super interp-op op)]
  10660. ))
  10661. (define/override ((interp-exp env) e)
  10662. (define (recur e) ((interp-exp env) e))
  10663. (match e
  10664. [(Value v) v]
  10665. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  10666. [else ((super interp-exp env) e)]))
  10667. ))
  10668. (define (interp-Rcast p)
  10669. (send (new interp-Rcast-class) interp-program p))
  10670. \end{lstlisting}
  10671. \caption{The interpreter for \LangCast{}.}
  10672. \label{fig:interp-Rcast}
  10673. \end{figure}
  10674. \begin{figure}[tbp]
  10675. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10676. (define (guarded-vector-ref vec i)
  10677. (match vec
  10678. [`(vector-proxy ,proxy)
  10679. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  10680. (define rd (vector-ref (vector-ref proxy 1) i))
  10681. (apply-fun rd (list val) 'guarded-vector-ref)]
  10682. [else (vector-ref vec i)]))
  10683. (define (guarded-vector-set! vec i arg)
  10684. (match vec
  10685. [`(vector-proxy ,proxy)
  10686. (define wr (vector-ref (vector-ref proxy 2) i))
  10687. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  10688. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  10689. [else (vector-set! vec i arg)]))
  10690. (define (guarded-vector-length vec)
  10691. (match vec
  10692. [`(vector-proxy ,proxy)
  10693. (guarded-vector-length (vector-ref proxy 0))]
  10694. [else (vector-length vec)]))
  10695. \end{lstlisting}
  10696. \caption{The guarded-vector auxiliary functions.}
  10697. \label{fig:guarded-vector}
  10698. \end{figure}
  10699. \section{Lower Casts}
  10700. \label{sec:lower-casts}
  10701. The next step in the journey towards x86 is the \code{lower-casts}
  10702. pass that translates the casts in \LangCast{} to the lower-level
  10703. \code{Inject} and \code{Project} operators and a new operator for
  10704. creating vector proxies, extending the \LangLoop{} language to create
  10705. \LangProxy{}. We recommend creating an auxiliary function named
  10706. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  10707. and a target type, and translates it to expression in \LangProxy{} that has
  10708. the same behavior as casting the expression from the source to the
  10709. target type in the interpreter.
  10710. The \code{lower-cast} function can follow a code structure similar to
  10711. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  10712. the interpreter for \LangCast{} because it must handle the same cases as
  10713. \code{apply-cast} and it needs to mimic the behavior of
  10714. \code{apply-cast}. The most interesting cases are those concerning the
  10715. casts between two vector types and between two function types.
  10716. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  10717. type to another vector type is accomplished by creating a proxy that
  10718. intercepts the operations on the underlying vector. Here we make the
  10719. creation of the proxy explicit with the \code{vector-proxy} primitive
  10720. operation. It takes three arguments, the first is an expression for
  10721. the vector, the second is a vector of functions for casting an element
  10722. that is being read from the vector, and the third is a vector of
  10723. functions for casting an element that is being written to the vector.
  10724. You can create the functions using \code{Lambda}. Also, as we shall
  10725. see in the next section, we need to differentiate these vectors from
  10726. the user-created ones, so we recommend using a new primitive operator
  10727. named \code{raw-vector} instead of \code{vector} to create these
  10728. vectors of functions. Figure~\ref{fig:map-vec-bang-lower-cast} shows
  10729. the output of \code{lower-casts} on the example in
  10730. Figure~\ref{fig:map-vec-bang} that involved casting a vector of
  10731. integers to a vector of \code{Any}.
  10732. \begin{figure}[tbp]
  10733. \begin{lstlisting}
  10734. (define (map-vec! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  10735. (begin
  10736. (vector-set! v 0 (f (vector-ref v 0)))
  10737. (vector-set! v 1 (f (vector-ref v 1)))))
  10738. (define (add1 [x : Any]) : Any
  10739. (inject (+ (project x Integer) 1) Integer))
  10740. (let ([v (vector 0 41)])
  10741. (begin
  10742. (map-vec! add1 (vector-proxy v
  10743. (raw-vector (lambda: ([x9 : Integer]) : Any
  10744. (inject x9 Integer))
  10745. (lambda: ([x9 : Integer]) : Any
  10746. (inject x9 Integer)))
  10747. (raw-vector (lambda: ([x9 : Any]) : Integer
  10748. (project x9 Integer))
  10749. (lambda: ([x9 : Any]) : Integer
  10750. (project x9 Integer)))))
  10751. (vector-ref v 1)))
  10752. \end{lstlisting}
  10753. \caption{Output of \code{lower-casts} on the example in
  10754. Figure~\ref{fig:map-vec-bang}.}
  10755. \label{fig:map-vec-bang-lower-cast}
  10756. \end{figure}
  10757. A cast from one function type to another function type is accomplished
  10758. by generating a \code{Lambda} whose parameter and return types match
  10759. the target function type. The body of the \code{Lambda} should cast
  10760. the parameters from the target type to the source type (yes,
  10761. backwards! functions are contravariant\index{contravariant} in the
  10762. parameters), then call the underlying function, and finally cast the
  10763. result from the source return type to the target return type.
  10764. Figure~\ref{fig:map-vec-lower-cast} shows the output of the
  10765. \code{lower-casts} pass on the \code{map-vec} example in
  10766. Figure~\ref{fig:gradual-map-vec}. Note that the \code{add1} argument
  10767. in the call to \code{map-vec} is wrapped in a \code{lambda}.
  10768. \begin{figure}[tbp]
  10769. \begin{lstlisting}
  10770. (define (map-vec [f : (Integer -> Integer)]
  10771. [v : (Vector Integer Integer)])
  10772. : (Vector Integer Integer)
  10773. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  10774. (define (add1 [x : Any]) : Any
  10775. (inject (+ (project x Integer) 1) Integer))
  10776. (vector-ref (map-vec (lambda: ([x9 : Integer]) : Integer
  10777. (project (add1 (inject x9 Integer)) Integer))
  10778. (vector 0 41)) 1)
  10779. \end{lstlisting}
  10780. \caption{Output of \code{lower-casts} on the example in
  10781. Figure~\ref{fig:gradual-map-vec}.}
  10782. \label{fig:map-vec-lower-cast}
  10783. \end{figure}
  10784. \section{Differentiate Proxies}
  10785. \label{sec:differentiate-proxies}
  10786. So far the job of differentiating vectors and vector proxies has been
  10787. the job of the interpreter. For example, the interpreter for \LangCast{}
  10788. implements \code{vector-ref} using the \code{guarded-vector-ref}
  10789. function in Figure~\ref{fig:guarded-vector}. In the
  10790. \code{differentiate-proxies} pass we shift this responsibility to the
  10791. generated code.
  10792. We begin by designing the output language $R^p_8$. In
  10793. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  10794. proxies. In $R^p_8$ we return the \code{Vector} type to
  10795. its original meaning, as the type of real vectors, and we introduce a
  10796. new type, \code{PVector}, whose values can be either real vectors or
  10797. vector proxies. This new type comes with a suite of new primitive
  10798. operations for creating and using values of type \code{PVector}. We
  10799. don't need to introduce a new type to represent vector proxies. A
  10800. proxy is represented by a vector containing three things: 1) the
  10801. underlying vector, 2) a vector of functions for casting elements that
  10802. are read from the vector, and 3) a vector of functions for casting
  10803. values to be written to the vector. So we define the following
  10804. abbreviation for the type of a vector proxy:
  10805. \[
  10806. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  10807. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  10808. \to (\key{PVector}~ T' \ldots)
  10809. \]
  10810. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  10811. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  10812. %
  10813. Next we describe each of the new primitive operations.
  10814. \begin{description}
  10815. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  10816. (\key{PVector} $T \ldots$)]\ \\
  10817. %
  10818. This operation brands a vector as a value of the \code{PVector} type.
  10819. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  10820. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  10821. %
  10822. This operation brands a vector proxy as value of the \code{PVector} type.
  10823. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  10824. \code{Boolean}] \ \\
  10825. %
  10826. returns true if the value is a vector proxy and false if it is a
  10827. real vector.
  10828. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  10829. (\key{Vector} $T \ldots$)]\ \\
  10830. %
  10831. Assuming that the input is a vector (and not a proxy), this
  10832. operation returns the vector.
  10833. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  10834. $\to$ \code{Boolean}]\ \\
  10835. %
  10836. Given a vector proxy, this operation returns the length of the
  10837. underlying vector.
  10838. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  10839. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  10840. %
  10841. Given a vector proxy, this operation returns the $i$th element of
  10842. the underlying vector.
  10843. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  10844. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  10845. proxy, this operation writes a value to the $i$th element of the
  10846. underlying vector.
  10847. \end{description}
  10848. Now to discuss the translation that differentiates vectors from
  10849. proxies. First, every type annotation in the program must be
  10850. translated (recursively) to replace \code{Vector} with \code{PVector}.
  10851. Next, we must insert uses of \code{PVector} operations in the
  10852. appropriate places. For example, we wrap every vector creation with an
  10853. \code{inject-vector}.
  10854. \begin{lstlisting}
  10855. (vector |$e_1 \ldots e_n$|)
  10856. |$\Rightarrow$|
  10857. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  10858. \end{lstlisting}
  10859. The \code{raw-vector} operator that we introduced in the previous
  10860. section does not get injected.
  10861. \begin{lstlisting}
  10862. (raw-vector |$e_1 \ldots e_n$|)
  10863. |$\Rightarrow$|
  10864. (vector |$e'_1 \ldots e'_n$|)
  10865. \end{lstlisting}
  10866. The \code{vector-proxy} primitive translates as follows.
  10867. \begin{lstlisting}
  10868. (vector-proxy |$e_1~e_2~e_3$|)
  10869. |$\Rightarrow$|
  10870. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  10871. \end{lstlisting}
  10872. We translate the vector operations into conditional expressions that
  10873. check whether the value is a proxy and then dispatch to either the
  10874. appropriate proxy vector operation or the regular vector operation.
  10875. For example, the following is the translation for \code{vector-ref}.
  10876. \begin{lstlisting}
  10877. (vector-ref |$e_1$| |$i$|)
  10878. |$\Rightarrow$|
  10879. (let ([|$v~e_1$|])
  10880. (if (proxy? |$v$|)
  10881. (proxy-vector-ref |$v$| |$i$|)
  10882. (vector-ref (project-vector |$v$|) |$i$|)
  10883. \end{lstlisting}
  10884. Note in the case of a real vector, we must apply \code{project-vector}
  10885. before the \code{vector-ref}.
  10886. \section{Reveal Casts}
  10887. \label{sec:reveal-casts-gradual}
  10888. Recall that the \code{reveal-casts} pass
  10889. (Section~\ref{sec:reveal-casts-r6}) is responsible for lowering
  10890. \code{Inject} and \code{Project} into lower-level operations. In
  10891. particular, \code{Project} turns into a conditional expression that
  10892. inspects the tag and retrieves the underlying value. Here we need to
  10893. augment the translation of \code{Project} to handle the situation when
  10894. the target type is \code{PVector}. Instead of using
  10895. \code{vector-length} we need to use \code{proxy-vector-length}.
  10896. \begin{lstlisting}
  10897. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  10898. |$\Rightarrow$|
  10899. (let |$\itm{tmp}$| |$e'$|
  10900. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  10901. (let |$\itm{vec}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  10902. (if (eq? (proxy-vector-length |$\itm{vec}$|) |$n$|) |$\itm{vec}$| (exit)))
  10903. (exit)))
  10904. \end{lstlisting}
  10905. \section{Closure Conversion}
  10906. \label{sec:closure-conversion-gradual}
  10907. The closure conversion pass only requires one minor adjustment. The
  10908. auxiliary function that translates type annotations needs to be
  10909. updated to handle the \code{PVector} type.
  10910. \section{Explicate Control}
  10911. \label{sec:explicate-control-gradual}
  10912. Update the \code{explicate-control} pass to handle the new primitive
  10913. operations on the \code{PVector} type.
  10914. \section{Select Instructions}
  10915. \label{sec:select-instructions-gradual}
  10916. Recall that the \code{select-instructions} pass is responsible for
  10917. lowering the primitive operations into x86 instructions. So we need
  10918. to translate the new \code{PVector} operations to x86. To do so, the
  10919. first question we need to answer is how will we differentiate the two
  10920. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  10921. We need just one bit to accomplish this, so we use the $57$th bit of
  10922. the 64-bit tag at the front of every vector (see
  10923. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  10924. for \code{inject-vector} we leave it that way.
  10925. \begin{lstlisting}
  10926. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  10927. |$\Rightarrow$|
  10928. movq |$e'_1$|, |$\itm{lhs'}$|
  10929. \end{lstlisting}
  10930. On the other hand, \code{inject-proxy} sets the $57$th bit to $1$.
  10931. \begin{lstlisting}
  10932. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  10933. |$\Rightarrow$|
  10934. movq |$e'_1$|, %r11
  10935. movq |$(1 << 57)$|, %rax
  10936. orq 0(%r11), %rax
  10937. movq %rax, 0(%r11)
  10938. movq %r11, |$\itm{lhs'}$|
  10939. \end{lstlisting}
  10940. The \code{proxy?} operation consumes the information so carefully
  10941. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  10942. isolates the $57$th bit to tell whether the value is a real vector or
  10943. a proxy.
  10944. \begin{lstlisting}
  10945. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  10946. |$\Rightarrow$|
  10947. movq |$e_1'$|, %r11
  10948. movq 0(%r11), %rax
  10949. sarq $57, %rax
  10950. andq $1, %rax
  10951. movq %rax, |$\itm{lhs'}$|
  10952. \end{lstlisting}
  10953. The \code{project-vector} operation is straightforward to translate,
  10954. so we leave it up to the reader.
  10955. Regarding the \code{proxy-vector} operations, the runtime provides
  10956. procedures that implement them (they are recursive functions!) so
  10957. here we simply need to translate these vector operations into the
  10958. appropriate function call. For example, here is the translation for
  10959. \code{proxy-vector-ref}.
  10960. \begin{lstlisting}
  10961. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  10962. |$\Rightarrow$|
  10963. movq |$e_1'$|, %rdi
  10964. movq |$e_2'$|, %rsi
  10965. callq proxy_vector_ref
  10966. movq %rax, |$\itm{lhs'}$|
  10967. \end{lstlisting}
  10968. We have another batch of vector operations to deal with, those for the
  10969. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  10970. \code{any-vector-ref} when there is a \code{vector-ref} on something
  10971. of type \code{Any}, and similarly for \code{any-vector-set!} and
  10972. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  10973. Section~\ref{sec:select-r6} we selected instructions for these
  10974. operations based on the idea that the underlying value was a real
  10975. vector. But in the current setting, the underlying value is of type
  10976. \code{PVector}. So \code{any-vector-ref} can be translates to
  10977. pseudo-x86 as follows. We begin by projecting the underlying value out
  10978. of the tagged value and then call the \code{proxy\_vector\_ref}
  10979. procedure in the runtime.
  10980. \begin{lstlisting}
  10981. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  10982. movq |$\neg 111$|, %rdi
  10983. andq |$e_1'$|, %rdi
  10984. movq |$e_2'$|, %rsi
  10985. callq proxy_vector_ref
  10986. movq %rax, |$\itm{lhs'}$|
  10987. \end{lstlisting}
  10988. The \code{any-vector-set!} and \code{any-vector-length} operators can
  10989. be translated in a similar way.
  10990. \begin{exercise}\normalfont
  10991. Implement a compiler for the gradually-typed \LangGrad{} language by
  10992. extending and adapting your compiler for \LangLoop{}. Create 10 new
  10993. partially-typed test programs. In addition to testing with these
  10994. new programs, also test your compiler on all the tests for \LangLoop{}
  10995. and tests for \LangDyn{}. Sometimes you may get a type checking error
  10996. on the \LangDyn{} programs but you can adapt them by inserting
  10997. a cast to the \code{Any} type around each subexpression
  10998. causing a type error. While \LangDyn{} doesn't have explicit casts,
  10999. you can induce one by wrapping the subexpression \code{e}
  11000. with a call to an un-annotated identity function, like this:
  11001. \code{((lambda (x) x) e)}.
  11002. \end{exercise}
  11003. \begin{figure}[p]
  11004. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11005. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  11006. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  11007. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  11008. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  11009. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  11010. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  11011. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  11012. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  11013. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  11014. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  11015. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  11016. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  11017. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  11018. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  11019. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  11020. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  11021. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  11022. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  11023. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  11024. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  11025. \path[->,bend right=15] (Rgradual) edge [above] node
  11026. {\ttfamily\footnotesize type-check} (Rgradualp);
  11027. \path[->,bend right=15] (Rgradualp) edge [above] node
  11028. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  11029. \path[->,bend right=15] (Rwhilepp) edge [right] node
  11030. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  11031. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  11032. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  11033. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  11034. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  11035. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  11036. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  11037. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  11038. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  11039. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  11040. {\ttfamily\footnotesize convert-assignments} (F1-1);
  11041. \path[->,bend left=15] (F1-1) edge [below] node
  11042. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  11043. \path[->,bend right=15] (F1-2) edge [above] node
  11044. {\ttfamily\footnotesize limit-fun.} (F1-3);
  11045. \path[->,bend right=15] (F1-3) edge [above] node
  11046. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  11047. \path[->,bend right=15] (F1-4) edge [above] node
  11048. {\ttfamily\footnotesize remove-complex.} (F1-5);
  11049. \path[->,bend right=15] (F1-5) edge [right] node
  11050. {\ttfamily\footnotesize explicate-control} (C3-2);
  11051. \path[->,bend left=15] (C3-2) edge [left] node
  11052. {\ttfamily\footnotesize select-instr.} (x86-2);
  11053. \path[->,bend right=15] (x86-2) edge [left] node
  11054. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  11055. \path[->,bend right=15] (x86-2-1) edge [below] node
  11056. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  11057. \path[->,bend right=15] (x86-2-2) edge [left] node
  11058. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  11059. \path[->,bend left=15] (x86-3) edge [above] node
  11060. {\ttfamily\footnotesize patch-instr.} (x86-4);
  11061. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  11062. \end{tikzpicture}
  11063. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  11064. \label{fig:Rgradual-passes}
  11065. \end{figure}
  11066. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  11067. for the compilation of \LangGrad{}.
  11068. \section{Further Reading}
  11069. This chapter just scratches the surface of gradual typing. The basic
  11070. approach described here is missing two key ingredients that one would
  11071. want in a implementation of gradual typing: blame
  11072. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  11073. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  11074. problem addressed by blame tracking is that when a cast on a
  11075. higher-order value fails, it often does so at a point in the program
  11076. that is far removed from the original cast. Blame tracking is a
  11077. technique for propagating extra information through casts and proxies
  11078. so that when a cast fails, the error message can point back to the
  11079. original location of the cast in the source program.
  11080. The problem addressed by space-efficient casts also relates to
  11081. higher-order casts. It turns out that in partially typed programs, a
  11082. function or vector can flow through very-many casts at runtime. With
  11083. the approach described in this chapter, each cast adds another
  11084. \code{lambda} wrapper or a vector proxy. Not only does this take up
  11085. considerable space, but it also makes the function calls and vector
  11086. operations slow. For example, a partially-typed version of quicksort
  11087. could, in the worst case, build a chain of proxies of length $O(n)$
  11088. around the vector, changing the overall time complexity of the
  11089. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  11090. solution to this problem by representing casts using the coercion
  11091. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  11092. long chains of proxies by compressing them into a concise normal
  11093. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  11094. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  11095. the Grift compiler.
  11096. \begin{center}
  11097. \url{https://github.com/Gradual-Typing/Grift}
  11098. \end{center}
  11099. There are also interesting interactions between gradual typing and
  11100. other language features, such as parametetric polymorphism,
  11101. information-flow types, and type inference, to name a few. We
  11102. recommend the reader to the online gradual typing bibliography:
  11103. \begin{center}
  11104. \url{http://samth.github.io/gradual-typing-bib/}
  11105. \end{center}
  11106. % TODO: challenge problem:
  11107. % type analysis and type specialization?
  11108. % coercions?
  11109. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11110. \chapter{Parametric Polymorphism}
  11111. \label{ch:parametric-polymorphism}
  11112. \index{parametric polymorphism}
  11113. \index{generics}
  11114. This chapter studies the compilation of parametric
  11115. polymorphism\index{parametric polymorphism}
  11116. (aka. generics\index{generics}) in the subset \LangPoly{} of Typed
  11117. Racket. Parametric polymorphism enables improved code reuse by
  11118. parameterizing functions and data structures with respect to the types
  11119. that they operate on. For example, Figure~\ref{fig:map-vec-poly}
  11120. revisits the \code{map-vec} example but this time gives it a more
  11121. fitting type. This \code{map-vec} function is parameterized with
  11122. respect to the element type of the vector. The type of \code{map-vec}
  11123. is the following polymorphic type as specified by the \code{All} and
  11124. the type parameter \code{a}.
  11125. \begin{lstlisting}
  11126. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  11127. \end{lstlisting}
  11128. The idea is that \code{map-vec} can be used at \emph{all} choices of a
  11129. type for parameter \code{a}. In Figure~\ref{fig:map-vec-poly} we apply
  11130. \code{map-vec} to a vector of integers, a choice of \code{Integer} for
  11131. \code{a}, but we could have just as well applied \code{map-vec} to a
  11132. vector of Booleans (and a function on Booleans).
  11133. \begin{figure}[tbp]
  11134. % poly_test_2.rkt
  11135. \begin{lstlisting}
  11136. (: map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  11137. (define (map-vec f v)
  11138. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11139. (define (add1 [x : Integer]) : Integer (+ x 1))
  11140. (vector-ref (map-vec add1 (vector 0 41)) 1)
  11141. \end{lstlisting}
  11142. \caption{The \code{map-vec} example using parametric polymorphism.}
  11143. \label{fig:map-vec-poly}
  11144. \end{figure}
  11145. Figure~\ref{fig:r10-concrete-syntax} defines the concrete syntax of
  11146. \LangPoly{} and Figure~\ref{fig:r10-syntax} defines the abstract
  11147. syntax. We add a second form for function definitions in which a type
  11148. declaration comes before the \code{define}. In the abstract syntax,
  11149. the return type in the \code{Def} is \code{Any}, but that should be
  11150. ignored in favor of the return type in the type declaration. (The
  11151. \code{Any} comes from using the same parser as in
  11152. Chapter~\ref{ch:type-dynamic}.) The presence of a type declaration
  11153. enables the use of an \code{All} type for a function, thereby making
  11154. it polymorphic. The grammar for types is extended to include
  11155. polymorphic types and type variables.
  11156. \begin{figure}[tp]
  11157. \centering
  11158. \fbox{
  11159. \begin{minipage}{0.96\textwidth}
  11160. \small
  11161. \[
  11162. \begin{array}{lcl}
  11163. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11164. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  11165. &\mid& \LP\key{:}~\Var~\Type\RP \\
  11166. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  11167. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  11168. \end{array}
  11169. \]
  11170. \end{minipage}
  11171. }
  11172. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  11173. (Figure~\ref{fig:r8-concrete-syntax}).}
  11174. \label{fig:r10-concrete-syntax}
  11175. \end{figure}
  11176. \begin{figure}[tp]
  11177. \centering
  11178. \fbox{
  11179. \begin{minipage}{0.96\textwidth}
  11180. \small
  11181. \[
  11182. \begin{array}{lcl}
  11183. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11184. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  11185. &\mid& \DECL{\Var}{\Type} \\
  11186. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  11187. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11188. \end{array}
  11189. \]
  11190. \end{minipage}
  11191. }
  11192. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  11193. (Figure~\ref{fig:r8-syntax}).}
  11194. \label{fig:r10-syntax}
  11195. \end{figure}
  11196. By including polymorphic types in the $\Type$ non-terminal we choose
  11197. to make them first-class which has interesting repercussions on the
  11198. compiler. Many languages with polymorphism, such as
  11199. C++~\citep{stroustrup88:_param_types} and Standard
  11200. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  11201. it is useful to see an example of first-class polymorphism. In
  11202. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  11203. whose parameter is a polymorphic function. The occurrence of a
  11204. polymorphic type underneath a function type is enabled by the normal
  11205. recursive structure of the grammar for $\Type$ and the categorization
  11206. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  11207. applies the polymorphic function to a Boolean and to an integer.
  11208. \begin{figure}[tbp]
  11209. \begin{lstlisting}
  11210. (: apply-twice ((All (b) (b -> b)) -> Integer))
  11211. (define (apply-twice f)
  11212. (if (f #t) (f 42) (f 777)))
  11213. (: id (All (a) (a -> a)))
  11214. (define (id x) x)
  11215. (apply-twice id)
  11216. \end{lstlisting}
  11217. \caption{An example illustrating first-class polymorphism.}
  11218. \label{fig:apply-twice}
  11219. \end{figure}
  11220. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Rvar0} has
  11221. three new responsibilities (compared to \LangLoop{}). The type checking of
  11222. function application is extended to handle the case where the operator
  11223. expression is a polymorphic function. In that case the type arguments
  11224. are deduced by matching the type of the parameters with the types of
  11225. the arguments.
  11226. %
  11227. The \code{match-types} auxiliary function carries out this deduction
  11228. by recursively descending through a parameter type \code{pt} and the
  11229. corresponding argument type \code{at}, making sure that they are equal
  11230. except when there is a type parameter on the left (in the parameter
  11231. type). If it's the first time that the type parameter has been
  11232. encountered, then the algorithm deduces an association of the type
  11233. parameter to the corresponding type on the right (in the argument
  11234. type). If it's not the first time that the type parameter has been
  11235. encountered, the algorithm looks up its deduced type and makes sure
  11236. that it is equal to the type on the right.
  11237. %
  11238. Once the type arguments are deduced, the operator expression is
  11239. wrapped in an \code{Inst} AST node (for instantiate) that records the
  11240. type of the operator, but more importantly, records the deduced type
  11241. arguments. The return type of the application is the return type of
  11242. the polymorphic function, but with the type parameters replaced by the
  11243. deduced type arguments, using the \code{subst-type} function.
  11244. The second responsibility of the type checker is extending the
  11245. function \code{type-equal?} to handle the \code{All} type. This is
  11246. not quite a simple as equal on other types, such as function and
  11247. vector types, because two polymorphic types can be syntactically
  11248. different even though they are equivalent types. For example,
  11249. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  11250. Two polymorphic types should be considered equal if they differ only
  11251. in the choice of the names of the type parameters. The
  11252. \code{type-equal?} function in Figure~\ref{fig:type-check-Rvar0-aux}
  11253. renames the type parameters of the first type to match the type
  11254. parameters of the second type.
  11255. The third responsibility of the type checker is making sure that only
  11256. defined type variables appear in type annotations. The
  11257. \code{check-well-formed} function defined in
  11258. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  11259. sure that each type variable has been defined.
  11260. The output language of the type checker is \LangInst{}, defined in
  11261. Figure~\ref{fig:r10-prime-syntax}. The type checker combines the type
  11262. declaration and polymorphic function into a single definition, using
  11263. the \code{Poly} form, to make polymorphic functions more convenient to
  11264. process in next pass of the compiler.
  11265. \begin{figure}[tp]
  11266. \centering
  11267. \fbox{
  11268. \begin{minipage}{0.96\textwidth}
  11269. \small
  11270. \[
  11271. \begin{array}{lcl}
  11272. \Type &::=& \ldots \mid \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \mid \Var \\
  11273. \Exp &::=& \ldots \mid \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  11274. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  11275. &\mid& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  11276. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11277. \end{array}
  11278. \]
  11279. \end{minipage}
  11280. }
  11281. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  11282. (Figure~\ref{fig:r8-syntax}).}
  11283. \label{fig:r10-prime-syntax}
  11284. \end{figure}
  11285. The output of the type checker on the polymorphic \code{map-vec}
  11286. example is listed in Figure~\ref{fig:map-vec-type-check}.
  11287. \begin{figure}[tbp]
  11288. % poly_test_2.rkt
  11289. \begin{lstlisting}
  11290. (poly (a) (define (map-vec [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  11291. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  11292. (define (add1 [x : Integer]) : Integer (+ x 1))
  11293. (vector-ref ((inst map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  11294. (Integer))
  11295. add1 (vector 0 41)) 1)
  11296. \end{lstlisting}
  11297. \caption{Output of the type checker on the \code{map-vec} example.}
  11298. \label{fig:map-vec-type-check}
  11299. \end{figure}
  11300. \begin{figure}[tbp]
  11301. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11302. (define type-check-poly-class
  11303. (class type-check-Rwhile-class
  11304. (super-new)
  11305. (inherit check-type-equal?)
  11306. (define/override (type-check-apply env e1 es)
  11307. (define-values (e^ ty) ((type-check-exp env) e1))
  11308. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  11309. ((type-check-exp env) e)))
  11310. (match ty
  11311. [`(,ty^* ... -> ,rt)
  11312. (for ([arg-ty ty*] [param-ty ty^*])
  11313. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  11314. (values e^ es^ rt)]
  11315. [`(All ,xs (,tys ... -> ,rt))
  11316. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  11317. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  11318. (match-types env^^ param-ty arg-ty)))
  11319. (define targs
  11320. (for/list ([x xs])
  11321. (match (dict-ref env^^ x (lambda () #f))
  11322. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  11323. x (Apply e1 es))]
  11324. [ty ty])))
  11325. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  11326. [else (error 'type-check "expected a function, not ~a" ty)]))
  11327. (define/override ((type-check-exp env) e)
  11328. (match e
  11329. [(Lambda `([,xs : ,Ts] ...) rT body)
  11330. (for ([T Ts]) ((check-well-formed env) T))
  11331. ((check-well-formed env) rT)
  11332. ((super type-check-exp env) e)]
  11333. [(HasType e1 ty)
  11334. ((check-well-formed env) ty)
  11335. ((super type-check-exp env) e)]
  11336. [else ((super type-check-exp env) e)]))
  11337. (define/override ((type-check-def env) d)
  11338. (verbose 'type-check "poly/def" d)
  11339. (match d
  11340. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  11341. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  11342. (for ([p ps]) ((check-well-formed ts-env) p))
  11343. ((check-well-formed ts-env) rt)
  11344. (define new-env (append ts-env (map cons xs ps) env))
  11345. (define-values (body^ ty^) ((type-check-exp new-env) body))
  11346. (check-type-equal? ty^ rt body)
  11347. (Generic ts (Def f p:t* rt info body^))]
  11348. [else ((super type-check-def env) d)]))
  11349. (define/override (type-check-program p)
  11350. (match p
  11351. [(Program info body)
  11352. (type-check-program (ProgramDefsExp info '() body))]
  11353. [(ProgramDefsExp info ds body)
  11354. (define ds^ (combine-decls-defs ds))
  11355. (define new-env (for/list ([d ds^])
  11356. (cons (def-name d) (fun-def-type d))))
  11357. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  11358. (define-values (body^ ty) ((type-check-exp new-env) body))
  11359. (check-type-equal? ty 'Integer body)
  11360. (ProgramDefsExp info ds^^ body^)]))
  11361. ))
  11362. \end{lstlisting}
  11363. \caption{Type checker for the \LangPoly{} language.}
  11364. \label{fig:type-check-Rvar0}
  11365. \end{figure}
  11366. \begin{figure}[tbp]
  11367. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11368. (define/override (type-equal? t1 t2)
  11369. (match* (t1 t2)
  11370. [(`(All ,xs ,T1) `(All ,ys ,T2))
  11371. (define env (map cons xs ys))
  11372. (type-equal? (subst-type env T1) T2)]
  11373. [(other wise)
  11374. (super type-equal? t1 t2)]))
  11375. (define/public (match-types env pt at)
  11376. (match* (pt at)
  11377. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  11378. [('Void 'Void) env] [('Any 'Any) env]
  11379. [(`(Vector ,pts ...) `(Vector ,ats ...))
  11380. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  11381. (match-types env^ pt1 at1))]
  11382. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  11383. (define env^ (match-types env prt art))
  11384. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  11385. (match-types env^^ pt1 at1))]
  11386. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  11387. (define env^ (append (map cons pxs axs) env))
  11388. (match-types env^ pt1 at1)]
  11389. [((? symbol? x) at)
  11390. (match (dict-ref env x (lambda () #f))
  11391. [#f (error 'type-check "undefined type variable ~a" x)]
  11392. ['Type (cons (cons x at) env)]
  11393. [t^ (check-type-equal? at t^ 'matching) env])]
  11394. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  11395. (define/public (subst-type env pt)
  11396. (match pt
  11397. ['Integer 'Integer] ['Boolean 'Boolean]
  11398. ['Void 'Void] ['Any 'Any]
  11399. [`(Vector ,ts ...)
  11400. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  11401. [`(,ts ... -> ,rt)
  11402. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  11403. [`(All ,xs ,t)
  11404. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  11405. [(? symbol? x) (dict-ref env x)]
  11406. [else (error 'type-check "expected a type not ~a" pt)]))
  11407. (define/public (combine-decls-defs ds)
  11408. (match ds
  11409. ['() '()]
  11410. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  11411. (unless (equal? name f)
  11412. (error 'type-check "name mismatch, ~a != ~a" name f))
  11413. (match type
  11414. [`(All ,xs (,ps ... -> ,rt))
  11415. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  11416. (cons (Generic xs (Def name params^ rt info body))
  11417. (combine-decls-defs ds^))]
  11418. [`(,ps ... -> ,rt)
  11419. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  11420. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  11421. [else (error 'type-check "expected a function type, not ~a" type) ])]
  11422. [`(,(Def f params rt info body) . ,ds^)
  11423. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  11424. \end{lstlisting}
  11425. \caption{Auxiliary functions for type checking \LangPoly{}.}
  11426. \label{fig:type-check-Rvar0-aux}
  11427. \end{figure}
  11428. \begin{figure}[tbp]
  11429. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  11430. (define/public ((check-well-formed env) ty)
  11431. (match ty
  11432. ['Integer (void)]
  11433. ['Boolean (void)]
  11434. ['Void (void)]
  11435. [(? symbol? a)
  11436. (match (dict-ref env a (lambda () #f))
  11437. ['Type (void)]
  11438. [else (error 'type-check "undefined type variable ~a" a)])]
  11439. [`(Vector ,ts ...)
  11440. (for ([t ts]) ((check-well-formed env) t))]
  11441. [`(,ts ... -> ,t)
  11442. (for ([t ts]) ((check-well-formed env) t))
  11443. ((check-well-formed env) t)]
  11444. [`(All ,xs ,t)
  11445. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  11446. ((check-well-formed env^) t)]
  11447. [else (error 'type-check "unrecognized type ~a" ty)]))
  11448. \end{lstlisting}
  11449. \caption{Well-formed types.}
  11450. \label{fig:well-formed-types}
  11451. \end{figure}
  11452. % TODO: interpreter for R'_10
  11453. \section{Compiling Polymorphism}
  11454. \label{sec:compiling-poly}
  11455. Broadly speaking, there are four approaches to compiling parametric
  11456. polymorphism, which we describe below.
  11457. \begin{description}
  11458. \item[Monomorphization] generates a different version of a polymorphic
  11459. function for each set of type arguments that it is used with,
  11460. producing type-specialized code. This approach results in the most
  11461. efficient code but requires whole-program compilation (no separate
  11462. compilation) and increases code size. For our current purposes
  11463. monomorphization is a non-starter because, with first-class
  11464. polymorphism, it is sometimes not possible to determine which
  11465. generic functions are used with which type arguments during
  11466. compilation. (It can be done at runtime, with just-in-time
  11467. compilation.) This approach is used to compile C++
  11468. templates~\citep{stroustrup88:_param_types} and polymorphic
  11469. functions in NESL~\citep{Blelloch:1993aa} and
  11470. ML~\citep{Weeks:2006aa}.
  11471. \item[Uniform representation] generates one version of each
  11472. polymorphic function but requires all values have a common ``boxed''
  11473. format, such as the tagged values of type \code{Any} in
  11474. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  11475. similarly to code in a dynamically typed language (like \LangDyn{}), in
  11476. which primitive operators require their arguments to be projected
  11477. from \code{Any} and their results are injected into \code{Any}. (In
  11478. object-oriented languages, the projection is accomplished via
  11479. virtual method dispatch.) The uniform representation approach is
  11480. compatible with separate compilation and with first-class
  11481. polymorphism. However, it produces the least-efficient code because
  11482. it introduces overhead in the entire program, including
  11483. non-polymorphic code. This approach is used in the implementation of
  11484. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  11485. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  11486. Java~\citep{Bracha:1998fk}.
  11487. \item[Mixed representation] generates one version of each polymorphic
  11488. function, using a boxed representation for type
  11489. variables. Monomorphic code is compiled as usual (as in \LangLoop{}) and
  11490. conversions are performed at the boundaries between monomorphic and
  11491. polymorphic (e.g. when a polymorphic function is instantiated and
  11492. called). This approach is compatible with separate compilation and
  11493. first-class polymorphism and maintains the efficiency for
  11494. monomorphic code. The tradeoff is increased overhead at the boundary
  11495. between monomorphic and polymorphic code. This approach is used in
  11496. compilers for variants of ML~\citep{Leroy:1992qb} and starting in
  11497. Java 5 with the addition of autoboxing.
  11498. \item[Type passing] uses the unboxed representation in both
  11499. monomorphic and polymorphic code. Each polymorphic function is
  11500. compiled to a single function with extra parameters that describe
  11501. the type arguments. The type information is used by the generated
  11502. code to direct access of the unboxed values at runtime. This
  11503. approach is used in compilers for the Napier88
  11504. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. This
  11505. approach is compatible with separate compilation and first-class
  11506. polymorphism and maintains the efficiency for monomorphic
  11507. code. There is runtime overhead in polymorphic code from dispatching
  11508. on type information.
  11509. \end{description}
  11510. In this chapter we use the mixed representation approach, partly
  11511. because of its favorable attributes, and partly because it is
  11512. straightforward to implement using the tools that we have already
  11513. built to support gradual typing. To compile polymorphic functions, we
  11514. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  11515. \LangCast{}.
  11516. \section{Erase Types}
  11517. \label{sec:erase-types}
  11518. We use the \code{Any} type from Chapter~\ref{ch:type-dynamic} to
  11519. represent type variables. For example, Figure~\ref{fig:map-vec-erase}
  11520. shows the output of the \code{erase-types} pass on the polymorphic
  11521. \code{map-vec} (Figure~\ref{fig:map-vec-poly}). The occurrences of
  11522. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  11523. \code{All} types are removed from the type of \code{map-vec}.
  11524. \begin{figure}[tbp]
  11525. \begin{lstlisting}
  11526. (define (map-vec [f : (Any -> Any)] [v : (Vector Any Any)])
  11527. : (Vector Any Any)
  11528. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11529. (define (add1 [x : Integer]) : Integer (+ x 1))
  11530. (vector-ref ((cast map-vec
  11531. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  11532. ((Integer -> Integer) (Vector Integer Integer)
  11533. -> (Vector Integer Integer)))
  11534. add1 (vector 0 41)) 1)
  11535. \end{lstlisting}
  11536. \caption{The polymorphic \code{map-vec} example after type erasure.}
  11537. \label{fig:map-vec-erase}
  11538. \end{figure}
  11539. This process of type erasure creates a challenge at points of
  11540. instantiation. For example, consider the instantiation of
  11541. \code{map-vec} in Figure~\ref{fig:map-vec-type-check}.
  11542. The type of \code{map-vec} is
  11543. \begin{lstlisting}
  11544. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  11545. \end{lstlisting}
  11546. and it is instantiated to
  11547. \begin{lstlisting}
  11548. ((Integer -> Integer) (Vector Integer Integer)
  11549. -> (Vector Integer Integer))
  11550. \end{lstlisting}
  11551. After erasure, the type of \code{map-vec} is
  11552. \begin{lstlisting}
  11553. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  11554. \end{lstlisting}
  11555. but we need to convert it to the instantiated type. This is easy to
  11556. do in the target language \LangCast{} with a single \code{cast}. In
  11557. Figure~\ref{fig:map-vec-erase}, the instantiation of \code{map-vec}
  11558. has been compiled to a \code{cast} from the type of \code{map-vec} to
  11559. the instantiated type. The source and target type of a cast must be
  11560. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  11561. because both the source and target are obtained from the same
  11562. polymorphic type of \code{map-vec}, replacing the type parameters with
  11563. \code{Any} in the former and with the deduced type arguments in the
  11564. later. (Recall that the \code{Any} type is consistent with any type.)
  11565. To implement the \code{erase-types} pass, we recommend defining a
  11566. recursive auxiliary function named \code{erase-type} that applies the
  11567. following two transformations. It replaces type variables with
  11568. \code{Any}
  11569. \begin{lstlisting}
  11570. |$x$|
  11571. |$\Rightarrow$|
  11572. Any
  11573. \end{lstlisting}
  11574. and it removes the polymorphic \code{All} types.
  11575. \begin{lstlisting}
  11576. (All |$xs$| |$T_1$|)
  11577. |$\Rightarrow$|
  11578. |$T'_1$|
  11579. \end{lstlisting}
  11580. Apply the \code{erase-type} function to all of the type annotations in
  11581. the program.
  11582. Regarding the translation of expressions, the case for \code{Inst} is
  11583. the interesting one. We translate it into a \code{Cast}, as shown
  11584. below. The type of the subexpression $e$ is the polymorphic type
  11585. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  11586. $T$, the type $T'$. The target type $T''$ is the result of
  11587. substituting the arguments types $ts$ for the type parameters $xs$ in
  11588. $T$ followed by doing type erasure.
  11589. \begin{lstlisting}
  11590. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  11591. |$\Rightarrow$|
  11592. (Cast |$e'$| |$T'$| |$T''$|)
  11593. \end{lstlisting}
  11594. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  11595. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  11596. Finally, each polymorphic function is translated to a regular
  11597. functions in which type erasure has been applied to all the type
  11598. annotations and the body.
  11599. \begin{lstlisting}
  11600. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  11601. |$\Rightarrow$|
  11602. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  11603. \end{lstlisting}
  11604. \begin{exercise}\normalfont
  11605. Implement a compiler for the polymorphic language \LangPoly{} by
  11606. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  11607. programs that use polymorphic functions. Some of them should make
  11608. use of first-class polymorphism.
  11609. \end{exercise}
  11610. \begin{figure}[p]
  11611. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11612. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  11613. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  11614. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  11615. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  11616. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  11617. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  11618. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  11619. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  11620. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  11621. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  11622. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  11623. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  11624. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  11625. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  11626. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  11627. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  11628. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  11629. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  11630. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  11631. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  11632. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  11633. \path[->,bend right=15] (Rpoly) edge [above] node
  11634. {\ttfamily\footnotesize type-check} (Rpolyp);
  11635. \path[->,bend right=15] (Rpolyp) edge [above] node
  11636. {\ttfamily\footnotesize erase-types} (Rgradualp);
  11637. \path[->,bend right=15] (Rgradualp) edge [above] node
  11638. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  11639. \path[->,bend right=15] (Rwhilepp) edge [right] node
  11640. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  11641. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  11642. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  11643. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  11644. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  11645. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  11646. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  11647. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  11648. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  11649. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  11650. {\ttfamily\footnotesize convert-assignments} (F1-1);
  11651. \path[->,bend left=15] (F1-1) edge [below] node
  11652. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  11653. \path[->,bend right=15] (F1-2) edge [above] node
  11654. {\ttfamily\footnotesize limit-fun.} (F1-3);
  11655. \path[->,bend right=15] (F1-3) edge [above] node
  11656. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  11657. \path[->,bend right=15] (F1-4) edge [above] node
  11658. {\ttfamily\footnotesize remove-complex.} (F1-5);
  11659. \path[->,bend right=15] (F1-5) edge [right] node
  11660. {\ttfamily\footnotesize explicate-control} (C3-2);
  11661. \path[->,bend left=15] (C3-2) edge [left] node
  11662. {\ttfamily\footnotesize select-instr.} (x86-2);
  11663. \path[->,bend right=15] (x86-2) edge [left] node
  11664. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  11665. \path[->,bend right=15] (x86-2-1) edge [below] node
  11666. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  11667. \path[->,bend right=15] (x86-2-2) edge [left] node
  11668. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  11669. \path[->,bend left=15] (x86-3) edge [above] node
  11670. {\ttfamily\footnotesize patch-instr.} (x86-4);
  11671. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  11672. \end{tikzpicture}
  11673. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  11674. \label{fig:Rpoly-passes}
  11675. \end{figure}
  11676. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  11677. for the compilation of \LangPoly{}.
  11678. % TODO: challenge problem: specialization of instantiations
  11679. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11680. \chapter{Appendix}
  11681. \section{Interpreters}
  11682. \label{appendix:interp}
  11683. \index{interpreter}
  11684. We provide interpreters for each of the source languages \LangInt{},
  11685. \LangVar{}, $\ldots$ in the files \code{interp-Rint.rkt},
  11686. \code{interp-Rvar.rkt}, etc. The interpreters for the intermediate
  11687. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  11688. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  11689. and x86 are in the \key{interp.rkt} file.
  11690. \section{Utility Functions}
  11691. \label{appendix:utilities}
  11692. The utility functions described in this section are in the
  11693. \key{utilities.rkt} file of the support code.
  11694. \paragraph{\code{interp-tests}}
  11695. The \key{interp-tests} function runs the compiler passes and the
  11696. interpreters on each of the specified tests to check whether each pass
  11697. is correct. The \key{interp-tests} function has the following
  11698. parameters:
  11699. \begin{description}
  11700. \item[name (a string)] a name to identify the compiler,
  11701. \item[typechecker] a function of exactly one argument that either
  11702. raises an error using the \code{error} function when it encounters a
  11703. type error, or returns \code{\#f} when it encounters a type
  11704. error. If there is no type error, the type checker returns the
  11705. program.
  11706. \item[passes] a list with one entry per pass. An entry is a list with
  11707. four things:
  11708. \begin{enumerate}
  11709. \item a string giving the name of the pass,
  11710. \item the function that implements the pass (a translator from AST
  11711. to AST),
  11712. \item a function that implements the interpreter (a function from
  11713. AST to result value) for the output language,
  11714. \item and a type checker for the output language. Type checkers for
  11715. the $R$ and $C$ languages are provided in the support code. For
  11716. example, the type checkers for \LangVar{} and \LangCVar{} are in
  11717. \code{type-check-Rvar.rkt} and \code{type-check-Cvar.rkt}. The
  11718. type checker entry is optional. The support code does not provide
  11719. type checkers for the x86 languages.
  11720. \end{enumerate}
  11721. \item[source-interp] an interpreter for the source language. The
  11722. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  11723. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  11724. \item[tests] a list of test numbers that specifies which tests to
  11725. run. (see below)
  11726. \end{description}
  11727. %
  11728. The \key{interp-tests} function assumes that the subdirectory
  11729. \key{tests} has a collection of Racket programs whose names all start
  11730. with the family name, followed by an underscore and then the test
  11731. number, ending with the file extension \key{.rkt}. Also, for each test
  11732. program that calls \code{read} one or more times, there is a file with
  11733. the same name except that the file extension is \key{.in} that
  11734. provides the input for the Racket program. If the test program is
  11735. expected to fail type checking, then there should be an empty file of
  11736. the same name but with extension \key{.tyerr}.
  11737. \paragraph{\code{compiler-tests}}
  11738. runs the compiler passes to generate x86 (a \key{.s} file) and then
  11739. runs the GNU C compiler (gcc) to generate machine code. It runs the
  11740. machine code and checks that the output is $42$. The parameters to the
  11741. \code{compiler-tests} function are similar to those of the
  11742. \code{interp-tests} function, and consist of
  11743. \begin{itemize}
  11744. \item a compiler name (a string),
  11745. \item a type checker,
  11746. \item description of the passes,
  11747. \item name of a test-family, and
  11748. \item a list of test numbers.
  11749. \end{itemize}
  11750. \paragraph{\code{compile-file}}
  11751. takes a description of the compiler passes (see the comment for
  11752. \key{interp-tests}) and returns a function that, given a program file
  11753. name (a string ending in \key{.rkt}), applies all of the passes and
  11754. writes the output to a file whose name is the same as the program file
  11755. name but with \key{.rkt} replaced with \key{.s}.
  11756. \paragraph{\code{read-program}}
  11757. takes a file path and parses that file (it must be a Racket program)
  11758. into an abstract syntax tree.
  11759. \paragraph{\code{parse-program}}
  11760. takes an S-expression representation of an abstract syntax tree and converts it into
  11761. the struct-based representation.
  11762. \paragraph{\code{assert}}
  11763. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  11764. and displays the message \key{msg} if the Boolean \key{bool} is false.
  11765. \paragraph{\code{lookup}}
  11766. % remove discussion of lookup? -Jeremy
  11767. takes a key and an alist, and returns the first value that is
  11768. associated with the given key, if there is one. If not, an error is
  11769. triggered. The alist may contain both immutable pairs (built with
  11770. \key{cons}) and mutable pairs (built with \key{mcons}).
  11771. %The \key{map2} function ...
  11772. \section{x86 Instruction Set Quick-Reference}
  11773. \label{sec:x86-quick-reference}
  11774. \index{x86}
  11775. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  11776. do. We write $A \to B$ to mean that the value of $A$ is written into
  11777. location $B$. Address offsets are given in bytes. The instruction
  11778. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  11779. registers (such as \code{\%rax}), or memory references (such as
  11780. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  11781. reference per instruction. Other operands must be immediates or
  11782. registers.
  11783. \begin{table}[tbp]
  11784. \centering
  11785. \begin{tabular}{l|l}
  11786. \textbf{Instruction} & \textbf{Operation} \\ \hline
  11787. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  11788. \texttt{negq} $A$ & $- A \to A$ \\
  11789. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  11790. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  11791. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  11792. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  11793. \texttt{retq} & Pops the return address and jumps to it \\
  11794. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  11795. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  11796. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  11797. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  11798. be an immediate) \\
  11799. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  11800. matches the condition code of the instruction, otherwise go to the
  11801. next instructions. The condition codes are \key{e} for ``equal'',
  11802. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  11803. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  11804. \texttt{jl} $L$ & \\
  11805. \texttt{jle} $L$ & \\
  11806. \texttt{jg} $L$ & \\
  11807. \texttt{jge} $L$ & \\
  11808. \texttt{jmp} $L$ & Jump to label $L$ \\
  11809. \texttt{movq} $A$, $B$ & $A \to B$ \\
  11810. \texttt{movzbq} $A$, $B$ &
  11811. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  11812. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  11813. and the extra bytes of $B$ are set to zero.} \\
  11814. & \\
  11815. & \\
  11816. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  11817. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  11818. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  11819. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  11820. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  11821. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  11822. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  11823. description of the condition codes. $A$ must be a single byte register
  11824. (e.g., \texttt{al} or \texttt{cl}).} \\
  11825. \texttt{setl} $A$ & \\
  11826. \texttt{setle} $A$ & \\
  11827. \texttt{setg} $A$ & \\
  11828. \texttt{setge} $A$ &
  11829. \end{tabular}
  11830. \vspace{5pt}
  11831. \caption{Quick-reference for the x86 instructions used in this book.}
  11832. \label{tab:x86-instr}
  11833. \end{table}
  11834. \cleardoublepage
  11835. \section{Concrete Syntax for Intermediate Languages}
  11836. The concrete syntax of \LangAny{} is defined in
  11837. Figure~\ref{fig:r6-concrete-syntax}.
  11838. \begin{figure}[tp]
  11839. \centering
  11840. \fbox{
  11841. \begin{minipage}{0.97\textwidth}\small
  11842. \[
  11843. \begin{array}{lcl}
  11844. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  11845. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \key{Void}} \\
  11846. &\mid& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \mid \key{Any} \\
  11847. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void}
  11848. \mid \LP\key{Vector}\; \key{Any}\ldots\RP \\
  11849. &\mid& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  11850. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \mid \CPROJECT{\Exp}{\FType}\\
  11851. &\mid& \LP\key{any-vector-length}\;\Exp\RP
  11852. \mid \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  11853. &\mid& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  11854. &\mid& \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP
  11855. \mid \LP\key{void?}\;\Exp\RP \\
  11856. &\mid& \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \\
  11857. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  11858. \LangAny{} &::=& \gray{\Def\ldots \; \Exp}
  11859. \end{array}
  11860. \]
  11861. \end{minipage}
  11862. }
  11863. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  11864. (Figure~\ref{fig:Rlam-syntax}) with \key{Any}.}
  11865. \label{fig:r6-concrete-syntax}
  11866. \end{figure}
  11867. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and \LangCFun{} is
  11868. defined in Figures~\ref{fig:c0-concrete-syntax},
  11869. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax},
  11870. and \ref{fig:c3-concrete-syntax}, respectively.
  11871. \begin{figure}[tbp]
  11872. \fbox{
  11873. \begin{minipage}{0.96\textwidth}
  11874. \[
  11875. \begin{array}{lcl}
  11876. \Atm &::=& \Int \mid \Var \\
  11877. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  11878. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  11879. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  11880. \LangCVar{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  11881. \end{array}
  11882. \]
  11883. \end{minipage}
  11884. }
  11885. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  11886. \label{fig:c0-concrete-syntax}
  11887. \end{figure}
  11888. \begin{figure}[tbp]
  11889. \fbox{
  11890. \begin{minipage}{0.96\textwidth}
  11891. \small
  11892. \[
  11893. \begin{array}{lcl}
  11894. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  11895. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  11896. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  11897. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  11898. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  11899. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  11900. \mid \key{goto}~\itm{label}\key{;}\\
  11901. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  11902. \LangCIf{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  11903. \end{array}
  11904. \]
  11905. \end{minipage}
  11906. }
  11907. \caption{The concrete syntax of the \LangCIf{} intermediate language.}
  11908. \label{fig:c1-concrete-syntax}
  11909. \end{figure}
  11910. \begin{figure}[tbp]
  11911. \fbox{
  11912. \begin{minipage}{0.96\textwidth}
  11913. \small
  11914. \[
  11915. \begin{array}{lcl}
  11916. \Atm &::=& \gray{ \Int \mid \Var \mid \itm{bool} } \\
  11917. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  11918. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  11919. &\mid& \gray{ \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP } \\
  11920. &\mid& \LP \key{allocate}~\Int~\Type \RP \\
  11921. &\mid& (\key{vector-ref}\;\Atm\;\Int) \mid (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  11922. &\mid& \LP \key{global-value}~\Var \RP \mid \LP \key{void} \RP \\
  11923. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \mid \LP\key{collect}~\Int \RP\\
  11924. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  11925. \mid \gray{ \key{goto}~\itm{label}\key{;} }\\
  11926. &\mid& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  11927. \LangCVec{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  11928. \end{array}
  11929. \]
  11930. \end{minipage}
  11931. }
  11932. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  11933. \label{fig:c2-concrete-syntax}
  11934. \end{figure}
  11935. \begin{figure}[tp]
  11936. \fbox{
  11937. \begin{minipage}{0.96\textwidth}
  11938. \small
  11939. \[
  11940. \begin{array}{lcl}
  11941. \Atm &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  11942. \\
  11943. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  11944. \Exp &::= & \gray{ \Atm \mid \LP\key{read}\RP \mid \LP\key{-}\;\Atm\RP \mid \LP\key{+} \; \Atm\;\Atm\RP
  11945. \mid \LP\key{not}\;\Atm\RP \mid \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  11946. &\mid& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  11947. \mid \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  11948. &\mid& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \mid \LP\key{global-value} \,\itm{name}\RP \mid \LP\key{void}\RP } \\
  11949. &\mid& \LP\key{fun-ref}~\itm{label}\RP \mid \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  11950. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  11951. \mid \LP\key{collect} \,\itm{int}\RP }\\
  11952. \Tail &::= & \gray{\RETURN{\Exp} \mid \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  11953. &\mid& \gray{\LP\key{goto}\,\itm{label}\RP
  11954. \mid \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  11955. &\mid& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  11956. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  11957. \LangCFun{} & ::= & \Def\ldots
  11958. \end{array}
  11959. \]
  11960. \end{minipage}
  11961. }
  11962. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  11963. \label{fig:c3-concrete-syntax}
  11964. \end{figure}
  11965. \cleardoublepage
  11966. \addcontentsline{toc}{chapter}{Index}
  11967. \printindex
  11968. \cleardoublepage
  11969. \bibliographystyle{plainnat}
  11970. \bibliography{all}
  11971. \addcontentsline{toc}{chapter}{Bibliography}
  11972. \end{document}
  11973. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  11974. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  11975. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  11976. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  11977. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator jane
  11978. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  11979. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  11980. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  11981. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs Tt
  11982. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  11983. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  11984. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  11985. %% LocalWords: boolean type-check notq cmpq sete movzbq jmp al xorq
  11986. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  11987. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  11988. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  11989. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  11990. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  11991. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  11992. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  11993. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  11994. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  11995. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  11996. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  11997. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  11998. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  11999. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  12000. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  12001. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  12002. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  12003. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  12004. % LocalWords: struct Friedman's MacOS Nystrom alist sam kate
  12005. % LocalWords: alists arity github unordered pqueue exprs ret param
  12006. % LocalWords: tyerr bytereg dh dl JmpIf HasType Osterlund Jacek TODO
  12007. % LocalWords: Gamari GlobalValue ProgramDefsExp prm ProgramDefs vn
  12008. % LocalWords: FunRef TailCall tailjmp IndirectCallq TailJmp Gilray
  12009. % LocalWords: dereference unbox Dataflow versa dataflow Kildall rhs
  12010. % LocalWords: Kleene enqueue dequeue AssignedFree FV cnvt SetBang tg
  12011. % LocalWords: ValueOf typechecker