book.tex 556 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588
  1. %\documentclass[]{TimesAPriori_MIT}%%6x9
  2. \documentclass[7x10]{TimesAPriori_MIT}%%7x10
  3. %\documentclass[8x10]{TimesAPriori_MIT}%%8x10
  4. \usepackage[utf8]{inputenc}
  5. %% \usepackage{setspace}
  6. %% \doublespacing
  7. \usepackage{listings}
  8. \usepackage{verbatim}
  9. \usepackage{amssymb}
  10. \usepackage{lmodern} % better typewriter font for code
  11. %\usepackage{wrapfig}
  12. \usepackage{multirow}
  13. \usepackage{tcolorbox}
  14. \usepackage{color}
  15. %\usepackage{ifthen}
  16. \definecolor{lightgray}{gray}{1}
  17. \newcommand{\black}[1]{{\color{black} #1}}
  18. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  19. \newcommand{\gray}[1]{{\color{gray} #1}}
  20. \def\racketEd{0}
  21. \def\pythonEd{1}
  22. \def\edition{1}
  23. % material that is specific to the Racket edition of the book
  24. \newcommand{\racket}[1]{{\if\edition\racketEd\color{olive}{#1}\fi}}
  25. % would like a command for: \if\edition\racketEd\color{olive}
  26. % and : \fi\color{black}
  27. % material that is specific to the Python edition of the book
  28. \newcommand{\python}[1]{{\if\edition\pythonEd\color{purple}{#1}\fi}}
  29. %% For multiple indices:
  30. \usepackage{multind}
  31. \makeindex{subject}
  32. \makeindex{authors}
  33. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  34. \lstset{%
  35. language=Lisp,
  36. basicstyle=\ttfamily\small,
  37. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  38. deletekeywords={read,mapping,vector},
  39. escapechar=|,
  40. columns=flexible,
  41. moredelim=[is][\color{red}]{~}{~},
  42. showstringspaces=false
  43. }
  44. %%% Any shortcut own defined macros place here
  45. %% sample of author macro:
  46. \input{defs}
  47. \newtheorem{exercise}[theorem]{Exercise}
  48. % Adjusted settings
  49. \setlength{\columnsep}{4pt}
  50. %% \begingroup
  51. %% \setlength{\intextsep}{0pt}%
  52. %% \setlength{\columnsep}{0pt}%
  53. %% \begin{wrapfigure}{r}{0.5\textwidth}
  54. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  55. %% \caption{Basic layout}
  56. %% \end{wrapfigure}
  57. %% \lipsum[1]
  58. %% \endgroup
  59. \newbox\oiintbox
  60. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  61. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  62. \def\oiint{\copy\oiintbox}
  63. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  64. %\usepackage{showframe}
  65. \def\ShowFrameLinethickness{0.125pt}
  66. \addbibresource{book.bib}
  67. \begin{document}
  68. \frontmatter
  69. \HalfTitle{Essentials of Compilation}
  70. \halftitlepage
  71. %% \begin{seriespage}
  72. %% \seriestitle{Industrial Economics}
  73. %% \serieseditor{Miriam Smith and Simon Rattle, editors}
  74. %% \title{Engineering and Economics}
  75. %% \author{Samuel Endgrove}
  76. %% \title{Structural Economics: From Beginning to End}
  77. %% \author{Guang Xi}
  78. %% \end{seriespage}
  79. \Title{Essentials of Compilation}
  80. \Booksubtitle{The Incremental, Nano-Pass Approach}
  81. \edition{First Edition}
  82. \BookAuthor{Jeremy G. Siek}
  83. \imprint{The MIT Press\\
  84. Cambridge, Massachusetts\\
  85. London, England}
  86. \begin{copyrightpage}
  87. \textcopyright\ 2021 Jeremy G. Siek. Available for free viewing
  88. or personal downloading under the
  89. \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  90. license.
  91. Copyright in this monograph has been licensed exclusively to The MIT
  92. Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  93. version to the public in 2022. All inquiries regarding rights should
  94. be addressed to The MIT Press, Rights and Permissions Department.
  95. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  96. %% All rights reserved. No part of this book may be reproduced in any
  97. %% form by any electronic or mechanical means (including photocopying,
  98. %% recording, or information storage and retrieval) without permission in
  99. %% writing from the publisher.
  100. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  101. %% United States of America.
  102. %% Library of Congress Cataloging-in-Publication Data is available.
  103. %% ISBN:
  104. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  105. \end{copyrightpage}
  106. \dedication{This book is dedicated to the programming language wonks
  107. at Indiana University.}
  108. %% \begin{epigraphpage}
  109. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  110. %% \textit{Book Name if any}}
  111. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  112. %% \end{epigraphpage}
  113. \tableofcontents
  114. \listoffigures
  115. \listoftables
  116. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  117. \chapter*{Preface}
  118. \addcontentsline{toc}{fmbm}{Preface}
  119. There is a magical moment when a programmer presses the ``run'' button
  120. and the software begins to execute. Somehow a program written in a
  121. high-level language is running on a computer that is only capable of
  122. shuffling bits. Here we reveal the wizardry that makes that moment
  123. possible. Beginning with the groundbreaking work of Backus and
  124. colleagues in the 1950s, computer scientists discovered techniques for
  125. constructing programs, called \emph{compilers}, that automatically
  126. translate high-level programs into machine code.
  127. We take you on a journey by constructing your own compiler for a small
  128. but powerful language. Along the way we explain the essential
  129. concepts, algorithms, and data structures that underlie compilers. We
  130. develop your understanding of how programs are mapped onto computer
  131. hardware, which is helpful when reasoning about properties at the
  132. junction between hardware and software such as execution time,
  133. software errors, and security vulnerabilities. For those interested
  134. in pursuing compiler construction, our goal is to provide a
  135. stepping-stone to advanced topics such as just-in-time compilation,
  136. program analysis, and program optimization. For those interested in
  137. designing and implementing programming languages, we connect
  138. language design choices to their impact on the compiler and the generated
  139. code.
  140. A compiler is typically organized as a sequence of stages that
  141. progressively translates a program to code that runs on hardware. We
  142. take this approach to the extreme by partitioning our compiler into a
  143. large number of \emph{nanopasses}, each of which performs a single
  144. task. This allows us to test the output of each pass in isolation, and
  145. furthermore, allows us to focus our attention making the compiler far
  146. easier to understand.
  147. %% [TODO: easier to understand/debug for those maintaining the compiler,
  148. %% proving correctness]
  149. The most familiar approach to describing compilers is with one pass
  150. per chapter. The problem with that is it obfuscates how language
  151. features motivate design choices in a compiler. We take an
  152. \emph{incremental} approach in which we build a complete compiler in
  153. each chapter, starting with arithmetic and variables and add new
  154. features in subsequent chapters.
  155. Our choice of language features is designed to elicit the fundamental
  156. concepts and algorithms used in compilers.
  157. \begin{itemize}
  158. \item We begin with integer arithmetic and local variables in
  159. Chapters~\ref{ch:trees-recur} and \ref{ch:Rvar}, where we introduce
  160. the fundamental tools of compiler construction: \emph{abstract
  161. syntax trees} and \emph{recursive functions}.
  162. \item In Chapter~\ref{ch:register-allocation-Rvar} we apply
  163. \emph{graph coloring} to assign variables to machine registers.
  164. \item Chapter~\ref{ch:Rif} adds \code{if} expressions, which motivates
  165. an elegant recursive algorithm for mapping expressions to
  166. \emph{control-flow graphs}.
  167. \item Chapter~\ref{ch:Rvec} adds heap-allocated tuples, motivating
  168. \emph{garbage collection}.
  169. \item Chapter~\ref{ch:Rfun} adds functions that are first-class values
  170. but lack lexical scoping, similar to the C programming
  171. language~\citep{Kernighan:1988nx} except that we generate efficient
  172. tail calls. The reader learns about the procedure call stack,
  173. \emph{calling conventions}, and their interaction with register
  174. allocation and garbage collection.
  175. \item Chapter~\ref{ch:Rlam} adds anonymous functions with lexical
  176. scoping, i.e., \emph{lambda abstraction}. The reader learns about
  177. \emph{closure conversion}, in which lambdas are translated into a
  178. combination of functions and tuples.
  179. \item Chapter~\ref{ch:Rdyn} adds \emph{dynamic typing}. Prior to this
  180. point the input languages are statically typed. The reader extends
  181. the statically typed language with an \code{Any} type which serves
  182. as a target for compiling the dynamically typed language.
  183. \item Chapter~\ref{ch:Rwhile} fleshes out support for imperative
  184. programming languages with the addition of loops and mutable
  185. variables. These additions elicit the need for \emph{dataflow
  186. analysis} in the register allocator.
  187. \item Chapter~\ref{ch:Rgrad} uses the \code{Any} type of
  188. Chapter~\ref{ch:Rdyn} to implement a \emph{gradually typed language}
  189. in which different regions of a program may be static or dynamically
  190. typed. The reader implements runtime support for \emph{proxies} that
  191. allow values to safely move between regions.
  192. \item Chapter~\ref{ch:Rpoly} adds \emph{generics} with autoboxing,
  193. leveraging the \code{Any} type and type casts developed in Chapters
  194. \ref{ch:Rdyn} and \ref{ch:Rgrad}.
  195. \end{itemize}
  196. There are many language features that we do not include. Our choices
  197. weigh the incidental complexity of a feature against the fundamental
  198. concepts that it exposes. For example, we include tuples and not
  199. records because they both elicit the study of heap allocation and
  200. garbage collection but records come with more incidental complexity.
  201. Since 2016 this book has served as the textbook for the compiler
  202. course at Indiana University, a 16-week course for upper-level
  203. undergraduates and first-year graduate students.
  204. %
  205. Prior to this course, students learn to program in both imperative and
  206. functional languages, study data structures and algorithms, and take
  207. discrete mathematics.
  208. %
  209. At the beginning of the course, students form groups of 2-4 people.
  210. The groups complete one chapter every two weeks, starting with
  211. Chapter~\ref{ch:Rvar} and finishing with Chapter~\ref{ch:Rdyn}. Many
  212. chapters include a challenge problem that we assign to the graduate
  213. students. The last two weeks of the course involve a final project in
  214. which students design and implement a compiler extension of their
  215. choosing. Chapters~\ref{ch:Rwhile}, \ref{ch:Rgrad}, and
  216. \ref{ch:Rpoly} can be used in support of these projects or they can
  217. replace some of the earlier chapters. For example, a course with an
  218. emphasis on statically-typed imperative languages would skip
  219. Chapter~\ref{ch:Rdyn} in favor of
  220. Chapter~\ref{ch:Rwhile}. Figure~\ref{fig:chapter-dependences} depicts
  221. the dependencies between chapters.
  222. This book has also been used in compiler courses at California
  223. Polytechnic State University, Portland State University, Rose–Hulman
  224. Institute of Technology, University of Massachusetts Lowell, and the
  225. University of Vermont.
  226. \begin{figure}[tp]
  227. \begin{tikzpicture}[baseline=(current bounding box.center)]
  228. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  229. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Rvar} Variables};
  230. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Rvar} Registers};
  231. \node (C4) at (0,0) {\small Ch.~\ref{ch:Rif} Control Flow};
  232. \node (C5) at (4,0) {\small Ch.~\ref{ch:Rvec} Tuples};
  233. \node (C6) at (8,0) {\small Ch.~\ref{ch:Rfun} Functions};
  234. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Rwhile} Loops};
  235. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Rdyn} Dynamic};
  236. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Rlam} Lambda};
  237. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Rgrad} Gradual};
  238. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Rpoly} Generics};
  239. \path[->] (C1) edge [above] node {} (C2);
  240. \path[->] (C2) edge [above] node {} (C3);
  241. \path[->] (C3) edge [above] node {} (C4);
  242. \path[->] (C4) edge [above] node {} (C5);
  243. \path[->] (C5) edge [above] node {} (C6);
  244. \path[->] (C6) edge [above] node {} (C7);
  245. \path[->] (C4) edge [above] node {} (C8);
  246. \path[->] (C4) edge [above] node {} (C9);
  247. \path[->] (C8) edge [above] node {} (C10);
  248. \path[->] (C10) edge [above] node {} (C11);
  249. \end{tikzpicture}
  250. \caption{Diagram of chapter dependencies.}
  251. \label{fig:chapter-dependences}
  252. \end{figure}
  253. \racket{
  254. We use the \href{https://racket-lang.org/}{Racket} language both for
  255. the implementation of the compiler and for the input language, so the
  256. reader should be proficient with Racket or Scheme. There are many
  257. excellent resources for learning Scheme and
  258. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  259. }
  260. \python{
  261. This edition of the book uses the \href{https://www.python.org/}{Python}
  262. both for the implementation of the compiler and for the input language, so the
  263. reader should be proficient with Python. There are many
  264. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.
  265. }
  266. The support code for this book is in the \code{github} repository at
  267. the following URL:
  268. \begin{center}\small
  269. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  270. \end{center}
  271. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  272. is helpful but not necessary for the reader to have taken a computer
  273. systems course~\citep{Bryant:2010aa}. This book introduces the parts
  274. of x86-64 assembly language that are needed.
  275. %
  276. We follow the System V calling
  277. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  278. that we generate works with the runtime system (written in C) when it
  279. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  280. operating systems.
  281. %
  282. On the Windows operating system, \code{gcc} uses the Microsoft x64
  283. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  284. assembly code that we generate does \emph{not} work with the runtime
  285. system on Windows. One workaround is to use a virtual machine with
  286. Linux as the guest operating system.
  287. \section*{Acknowledgments}
  288. The tradition of compiler construction at Indiana University goes back
  289. to research and courses on programming languages by Daniel Friedman in
  290. the 1970's and 1980's. One of his students, Kent Dybvig, implemented
  291. Chez Scheme~\citep{Dybvig:2006aa}, a production-quality, efficient
  292. compiler for Scheme. Throughout the 1990's and 2000's, Dybvig taught
  293. the compiler course and continued the development of Chez Scheme.
  294. %
  295. The compiler course evolved to incorporate novel pedagogical ideas
  296. while also including elements of efficient real-world compilers. One
  297. of Friedman's ideas was to split the compiler into many small
  298. passes. Another idea, called ``the game'', was to test the code
  299. generated by each pass using interpreters.
  300. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  301. developed infrastructure to support this approach and evolved the
  302. course to use even smaller
  303. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  304. design decisions in this book are inspired by the assignment
  305. descriptions of \citet{Dybvig:2010aa}. In the mid 2000's a student of
  306. Dybvig's named Abdulaziz Ghuloum observed that the front-to-back
  307. organization of the course made it difficult for students to
  308. understand the rationale for the compiler design. Ghuloum proposed the
  309. incremental approach~\citep{Ghuloum:2006bh} that this book is based
  310. on.
  311. We thank the many students who served as teaching assistants for the
  312. compiler course at IU and made suggestions for improving the book
  313. including Carl Factora, Ryan Scott, and Cameron Swords. We especially
  314. thank Andre Kuhlenschmidt for his work on the garbage collector,
  315. Michael Vollmer for his work on efficient tail calls, and Michael
  316. Vitousek for his help running the first offering of the incremental
  317. compiler course at IU.
  318. We thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  319. Near, Ryan Newton, Nate Nystrom, Andrew Tolmach, and Michael Wollowski
  320. for teaching courses based on drafts of this book and for their
  321. invaluable feedback.
  322. We thank Ronald Garcia for helping Jeremy survive Dybvig's compiler
  323. course in the early 2000's and especially for finding the bug that
  324. sent our garbage collector on a wild goose chase!
  325. \mbox{}\\
  326. \noindent Jeremy G. Siek \\
  327. Bloomington, Indiana
  328. \mainmatter
  329. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  330. \chapter{Preliminaries}
  331. \label{ch:trees-recur}
  332. In this chapter we review the basic tools that are needed to implement
  333. a compiler. Programs are typically input by a programmer as text,
  334. i.e., a sequence of characters. The program-as-text representation is
  335. called \emph{concrete syntax}. We use concrete syntax to concisely
  336. write down and talk about programs. Inside the compiler, we use
  337. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  338. that efficiently supports the operations that the compiler needs to
  339. perform.\index{subject}{concrete syntax}\index{subject}{abstract syntax}\index{subject}{abstract
  340. syntax tree}\index{subject}{AST}\index{subject}{program}\index{subject}{parse} The translation
  341. from concrete syntax to abstract syntax is a process called
  342. \emph{parsing}~\citep{Aho:1986qf}. We do not cover the theory and
  343. implementation of parsing in this book.
  344. %
  345. \racket{A parser is provided in the support code for translating from
  346. concrete to abstract syntax.}
  347. %
  348. \python{We use Python's \code{ast} module to translate from concrete
  349. to abstract syntax.}
  350. ASTs can be represented in many different ways inside the compiler,
  351. depending on the programming language used to write the compiler.
  352. %
  353. \racket{We use Racket's
  354. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  355. feature to represent ASTs (Section~\ref{sec:ast}).}
  356. %
  357. \python{We use Python classes and objects to represent ASTs, especially the
  358. classes defined in the standard \code{ast} module for the Python
  359. source language.}
  360. %
  361. We use grammars to define the abstract syntax of programming languages
  362. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  363. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  364. recursive functions to construct and deconstruct ASTs
  365. (Section~\ref{sec:recursion}). This chapter provides an brief
  366. introduction to these ideas.
  367. \racket{\index{subject}{struct}}
  368. \python{\index{subject}{class}\index{subject}{object}}
  369. \section{Abstract Syntax Trees}
  370. \label{sec:ast}
  371. Compilers use abstract syntax trees to represent programs because they
  372. often need to ask questions like: for a given part of a program, what
  373. kind of language feature is it? What are its sub-parts? Consider the
  374. program on the left and its AST on the right. This program is an
  375. addition operation and it has two sub-parts, a read operation and a
  376. negation. The negation has another sub-part, the integer constant
  377. \code{8}. By using a tree to represent the program, we can easily
  378. follow the links to go from one part of a program to its sub-parts.
  379. \begin{center}
  380. \begin{minipage}{0.4\textwidth}
  381. \if\edition\racketEd
  382. \begin{lstlisting}
  383. (+ (read) (- 8))
  384. \end{lstlisting}
  385. \fi
  386. \if\edition\pythonEd
  387. \begin{lstlisting}
  388. input_int() + -8
  389. \end{lstlisting}
  390. \fi
  391. \end{minipage}
  392. \begin{minipage}{0.4\textwidth}
  393. \begin{equation}
  394. \begin{tikzpicture}
  395. \node[draw] (plus) at (0 , 0) {\key{+}};
  396. \node[draw] (read) at (-1, -1.5) {{\if\edition\racketEd\footnotesize\key{read}\fi\if\edition\pythonEd\key{input\_int()}\fi}};
  397. \node[draw] (minus) at (1 , -1.5) {$\key{-}$};
  398. \node[draw] (8) at (1 , -3) {\key{8}};
  399. \draw[->] (plus) to (read);
  400. \draw[->] (plus) to (minus);
  401. \draw[->] (minus) to (8);
  402. \end{tikzpicture}
  403. \label{eq:arith-prog}
  404. \end{equation}
  405. \end{minipage}
  406. \end{center}
  407. We use the standard terminology for trees to describe ASTs: each
  408. rectangle above is called a \emph{node}. The arrows connect a node to its
  409. \emph{children} (which are also nodes). The top-most node is the
  410. \emph{root}. Every node except for the root has a \emph{parent} (the
  411. node it is the child of). If a node has no children, it is a
  412. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  413. \index{subject}{node}
  414. \index{subject}{children}
  415. \index{subject}{root}
  416. \index{subject}{parent}
  417. \index{subject}{leaf}
  418. \index{subject}{internal node}
  419. %% Recall that an \emph{symbolic expression} (S-expression) is either
  420. %% \begin{enumerate}
  421. %% \item an atom, or
  422. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  423. %% where $e_1$ and $e_2$ are each an S-expression.
  424. %% \end{enumerate}
  425. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  426. %% null value \code{'()}, etc. We can create an S-expression in Racket
  427. %% simply by writing a backquote (called a quasi-quote in Racket)
  428. %% followed by the textual representation of the S-expression. It is
  429. %% quite common to use S-expressions to represent a list, such as $a, b
  430. %% ,c$ in the following way:
  431. %% \begin{lstlisting}
  432. %% `(a . (b . (c . ())))
  433. %% \end{lstlisting}
  434. %% Each element of the list is in the first slot of a pair, and the
  435. %% second slot is either the rest of the list or the null value, to mark
  436. %% the end of the list. Such lists are so common that Racket provides
  437. %% special notation for them that removes the need for the periods
  438. %% and so many parenthesis:
  439. %% \begin{lstlisting}
  440. %% `(a b c)
  441. %% \end{lstlisting}
  442. %% The following expression creates an S-expression that represents AST
  443. %% \eqref{eq:arith-prog}.
  444. %% \begin{lstlisting}
  445. %% `(+ (read) (- 8))
  446. %% \end{lstlisting}
  447. %% When using S-expressions to represent ASTs, the convention is to
  448. %% represent each AST node as a list and to put the operation symbol at
  449. %% the front of the list. The rest of the list contains the children. So
  450. %% in the above case, the root AST node has operation \code{`+} and its
  451. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  452. %% diagram \eqref{eq:arith-prog}.
  453. %% To build larger S-expressions one often needs to splice together
  454. %% several smaller S-expressions. Racket provides the comma operator to
  455. %% splice an S-expression into a larger one. For example, instead of
  456. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  457. %% we could have first created an S-expression for AST
  458. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  459. %% S-expression.
  460. %% \begin{lstlisting}
  461. %% (define ast1.4 `(- 8))
  462. %% (define ast1_1 `(+ (read) ,ast1.4))
  463. %% \end{lstlisting}
  464. %% In general, the Racket expression that follows the comma (splice)
  465. %% can be any expression that produces an S-expression.
  466. {\if\edition\racketEd\color{olive}
  467. We define a Racket \code{struct} for each kind of node. For this
  468. chapter we require just two kinds of nodes: one for integer constants
  469. and one for primitive operations. The following is the \code{struct}
  470. definition for integer constants.
  471. \begin{lstlisting}
  472. (struct Int (value))
  473. \end{lstlisting}
  474. An integer node includes just one thing: the integer value.
  475. To create an AST node for the integer $8$, we write \INT{8}.
  476. \begin{lstlisting}
  477. (define eight (Int 8))
  478. \end{lstlisting}
  479. We say that the value created by \INT{8} is an
  480. \emph{instance} of the
  481. \code{Int} structure.
  482. The following is the \code{struct} definition for primitive operations.
  483. \begin{lstlisting}
  484. (struct Prim (op args))
  485. \end{lstlisting}
  486. A primitive operation node includes an operator symbol \code{op} and a
  487. list of child \code{args}. For example, to create an AST that negates
  488. the number $8$, we write \code{(Prim '- (list eight))}.
  489. \begin{lstlisting}
  490. (define neg-eight (Prim '- (list eight)))
  491. \end{lstlisting}
  492. Primitive operations may have zero or more children. The \code{read}
  493. operator has zero children:
  494. \begin{lstlisting}
  495. (define rd (Prim 'read '()))
  496. \end{lstlisting}
  497. whereas the addition operator has two children:
  498. \begin{lstlisting}
  499. (define ast1_1 (Prim '+ (list rd neg-eight)))
  500. \end{lstlisting}
  501. We have made a design choice regarding the \code{Prim} structure.
  502. Instead of using one structure for many different operations
  503. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  504. structure for each operation, as follows.
  505. \begin{lstlisting}
  506. (struct Read ())
  507. (struct Add (left right))
  508. (struct Neg (value))
  509. \end{lstlisting}
  510. The reason we choose to use just one structure is that in many parts
  511. of the compiler the code for the different primitive operators is the
  512. same, so we might as well just write that code once, which is enabled
  513. by using a single structure.
  514. \fi}
  515. {\if\edition\pythonEd\color{purple}
  516. We use a Python \code{class} for each kind of node.
  517. The following is the class definition for constants.
  518. \begin{lstlisting}
  519. class Constant:
  520. def __init__(self, value):
  521. self.value = value
  522. \end{lstlisting}
  523. An integer constant node includes just one thing: the integer value.
  524. To create an AST node for the integer $8$, we write \INT{8}.
  525. \begin{lstlisting}
  526. eight = Constant(8)
  527. \end{lstlisting}
  528. We say that the value created by \INT{8} is an
  529. \emph{instance} of the \code{Constant} class.
  530. The following is class definition for unary operators.
  531. \begin{lstlisting}
  532. class UnaryOp:
  533. def __init__(self, op, operand):
  534. self.op = op
  535. self.operand = operand
  536. \end{lstlisting}
  537. The specific operation is specified by the \code{op} parameter. For
  538. example, the class \code{USub} is for unary subtraction. (More unary
  539. operators are introduced in later chapters.) To create an AST that
  540. negates the number $8$, we write \NEG{\code{eight}}.
  541. \begin{lstlisting}
  542. neg_eight = UnaryOp(USub(), eight)
  543. \end{lstlisting}
  544. The call to the \code{input\_int} function is represented by the
  545. \code{Call} and \code{Name} classes.
  546. \begin{lstlisting}
  547. class Call:
  548. def __init__(self, func, args):
  549. self.func = func
  550. self.args = args
  551. class Name:
  552. def __init__(self, id):
  553. self.id = id
  554. \end{lstlisting}
  555. To create an AST node that calls \code{input\_int}, we write
  556. \begin{lstlisting}
  557. read = Call(Name('input_int'), [])
  558. \end{lstlisting}
  559. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  560. the \code{BinOp} class for binary operators.
  561. \begin{lstlisting}
  562. class BinOp:
  563. def __init__(self, left, op, right):
  564. self.op = op
  565. self.left = left
  566. self.right = right
  567. \end{lstlisting}
  568. Similar to \code{UnaryOp}, the specific operation is specified by the
  569. \code{op} parameter, which for now is just an instance of the
  570. \code{Add} class. So to create the AST node that adds negative eight
  571. to some user input, we write the following.
  572. \begin{lstlisting}
  573. ast1_1 = BinOp(read, Add(), neg_eight)
  574. \end{lstlisting}
  575. \fi}
  576. When compiling a program such as \eqref{eq:arith-prog}, we need to
  577. know that the operation associated with the root node is addition and
  578. we need to be able to access its two children. \racket{Racket}\python{Python}
  579. provides pattern matching to support these kinds of queries, as we see in
  580. Section~\ref{sec:pattern-matching}.
  581. In this book, we often write down the concrete syntax of a program
  582. even when we really have in mind the AST because the concrete syntax
  583. is more concise. We recommend that, in your mind, you always think of
  584. programs as abstract syntax trees.
  585. \section{Grammars}
  586. \label{sec:grammar}
  587. \index{subject}{integer}
  588. \index{subject}{literal}
  589. \index{subject}{constant}
  590. A programming language can be thought of as a \emph{set} of programs.
  591. The set is typically infinite (one can always create larger and larger
  592. programs), so one cannot simply describe a language by listing all of
  593. the programs in the language. Instead we write down a set of rules, a
  594. \emph{grammar}, for building programs. Grammars are often used to
  595. define the concrete syntax of a language, but they can also be used to
  596. describe the abstract syntax. We write our rules in a variant of
  597. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  598. \index{subject}{Backus-Naur Form}\index{subject}{BNF}
  599. As an example, we describe a small language, named \LangInt{}, that consists of
  600. integers and arithmetic operations.
  601. \index{subject}{grammar}
  602. The first grammar rule for the abstract syntax of \LangInt{} says that an
  603. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  604. \begin{equation}
  605. \Exp ::= \INT{\Int} \label{eq:arith-int}
  606. \end{equation}
  607. %
  608. Each rule has a left-hand-side and a right-hand-side.
  609. If you have an AST node that matches the
  610. right-hand-side, then you can categorize it according to the
  611. left-hand-side.
  612. %
  613. A name such as $\Exp$ that is defined by the grammar rules is a
  614. \emph{non-terminal}. \index{subject}{non-terminal}
  615. %
  616. The name $\Int$ is also a non-terminal, but instead of defining it
  617. with a grammar rule, we define it with the following explanation. An
  618. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  619. $-$ (for negative integers), such that the sequence of decimals
  620. represent an integer in range $-2^{62}$ to $2^{62}-1$. This enables
  621. the representation of integers using 63 bits, which simplifies several
  622. aspects of compilation. \racket{Thus, these integers corresponds to
  623. the Racket \texttt{fixnum} datatype on a 64-bit machine.}
  624. \python{In contrast, integers in Python have unlimited precision, but
  625. the techniques need to handle unlimited precision fall outside the
  626. scope of this book.}
  627. The second grammar rule is the \READOP{} operation that receives an
  628. input integer from the user of the program.
  629. \begin{equation}
  630. \Exp ::= \READ{} \label{eq:arith-read}
  631. \end{equation}
  632. The third rule says that, given an $\Exp$ node, the negation of that
  633. node is also an $\Exp$.
  634. \begin{equation}
  635. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  636. \end{equation}
  637. Symbols in typewriter font are \emph{terminal} symbols and must
  638. literally appear in the program for the rule to be applicable.
  639. \index{subject}{terminal}
  640. We can apply these rules to categorize the ASTs that are in the
  641. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  642. \INT{8} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  643. following AST is an $\Exp$.
  644. \begin{center}
  645. \begin{minipage}{0.5\textwidth}
  646. \NEG{\INT{\code{8}}}
  647. \end{minipage}
  648. \begin{minipage}{0.25\textwidth}
  649. \begin{equation}
  650. \begin{tikzpicture}
  651. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  652. \node[draw, circle] (8) at (0, -1.2) {$8$};
  653. \draw[->] (minus) to (8);
  654. \end{tikzpicture}
  655. \label{eq:arith-neg8}
  656. \end{equation}
  657. \end{minipage}
  658. \end{center}
  659. The next grammar rule is for addition expressions:
  660. \begin{equation}
  661. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  662. \end{equation}
  663. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  664. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  665. \eqref{eq:arith-read} and we have already categorized
  666. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  667. to show that
  668. \[
  669. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  670. \]
  671. is an $\Exp$ in the \LangInt{} language.
  672. If you have an AST for which the above rules do not apply, then the
  673. AST is not in \LangInt{}. For example, the program \racket{\code{(-
  674. (read) 8)}} \python{\code{input\_int() - 8}} is not in \LangInt{}
  675. because there are no rules for the \key{-} operator with two
  676. arguments. Whenever we define a language with a grammar, the language
  677. only includes those programs that are justified by the rules.
  678. {\if\edition\pythonEd\color{purple}
  679. The language \LangInt{} includes a second non-terminal $\Stmt$ for statements.
  680. There is a statement for printing the value of an expression
  681. \[
  682. \Stmt{} ::= \PRINT{\Exp}
  683. \]
  684. and a statement that evaluates an expression but ignores the result.
  685. \[
  686. \Stmt{} ::= \EXPR{\Exp}
  687. \]
  688. \fi}
  689. {\if\edition\racketEd\color{olive}
  690. The last grammar rule for \LangInt{} states that there is a
  691. \code{Program} node to mark the top of the whole program:
  692. \[
  693. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  694. \]
  695. The \code{Program} structure is defined as follows
  696. \begin{lstlisting}
  697. (struct Program (info body))
  698. \end{lstlisting}
  699. where \code{body} is an expression. In later chapters, the \code{info}
  700. part will be used to store auxiliary information but for now it is
  701. just the empty list.
  702. \fi}
  703. {\if\edition\pythonEd\color{purple}
  704. The last grammar rule for \LangInt{} states that there is a
  705. \code{Module} node to mark the top of the whole program:
  706. \[
  707. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  708. \]
  709. The asterisk symbol $*$ indicates a list of the preceding grammar item, in
  710. this case, a list of statements.
  711. %
  712. The \code{Module} class is defined as follows
  713. \begin{lstlisting}
  714. class Module:
  715. def __init__(self, body):
  716. self.body = body
  717. \end{lstlisting}
  718. where \code{body} is a list of statements.
  719. \fi}
  720. It is common to have many grammar rules with the same left-hand side
  721. but different right-hand sides, such as the rules for $\Exp$ in the
  722. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  723. combine several right-hand-sides into a single rule.
  724. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  725. in Figure~\ref{fig:r0-syntax}. The concrete syntax for \LangInt{} is
  726. defined in Figure~\ref{fig:r0-concrete-syntax}.
  727. \racket{The \code{read-program} function provided in
  728. \code{utilities.rkt} of the support code reads a program in from a
  729. file (the sequence of characters in the concrete syntax of Racket)
  730. and parses it into an abstract syntax tree. See the description of
  731. \code{read-program} in Appendix~\ref{appendix:utilities} for more
  732. details.}
  733. \python{The \code{parse} function in Python's \code{ast} module
  734. converts the concrete syntax (represented as a string) into an
  735. abstract syntax tree.}
  736. \begin{figure}[tp]
  737. \fbox{
  738. \begin{minipage}{0.96\textwidth}
  739. {\if\edition\racketEd\color{olive}
  740. \[
  741. \begin{array}{rcl}
  742. \Exp &::=& \Int \MID \LP\key{read}\RP \MID \LP\key{-}\;\Exp\RP \MID \LP\key{+} \; \Exp\;\Exp\RP\\
  743. \LangInt{} &::=& \Exp
  744. \end{array}
  745. \]
  746. \fi}
  747. {\if\edition\pythonEd\color{purple}
  748. \[
  749. \begin{array}{rcl}
  750. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp\\
  751. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp\\
  752. \LangInt{} &::=& \Stmt^{*}
  753. \end{array}
  754. \]
  755. \fi}
  756. \end{minipage}
  757. }
  758. \caption{The concrete syntax of \LangInt{}.}
  759. \label{fig:r0-concrete-syntax}
  760. \end{figure}
  761. \begin{figure}[tp]
  762. \fbox{
  763. \begin{minipage}{0.96\textwidth}
  764. {\if\edition\racketEd\color{olive}
  765. \[
  766. \begin{array}{rcl}
  767. \Exp &::=& \INT{\Int} \MID \READ{} \MID \NEG{\Exp} \\
  768. &\MID& \ADD{\Exp}{\Exp} \\
  769. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  770. \end{array}
  771. \]
  772. \fi}
  773. {\if\edition\pythonEd\color{purple}
  774. \[
  775. \begin{array}{rcl}
  776. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  777. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \\
  778. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  779. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  780. \end{array}
  781. \]
  782. \fi}
  783. \end{minipage}
  784. }
  785. \caption{The abstract syntax of \LangInt{}.}
  786. \label{fig:r0-syntax}
  787. \end{figure}
  788. \section{Pattern Matching}
  789. \label{sec:pattern-matching}
  790. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  791. the parts of an AST node. \racket{Racket}\python{Python} provides the
  792. \texttt{match} feature to access the parts of a value.
  793. Consider the following example. \index{subject}{match} \index{subject}{pattern matching}
  794. \begin{center}
  795. \begin{minipage}{0.5\textwidth}
  796. {\if\edition\racketEd\color{olive}
  797. \begin{lstlisting}
  798. (match ast1_1
  799. [(Prim op (list child1 child2))
  800. (print op)])
  801. \end{lstlisting}
  802. \fi}
  803. {\if\edition\pythonEd\color{purple}
  804. \begin{lstlisting}
  805. match ast1_1:
  806. case BinOp(child1, op, child2):
  807. print(op)
  808. \end{lstlisting}
  809. \fi}
  810. \end{minipage}
  811. \end{center}
  812. {\if\edition\racketEd\color{olive}
  813. %
  814. In the above example, the \texttt{match} form checks whether the AST
  815. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  816. three pattern variables \texttt{op}, \texttt{child1}, and
  817. \texttt{child2}, and then prints out the operator. In general, a match
  818. clause consists of a \emph{pattern} and a
  819. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  820. to be either a pattern variable, a structure name followed by a
  821. pattern for each of the structure's arguments, or an S-expression
  822. (symbols, lists, etc.). (See Chapter 12 of The Racket
  823. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  824. and Chapter 9 of The Racket
  825. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  826. for a complete description of \code{match}.)
  827. %
  828. The body of a match clause may contain arbitrary Racket code. The
  829. pattern variables can be used in the scope of the body, such as
  830. \code{op} in \code{(print op)}.
  831. %
  832. \fi}
  833. %
  834. %
  835. {\if\edition\pythonEd\color{purple}
  836. %
  837. In the above example, the \texttt{match} form checks whether the AST
  838. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  839. three pattern variables \texttt{child1}, \texttt{op}, and
  840. \texttt{child2}, and then prints out the operator. In general, each
  841. \code{case} consists of a \emph{pattern} and a
  842. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  843. to be either a pattern variable, a class name followed by a pattern
  844. for each of its constructor's arguments, or other literals such as
  845. strings, lists, etc.
  846. %
  847. The body of each \code{case} may contain arbitrary Python code. The
  848. pattern variables can be used in the body, such as \code{op} in
  849. \code{print(op)}.
  850. %
  851. \fi}
  852. A \code{match} form may contain several clauses, as in the following
  853. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  854. the AST. The \code{match} proceeds through the clauses in order,
  855. checking whether the pattern can match the input AST. The body of the
  856. first clause that matches is executed. The output of \code{leaf} for
  857. several ASTs is shown on the right.
  858. \begin{center}
  859. \begin{minipage}{0.6\textwidth}
  860. {\if\edition\racketEd\color{olive}
  861. \begin{lstlisting}
  862. (define (leaf arith)
  863. (match arith
  864. [(Int n) #t]
  865. [(Prim 'read '()) #t]
  866. [(Prim '- (list e1)) #f]
  867. [(Prim '+ (list e1 e2)) #f]))
  868. (leaf (Prim 'read '()))
  869. (leaf (Prim '- (list (Int 8))))
  870. (leaf (Int 8))
  871. \end{lstlisting}
  872. \fi}
  873. {\if\edition\pythonEd\color{purple}
  874. \begin{lstlisting}
  875. def leaf(arith):
  876. match arith:
  877. case Constant(n):
  878. return True
  879. case Call(Name('input_int'), []):
  880. return True
  881. case UnaryOp(USub(), e1):
  882. return False
  883. case BinOp(e1, Add(), e2):
  884. return False
  885. case _:
  886. return False
  887. print(leaf(Call(Name('input_int'), [])))
  888. print(leaf(UnaryOp(USub(), eight)))
  889. print(leaf(Constant(8)))
  890. \end{lstlisting}
  891. \fi}
  892. \end{minipage}
  893. \vrule
  894. \begin{minipage}{0.25\textwidth}
  895. {\if\edition\racketEd\color{olive}
  896. \begin{lstlisting}
  897. #t
  898. #f
  899. #t
  900. \end{lstlisting}
  901. \fi}
  902. {\if\edition\pythonEd\color{purple}
  903. \begin{lstlisting}
  904. True
  905. False
  906. True
  907. \end{lstlisting}
  908. \fi}
  909. \end{minipage}
  910. \end{center}
  911. When writing a \code{match}, we refer to the grammar definition to
  912. identify which non-terminal we are expecting to match against, then we
  913. make sure that 1) we have one \racket{clause}\python{case} for each alternative of that
  914. non-terminal and 2) that the pattern in each \racket{clause}\python{case} corresponds to the
  915. corresponding right-hand side of a grammar rule. For the \code{match}
  916. in the \code{leaf} function, we refer to the grammar for \LangInt{} in
  917. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  918. alternatives, so the \code{match} has 4 \racket{clauses}\python{cases}.
  919. The pattern in each \racket{clause}\python{case} corresponds to the right-hand side
  920. of a grammar rule. For example, the pattern \ADD{\code{e1}}{\code{e2}} corresponds to the
  921. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  922. patterns, replace non-terminals such as $\Exp$ with pattern variables
  923. of your choice (e.g. \code{e1} and \code{e2}).
  924. \section{Recursive Functions}
  925. \label{sec:recursion}
  926. \index{subject}{recursive function}
  927. Programs are inherently recursive. For example, an \LangInt{}
  928. expression is often made of smaller expressions. Thus, the natural way
  929. to process an entire program is with a recursive function. As a first
  930. example of such a recursive function, we define the function
  931. \code{exp} in Figure~\ref{fig:exp-predicate}, which takes an
  932. arbitrary value and determines whether or not it is an \LangInt{}
  933. expression.
  934. %
  935. We say that a function is defined by \emph{structural recursion} when
  936. it is defined using a sequence of match \racket{clauses}\python{cases}
  937. that correspond to a grammar, and the body of each \racket{clause}\python{case}
  938. makes a recursive call on each
  939. child node.\footnote{This principle of structuring code according to
  940. the data definition is advocated in the book \emph{How to Design
  941. Programs} \url{https://htdp.org/2020-8-1/Book/index.html}.}.
  942. \python{We define a second function, named \code{stmt}, that recognizes
  943. whether a value is a \LangInt{} statement.}
  944. \python{Finally, }
  945. Figure~\ref{fig:exp-predicate} \racket{also} defines \code{Rint}, which
  946. determines whether an AST is a program in \LangInt{}. In general we can
  947. expect to write one recursive function to handle each non-terminal in
  948. a grammar.\index{subject}{structural recursion}
  949. \begin{figure}[tp]
  950. {\if\edition\racketEd\color{olive}
  951. \begin{minipage}{0.7\textwidth}
  952. \begin{lstlisting}
  953. (define (exp ast)
  954. (match ast
  955. [(Int n) #t]
  956. [(Prim 'read '()) #t]
  957. [(Prim '- (list e)) (exp e)]
  958. [(Prim '+ (list e1 e2))
  959. (and (exp e1) (exp e2))]
  960. [else #f]))
  961. (define (Rint ast)
  962. (match ast
  963. [(Program '() e) (exp e)]
  964. [else #f]))
  965. (Rint (Program '() ast1_1)
  966. (Rint (Program '()
  967. (Prim '- (list (Prim 'read '())
  968. (Prim '+ (list (Num 8)))))))
  969. \end{lstlisting}
  970. \end{minipage}
  971. \vrule
  972. \begin{minipage}{0.25\textwidth}
  973. \begin{lstlisting}
  974. #t
  975. #f
  976. \end{lstlisting}
  977. \end{minipage}
  978. \fi}
  979. {\if\edition\pythonEd\color{purple}
  980. \begin{minipage}{0.7\textwidth}
  981. \begin{lstlisting}
  982. def exp(e):
  983. match e:
  984. case Constant(n):
  985. return True
  986. case Call(Name('input_int'), []):
  987. return True
  988. case UnaryOp(USub(), e1):
  989. return exp(e1)
  990. case BinOp(e1, Add(), e2):
  991. return exp(e1) and exp(e2)
  992. case _:
  993. return False
  994. def stmt(s):
  995. match s:
  996. case Call(Name('print'), [e]):
  997. return exp(e)
  998. case Expr(e):
  999. return exp(e)
  1000. case _:
  1001. return False
  1002. def Rint(p):
  1003. match p:
  1004. case Module(body):
  1005. return all([stmt(s) for s in body])
  1006. case _:
  1007. return False
  1008. print(Rint(Module([Expr(ast1_1)])))
  1009. print(Rint(Module([Expr(BinOp(read, Sub(),
  1010. UnaryOp(Add(), Constant(8))))])))
  1011. \end{lstlisting}
  1012. \end{minipage}
  1013. \vrule
  1014. \begin{minipage}{0.25\textwidth}
  1015. \begin{lstlisting}
  1016. True
  1017. False
  1018. \end{lstlisting}
  1019. \end{minipage}
  1020. \fi}
  1021. \caption{Example of recursive functions for \LangInt{}. These functions
  1022. recognize whether an AST is in \LangInt{}.}
  1023. \label{fig:exp-predicate}
  1024. \end{figure}
  1025. %% You may be tempted to merge the two functions into one, like this:
  1026. %% \begin{center}
  1027. %% \begin{minipage}{0.5\textwidth}
  1028. %% \begin{lstlisting}
  1029. %% (define (Rint ast)
  1030. %% (match ast
  1031. %% [(Int n) #t]
  1032. %% [(Prim 'read '()) #t]
  1033. %% [(Prim '- (list e)) (Rint e)]
  1034. %% [(Prim '+ (list e1 e2)) (and (Rint e1) (Rint e2))]
  1035. %% [(Program '() e) (Rint e)]
  1036. %% [else #f]))
  1037. %% \end{lstlisting}
  1038. %% \end{minipage}
  1039. %% \end{center}
  1040. %% %
  1041. %% Sometimes such a trick will save a few lines of code, especially when
  1042. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1043. %% \emph{not} recommended because it can get you into trouble.
  1044. %% %
  1045. %% For example, the above function is subtly wrong:
  1046. %% \lstinline{(Rint (Program '() (Program '() (Int 3))))}
  1047. %% returns true when it should return false.
  1048. \section{Interpreters}
  1049. \label{sec:interp_Rint}
  1050. \index{subject}{interpreter}
  1051. The behavior of a program is defined by the specification of the
  1052. programming language.
  1053. %
  1054. \racket{For example, the Scheme language is defined in the report by
  1055. \cite{SPERBER:2009aa}. The Racket language is defined in its
  1056. reference manual~\citep{plt-tr}.}
  1057. %
  1058. \python{For example, the Python language is defined in the Python
  1059. Language Reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1060. %
  1061. In this book we use interpreters
  1062. to specify each language that we consider. An interpreter that is
  1063. designated as the definition of a language is called a
  1064. \emph{definitional interpreter}~\citep{reynolds72:_def_interp}.
  1065. \index{subject}{definitional interpreter} We warm up by creating a
  1066. definitional interpreter for the \LangInt{} language, which serves as
  1067. a second example of structural recursion. The \texttt{interp\_Rint}
  1068. function is defined in Figure~\ref{fig:interp_Rint}. The body of the
  1069. function is a match on the input program followed by a call to the
  1070. \lstinline{interp_exp} helper function, which in turn has one match
  1071. clause per grammar rule for \LangInt{} expressions.
  1072. \begin{figure}[tp]
  1073. {\if\edition\racketEd\color{olive}
  1074. \begin{lstlisting}
  1075. (define (interp_exp e)
  1076. (match e
  1077. [(Int n) n]
  1078. [(Prim 'read '())
  1079. (define r (read))
  1080. (cond [(fixnum? r) r]
  1081. [else (error 'interp_exp "read expected an integer" r)])]
  1082. [(Prim '- (list e))
  1083. (define v (interp_exp e))
  1084. (fx- 0 v)]
  1085. [(Prim '+ (list e1 e2))
  1086. (define v1 (interp_exp e1))
  1087. (define v2 (interp_exp e2))
  1088. (fx+ v1 v2)]))
  1089. (define (interp_Rint p)
  1090. (match p
  1091. [(Program '() e) (interp_exp e)]))
  1092. \end{lstlisting}
  1093. \fi}
  1094. {\if\edition\pythonEd\color{purple}
  1095. \begin{lstlisting}
  1096. def interp_exp(e):
  1097. match e:
  1098. case BinOp(left, Add(), right):
  1099. l = interp_exp(left)
  1100. r = interp_exp(right)
  1101. return l + r
  1102. case UnaryOp(USub(), v):
  1103. return - interp_exp(v)
  1104. case Constant(value):
  1105. return value
  1106. case Call(Name('input_int'), []):
  1107. return int(input())
  1108. def interp_stmt(s):
  1109. match s:
  1110. case Expr(Call(Name('print'), [arg])):
  1111. print(interp_exp(arg))
  1112. case Expr(value):
  1113. interp_exp(value)
  1114. def interp_Pint(p):
  1115. match p:
  1116. case Module(body):
  1117. for s in body:
  1118. interp_stmt(s)
  1119. \end{lstlisting}
  1120. \fi}
  1121. \caption{Interpreter for the \LangInt{} language.}
  1122. \label{fig:interp_Rint}
  1123. \end{figure}
  1124. Let us consider the result of interpreting a few \LangInt{} programs. The
  1125. following program adds two integers.
  1126. {\if\edition\racketEd\color{olive}
  1127. \begin{lstlisting}
  1128. (+ 10 32)
  1129. \end{lstlisting}
  1130. \fi}
  1131. {\if\edition\pythonEd\color{purple}
  1132. \begin{lstlisting}
  1133. print(10 + 32)
  1134. \end{lstlisting}
  1135. \fi}
  1136. The result is \key{42}, the answer to life, the universe, and
  1137. everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to the
  1138. Galaxy} by Douglas Adams.}.
  1139. %
  1140. We wrote the above program in concrete syntax whereas the parsed
  1141. abstract syntax is:
  1142. {\if\edition\racketEd\color{olive}
  1143. \begin{lstlisting}
  1144. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1145. \end{lstlisting}
  1146. \fi}
  1147. {\if\edition\pythonEd\color{purple}
  1148. \begin{lstlisting}
  1149. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1150. \end{lstlisting}
  1151. \fi}
  1152. The next example demonstrates that expressions may be nested within
  1153. each other, in this case nesting several additions and negations.
  1154. {\if\edition\racketEd\color{olive}
  1155. \begin{lstlisting}
  1156. (+ 10 (- (+ 12 20)))
  1157. \end{lstlisting}
  1158. \fi}
  1159. {\if\edition\pythonEd\color{purple}
  1160. \begin{lstlisting}
  1161. print(10 + -(12 + 20))
  1162. \end{lstlisting}
  1163. \fi}
  1164. What is the result of the above program?
  1165. {\if\edition\racketEd\color{olive}
  1166. As mentioned previously, the \LangInt{} language does not support
  1167. arbitrarily-large integers, but only $63$-bit integers, so we
  1168. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1169. in Racket.
  1170. Suppose
  1171. \[
  1172. n = 999999999999999999
  1173. \]
  1174. which indeed fits in $63$-bits. What happens when we run the
  1175. following program in our interpreter?
  1176. \begin{lstlisting}
  1177. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1178. \end{lstlisting}
  1179. It produces an error:
  1180. \begin{lstlisting}
  1181. fx+: result is not a fixnum
  1182. \end{lstlisting}
  1183. We establish the convention that if running the definitional
  1184. interpreter on a program produces an error then the meaning of that
  1185. program is \emph{unspecified}\index{subject}{unspecified behavior}, unless the
  1186. error is a \code{trapped-error}. A compiler for the language is under
  1187. no obligations regarding programs with unspecified behavior; it does
  1188. not have to produce an executable, and if it does, that executable can
  1189. do anything. On the other hand, if the error is a
  1190. \code{trapped-error}, then the compiler must produce an executable and
  1191. it is required to report that an error occurred. To signal an error,
  1192. exit with a return code of \code{255}. The interpreters in chapters
  1193. \ref{ch:Rdyn} and \ref{ch:Rgrad} use
  1194. \code{trapped-error}.
  1195. \fi}
  1196. % TODO: how to deal with too-large integers in the Python interpreter?
  1197. %% This convention applies to the languages defined in this
  1198. %% book, as a way to simplify the student's task of implementing them,
  1199. %% but this convention is not applicable to all programming languages.
  1200. %%
  1201. Moving on to the last feature of the \LangInt{} language, the
  1202. \READOP{} operation prompts the user of the program for an integer.
  1203. Recall that program \eqref{eq:arith-prog} requests an integer input
  1204. and then subtracts \code{8}. So if we run
  1205. {\if\edition\racketEd\color{olive}
  1206. \begin{lstlisting}
  1207. (interp_Rint (Program '() ast1_1))
  1208. \end{lstlisting}
  1209. \fi}
  1210. {\if\edition\pythonEd\color{purple}
  1211. \begin{lstlisting}
  1212. interp_Pint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1213. \end{lstlisting}
  1214. \fi}
  1215. \noindent and if the input is \code{50}, the result is \code{42}.
  1216. We include the \READOP{} operation in \LangInt{} so a clever student
  1217. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  1218. during compilation to obtain the output and then generates the trivial
  1219. code to produce the output.\footnote{Yes, a clever student did this in the
  1220. first instance of this course!}
  1221. The job of a compiler is to translate a program in one language into a
  1222. program in another language so that the output program behaves the
  1223. same way as the input program does. This idea is depicted in the
  1224. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1225. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1226. Given a compiler that translates from language $\mathcal{L}_1$ to
  1227. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1228. compiler must translate it into some program $P_2$ such that
  1229. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1230. same input $i$ yields the same output $o$.
  1231. \begin{equation} \label{eq:compile-correct}
  1232. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1233. \node (p1) at (0, 0) {$P_1$};
  1234. \node (p2) at (3, 0) {$P_2$};
  1235. \node (o) at (3, -2.5) {$o$};
  1236. \path[->] (p1) edge [above] node {compile} (p2);
  1237. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  1238. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  1239. \end{tikzpicture}
  1240. \end{equation}
  1241. In the next section we see our first example of a compiler.
  1242. \section{Example Compiler: a Partial Evaluator}
  1243. \label{sec:partial-evaluation}
  1244. In this section we consider a compiler that translates \LangInt{} programs
  1245. into \LangInt{} programs that may be more efficient, that is, this compiler
  1246. is an optimizer. This optimizer eagerly computes the parts of the
  1247. program that do not depend on any inputs, a process known as
  1248. \emph{partial evaluation}~\citep{Jones:1993uq}.
  1249. \index{subject}{partial evaluation}
  1250. For example, given the following program
  1251. {\if\edition\racketEd\color{olive}
  1252. \begin{lstlisting}
  1253. (+ (read) (- (+ 5 3)))
  1254. \end{lstlisting}
  1255. \fi}
  1256. {\if\edition\pythonEd\color{purple}
  1257. \begin{lstlisting}
  1258. print input_int() + -(5 + 3)
  1259. \end{lstlisting}
  1260. \fi}
  1261. \noindent our compiler translates it into the program
  1262. {\if\edition\racketEd\color{olive}
  1263. \begin{lstlisting}
  1264. (+ (read) -8)
  1265. \end{lstlisting}
  1266. \fi}
  1267. {\if\edition\pythonEd\color{purple}
  1268. \begin{lstlisting}
  1269. print input_int() + -8
  1270. \end{lstlisting}
  1271. \fi}
  1272. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1273. evaluator for the \LangInt{} language. The output of the partial evaluator
  1274. is an \LangInt{} program. In Figure~\ref{fig:pe-arith}, the structural
  1275. recursion over $\Exp$ is captured in the \code{pe\_exp} function
  1276. whereas the code for partially evaluating the negation and addition
  1277. operations is factored into two separate helper functions:
  1278. \code{pe\_neg} and \code{pe\_add}. The input to these helper
  1279. functions is the output of partially evaluating the children.
  1280. The \code{pe\_neg} and \code{pe\_add} functions check whether their
  1281. arguments are integers and if they are, perform the appropriate
  1282. arithmetic. Otherwise, they create an AST node for the arithmetic
  1283. operation.
  1284. \begin{figure}[tp]
  1285. {\if\edition\racketEd\color{olive}
  1286. \begin{lstlisting}
  1287. (define (pe_neg r)
  1288. (match r
  1289. [(Int n) (Int (fx- 0 n))]
  1290. [else (Prim '- (list r))]))
  1291. (define (pe_add r1 r2)
  1292. (match* (r1 r2)
  1293. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1294. [(_ _) (Prim '+ (list r1 r2))]))
  1295. (define (pe_exp e)
  1296. (match e
  1297. [(Int n) (Int n)]
  1298. [(Prim 'read '()) (Prim 'read '())]
  1299. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1300. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]))
  1301. (define (pe_Rint p)
  1302. (match p
  1303. [(Program '() e) (Program '() (pe_exp e))]))
  1304. \end{lstlisting}
  1305. \fi}
  1306. {\if\edition\pythonEd\color{purple}
  1307. \begin{lstlisting}
  1308. def pe_neg(r):
  1309. match r:
  1310. case Constant(n):
  1311. return Constant(-n)
  1312. case _:
  1313. return UnaryOp(USub(), r)
  1314. def pe_add(r1, r2):
  1315. match (r1, r2):
  1316. case (Constant(n1), Constant(n2)):
  1317. return Constant(n1 + n2)
  1318. case _:
  1319. return BinOp(r1, Add(), r2)
  1320. def pe_exp(e):
  1321. match e:
  1322. case BinOp(left, Add(), right):
  1323. return pe_add(pe_exp(left), pe_exp(right))
  1324. case UnaryOp(USub(), v):
  1325. return pe_neg(pe_exp(v))
  1326. case Constant(value):
  1327. return e
  1328. case Call(Name('input_int'), []):
  1329. return e
  1330. def pe_stmt(s):
  1331. match s:
  1332. case Expr(Call(Name('print'), [arg])):
  1333. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1334. case Expr(value):
  1335. return Expr(pe_exp(value))
  1336. def pe_Pint(p):
  1337. match p:
  1338. case Module(body):
  1339. new_body = [pe_stmt(s) for s in body]
  1340. return Module(new_body)
  1341. \end{lstlisting}
  1342. \fi}
  1343. \caption{A partial evaluator for \LangInt{}.}
  1344. \label{fig:pe-arith}
  1345. \end{figure}
  1346. To gain some confidence that the partial evaluator is correct, we can
  1347. test whether it produces programs that get the same result as the
  1348. input programs. That is, we can test whether it satisfies Diagram
  1349. \ref{eq:compile-correct}.
  1350. %
  1351. {\if\edition\racketEd\color{olive}
  1352. The following code runs the partial evaluator on several examples and
  1353. tests the output program. The \texttt{parse-program} and
  1354. \texttt{assert} functions are defined in
  1355. Appendix~\ref{appendix:utilities}.\\
  1356. \begin{minipage}{1.0\textwidth}
  1357. \begin{lstlisting}
  1358. (define (test_pe p)
  1359. (assert "testing pe_Rint"
  1360. (equal? (interp_Rint p) (interp_Rint (pe_Rint p)))))
  1361. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1362. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1363. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1364. \end{lstlisting}
  1365. \end{minipage}
  1366. \fi}
  1367. % TODO: python version of testing the PE
  1368. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1369. \chapter{Integers and Variables}
  1370. \label{ch:Rvar}
  1371. This chapter is about compiling a subset of \racket{Racket}\python{Python}
  1372. to x86-64 assembly
  1373. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1374. integer arithmetic and local variable binding. We often refer to
  1375. x86-64 simply as x86. The chapter begins with a description of the
  1376. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  1377. to x86 assembly (Section~\ref{sec:x86}). The x86 assembly language
  1378. is large so we discuss only the instructions needed for compiling
  1379. \LangVar{}. We introduce more x86 instructions in later chapters.
  1380. After introducing \LangVar{} and x86, we reflect on their differences
  1381. and come up with a plan to break down the translation from \LangVar{}
  1382. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  1383. rest of the sections in this chapter give detailed hints regarding
  1384. each step (Sections~\ref{sec:uniquify-Rvar} through \ref{sec:patch-s0}).
  1385. We hope to give enough hints that the well-prepared reader, together
  1386. with a few friends, can implement a compiler from \LangVar{} to x86 in
  1387. a couple weeks. To give the reader a feeling for the scale of this
  1388. first compiler, the instructor solution for the \LangVar{} compiler is
  1389. approximately \racket{500}\python{300} lines of code.
  1390. \section{The \LangVar{} Language}
  1391. \label{sec:s0}
  1392. \index{subject}{variable}
  1393. The \LangVar{} language extends the \LangInt{} language with
  1394. variables. The concrete syntax of the \LangVar{} language is defined
  1395. by the grammar in Figure~\ref{fig:Rvar-concrete-syntax} and the
  1396. abstract syntax is defined in Figure~\ref{fig:Rvar-syntax}. The
  1397. non-terminal \Var{} may be any Racket identifier. As in \LangInt{},
  1398. \key{read} is a nullary operator, \key{-} is a unary operator, and
  1399. \key{+} is a binary operator. Similar to \LangInt{}, the abstract
  1400. syntax of \LangVar{} includes the \racket{\key{Program}
  1401. struct}\python{\key{Module} instance} to mark the top of the
  1402. program.
  1403. %% The $\itm{info}$
  1404. %% field of the \key{Program} structure contains an \emph{association
  1405. %% list} (a list of key-value pairs) that is used to communicate
  1406. %% auxiliary data from one compiler pass the next.
  1407. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1408. exhibit several compilation techniques.
  1409. \begin{figure}[tp]
  1410. \centering
  1411. \fbox{
  1412. \begin{minipage}{0.96\textwidth}
  1413. {\if\edition\racketEd\color{olive}
  1414. \[
  1415. \begin{array}{rcl}
  1416. \Exp &::=& \Int{} \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}\\
  1417. &\MID& \Var{} \MID \CLET{\Var}{\Exp}{\Exp} \\
  1418. \LangVarM{} &::=& \Exp
  1419. \end{array}
  1420. \]
  1421. \fi}
  1422. {\if\edition\pythonEd\color{purple}
  1423. \[
  1424. \begin{array}{rcl}
  1425. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Var{} \\
  1426. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp \MID \Var\mathop{\key{=}}\Exp\\
  1427. \LangVarM{} &::=& \Stmt^{*}
  1428. \end{array}
  1429. \]
  1430. \fi}
  1431. \end{minipage}
  1432. }
  1433. \caption{The concrete syntax of \LangVar{}.}
  1434. \label{fig:Rvar-concrete-syntax}
  1435. \end{figure}
  1436. \begin{figure}[tp]
  1437. \centering
  1438. \fbox{
  1439. \begin{minipage}{0.96\textwidth}
  1440. {\if\edition\racketEd\color{olive}
  1441. \[
  1442. \begin{array}{rcl}
  1443. \Exp &::=& \INT{\Int} \MID \READ{} \\
  1444. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \\
  1445. &\MID& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} \\
  1446. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1447. \end{array}
  1448. \]
  1449. \fi}
  1450. {\if\edition\pythonEd\color{purple}
  1451. \[
  1452. \begin{array}{rcl}
  1453. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  1454. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \VAR{\Var{}} \\
  1455. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  1456. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  1457. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1458. \end{array}
  1459. \]
  1460. \fi}
  1461. \end{minipage}
  1462. }
  1463. \caption{The abstract syntax of \LangVar{}.}
  1464. \label{fig:Rvar-syntax}
  1465. \end{figure}
  1466. {\if\edition\racketEd\color{olive}
  1467. Let us dive further into the syntax and semantics of the \LangVar{}
  1468. language. The \key{let} feature defines a variable for use within its
  1469. body and initializes the variable with the value of an expression.
  1470. The abstract syntax for \key{let} is defined in
  1471. Figure~\ref{fig:Rvar-syntax}. The concrete syntax for \key{let} is
  1472. \begin{lstlisting}
  1473. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1474. \end{lstlisting}
  1475. For example, the following program initializes \code{x} to $32$ and then
  1476. evaluates the body \code{(+ 10 x)}, producing $42$.
  1477. \begin{lstlisting}
  1478. (let ([x (+ 12 20)]) (+ 10 x))
  1479. \end{lstlisting}
  1480. \fi}
  1481. %
  1482. {\if\edition\pythonEd\color{purple}
  1483. The \LangVar{} language adds variables and the assignment statement
  1484. to \LangInt{}. The assignment statement defines a variable for use by
  1485. later statements and initializes the variable with the value of an expression.
  1486. The abstract syntax for assignment is defined in
  1487. Figure~\ref{fig:Rvar-syntax}. The concrete syntax for assignment is
  1488. \begin{lstlisting}
  1489. |$\itm{var}$| = |$\itm{exp}$|
  1490. \end{lstlisting}
  1491. For example, the following program initializes \code{x} to $32$ and then
  1492. prints the result of \code{10 + x}, producing $42$.
  1493. \begin{lstlisting}
  1494. x = 12 + 20
  1495. print(10 + x)
  1496. \end{lstlisting}
  1497. \fi}
  1498. {\if\edition\racketEd\color{olive}
  1499. When there are multiple \key{let}'s for the same variable, the closest
  1500. enclosing \key{let} is used. That is, variable definitions overshadow
  1501. prior definitions. Consider the following program with two \key{let}'s
  1502. that define variables named \code{x}. Can you figure out the result?
  1503. \begin{lstlisting}
  1504. (let ([x 32]) (+ (let ([x 10]) x) x))
  1505. \end{lstlisting}
  1506. For the purposes of depicting which variable uses correspond to which
  1507. definitions, the following shows the \code{x}'s annotated with
  1508. subscripts to distinguish them. Double check that your answer for the
  1509. above is the same as your answer for this annotated version of the
  1510. program.
  1511. \begin{lstlisting}
  1512. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1513. \end{lstlisting}
  1514. The initializing expression is always evaluated before the body of the
  1515. \key{let}, so in the following, the \key{read} for \code{x} is
  1516. performed before the \key{read} for \code{y}. Given the input
  1517. $52$ then $10$, the following produces $42$ (not $-42$).
  1518. \begin{lstlisting}
  1519. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1520. \end{lstlisting}
  1521. \fi}
  1522. \subsection{Extensible Interpreters via Method Overriding}
  1523. \label{sec:extensible-interp}
  1524. To prepare for discussing the interpreter for \LangVar{}, we
  1525. explain why we to implement the interpreter using
  1526. object-oriented programming, that is, as a collection of methods
  1527. inside of a class. Throughout this book we define many interpreters,
  1528. one for each of the languages that we study. Because each language
  1529. builds on the prior one, there is a lot of commonality between these
  1530. interpreters. We want to write down the common parts just once
  1531. instead of many times. A naive approach would be to have, for example,
  1532. the interpreter for \LangIf{} handle all of the new features in that
  1533. language and then have a default case that dispatches to the
  1534. interpreter for \LangVar{}. The following code sketches this idea.
  1535. \begin{center}
  1536. {\if\edition\racketEd\color{olive}
  1537. \begin{minipage}{0.45\textwidth}
  1538. \begin{lstlisting}
  1539. (define (interp_Rvar_exp e)
  1540. (match e
  1541. [(Prim '- (list e1))
  1542. (fx- 0 (interp_Rvar_exp e1))]
  1543. ...))
  1544. \end{lstlisting}
  1545. \end{minipage}
  1546. \begin{minipage}{0.45\textwidth}
  1547. \begin{lstlisting}
  1548. (define (interp_Rif_exp e)
  1549. (match e
  1550. [(If cnd thn els)
  1551. (match (interp_Rif_exp cnd)
  1552. [#t (interp_Rif_exp thn)]
  1553. [#f (interp_Rif_exp els)])]
  1554. ...
  1555. [else (interp_Rvar_exp e)]))
  1556. \end{lstlisting}
  1557. \end{minipage}
  1558. \fi}
  1559. {\if\edition\pythonEd\color{purple}
  1560. \begin{minipage}{0.45\textwidth}
  1561. \begin{lstlisting}
  1562. def interp_Rvar_exp(e):
  1563. match e:
  1564. case UnaryOp(USub(), e1):
  1565. return - interp_Rvar_exp(e1)
  1566. ...
  1567. \end{lstlisting}
  1568. \end{minipage}
  1569. \begin{minipage}{0.45\textwidth}
  1570. \begin{lstlisting}
  1571. def interp_Rif_exp(e):
  1572. match e:
  1573. case IfExp(cnd, thn, els):
  1574. match interp_Rif_exp(cnd):
  1575. case True:
  1576. return interp_Rif_exp(thn)
  1577. case False:
  1578. return interp_Rif_exp(els)
  1579. ...
  1580. case _:
  1581. return interp_Rvar_exp(e)
  1582. \end{lstlisting}
  1583. \end{minipage}
  1584. \fi}
  1585. \end{center}
  1586. The problem with this approach is that it does not handle situations
  1587. in which an \LangIf{} feature, such as a conditional expression, is
  1588. nested inside an \LangVar{} feature, like the \code{-} operator, as in
  1589. the following program.
  1590. {\if\edition\racketEd\color{olive}
  1591. \begin{lstlisting}
  1592. (Prim '- (list (If (Bool #t) (Int 42) (Int 0))))
  1593. \end{lstlisting}
  1594. \fi}
  1595. {\if\edition\pythonEd\color{purple}
  1596. \begin{lstlisting}
  1597. print(-(42 if True else 0))
  1598. \end{lstlisting}
  1599. \fi}
  1600. If we invoke \code{interp\_Rif\_exp} on this program, it dispatches to
  1601. \code{interp\_Rvar\_exp} to handle the \code{-} operator, but then it
  1602. recurisvely calls \code{interp\_Rvar\_exp} again on the argument of \code{-},
  1603. which is an \code{If}. But there is no case for \code{If} in
  1604. \code{interp\_Rvar\_exp}, so we get an error!
  1605. To make our interpreters extensible we need something called
  1606. \emph{open recursion}\index{subject}{open recursion}, where the tying of the
  1607. recursive knot is delayed to when the functions are
  1608. composed. Object-oriented languages provide open recursion with the
  1609. late-binding of overridden methods\index{subject}{method overriding}. The
  1610. following code sketches this idea for interpreting \LangVar{} and
  1611. \LangIf{} using
  1612. \racket{the
  1613. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1614. \index{subject}{class} feature of Racket}
  1615. \python{a Python \code{class} definition}. We define one class for each
  1616. language and define a method for interpreting expressions inside each
  1617. class. The class for \LangIf{} inherits from the class for \LangVar{}
  1618. and the method \code{interp\_exp} in \LangIf{} overrides the
  1619. \code{interp\_exp} in \LangVar{}. Note that the default case of
  1620. \code{interp\_exp} in \LangIf{} uses \code{super} to invoke
  1621. \code{interp\_exp}, and because \LangIf{} inherits from \LangVar{},
  1622. that dispatches to the \code{interp\_exp} in \LangVar{}.
  1623. \begin{center}
  1624. {\if\edition\racketEd\color{olive}
  1625. \begin{minipage}{0.45\textwidth}
  1626. \begin{lstlisting}
  1627. (define interp-Rvar-class
  1628. (class object%
  1629. (define/public (interp-exp e)
  1630. (match e
  1631. [(Prim '- (list e))
  1632. (fx- 0 (interp-exp e))]
  1633. ...))
  1634. ...))
  1635. \end{lstlisting}
  1636. \end{minipage}
  1637. \begin{minipage}{0.45\textwidth}
  1638. \begin{lstlisting}
  1639. (define interp-Rif-class
  1640. (class interp-Rvar-class
  1641. (define/override (interp-exp e)
  1642. (match e
  1643. [(If cnd thn els)
  1644. (match (interp-exp cnd)
  1645. [#t (interp-exp thn)]
  1646. [#f (interp-exp els)])]
  1647. ...
  1648. [else (super interp-exp e)]))
  1649. ...
  1650. ))
  1651. \end{lstlisting}
  1652. \end{minipage}
  1653. \fi}
  1654. {\if\edition\pythonEd\color{purple}
  1655. \begin{minipage}{0.45\textwidth}
  1656. \begin{lstlisting}
  1657. class InterpRvar:
  1658. def interp_exp(e):
  1659. match e:
  1660. case UnaryOp(USub(), e1):
  1661. return -self.interp_exp(e1)
  1662. ...
  1663. ...
  1664. \end{lstlisting}
  1665. \end{minipage}
  1666. \begin{minipage}{0.45\textwidth}
  1667. \begin{lstlisting}
  1668. def InterpRif(InterpRVar):
  1669. def interp_exp(e):
  1670. match e:
  1671. case IfExp(cnd, thn, els):
  1672. match self.interp_exp(cnd):
  1673. case True:
  1674. return self.interp_exp(thn)
  1675. case False:
  1676. return self.interp_exp(els)
  1677. ...
  1678. case _:
  1679. return super().interp_exp(e)
  1680. ...
  1681. \end{lstlisting}
  1682. \end{minipage}
  1683. \fi}
  1684. \end{center}
  1685. Getting back to the troublesome example, repeated here:
  1686. {\if\edition\racketEd\color{olive}
  1687. \begin{lstlisting}
  1688. (define e0 (Prim '- (list (If (Bool #t) (Int 42) (Int 0)))))
  1689. \end{lstlisting}
  1690. \fi}
  1691. {\if\edition\pythonEd\color{purple}
  1692. \begin{lstlisting}
  1693. -(42 if True else 0)
  1694. \end{lstlisting}
  1695. \fi}
  1696. \noindent We can invoke the \code{interp\_exp} method for \LangIf{} on this
  1697. expression, call it \code{e0}, by creating an object of the \LangIf{} class
  1698. and calling the \code{interp\_exp} method.
  1699. {\if\edition\racketEd\color{olive}
  1700. \begin{lstlisting}
  1701. (send (new interp-Rif-class) interp-exp e0)
  1702. \end{lstlisting}
  1703. \fi}
  1704. {\if\edition\pythonEd\color{purple}
  1705. \begin{lstlisting}
  1706. InterpRif().interp_exp(e0)
  1707. \end{lstlisting}
  1708. \fi}
  1709. \noindent The default case of \code{interp\_exp} in \LangIf{} handles it by
  1710. dispatching to the \code{interp\_exp} method in \LangVar{}, which
  1711. handles the \code{-} operator. But then for the recursive method call,
  1712. it dispatches back to \code{interp\_exp} in \LangIf{}, where the
  1713. \code{If} is handled correctly. Thus, method overriding gives us the
  1714. open recursion that we need to implement our interpreters in an
  1715. extensible way.
  1716. \subsection{Definitional Interpreter for \LangVar{}}
  1717. {\if\edition\racketEd\color{olive}
  1718. \begin{figure}[tp]
  1719. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  1720. \small
  1721. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1722. An \emph{association list} (alist) is a list of key-value pairs.
  1723. For example, we can map people to their ages with an alist.
  1724. \index{subject}{alist}\index{subject}{association list}
  1725. \begin{lstlisting}[basicstyle=\ttfamily]
  1726. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  1727. \end{lstlisting}
  1728. The \emph{dictionary} interface is for mapping keys to values.
  1729. Every alist implements this interface. \index{subject}{dictionary} The package
  1730. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1731. provides many functions for working with dictionaries. Here
  1732. are a few of them:
  1733. \begin{description}
  1734. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1735. returns the value associated with the given $\itm{key}$.
  1736. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1737. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1738. but otherwise is the same as $\itm{dict}$.
  1739. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1740. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1741. of keys and values in $\itm{dict}$. For example, the following
  1742. creates a new alist in which the ages are incremented.
  1743. \end{description}
  1744. \vspace{-10pt}
  1745. \begin{lstlisting}[basicstyle=\ttfamily]
  1746. (for/list ([(k v) (in-dict ages)])
  1747. (cons k (add1 v)))
  1748. \end{lstlisting}
  1749. \end{tcolorbox}
  1750. %\end{wrapfigure}
  1751. \caption{Association lists implement the dictionary interface.}
  1752. \label{fig:alist}
  1753. \end{figure}
  1754. \fi}
  1755. Having justified the use of classes and methods to implement
  1756. interpreters, we turn to the definitional interpreter for \LangVar{}
  1757. in Figure~\ref{fig:interp-Rvar}. It is similar to the interpreter for
  1758. \LangInt{} but adds two new \key{match} cases for variables and
  1759. \racket{\key{let}}\python{assignment}. For
  1760. \racket{\key{let}}\python{assignment} we need a way to communicate the
  1761. value bound to a variable to all the uses of the variable. To
  1762. accomplish this, we maintain a mapping from variables to
  1763. values. Throughout the compiler we often need to map variables to
  1764. information about them. We refer to these mappings as
  1765. \emph{environments}\index{subject}{environment}.\footnote{Another
  1766. common term for environment in the compiler literature is \emph{symbol
  1767. table}\index{subject}{symbol table}.}
  1768. %
  1769. For simplicity, we use \racket{an association list
  1770. (alist)}\python{dictionary} to represent the
  1771. environment. \racket{Figure~\ref{fig:alist} gives a brief introduction
  1772. to alists and the \code{racket/dict} package.} The
  1773. \code{interp\_exp} function takes the current environment, \code{env},
  1774. as an extra parameter. When the interpreter encounters a variable, it
  1775. looks up the corresponding value in the dictionary.
  1776. %
  1777. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  1778. initializing expression, extends the environment with the result
  1779. value bound to the variable, using \code{dict-set}, then evaluates
  1780. the body of the \key{Let}.}
  1781. %
  1782. \python{When the interpreter encounters an assignment, it evaluates
  1783. the initializing expression and then associates the resulting value
  1784. with the variable in the environment.}
  1785. \begin{figure}[tp]
  1786. {\if\edition\racketEd\color{olive}
  1787. \begin{lstlisting}
  1788. (define interp-Rvar-class
  1789. (class object%
  1790. (super-new)
  1791. (define/public ((interp_exp env) e)
  1792. (match e
  1793. [(Int n) n]
  1794. [(Prim 'read '())
  1795. (define r (read))
  1796. (cond [(fixnum? r) r]
  1797. [else (error 'interp_exp "expected an integer" r)])]
  1798. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  1799. [(Prim '+ (list e1 e2))
  1800. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  1801. [(Var x) (dict-ref env x)]
  1802. [(Let x e body)
  1803. (define new-env (dict-set env x ((interp_exp env) e)))
  1804. ((interp_exp new-env) body)]))
  1805. (define/public (interp-program p)
  1806. (match p
  1807. [(Program '() e) ((interp_exp '()) e)]))
  1808. ))
  1809. (define (interp-Rvar p)
  1810. (send (new interp-Rvar-class) interp-program p))
  1811. \end{lstlisting}
  1812. \fi}
  1813. {\if\edition\pythonEd\color{purple}
  1814. \begin{lstlisting}
  1815. class InterpPvar:
  1816. def interp_exp(self, e, env):
  1817. match e:
  1818. case BinOp(left, Add(), right):
  1819. l = self.interp_exp(left, env)
  1820. r = self.interp_exp(right, env)
  1821. return l + r
  1822. case UnaryOp(USub(), v):
  1823. return - self.interp_exp(v, env)
  1824. case Name(id):
  1825. return env[id]
  1826. case Constant(value):
  1827. return value
  1828. case Call(Name('input_int'), []):
  1829. return int(input())
  1830. def interp_stmt(self, s, env):
  1831. match s:
  1832. case Assign([lhs], value):
  1833. env[lhs.id] = self.interp_exp(value, env)
  1834. case Expr(Call(Name('print'), [arg])):
  1835. print(self.interp_exp(arg, env))
  1836. case Expr(value):
  1837. self.interp_exp(value, env)
  1838. def interp_Pvar(self, p):
  1839. match p:
  1840. case Module(body):
  1841. env = {}
  1842. for s in body:
  1843. self.interp_stmt(s, env)
  1844. \end{lstlisting}
  1845. \fi}
  1846. \caption{Interpreter for the \LangVar{} language.}
  1847. \label{fig:interp-Rvar}
  1848. \end{figure}
  1849. The goal for this chapter is to implement a compiler that translates
  1850. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  1851. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1852. computer as the $P_1$ program interpreted by \code{interp\_Rvar}. That
  1853. is, they output the same integer $n$. We depict this correctness
  1854. criteria in the following diagram.
  1855. \[
  1856. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1857. \node (p1) at (0, 0) {$P_1$};
  1858. \node (p2) at (4, 0) {$P_2$};
  1859. \node (o) at (4, -2) {$n$};
  1860. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1861. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Rvar}} (o);
  1862. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  1863. \end{tikzpicture}
  1864. \]
  1865. In the next section we introduce the \LangXInt{} subset of x86 that
  1866. suffices for compiling \LangVar{}.
  1867. \section{The \LangXInt{} Assembly Language}
  1868. \label{sec:x86}
  1869. \index{subject}{x86}
  1870. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  1871. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  1872. assembler.
  1873. %
  1874. A program begins with a \code{main} label followed by a sequence of
  1875. instructions. The \key{globl} directive says that the \key{main}
  1876. procedure is externally visible, which is necessary so that the
  1877. operating system can call it. In the grammar, ellipses such as
  1878. $\ldots$ are used to indicate a sequence of items, e.g., $\Instr
  1879. \ldots$ is a sequence of instructions.\index{subject}{instruction}
  1880. %
  1881. An x86 program is stored in the computer's memory. For our purposes,
  1882. the computer's memory is a mapping of 64-bit addresses to 64-bit
  1883. values. The computer has a \emph{program counter} (PC)\index{subject}{program
  1884. counter}\index{subject}{PC} stored in the \code{rip} register that points to
  1885. the address of the next instruction to be executed. For most
  1886. instructions, the program counter is incremented after the instruction
  1887. is executed, so it points to the next instruction in memory. Most x86
  1888. instructions take two operands, where each operand is either an
  1889. integer constant (called an \emph{immediate value}\index{subject}{immediate
  1890. value}), a \emph{register}\index{subject}{register}, or a memory location.
  1891. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  1892. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  1893. && \key{r8} \MID \key{r9} \MID \key{r10}
  1894. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  1895. \MID \key{r14} \MID \key{r15}}
  1896. \begin{figure}[tp]
  1897. \fbox{
  1898. \begin{minipage}{0.96\textwidth}
  1899. \[
  1900. \begin{array}{lcl}
  1901. \Reg &::=& \allregisters{} \\
  1902. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  1903. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  1904. \key{subq} \; \Arg\key{,} \Arg \MID
  1905. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  1906. && \key{callq} \; \mathit{label} \MID
  1907. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \MID \key{jmp}\,\itm{label} \\
  1908. && \itm{label}\key{:}\; \Instr \\
  1909. \LangXIntM{} &::= & \key{.globl main}\\
  1910. & & \key{main:} \; \Instr\ldots
  1911. \end{array}
  1912. \]
  1913. \end{minipage}
  1914. }
  1915. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  1916. \label{fig:x86-int-concrete}
  1917. \end{figure}
  1918. A register is a special kind of variable. Each one holds a 64-bit
  1919. value; there are 16 general-purpose registers in the computer and
  1920. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  1921. is written with a \key{\%} followed by the register name, such as
  1922. \key{\%rax}.
  1923. An immediate value is written using the notation \key{\$}$n$ where $n$
  1924. is an integer.
  1925. %
  1926. %
  1927. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1928. which obtains the address stored in register $r$ and then adds $n$
  1929. bytes to the address. The resulting address is used to load or store
  1930. to memory depending on whether it occurs as a source or destination
  1931. argument of an instruction.
  1932. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1933. source $s$ and destination $d$, applies the arithmetic operation, then
  1934. writes the result back to the destination $d$.
  1935. %
  1936. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1937. stores the result in $d$.
  1938. %
  1939. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  1940. specified by the label and $\key{retq}$ returns from a procedure to
  1941. its caller.
  1942. %
  1943. We discuss procedure calls in more detail later in this chapter and in
  1944. Chapter~\ref{ch:Rfun}. The instruction $\key{jmp}\,\itm{label}$
  1945. updates the program counter to the address of the instruction after
  1946. the specified label.
  1947. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  1948. all of the x86 instructions used in this book.
  1949. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  1950. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  1951. \lstinline{movq $10, %rax}
  1952. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  1953. adds $32$ to the $10$ in \key{rax} and
  1954. puts the result, $42$, back into \key{rax}.
  1955. %
  1956. The last instruction, \key{retq}, finishes the \key{main} function by
  1957. returning the integer in \key{rax} to the operating system. The
  1958. operating system interprets this integer as the program's exit
  1959. code. By convention, an exit code of 0 indicates that a program
  1960. completed successfully, and all other exit codes indicate various
  1961. errors. Nevertheless, in this book we return the result of the program
  1962. as the exit code.
  1963. \begin{figure}[tbp]
  1964. \begin{lstlisting}
  1965. .globl main
  1966. main:
  1967. movq $10, %rax
  1968. addq $32, %rax
  1969. retq
  1970. \end{lstlisting}
  1971. \caption{An x86 program that computes
  1972. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  1973. \label{fig:p0-x86}
  1974. \end{figure}
  1975. The x86 assembly language varies in a couple of ways depending on what
  1976. operating system it is assembled in. The code examples shown here are
  1977. correct on Linux and most Unix-like platforms, but when assembled on
  1978. Mac OS X, labels like \key{main} must be prefixed with an underscore,
  1979. as in \key{\_main}.
  1980. We exhibit the use of memory for storing intermediate results in the
  1981. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  1982. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  1983. uses a region of memory called the \emph{procedure call stack} (or
  1984. \emph{stack} for
  1985. short). \index{subject}{stack}\index{subject}{procedure call stack}
  1986. The stack consists of a separate \emph{frame}\index{subject}{frame}
  1987. for each procedure call. The memory layout for an individual frame is
  1988. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1989. \emph{stack pointer}\index{subject}{stack pointer} and points to the
  1990. item at the top of the stack. The stack grows downward in memory, so
  1991. we increase the size of the stack by subtracting from the stack
  1992. pointer. In the context of a procedure call, the \emph{return
  1993. address}\index{subject}{return address} is the instruction after the
  1994. call instruction on the caller side. The function call instruction,
  1995. \code{callq}, pushes the return address onto the stack prior to
  1996. jumping to the procedure. The register \key{rbp} is the \emph{base
  1997. pointer}\index{subject}{base pointer} and is used to access variables
  1998. that are stored in the frame of the current procedure call. The base
  1999. pointer of the caller is pushed onto the stack after the return
  2000. address and then the base pointer is set to the location of the old
  2001. base pointer. In Figure~\ref{fig:frame} we number the variables from
  2002. $1$ to $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$,
  2003. variable $2$ at $-16\key{(\%rbp)}$, etc.
  2004. \begin{figure}[tbp]
  2005. \begin{lstlisting}
  2006. start:
  2007. movq $10, -8(%rbp)
  2008. negq -8(%rbp)
  2009. movq -8(%rbp), %rax
  2010. addq $52, %rax
  2011. jmp conclusion
  2012. .globl main
  2013. main:
  2014. pushq %rbp
  2015. movq %rsp, %rbp
  2016. subq $16, %rsp
  2017. jmp start
  2018. conclusion:
  2019. addq $16, %rsp
  2020. popq %rbp
  2021. retq
  2022. \end{lstlisting}
  2023. \caption{An x86 program that computes
  2024. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2025. \label{fig:p1-x86}
  2026. \end{figure}
  2027. \begin{figure}[tbp]
  2028. \centering
  2029. \begin{tabular}{|r|l|} \hline
  2030. Position & Contents \\ \hline
  2031. 8(\key{\%rbp}) & return address \\
  2032. 0(\key{\%rbp}) & old \key{rbp} \\
  2033. -8(\key{\%rbp}) & variable $1$ \\
  2034. -16(\key{\%rbp}) & variable $2$ \\
  2035. \ldots & \ldots \\
  2036. 0(\key{\%rsp}) & variable $n$\\ \hline
  2037. \end{tabular}
  2038. \caption{Memory layout of a frame.}
  2039. \label{fig:frame}
  2040. \end{figure}
  2041. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  2042. control is transferred from the operating system to the \code{main}
  2043. function. The operating system issues a \code{callq main} instruction
  2044. which pushes its return address on the stack and then jumps to
  2045. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2046. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2047. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  2048. alignment (because the \code{callq} pushed the return address). The
  2049. first three instructions are the typical \emph{prelude}\index{subject}{prelude}
  2050. for a procedure. The instruction \code{pushq \%rbp} saves the base
  2051. pointer for the caller onto the stack and subtracts $8$ from the stack
  2052. pointer. The second instruction \code{movq \%rsp, \%rbp} changes the
  2053. base pointer so that it points the location of the old base
  2054. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  2055. pointer down to make enough room for storing variables. This program
  2056. needs one variable ($8$ bytes) but we round up to 16 bytes so that
  2057. \code{rsp} is 16-byte aligned and we're ready to make calls to other
  2058. functions. The last instruction of the prelude is \code{jmp start},
  2059. which transfers control to the instructions that were generated from
  2060. the expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.
  2061. The first instruction under the \code{start} label is
  2062. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2063. %
  2064. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  2065. %
  2066. The next instruction moves the $-10$ from variable $1$ into the
  2067. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2068. the value in \code{rax}, updating its contents to $42$.
  2069. The three instructions under the label \code{conclusion} are the
  2070. typical \emph{conclusion}\index{subject}{conclusion} of a procedure. The first
  2071. two instructions restore the \code{rsp} and \code{rbp} registers to
  2072. the state they were in at the beginning of the procedure. The
  2073. instruction \key{addq \$16, \%rsp} moves the stack pointer back to
  2074. point at the old base pointer. Then \key{popq \%rbp} returns the old
  2075. base pointer to \key{rbp} and adds $8$ to the stack pointer. The last
  2076. instruction, \key{retq}, jumps back to the procedure that called this
  2077. one and adds $8$ to the stack pointer.
  2078. The compiler needs a convenient representation for manipulating x86
  2079. programs, so we define an abstract syntax for x86 in
  2080. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  2081. \LangXInt{}.
  2082. %
  2083. {\if\edition\racketEd\color{olive}
  2084. The main difference compared to the concrete syntax of \LangXInt{}
  2085. (Figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2086. front of every instruction. Instead instructions are grouped into
  2087. \emph{blocks}\index{subject}{block}\index{subject}{basic block} with a
  2088. label associated with every block, which is why the \key{X86Program}
  2089. struct includes an alist mapping labels to blocks. The reason for this
  2090. organization becomes apparent in Chapter~\ref{ch:Rif} when we
  2091. introduce conditional branching. The \code{Block} structure includes
  2092. an $\itm{info}$ field that is not needed for this chapter, but becomes
  2093. useful in Chapter~\ref{ch:register-allocation-Rvar}. For now, the
  2094. $\itm{info}$ field should contain an empty list.
  2095. \fi}
  2096. %
  2097. {\if\edition\pythonEd\color{purple}
  2098. %
  2099. The main difference compared to the concrete syntax of \LangXInt{}
  2100. (Figure~\ref{fig:x86-int-concrete}) is that we do not yet include a
  2101. way to label instructions but instead recommend inserting the
  2102. \key{main}, \key{start}, and \key{conclusion} labels when printing the
  2103. final x86 program.
  2104. %
  2105. \fi}
  2106. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2107. node includes an integer for representing the arity of the function,
  2108. i.e., the number of arguments, which is helpful to know during
  2109. register allocation (Chapter~\ref{ch:register-allocation-Rvar}).
  2110. \begin{figure}[tp]
  2111. \fbox{
  2112. \begin{minipage}{0.98\textwidth}
  2113. \small
  2114. {\if\edition\racketEd\color{olive}
  2115. \[
  2116. \begin{array}{lcl}
  2117. \Reg &::=& \allregisters{} \\
  2118. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2119. \MID \DEREF{\Reg}{\Int} \\
  2120. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2121. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  2122. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2123. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2124. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  2125. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} \\
  2126. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP} \\
  2127. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2128. \end{array}
  2129. \]
  2130. \fi}
  2131. {\if\edition\pythonEd\color{purple}
  2132. \[
  2133. \begin{array}{lcl}
  2134. \Reg &::=& \allregisters{} \\
  2135. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2136. \MID \DEREF{\Reg}{\Int} \\
  2137. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2138. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  2139. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2140. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2141. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  2142. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} \\
  2143. \LangXIntM{} &::= & \XPROGRAM{\Instr^{*}}{}
  2144. \end{array}
  2145. \]
  2146. \fi}
  2147. \end{minipage}
  2148. }
  2149. \caption{The abstract syntax of \LangXInt{} assembly.}
  2150. \label{fig:x86-int-ast}
  2151. \end{figure}
  2152. \section{Planning the trip to x86 via the \LangCVar{} language}
  2153. \label{sec:plan-s0-x86}
  2154. To compile one language to another it helps to focus on the
  2155. differences between the two languages because the compiler will need
  2156. to bridge those differences. What are the differences between \LangVar{}
  2157. and x86 assembly? Here are some of the most important ones:
  2158. \begin{enumerate}
  2159. \item[(a)] x86 arithmetic instructions typically have two arguments
  2160. and update the second argument in place. In contrast, \LangVar{}
  2161. arithmetic operations take two arguments and produce a new value.
  2162. An x86 instruction may have at most one memory-accessing argument.
  2163. Furthermore, some instructions place special restrictions on their
  2164. arguments.
  2165. \item[(b)] An argument of an \LangVar{} operator can be a deeply-nested
  2166. expression, whereas x86 instructions restrict their arguments to be
  2167. integer constants, registers, and memory locations.
  2168. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  2169. sequence of instructions and jumps to labeled positions, whereas in
  2170. \LangVar{} the order of evaluation is a left-to-right depth-first
  2171. traversal of the abstract syntax tree.
  2172. \item[(d)] A program in \LangVar{} can have any number of variables
  2173. whereas x86 has 16 registers and the procedure calls stack.
  2174. {\if\edition\racketEd\color{olive}
  2175. \item[(e)] Variables in \LangVar{} can shadow other variables with the
  2176. same name. In x86, registers have unique names and memory locations
  2177. have unique addresses.
  2178. \fi}
  2179. \end{enumerate}
  2180. We ease the challenge of compiling from \LangVar{} to x86 by breaking down
  2181. the problem into several steps, dealing with the above differences one
  2182. at a time. Each of these steps is called a \emph{pass} of the
  2183. compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2184. %
  2185. This terminology comes from the way each step passes over the AST of
  2186. the program.
  2187. %
  2188. We begin by sketching how we might implement each pass, and give them
  2189. names. We then figure out an ordering of the passes and the
  2190. input/output language for each pass. The very first pass has
  2191. \LangVar{} as its input language and the last pass has \LangXInt{} as
  2192. its output language. In between we can choose whichever language is
  2193. most convenient for expressing the output of each pass, whether that
  2194. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  2195. our own design. Finally, to implement each pass we write one
  2196. recursive function per non-terminal in the grammar of the input
  2197. language of the pass. \index{subject}{intermediate language}
  2198. \begin{description}
  2199. \item[\key{select-instructions}] handles the difference between
  2200. \LangVar{} operations and x86 instructions. This pass converts each
  2201. \LangVar{} operation to a short sequence of instructions that
  2202. accomplishes the same task.
  2203. \item[\key{remove-complex-opera*}] ensures that each subexpression of
  2204. a primitive operation is a variable or integer, that is, an
  2205. \emph{atomic} expression. We refer to non-atomic expressions as
  2206. \emph{complex}. This pass introduces temporary variables to hold
  2207. the results of complex subexpressions.\index{subject}{atomic
  2208. expression}\index{subject}{complex expression}%
  2209. \footnote{The subexpressions of an operation are often called
  2210. operators and operands which explains the presence of
  2211. \code{opera*} in the name of this pass.}
  2212. {\if\edition\racketEd\color{olive}
  2213. \item[\key{explicate-control}] makes the execution order of the
  2214. program explicit. It convert the abstract syntax tree representation
  2215. into a control-flow graph in which each node contains a sequence of
  2216. statements and the edges between nodes say which nodes contain jumps
  2217. to other nodes.
  2218. \fi}
  2219. \item[\key{assign-homes}] replaces the variables in \LangVar{} with
  2220. registers or stack locations in x86.
  2221. {\if\edition\racketEd\color{olive}
  2222. \item[\key{uniquify}] deals with the shadowing of variables by
  2223. renaming every variable to a unique name.
  2224. \fi}
  2225. \end{description}
  2226. The next question is: in what order should we apply these passes? This
  2227. question can be challenging because it is difficult to know ahead of
  2228. time which orderings will be better (easier to implement, produce more
  2229. efficient code, etc.) so oftentimes trial-and-error is
  2230. involved. Nevertheless, we can try to plan ahead and make educated
  2231. choices regarding the ordering.
  2232. What should be the ordering of \key{explicate-control} with respect to
  2233. \key{uniquify}? The \key{uniquify} pass should come first because
  2234. \key{explicate-control} changes all the \key{let}-bound variables to
  2235. become local variables whose scope is the entire program, which would
  2236. confuse variables with the same name.
  2237. %
  2238. We place \key{remove-complex-opera*} before \key{explicate-control}
  2239. because the later removes the \key{let} form, but it is convenient to
  2240. use \key{let} in the output of \key{remove-complex-opera*}.
  2241. %
  2242. The ordering of \key{uniquify} with respect to
  2243. \key{remove-complex-opera*} does not matter so we arbitrarily choose
  2244. \key{uniquify} to come first.
  2245. Last, we consider \key{select-instructions} and \key{assign-homes}.
  2246. These two passes are intertwined. In Chapter~\ref{ch:Rfun} we
  2247. learn that, in x86, registers are used for passing arguments to
  2248. functions and it is preferable to assign parameters to their
  2249. corresponding registers. On the other hand, by selecting instructions
  2250. first we may run into a dead end in \key{assign-homes}. Recall that
  2251. only one argument of an x86 instruction may be a memory access but
  2252. \key{assign-homes} might fail to assign even one of them to a
  2253. register.
  2254. %
  2255. A sophisticated approach is to iteratively repeat the two passes until
  2256. a solution is found. However, to reduce implementation complexity we
  2257. recommend a simpler approach in which \key{select-instructions} comes
  2258. first, followed by the \key{assign-homes}, then a third pass named
  2259. \key{patch-instructions} that uses a reserved register to fix
  2260. outstanding problems.
  2261. \begin{figure}[tbp]
  2262. {\if\edition\racketEd\color{olive}
  2263. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2264. \node (Rvar) at (0,2) {\large \LangVar{}};
  2265. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  2266. \node (Rvar-3) at (6,2) {\large \LangVarANF{}};
  2267. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2268. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  2269. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  2270. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  2271. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  2272. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  2273. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  2274. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvar-3);
  2275. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate-control} (Cvar-2);
  2276. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  2277. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  2278. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  2279. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  2280. \end{tikzpicture}
  2281. \fi}
  2282. {\if\edition\pythonEd\color{purple}
  2283. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2284. \node (Rvar) at (0,2) {\large \LangVar{}};
  2285. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  2286. \node (x86-1) at (3,0) {\large \LangXVar{}};
  2287. \node (x86-2) at (6,0) {\large \LangXVar{}};
  2288. \node (x86-3) at (9,0) {\large \LangXInt{}};
  2289. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2290. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvar-2);
  2291. \path[->,bend right=15] (Rvar-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-1);
  2292. \path[->,bend left=15] (x86-1) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-2);
  2293. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-3);
  2294. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize print-x86} (x86-4);
  2295. \end{tikzpicture}
  2296. \fi}
  2297. \caption{Diagram of the passes for compiling \LangVar{}. }
  2298. \label{fig:Rvar-passes}
  2299. \end{figure}
  2300. Figure~\ref{fig:Rvar-passes} presents the ordering of the compiler
  2301. passes and identifies the input and output language of each pass. The
  2302. last pass, \key{print-x86}, converts from the abstract syntax of
  2303. \LangXInt{} to the concrete syntax.
  2304. %
  2305. \racket{In the following two sections we discuss the \LangCVar{}
  2306. intermediate language and the \LangXVar{} dialect of x86.}
  2307. %
  2308. \python{In the following section we discuss the \LangXVar{} dialect of
  2309. x86.}
  2310. %
  2311. The remainder of this chapter gives hints regarding the implementation
  2312. of each of the compiler passes in Figure~\ref{fig:Rvar-passes}.
  2313. %% The output of \key{uniquify} and \key{remove-complex-opera*}
  2314. %% are programs that are still in the \LangVar{} language, though the
  2315. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2316. %% (Section~\ref{sec:remove-complex-opera-Rvar}).
  2317. %% %
  2318. %% The output of \key{explicate-control} is in an intermediate language
  2319. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2320. %% syntax, which we introduce in the next section. The
  2321. %% \key{select-instruction} pass translates from \LangCVar{} to
  2322. %% \LangXVar{}. The \key{assign-homes} and
  2323. %% \key{patch-instructions}
  2324. %% passes input and output variants of x86 assembly.
  2325. {\if\edition\racketEd\color{olive}
  2326. \subsection{The \LangCVar{} Intermediate Language}
  2327. The output of \key{explicate-control} is similar to the $C$
  2328. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2329. categories for expressions and statements, so we name it \LangCVar{}. The
  2330. abstract syntax for \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  2331. (The concrete syntax for \LangCVar{} is in the Appendix,
  2332. Figure~\ref{fig:c0-concrete-syntax}.)
  2333. %
  2334. The \LangCVar{} language supports the same operators as \LangVar{} but
  2335. the arguments of operators are restricted to atomic
  2336. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2337. assignment statements which can be executed in sequence using the
  2338. \key{Seq} form. A sequence of statements always ends with
  2339. \key{Return}, a guarantee that is baked into the grammar rules for
  2340. \itm{tail}. The naming of this non-terminal comes from the term
  2341. \emph{tail position}\index{subject}{tail position}, which refers to an
  2342. expression that is the last one to execute within a function.
  2343. A \LangCVar{} program consists of a control-flow graph represented as
  2344. an alist mapping labels to tails. This is more general than necessary
  2345. for the present chapter, as we do not yet introduce \key{goto} for
  2346. jumping to labels, but it saves us from having to change the syntax in
  2347. Chapter~\ref{ch:Rif}. For now there will be just one label,
  2348. \key{start}, and the whole program is its tail.
  2349. %
  2350. The $\itm{info}$ field of the \key{CProgram} form, after the
  2351. \key{explicate-control} pass, contains a mapping from the symbol
  2352. \key{locals} to a list of variables, that is, a list of all the
  2353. variables used in the program. At the start of the program, these
  2354. variables are uninitialized; they become initialized on their first
  2355. assignment.
  2356. \begin{figure}[tbp]
  2357. \fbox{
  2358. \begin{minipage}{0.96\textwidth}
  2359. \[
  2360. \begin{array}{lcl}
  2361. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2362. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2363. &\MID& \ADD{\Atm}{\Atm}\\
  2364. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2365. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail} \\
  2366. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2367. \end{array}
  2368. \]
  2369. \end{minipage}
  2370. }
  2371. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2372. \label{fig:c0-syntax}
  2373. \end{figure}
  2374. The definitional interpreter for \LangCVar{} is in the support code,
  2375. in the file \code{interp-Cvar.rkt}.
  2376. \fi}
  2377. \section{The \LangXVar{} dialect}
  2378. The \LangXVar{} language is the output of the pass
  2379. \key{select-instructions}. It extends \LangXInt{} with an unbounded
  2380. number of program-scope variables and removes the restrictions
  2381. regarding instruction arguments.
  2382. {\if\edition\racketEd\color{olive}
  2383. \section{Uniquify Variables}
  2384. \label{sec:uniquify-Rvar}
  2385. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2386. programs in which every \key{let} binds a unique variable name. For
  2387. example, the \code{uniquify} pass should translate the program on the
  2388. left into the program on the right.
  2389. \begin{transformation}
  2390. \begin{lstlisting}
  2391. (let ([x 32])
  2392. (+ (let ([x 10]) x) x))
  2393. \end{lstlisting}
  2394. \compilesto
  2395. \begin{lstlisting}
  2396. (let ([x.1 32])
  2397. (+ (let ([x.2 10]) x.2) x.1))
  2398. \end{lstlisting}
  2399. \end{transformation}
  2400. The following is another example translation, this time of a program
  2401. with a \key{let} nested inside the initializing expression of another
  2402. \key{let}.
  2403. \begin{transformation}
  2404. \begin{lstlisting}
  2405. (let ([x (let ([x 4])
  2406. (+ x 1))])
  2407. (+ x 2))
  2408. \end{lstlisting}
  2409. \compilesto
  2410. \begin{lstlisting}
  2411. (let ([x.2 (let ([x.1 4])
  2412. (+ x.1 1))])
  2413. (+ x.2 2))
  2414. \end{lstlisting}
  2415. \end{transformation}
  2416. We recommend implementing \code{uniquify} by creating a structurally
  2417. recursive function named \code{uniquify-exp} that mostly just copies
  2418. an expression. However, when encountering a \key{let}, it should
  2419. generate a unique name for the variable and associate the old name
  2420. with the new name in an alist.\footnote{The Racket function
  2421. \code{gensym} is handy for generating unique variable names.} The
  2422. \code{uniquify-exp} function needs to access this alist when it gets
  2423. to a variable reference, so we add a parameter to \code{uniquify-exp}
  2424. for the alist.
  2425. The skeleton of the \code{uniquify-exp} function is shown in
  2426. Figure~\ref{fig:uniquify-Rvar}. The function is curried so that it is
  2427. convenient to partially apply it to an alist and then apply it to
  2428. different expressions, as in the last case for primitive operations in
  2429. Figure~\ref{fig:uniquify-Rvar}. The
  2430. %
  2431. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2432. %
  2433. form of Racket is useful for transforming each element of a list to
  2434. produce a new list.\index{subject}{for/list}
  2435. \begin{figure}[tbp]
  2436. \begin{lstlisting}
  2437. (define (uniquify-exp env)
  2438. (lambda (e)
  2439. (match e
  2440. [(Var x) ___]
  2441. [(Int n) (Int n)]
  2442. [(Let x e body) ___]
  2443. [(Prim op es)
  2444. (Prim op (for/list ([e es]) ((uniquify-exp env) e)))])))
  2445. (define (uniquify p)
  2446. (match p
  2447. [(Program '() e) (Program '() ((uniquify-exp '()) e))]))
  2448. \end{lstlisting}
  2449. \caption{Skeleton for the \key{uniquify} pass.}
  2450. \label{fig:uniquify-Rvar}
  2451. \end{figure}
  2452. \begin{exercise}
  2453. \normalfont % I don't like the italics for exercises. -Jeremy
  2454. Complete the \code{uniquify} pass by filling in the blanks in
  2455. Figure~\ref{fig:uniquify-Rvar}, that is, implement the cases for
  2456. variables and for the \key{let} form in the file \code{compiler.rkt}
  2457. in the support code.
  2458. \end{exercise}
  2459. \begin{exercise}
  2460. \normalfont % I don't like the italics for exercises. -Jeremy
  2461. \label{ex:Rvar}
  2462. Create five \LangVar{} programs that exercise the most interesting
  2463. parts of the \key{uniquify} pass, that is, the programs should include
  2464. \key{let} forms, variables, and variables that shadow each other.
  2465. The five programs should be placed in the subdirectory named
  2466. \key{tests} and the file names should start with \code{var\_test\_}
  2467. followed by a unique integer and end with the file extension
  2468. \key{.rkt}.
  2469. %
  2470. The \key{run-tests.rkt} script in the support code checks whether the
  2471. output programs produce the same result as the input programs. The
  2472. script uses the \key{interp-tests} function
  2473. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2474. your \key{uniquify} pass on the example programs. The \code{passes}
  2475. parameter of \key{interp-tests} is a list that should have one entry
  2476. for each pass in your compiler. For now, define \code{passes} to
  2477. contain just one entry for \code{uniquify} as shown below.
  2478. \begin{lstlisting}
  2479. (define passes
  2480. (list (list "uniquify" uniquify interp-Rvar type-check-Rvar)))
  2481. \end{lstlisting}
  2482. Run the \key{run-tests.rkt} script in the support code to check
  2483. whether the output programs produce the same result as the input
  2484. programs.
  2485. \end{exercise}
  2486. \fi}
  2487. \section{Remove Complex Operands}
  2488. \label{sec:remove-complex-opera-Rvar}
  2489. The \code{remove-complex-opera*} pass compiles \LangVar{} programs
  2490. into a restricted form in which the arguments of operations are atomic
  2491. expressions. Put another way, this pass removes complex
  2492. operands\index{subject}{complex operand}, such as the expression \code{(- 10)}
  2493. in the program below. This is accomplished by introducing a new
  2494. \key{let}-bound variable, binding the complex operand to the new
  2495. variable, and then using the new variable in place of the complex
  2496. operand, as shown in the output of \code{remove-complex-opera*} on the
  2497. right.
  2498. {\if\edition\racketEd\color{olive}
  2499. \begin{transformation}
  2500. % var_test_19.rkt
  2501. \begin{lstlisting}
  2502. (let ([x (+ 42 (- 10))])
  2503. (+ x 10))
  2504. \end{lstlisting}
  2505. \compilesto
  2506. \begin{lstlisting}
  2507. (let ([x (let ([tmp.1 (- 10)])
  2508. (+ 42 tmp.1))])
  2509. (+ x 10))
  2510. \end{lstlisting}
  2511. \end{transformation}
  2512. \fi}
  2513. {\if\edition\pythonEd\color{purple}
  2514. \begin{transformation}
  2515. \begin{lstlisting}
  2516. x = 42 + (- 10)
  2517. print(x + 10)
  2518. \end{lstlisting}
  2519. \compilesto
  2520. \begin{lstlisting}
  2521. tmp_0 = - 10
  2522. x = 42 + tmp_0
  2523. tmp_1 = x + 10
  2524. print(tmp_1)
  2525. \end{lstlisting}
  2526. \end{transformation}
  2527. \fi}
  2528. \begin{figure}[tp]
  2529. \centering
  2530. \fbox{
  2531. \begin{minipage}{0.96\textwidth}
  2532. {\if\edition\racketEd\color{olive}
  2533. \[
  2534. \begin{array}{rcl}
  2535. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2536. \Exp &::=& \Atm \MID \READ{} \\
  2537. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \\
  2538. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2539. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  2540. \end{array}
  2541. \]
  2542. \fi}
  2543. {\if\edition\pythonEd\color{purple}
  2544. \[
  2545. \begin{array}{rcl}
  2546. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2547. \Exp{} &::=& \Atm \MID \READ{} \\
  2548. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \\
  2549. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2550. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  2551. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  2552. \end{array}
  2553. \]
  2554. \fi}
  2555. \end{minipage}
  2556. }
  2557. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  2558. atomic expressions, like administrative normal form (ANF).}
  2559. \label{fig:Rvar-anf-syntax}
  2560. \end{figure}
  2561. Figure~\ref{fig:Rvar-anf-syntax} presents the grammar for the output of
  2562. this pass, the language \LangVarANF{}. The only difference is that
  2563. operator arguments are restricted to be atomic expressions that are
  2564. defined by the \Atm{} non-terminal. In particular, integer constants
  2565. and variables are atomic. In the literature, restricting arguments to
  2566. be atomic expressions is one of the ideas in \emph{administrative
  2567. normal form}, or ANF for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2568. \index{subject}{administrative normal form} \index{subject}{ANF}
  2569. \python{UNDER CONSTRUCTION}
  2570. We recommend implementing this pass with two mutually recursive
  2571. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  2572. \code{rco\_atom} to subexpressions that need to become atomic and to
  2573. apply \code{rco\_exp} to subexpressions that do not. Both functions
  2574. take an \LangVar{} expression as input. The \code{rco\_exp} function
  2575. returns an expression. The \code{rco\_atom} function returns two
  2576. things: an atomic expression and an alist mapping temporary variables to
  2577. complex subexpressions. You can return multiple things from a function
  2578. using Racket's \key{values} form and you can receive multiple things
  2579. from a function call using the \key{define-values} form.
  2580. Also, the
  2581. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  2582. form is useful for applying a function to each element of a list, in
  2583. the case where the function returns multiple values.
  2584. \index{subject}{for/lists}
  2585. Returning to the example program with the expression \code{(+ 42 (-
  2586. 10))}, the subexpression \code{(- 10)} should be processed using the
  2587. \code{rco\_atom} function because it is an argument of the \code{+} and
  2588. therefore needs to become atomic. The output of \code{rco\_atom}
  2589. applied to \code{(- 10)} is as follows.
  2590. \begin{transformation}
  2591. \begin{lstlisting}
  2592. (- 10)
  2593. \end{lstlisting}
  2594. \compilesto
  2595. \begin{lstlisting}
  2596. tmp.1
  2597. ((tmp.1 . (- 10)))
  2598. \end{lstlisting}
  2599. \end{transformation}
  2600. Take special care of programs such as the following that bind a
  2601. variable to an atomic expression. You should leave such variable
  2602. bindings unchanged, as shown in the program on the right \\
  2603. \begin{transformation}
  2604. % var_test_20.rkt
  2605. \begin{lstlisting}
  2606. (let ([a 42])
  2607. (let ([b a])
  2608. b))
  2609. \end{lstlisting}
  2610. \compilesto
  2611. \begin{lstlisting}
  2612. (let ([a 42])
  2613. (let ([b a])
  2614. b))
  2615. \end{lstlisting}
  2616. \end{transformation}
  2617. A careless implementation of \key{rco\_exp} and \key{rco\_atom} might
  2618. produce the following output with unnecessary temporary variables.
  2619. \begin{center}
  2620. \begin{minipage}{0.4\textwidth}
  2621. \begin{lstlisting}
  2622. (let ([tmp.1 42])
  2623. (let ([a tmp.1])
  2624. (let ([tmp.2 a])
  2625. (let ([b tmp.2])
  2626. b))))
  2627. \end{lstlisting}
  2628. \end{minipage}
  2629. \end{center}
  2630. \begin{exercise}
  2631. \normalfont
  2632. Implement the \code{remove-complex-opera*} function in
  2633. \code{compiler.rkt}.
  2634. %
  2635. Create three new \LangVar{} programs that exercise the interesting
  2636. code in the \code{remove-complex-opera*} pass. Follow the guidelines
  2637. regarding file names described in Exercise~\ref{ex:Rvar}.
  2638. %
  2639. In the \code{run-tests.rkt} script, add the following entry to the
  2640. list of \code{passes} and then run the script to test your compiler.
  2641. \begin{lstlisting}
  2642. (list "remove-complex" remove-complex-opera* interp-Rvar type-check-Rvar)
  2643. \end{lstlisting}
  2644. While debugging your compiler, it is often useful to see the
  2645. intermediate programs that are output from each pass. To print the
  2646. intermediate programs, place \lstinline{(debug-level 1)} before the call to
  2647. \code{interp-tests} in \code{run-tests.rkt}.
  2648. \end{exercise}
  2649. {\if\edition\racketEd\color{olive}
  2650. \section{Explicate Control}
  2651. \label{sec:explicate-control-Rvar}
  2652. The \code{explicate-control} pass compiles \LangVar{} programs into \LangCVar{}
  2653. programs that make the order of execution explicit in their
  2654. syntax. For now this amounts to flattening \key{let} constructs into a
  2655. sequence of assignment statements. For example, consider the following
  2656. \LangVar{} program.\\
  2657. % var_test_11.rkt
  2658. \begin{minipage}{0.96\textwidth}
  2659. \begin{lstlisting}
  2660. (let ([y (let ([x 20])
  2661. (+ x (let ([x 22]) x)))])
  2662. y)
  2663. \end{lstlisting}
  2664. \end{minipage}\\
  2665. %
  2666. The output of the previous pass and of \code{explicate-control} is
  2667. shown below. Recall that the right-hand-side of a \key{let} executes
  2668. before its body, so the order of evaluation for this program is to
  2669. assign \code{20} to \code{x.1}, \code{22} to \code{x.2}, and
  2670. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  2671. output of \code{explicate-control} makes this ordering explicit.
  2672. \begin{transformation}
  2673. \begin{lstlisting}
  2674. (let ([y (let ([x.1 20])
  2675. (let ([x.2 22])
  2676. (+ x.1 x.2)))])
  2677. y)
  2678. \end{lstlisting}
  2679. \compilesto
  2680. \begin{lstlisting}[language=C]
  2681. start:
  2682. x.1 = 20;
  2683. x.2 = 22;
  2684. y = (+ x.1 x.2);
  2685. return y;
  2686. \end{lstlisting}
  2687. \end{transformation}
  2688. \begin{figure}[tbp]
  2689. \begin{lstlisting}
  2690. (define (explicate-tail e)
  2691. (match e
  2692. [(Var x) ___]
  2693. [(Int n) (Return (Int n))]
  2694. [(Let x rhs body) ___]
  2695. [(Prim op es) ___]
  2696. [else (error "explicate-tail unhandled case" e)]))
  2697. (define (explicate-assign e x cont)
  2698. (match e
  2699. [(Var x) ___]
  2700. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  2701. [(Let y rhs body) ___]
  2702. [(Prim op es) ___]
  2703. [else (error "explicate-assign unhandled case" e)]))
  2704. (define (explicate-control p)
  2705. (match p
  2706. [(Program info body) ___]))
  2707. \end{lstlisting}
  2708. \caption{Skeleton for the \key{explicate-control} pass.}
  2709. \label{fig:explicate-control-Rvar}
  2710. \end{figure}
  2711. The organization of this pass depends on the notion of tail position
  2712. that we have alluded to earlier.
  2713. \begin{definition}
  2714. The following rules define when an expression is in \textbf{\emph{tail
  2715. position}}\index{subject}{tail position} for the language \LangVar{}.
  2716. \begin{enumerate}
  2717. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  2718. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  2719. \end{enumerate}
  2720. \end{definition}
  2721. We recommend implementing \code{explicate-control} using two mutually
  2722. recursive functions, \code{explicate-tail} and
  2723. \code{explicate-assign}, as suggested in the skeleton code in
  2724. Figure~\ref{fig:explicate-control-Rvar}. The \code{explicate-tail}
  2725. function should be applied to expressions in tail position whereas the
  2726. \code{explicate-assign} should be applied to expressions that occur on
  2727. the right-hand-side of a \key{let}.
  2728. %
  2729. The \code{explicate-tail} function takes an \Exp{} in \LangVar{} as
  2730. input and produces a \Tail{} in \LangCVar{} (see
  2731. Figure~\ref{fig:c0-syntax}).
  2732. %
  2733. The \code{explicate-assign} function takes an \Exp{} in \LangVar{},
  2734. the variable that it is to be assigned to, and a \Tail{} in
  2735. \LangCVar{} for the code that comes after the assignment. The
  2736. \code{explicate-assign} function returns a $\Tail$ in \LangCVar{}.
  2737. The \code{explicate-assign} function is in accumulator-passing style:
  2738. the \code{cont} parameter is used for accumulating the output. This
  2739. accumulator-passing style plays an important role in how we generate
  2740. high-quality code for conditional expressions in Chapter~\ref{ch:Rif}.
  2741. \begin{exercise}\normalfont
  2742. %
  2743. Implement the \code{explicate-control} function in
  2744. \code{compiler.rkt}. Create three new \LangInt{} programs that
  2745. exercise the code in \code{explicate-control}.
  2746. %
  2747. In the \code{run-tests.rkt} script, add the following entry to the
  2748. list of \code{passes} and then run the script to test your compiler.
  2749. \begin{lstlisting}
  2750. (list "explicate control" explicate-control interp-Cvar type-check-Cvar)
  2751. \end{lstlisting}
  2752. \end{exercise}
  2753. \fi}
  2754. \section{Select Instructions}
  2755. \label{sec:select-Rvar}
  2756. \index{subject}{instruction selection}
  2757. In the \code{select-instructions} pass we begin the work of
  2758. translating from \LangCVar{} to \LangXVar{}. The target language of
  2759. this pass is a variant of x86 that still uses variables, so we add an
  2760. AST node of the form $\VAR{\itm{var}}$ to the \Arg{} non-terminal of
  2761. the \LangXInt{} abstract syntax (Figure~\ref{fig:x86-int-ast}). We
  2762. recommend implementing the \code{select-instructions} with
  2763. three auxiliary functions, one for each of the non-terminals of
  2764. \LangCVar{}: $\Atm$, $\Stmt$, and $\Tail$.
  2765. The cases for $\Atm$ are straightforward; variables stay
  2766. the same and integer constants are changed to immediates:
  2767. $\INT{n}$ changes to $\IMM{n}$.
  2768. Next we consider the cases for $\Stmt$, starting with arithmetic
  2769. operations. For example, consider the addition operation. We can use
  2770. the \key{addq} instruction, but it performs an in-place update. So we
  2771. could move $\itm{arg}_1$ into the left-hand side \itm{var} and then
  2772. add $\itm{arg}_2$ to \itm{var}.
  2773. \begin{transformation}
  2774. \begin{lstlisting}
  2775. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{arg}_2$|);
  2776. \end{lstlisting}
  2777. \compilesto
  2778. \begin{lstlisting}
  2779. movq |$\itm{arg}_1$|, |$\itm{var}$|
  2780. addq |$\itm{arg}_2$|, |$\itm{var}$|
  2781. \end{lstlisting}
  2782. \end{transformation}
  2783. There are also cases that require special care to avoid generating
  2784. needlessly complicated code. For example, if one of the arguments of
  2785. the addition is the same variable as the left-hand side of the
  2786. assignment, then there is no need for the extra move instruction. The
  2787. assignment statement can be translated into a single \key{addq}
  2788. instruction as follows.
  2789. \begin{transformation}
  2790. \begin{lstlisting}
  2791. |$\itm{var}$| = (+ |$\itm{arg}_1$| |$\itm{var}$|);
  2792. \end{lstlisting}
  2793. \compilesto
  2794. \begin{lstlisting}
  2795. addq |$\itm{arg}_1$|, |$\itm{var}$|
  2796. \end{lstlisting}
  2797. \end{transformation}
  2798. The \key{read} operation does not have a direct counterpart in x86
  2799. assembly, so we provide this functionality with the function
  2800. \code{read\_int} in the file \code{runtime.c}, written in
  2801. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  2802. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  2803. system}, or simply the \emph{runtime} for short. When compiling your
  2804. generated x86 assembly code, you need to compile \code{runtime.c} to
  2805. \code{runtime.o} (an ``object file'', using \code{gcc} option
  2806. \code{-c}) and link it into the executable. For our purposes of code
  2807. generation, all you need to do is translate an assignment of
  2808. \key{read} into a call to the \code{read\_int} function followed by a
  2809. move from \code{rax} to the left-hand-side variable. (Recall that the
  2810. return value of a function goes into \code{rax}.)
  2811. \begin{transformation}
  2812. \begin{lstlisting}
  2813. |$\itm{var}$| = (read);
  2814. \end{lstlisting}
  2815. \compilesto
  2816. \begin{lstlisting}
  2817. callq read_int
  2818. movq %rax, |$\itm{var}$|
  2819. \end{lstlisting}
  2820. \end{transformation}
  2821. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  2822. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  2823. assignment to the \key{rax} register followed by a jump to the
  2824. conclusion of the program (so the conclusion needs to be labeled).
  2825. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  2826. recursively and then append the resulting instructions.
  2827. \begin{exercise}
  2828. \normalfont Implement the \key{select-instructions} pass in
  2829. \code{compiler.rkt}. Create three new example programs that are
  2830. designed to exercise all of the interesting cases in this pass.
  2831. %
  2832. In the \code{run-tests.rkt} script, add the following entry to the
  2833. list of \code{passes} and then run the script to test your compiler.
  2834. \begin{lstlisting}
  2835. (list "instruction selection" select-instructions interp-pseudo-x86-0)
  2836. \end{lstlisting}
  2837. \end{exercise}
  2838. \section{Assign Homes}
  2839. \label{sec:assign-Rvar}
  2840. The \key{assign-homes} pass compiles \LangXVar{} programs to
  2841. \LangXVar{} programs that no longer use program variables.
  2842. Thus, the \key{assign-homes} pass is responsible for placing all of
  2843. the program variables in registers or on the stack. For runtime
  2844. efficiency, it is better to place variables in registers, but as there
  2845. are only 16 registers, some programs must necessarily resort to
  2846. placing some variables on the stack. In this chapter we focus on the
  2847. mechanics of placing variables on the stack. We study an algorithm for
  2848. placing variables in registers in
  2849. Chapter~\ref{ch:register-allocation-Rvar}.
  2850. Consider again the following \LangVar{} program from
  2851. Section~\ref{sec:remove-complex-opera-Rvar}.
  2852. % var_test_20.rkt
  2853. \begin{lstlisting}
  2854. (let ([a 42])
  2855. (let ([b a])
  2856. b))
  2857. \end{lstlisting}
  2858. The output of \code{select-instructions} is shown on the left and the
  2859. output of \code{assign-homes} on the right. In this example, we
  2860. assign variable \code{a} to stack location \code{-8(\%rbp)} and
  2861. variable \code{b} to location \code{-16(\%rbp)}.
  2862. \begin{transformation}
  2863. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2864. locals-types:
  2865. a : Integer, b : Integer
  2866. start:
  2867. movq $42, a
  2868. movq a, b
  2869. movq b, %rax
  2870. jmp conclusion
  2871. \end{lstlisting}
  2872. \compilesto
  2873. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2874. stack-space: 16
  2875. start:
  2876. movq $42, -8(%rbp)
  2877. movq -8(%rbp), -16(%rbp)
  2878. movq -16(%rbp), %rax
  2879. jmp conclusion
  2880. \end{lstlisting}
  2881. \end{transformation}
  2882. The \code{locals-types} entry in the $\itm{info}$ of the
  2883. \code{X86Program} node is an alist mapping all the variables in the
  2884. program to their types (for now just \code{Integer}). The
  2885. \code{assign-homes} pass should replace all uses of those variables
  2886. with stack locations. As an aside, the \code{locals-types} entry is
  2887. computed by \code{type-check-Cvar} in the support code, which installs
  2888. it in the $\itm{info}$ field of the \code{CProgram} node, which should
  2889. be propagated to the \code{X86Program} node.
  2890. In the process of assigning variables to stack locations, it is
  2891. convenient for you to compute and store the size of the frame (in
  2892. bytes) in the $\itm{info}$ field of the \key{X86Program} node, with
  2893. the key \code{stack-space}, which is needed later to generate the
  2894. conclusion of the \code{main} procedure. The x86-64 standard requires
  2895. the frame size to be a multiple of 16 bytes.\index{subject}{frame}
  2896. \begin{exercise}\normalfont
  2897. Implement the \key{assign-homes} pass in \code{compiler.rkt}, defining
  2898. auxiliary functions for the non-terminals \Arg{}, \Instr{}, and
  2899. \Block{}. We recommend that the auxiliary functions take an extra
  2900. parameter that is an alist mapping variable names to homes (stack
  2901. locations for now).
  2902. %
  2903. In the \code{run-tests.rkt} script, add the following entry to the
  2904. list of \code{passes} and then run the script to test your compiler.
  2905. \begin{lstlisting}
  2906. (list "assign homes" assign-homes interp-x86-0)
  2907. \end{lstlisting}
  2908. \end{exercise}
  2909. \section{Patch Instructions}
  2910. \label{sec:patch-s0}
  2911. The \code{patch-instructions} pass compiles from \LangXVar{} to
  2912. \LangXInt{} by making sure that each instruction adheres to the
  2913. restriction that at most one argument of an instruction may be a
  2914. memory reference.
  2915. We return to the following example.\\
  2916. \begin{minipage}{0.5\textwidth}
  2917. % var_test_20.rkt
  2918. \begin{lstlisting}
  2919. (let ([a 42])
  2920. (let ([b a])
  2921. b))
  2922. \end{lstlisting}
  2923. \end{minipage}\\
  2924. The \key{assign-homes} pass produces the following output
  2925. for this program. \\
  2926. \begin{minipage}{0.5\textwidth}
  2927. \begin{lstlisting}
  2928. stack-space: 16
  2929. start:
  2930. movq $42, -8(%rbp)
  2931. movq -8(%rbp), -16(%rbp)
  2932. movq -16(%rbp), %rax
  2933. jmp conclusion
  2934. \end{lstlisting}
  2935. \end{minipage}\\
  2936. The second \key{movq} instruction is problematic because both
  2937. arguments are stack locations. We suggest fixing this problem by
  2938. moving from the source location to the register \key{rax} and then
  2939. from \key{rax} to the destination location, as follows.
  2940. \begin{lstlisting}
  2941. movq -8(%rbp), %rax
  2942. movq %rax, -16(%rbp)
  2943. \end{lstlisting}
  2944. \begin{exercise}
  2945. \normalfont Implement the \key{patch-instructions} pass in
  2946. \code{compiler.rkt}. Create three new example programs that are
  2947. designed to exercise all of the interesting cases in this pass.
  2948. %
  2949. In the \code{run-tests.rkt} script, add the following entry to the
  2950. list of \code{passes} and then run the script to test your compiler.
  2951. \begin{lstlisting}
  2952. (list "patch instructions" patch-instructions interp-x86-0)
  2953. \end{lstlisting}
  2954. \end{exercise}
  2955. \section{Print x86}
  2956. \label{sec:print-x86}
  2957. The last step of the compiler from \LangVar{} to x86 is to convert the
  2958. \LangXInt{} AST (defined in Figure~\ref{fig:x86-int-ast}) to the
  2959. string representation (defined in
  2960. Figure~\ref{fig:x86-int-concrete}). The Racket \key{format} and
  2961. \key{string-append} functions are useful in this regard. The main work
  2962. that this step needs to perform is to create the \key{main} function
  2963. and the standard instructions for its prelude and conclusion, as shown
  2964. in Figure~\ref{fig:p1-x86} of Section~\ref{sec:x86}. You will need to
  2965. know the amount of space needed for the stack frame, which you can
  2966. obtain from the \code{stack-space} entry in the $\itm{info}$ field of
  2967. the \key{X86Program} node.
  2968. When running on Mac OS X, you compiler should prefix an underscore to
  2969. labels like \key{main}. The Racket call \code{(system-type 'os)} is
  2970. useful for determining which operating system the compiler is running
  2971. on. It returns \code{'macosx}, \code{'unix}, or \code{'windows}.
  2972. \begin{exercise}\normalfont
  2973. %
  2974. Implement the \key{print-x86} pass in \code{compiler.rkt}.
  2975. %
  2976. In the \code{run-tests.rkt} script, add the following entry to the
  2977. list of \code{passes} and then run the script to test your compiler.
  2978. \begin{lstlisting}
  2979. (list "print x86" print-x86 #f)
  2980. \end{lstlisting}
  2981. %
  2982. Uncomment the call to the \key{compiler-tests} function
  2983. (Appendix~\ref{appendix:utilities}), which tests your complete
  2984. compiler by executing the generated x86 code. Compile the provided
  2985. \key{runtime.c} file to \key{runtime.o} using \key{gcc}. Run the
  2986. script to test your compiler.
  2987. \end{exercise}
  2988. \section{Challenge: Partial Evaluator for \LangVar{}}
  2989. \label{sec:pe-Rvar}
  2990. \index{subject}{partial evaluation}
  2991. This section describes optional challenge exercises that involve
  2992. adapting and improving the partial evaluator for \LangInt{} that was
  2993. introduced in Section~\ref{sec:partial-evaluation}.
  2994. \begin{exercise}\label{ex:pe-Rvar}
  2995. \normalfont
  2996. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2997. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  2998. instead of \LangInt{} programs. Recall that \LangVar{} adds \key{let} binding
  2999. and variables to the \LangInt{} language, so you will need to add cases for
  3000. them in the \code{pe\_exp} function. Once complete, add the partial
  3001. evaluation pass to the front of your compiler and make sure that your
  3002. compiler still passes all of the tests.
  3003. \end{exercise}
  3004. The next exercise builds on Exercise~\ref{ex:pe-Rvar}.
  3005. \begin{exercise}
  3006. \normalfont
  3007. Improve on the partial evaluator by replacing the \code{pe-neg} and
  3008. \code{pe-add} auxiliary functions with functions that know more about
  3009. arithmetic. For example, your partial evaluator should translate
  3010. \[
  3011. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3012. \code{(+ 2 (read))}
  3013. \]
  3014. To accomplish this, the \code{pe\_exp} function should produce output
  3015. in the form of the $\itm{residual}$ non-terminal of the following
  3016. grammar. The idea is that when processing an addition expression, we
  3017. can always produce either 1) an integer constant, 2) an addition
  3018. expression with an integer constant on the left-hand side but not the
  3019. right-hand side, or 3) or an addition expression in which neither
  3020. subexpression is a constant.
  3021. \[
  3022. \begin{array}{lcl}
  3023. \itm{inert} &::=& \Var
  3024. \MID \LP\key{read}\RP
  3025. \MID \LP\key{-} ~\Var\RP
  3026. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3027. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3028. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3029. \itm{residual} &::=& \Int
  3030. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3031. \MID \itm{inert}
  3032. \end{array}
  3033. \]
  3034. The \code{pe-add} and \code{pe-neg} functions may assume that their
  3035. inputs are $\itm{residual}$ expressions and they should return
  3036. $\itm{residual}$ expressions. Once the improvements are complete,
  3037. make sure that your compiler still passes all of the tests. After
  3038. all, fast code is useless if it produces incorrect results!
  3039. \end{exercise}
  3040. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3041. \chapter{Register Allocation}
  3042. \label{ch:register-allocation-Rvar}
  3043. \index{subject}{register allocation}
  3044. In Chapter~\ref{ch:Rvar} we learned how to store variables on the
  3045. stack. In this Chapter we learn how to improve the performance of the
  3046. generated code by placing some variables into registers. The CPU can
  3047. access a register in a single cycle, whereas accessing the stack can
  3048. take 10s to 100s of cycles. The program in Figure~\ref{fig:reg-eg}
  3049. serves as a running example. The source program is on the left and the
  3050. output of instruction selection is on the right. The program is almost
  3051. in the x86 assembly language but it still uses variables.
  3052. \begin{figure}
  3053. \begin{minipage}{0.45\textwidth}
  3054. Example \LangVar{} program:
  3055. % var_test_28.rkt
  3056. \begin{lstlisting}
  3057. (let ([v 1])
  3058. (let ([w 42])
  3059. (let ([x (+ v 7)])
  3060. (let ([y x])
  3061. (let ([z (+ x w)])
  3062. (+ z (- y)))))))
  3063. \end{lstlisting}
  3064. \end{minipage}
  3065. \begin{minipage}{0.45\textwidth}
  3066. After instruction selection:
  3067. \begin{lstlisting}
  3068. locals-types:
  3069. x : Integer, y : Integer,
  3070. z : Integer, t : Integer,
  3071. v : Integer, w : Integer
  3072. start:
  3073. movq $1, v
  3074. movq $42, w
  3075. movq v, x
  3076. addq $7, x
  3077. movq x, y
  3078. movq x, z
  3079. addq w, z
  3080. movq y, t
  3081. negq t
  3082. movq z, %rax
  3083. addq t, %rax
  3084. jmp conclusion
  3085. \end{lstlisting}
  3086. \end{minipage}
  3087. \caption{A running example for register allocation.}
  3088. \label{fig:reg-eg}
  3089. \end{figure}
  3090. The goal of register allocation is to fit as many variables into
  3091. registers as possible. Some programs have more variables than
  3092. registers so we cannot always map each variable to a different
  3093. register. Fortunately, it is common for different variables to be
  3094. needed during different periods of time during program execution, and
  3095. in such cases several variables can be mapped to the same register.
  3096. Consider variables \code{x} and \code{z} in Figure~\ref{fig:reg-eg}.
  3097. After the variable \code{x} is moved to \code{z} it is no longer
  3098. needed. Variable \code{z}, on the other hand, is used only after this
  3099. point, so \code{x} and \code{z} could share the same register. The
  3100. topic of Section~\ref{sec:liveness-analysis-Rvar} is how to compute
  3101. where a variable is needed. Once we have that information, we compute
  3102. which variables are needed at the same time, i.e., which ones
  3103. \emph{interfere} with each other, and represent this relation as an
  3104. undirected graph whose vertices are variables and edges indicate when
  3105. two variables interfere (Section~\ref{sec:build-interference}). We
  3106. then model register allocation as a graph coloring problem
  3107. (Section~\ref{sec:graph-coloring}).
  3108. If we run out of registers despite these efforts, we place the
  3109. remaining variables on the stack, similar to what we did in
  3110. Chapter~\ref{ch:Rvar}. It is common to use the verb \emph{spill}
  3111. for assigning a variable to a stack location. The decision to spill a
  3112. variable is handled as part of the graph coloring process
  3113. (Section~\ref{sec:graph-coloring}).
  3114. We make the simplifying assumption that each variable is assigned to
  3115. one location (a register or stack address). A more sophisticated
  3116. approach is to assign a variable to one or more locations in different
  3117. regions of the program. For example, if a variable is used many times
  3118. in short sequence and then only used again after many other
  3119. instructions, it could be more efficient to assign the variable to a
  3120. register during the initial sequence and then move it to the stack for
  3121. the rest of its lifetime. We refer the interested reader to
  3122. \citet{Cooper:2011aa} for more information about that approach.
  3123. % discuss prioritizing variables based on how much they are used.
  3124. \section{Registers and Calling Conventions}
  3125. \label{sec:calling-conventions}
  3126. \index{subject}{calling conventions}
  3127. As we perform register allocation, we need to be aware of the
  3128. \emph{calling conventions} \index{subject}{calling conventions} that govern how
  3129. functions calls are performed in x86.
  3130. %
  3131. Even though \LangVar{} does not include programmer-defined functions,
  3132. our generated code includes a \code{main} function that is called by
  3133. the operating system and our generated code contains calls to the
  3134. \code{read\_int} function.
  3135. Function calls require coordination between two pieces of code that
  3136. may be written by different programmers or generated by different
  3137. compilers. Here we follow the System V calling conventions that are
  3138. used by the GNU C compiler on Linux and
  3139. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  3140. %
  3141. The calling conventions include rules about how functions share the
  3142. use of registers. In particular, the caller is responsible for freeing
  3143. up some registers prior to the function call for use by the callee.
  3144. These are called the \emph{caller-saved registers}
  3145. \index{subject}{caller-saved registers}
  3146. and they are
  3147. \begin{lstlisting}
  3148. rax rcx rdx rsi rdi r8 r9 r10 r11
  3149. \end{lstlisting}
  3150. On the other hand, the callee is responsible for preserving the values
  3151. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  3152. which are
  3153. \begin{lstlisting}
  3154. rsp rbp rbx r12 r13 r14 r15
  3155. \end{lstlisting}
  3156. We can think about this caller/callee convention from two points of
  3157. view, the caller view and the callee view:
  3158. \begin{itemize}
  3159. \item The caller should assume that all the caller-saved registers get
  3160. overwritten with arbitrary values by the callee. On the other hand,
  3161. the caller can safely assume that all the callee-saved registers
  3162. contain the same values after the call that they did before the
  3163. call.
  3164. \item The callee can freely use any of the caller-saved registers.
  3165. However, if the callee wants to use a callee-saved register, the
  3166. callee must arrange to put the original value back in the register
  3167. prior to returning to the caller. This can be accomplished by saving
  3168. the value to the stack in the prelude of the function and restoring
  3169. the value in the conclusion of the function.
  3170. \end{itemize}
  3171. In x86, registers are also used for passing arguments to a function
  3172. and for the return value. In particular, the first six arguments to a
  3173. function are passed in the following six registers, in this order.
  3174. \begin{lstlisting}
  3175. rdi rsi rdx rcx r8 r9
  3176. \end{lstlisting}
  3177. If there are more than six arguments, then the convention is to use
  3178. space on the frame of the caller for the rest of the
  3179. arguments. However, in Chapter~\ref{ch:Rfun} we arrange never to
  3180. need more than six arguments. For now, the only function we care about
  3181. is \code{read\_int} and it takes zero arguments.
  3182. %
  3183. The register \code{rax} is used for the return value of a function.
  3184. The next question is how these calling conventions impact register
  3185. allocation. Consider the \LangVar{} program in
  3186. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  3187. example from the caller point of view and then from the callee point
  3188. of view.
  3189. The program makes two calls to the \code{read} function. Also, the
  3190. variable \code{x} is in use during the second call to \code{read}, so
  3191. we need to make sure that the value in \code{x} does not get
  3192. accidentally wiped out by the call to \code{read}. One obvious
  3193. approach is to save all the values in caller-saved registers to the
  3194. stack prior to each function call, and restore them after each
  3195. call. That way, if the register allocator chooses to assign \code{x}
  3196. to a caller-saved register, its value will be preserved across the
  3197. call to \code{read}. However, saving and restoring to the stack is
  3198. relatively slow. If \code{x} is not used many times, it may be better
  3199. to assign \code{x} to a stack location in the first place. Or better
  3200. yet, if we can arrange for \code{x} to be placed in a callee-saved
  3201. register, then it won't need to be saved and restored during function
  3202. calls.
  3203. The approach that we recommend for variables that are in use during a
  3204. function call is to either assign them to callee-saved registers or to
  3205. spill them to the stack. On the other hand, for variables that are not
  3206. in use during a function call, we try the following alternatives in
  3207. order 1) look for an available caller-saved register (to leave room
  3208. for other variables in the callee-saved register), 2) look for a
  3209. callee-saved register, and 3) spill the variable to the stack.
  3210. It is straightforward to implement this approach in a graph coloring
  3211. register allocator. First, we know which variables are in use during
  3212. every function call because we compute that information for every
  3213. instruction (Section~\ref{sec:liveness-analysis-Rvar}). Second, when we
  3214. build the interference graph (Section~\ref{sec:build-interference}),
  3215. we can place an edge between each of these variables and the
  3216. caller-saved registers in the interference graph. This will prevent
  3217. the graph coloring algorithm from assigning those variables to
  3218. caller-saved registers.
  3219. Returning to the example in
  3220. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  3221. generated x86 code on the right-hand side, focusing on the
  3222. \code{start} block. Notice that variable \code{x} is assigned to
  3223. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  3224. place during the second call to \code{read\_int}. Next, notice that
  3225. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  3226. because there are no function calls in the remainder of the block.
  3227. Next we analyze the example from the callee point of view, focusing on
  3228. the prelude and conclusion of the \code{main} function. As usual the
  3229. prelude begins with saving the \code{rbp} register to the stack and
  3230. setting the \code{rbp} to the current stack pointer. We now know why
  3231. it is necessary to save the \code{rbp}: it is a callee-saved register.
  3232. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  3233. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  3234. (\code{x}). The other callee-saved registers are not saved in the
  3235. prelude because they are not used. The prelude subtracts 8 bytes from
  3236. the \code{rsp} to make it 16-byte aligned and then jumps to the
  3237. \code{start} block. Shifting attention to the \code{conclusion}, we
  3238. see that \code{rbx} is restored from the stack with a \code{popq}
  3239. instruction. \index{subject}{prelude}\index{subject}{conclusion}
  3240. \begin{figure}[tp]
  3241. \begin{minipage}{0.45\textwidth}
  3242. Example \LangVar{} program:
  3243. %var_test_14.rkt
  3244. \begin{lstlisting}
  3245. (let ([x (read)])
  3246. (let ([y (read)])
  3247. (+ (+ x y) 42)))
  3248. \end{lstlisting}
  3249. \end{minipage}
  3250. \begin{minipage}{0.45\textwidth}
  3251. Generated x86 assembly:
  3252. \begin{lstlisting}
  3253. start:
  3254. callq read_int
  3255. movq %rax, %rbx
  3256. callq read_int
  3257. movq %rax, %rcx
  3258. addq %rcx, %rbx
  3259. movq %rbx, %rax
  3260. addq $42, %rax
  3261. jmp _conclusion
  3262. .globl main
  3263. main:
  3264. pushq %rbp
  3265. movq %rsp, %rbp
  3266. pushq %rbx
  3267. subq $8, %rsp
  3268. jmp start
  3269. conclusion:
  3270. addq $8, %rsp
  3271. popq %rbx
  3272. popq %rbp
  3273. retq
  3274. \end{lstlisting}
  3275. \end{minipage}
  3276. \caption{An example with function calls.}
  3277. \label{fig:example-calling-conventions}
  3278. \end{figure}
  3279. %\clearpage
  3280. \section{Liveness Analysis}
  3281. \label{sec:liveness-analysis-Rvar}
  3282. \index{subject}{liveness analysis}
  3283. The \code{uncover-live} pass performs \emph{liveness analysis}, that
  3284. is, it discovers which variables are in-use in different regions of a
  3285. program.
  3286. %
  3287. A variable or register is \emph{live} at a program point if its
  3288. current value is used at some later point in the program. We
  3289. refer to variables and registers collectively as \emph{locations}.
  3290. %
  3291. Consider the following code fragment in which there are two writes to
  3292. \code{b}. Are \code{a} and \code{b} both live at the same time?
  3293. \begin{center}
  3294. \begin{minipage}{0.96\textwidth}
  3295. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  3296. movq $5, a
  3297. movq $30, b
  3298. movq a, c
  3299. movq $10, b
  3300. addq b, c
  3301. \end{lstlisting}
  3302. \end{minipage}
  3303. \end{center}
  3304. The answer is no because \code{a} is live from line 1 to 3 and
  3305. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  3306. line 2 is never used because it is overwritten (line 4) before the
  3307. next read (line 5).
  3308. The live locations can be computed by traversing the instruction
  3309. sequence back to front (i.e., backwards in execution order). Let
  3310. $I_1,\ldots, I_n$ be the instruction sequence. We write
  3311. $L_{\mathsf{after}}(k)$ for the set of live locations after
  3312. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  3313. locations before instruction $I_k$. We recommend represeting these
  3314. sets with the Racket \code{set} data structure described in
  3315. Figure~\ref{fig:set}.
  3316. \begin{figure}[tp]
  3317. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  3318. \small
  3319. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  3320. A \emph{set} is an unordered collection of elements without duplicates.
  3321. Here are some of the operations defined on sets.
  3322. \index{subject}{set}
  3323. \begin{description}
  3324. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  3325. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  3326. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  3327. difference of the two sets.
  3328. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  3329. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  3330. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  3331. \end{description}
  3332. \end{tcolorbox}
  3333. %\end{wrapfigure}
  3334. \caption{The \code{set} data structure.}
  3335. \label{fig:set}
  3336. \end{figure}
  3337. The live locations after an instruction are always the same as the
  3338. live locations before the next instruction.
  3339. \index{subject}{live-after} \index{subject}{live-before}
  3340. \begin{equation} \label{eq:live-after-before-next}
  3341. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  3342. \end{equation}
  3343. To start things off, there are no live locations after the last
  3344. instruction, so
  3345. \begin{equation}\label{eq:live-last-empty}
  3346. L_{\mathsf{after}}(n) = \emptyset
  3347. \end{equation}
  3348. We then apply the following rule repeatedly, traversing the
  3349. instruction sequence back to front.
  3350. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  3351. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  3352. \end{equation}
  3353. where $W(k)$ are the locations written to by instruction $I_k$ and
  3354. $R(k)$ are the locations read by instruction $I_k$.
  3355. There is a special case for \code{jmp} instructions. The locations
  3356. that are live before a \code{jmp} should be the locations in
  3357. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  3358. maintaining an alist named \code{label->live} that maps each label to
  3359. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  3360. now the only \code{jmp} in a \LangXVar{} program is the one at the
  3361. end, to the conclusion. (For example, see Figure~\ref{fig:reg-eg}.)
  3362. The conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should
  3363. map \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  3364. Let us walk through the above example, applying these formulas
  3365. starting with the instruction on line 5. We collect the answers in
  3366. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  3367. \code{addq b, c} instruction is $\emptyset$ because it is the last
  3368. instruction (formula~\ref{eq:live-last-empty}). The
  3369. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  3370. because it reads from variables \code{b} and \code{c}
  3371. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  3372. \[
  3373. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  3374. \]
  3375. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  3376. the live-before set from line 5 to be the live-after set for this
  3377. instruction (formula~\ref{eq:live-after-before-next}).
  3378. \[
  3379. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  3380. \]
  3381. This move instruction writes to \code{b} and does not read from any
  3382. variables, so we have the following live-before set
  3383. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  3384. \[
  3385. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  3386. \]
  3387. The live-before for instruction \code{movq a, c}
  3388. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  3389. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  3390. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  3391. variable that is not live and does not read from a variable.
  3392. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  3393. because it writes to variable \code{a}.
  3394. \begin{figure}[tbp]
  3395. \begin{minipage}{0.45\textwidth}
  3396. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  3397. movq $5, a
  3398. movq $30, b
  3399. movq a, c
  3400. movq $10, b
  3401. addq b, c
  3402. \end{lstlisting}
  3403. \end{minipage}
  3404. \vrule\hspace{10pt}
  3405. \begin{minipage}{0.45\textwidth}
  3406. \begin{align*}
  3407. L_{\mathsf{before}}(1)= \emptyset,
  3408. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  3409. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  3410. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  3411. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  3412. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  3413. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  3414. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  3415. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  3416. L_{\mathsf{after}}(5)= \emptyset
  3417. \end{align*}
  3418. \end{minipage}
  3419. \caption{Example output of liveness analysis on a short example.}
  3420. \label{fig:liveness-example-0}
  3421. \end{figure}
  3422. \begin{exercise}\normalfont
  3423. Perform liveness analysis on the running example in
  3424. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  3425. sets for each instruction. Compare your answers to the solution
  3426. shown in Figure~\ref{fig:live-eg}.
  3427. \end{exercise}
  3428. \begin{figure}[tp]
  3429. \hspace{20pt}
  3430. \begin{minipage}{0.45\textwidth}
  3431. \begin{lstlisting}
  3432. |$\{\ttm{rsp}\}$|
  3433. movq $1, v
  3434. |$\{\ttm{v},\ttm{rsp}\}$|
  3435. movq $42, w
  3436. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  3437. movq v, x
  3438. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  3439. addq $7, x
  3440. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  3441. movq x, y
  3442. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  3443. movq x, z
  3444. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  3445. addq w, z
  3446. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  3447. movq y, t
  3448. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  3449. negq t
  3450. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  3451. movq z, %rax
  3452. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  3453. addq t, %rax
  3454. |$\{\ttm{rax},\ttm{rsp}\}$|
  3455. jmp conclusion
  3456. \end{lstlisting}
  3457. \end{minipage}
  3458. \caption{The running example annotated with live-after sets.}
  3459. \label{fig:live-eg}
  3460. \end{figure}
  3461. \begin{exercise}\normalfont
  3462. Implement the \code{uncover-live} pass. Store the sequence of
  3463. live-after sets in the $\itm{info}$ field of the \code{Block}
  3464. structure.
  3465. %
  3466. We recommend creating an auxiliary function that takes a list of
  3467. instructions and an initial live-after set (typically empty) and
  3468. returns the list of live-after sets.
  3469. %
  3470. We also recommend creating auxiliary functions to 1) compute the set
  3471. of locations that appear in an \Arg{}, 2) compute the locations read
  3472. by an instruction (the $R$ function), and 3) the locations written by
  3473. an instruction (the $W$ function). The \code{callq} instruction should
  3474. include all of the caller-saved registers in its write-set $W$ because
  3475. the calling convention says that those registers may be written to
  3476. during the function call. Likewise, the \code{callq} instruction
  3477. should include the appropriate argument-passing registers in its
  3478. read-set $R$, depending on the arity of the function being
  3479. called. (This is why the abstract syntax for \code{callq} includes the
  3480. arity.)
  3481. \end{exercise}
  3482. %\clearpage
  3483. \section{Build the Interference Graph}
  3484. \label{sec:build-interference}
  3485. \begin{figure}[tp]
  3486. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  3487. \small
  3488. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  3489. A \emph{graph} is a collection of vertices and edges where each
  3490. edge connects two vertices. A graph is \emph{directed} if each
  3491. edge points from a source to a target. Otherwise the graph is
  3492. \emph{undirected}.
  3493. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  3494. \begin{description}
  3495. %% We currently don't use directed graphs. We instead use
  3496. %% directed multi-graphs. -Jeremy
  3497. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  3498. directed graph from a list of edges. Each edge is a list
  3499. containing the source and target vertex.
  3500. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  3501. undirected graph from a list of edges. Each edge is represented by
  3502. a list containing two vertices.
  3503. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  3504. inserts a vertex into the graph.
  3505. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  3506. inserts an edge between the two vertices.
  3507. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  3508. returns a sequence of vertices adjacent to the vertex.
  3509. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  3510. returns a sequence of all vertices in the graph.
  3511. \end{description}
  3512. \end{tcolorbox}
  3513. %\end{wrapfigure}
  3514. \caption{The Racket \code{graph} package.}
  3515. \label{fig:graph}
  3516. \end{figure}
  3517. Based on the liveness analysis, we know where each location is live.
  3518. However, during register allocation, we need to answer questions of
  3519. the specific form: are locations $u$ and $v$ live at the same time?
  3520. (And therefore cannot be assigned to the same register.) To make this
  3521. question more efficient to answer, we create an explicit data
  3522. structure, an \emph{interference graph}\index{subject}{interference
  3523. graph}. An interference graph is an undirected graph that has an
  3524. edge between two locations if they are live at the same time, that is,
  3525. if they interfere with each other. We recommend using the Racket
  3526. \code{graph} package (Figure~\ref{fig:graph}) to represent
  3527. the interference graph.
  3528. An obvious way to compute the interference graph is to look at the set
  3529. of live locations between each instruction and the next and add an edge to the graph
  3530. for every pair of variables in the same set. This approach is less
  3531. than ideal for two reasons. First, it can be expensive because it
  3532. takes $O(n^2)$ time to consider at every pair in a set of $n$ live
  3533. locations. Second, in the special case where two locations hold the
  3534. same value (because one was assigned to the other), they can be live
  3535. at the same time without interfering with each other.
  3536. A better way to compute the interference graph is to focus on
  3537. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  3538. must not overwrite something in a live location. So for each
  3539. instruction, we create an edge between the locations being written to
  3540. and the live locations. (Except that one should not create self
  3541. edges.) Note that for the \key{callq} instruction, we consider all of
  3542. the caller-saved registers as being written to, so an edge is added
  3543. between every live variable and every caller-saved register. For
  3544. \key{movq}, we deal with the above-mentioned special case by not
  3545. adding an edge between a live variable $v$ and the destination if $v$
  3546. matches the source. So we have the following two rules.
  3547. \begin{enumerate}
  3548. \item If instruction $I_k$ is a move such as \key{movq} $s$\key{,}
  3549. $d$, then add the edge $(d,v)$ for every $v \in
  3550. L_{\mathsf{after}}(k)$ unless $v = d$ or $v = s$.
  3551. \item For any other instruction $I_k$, for every $d \in W(k)$
  3552. add an edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  3553. %% \item If instruction $I_k$ is an arithmetic instruction such as
  3554. %% \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  3555. %% L_{\mathsf{after}}(k)$ unless $v = d$.
  3556. %% \item If instruction $I_k$ is of the form \key{callq}
  3557. %% $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  3558. %% register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  3559. \end{enumerate}
  3560. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  3561. the above rules to each instruction. We highlight a few of the
  3562. instructions. The first instruction is \lstinline{movq $1, v} and the
  3563. live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies, so \code{v}
  3564. interferes with \code{rsp}.
  3565. %
  3566. The fourth instruction is \lstinline{addq $7, x} and the live-after
  3567. set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so $\ttm{x}$
  3568. interferes with \ttm{w} and \ttm{rsp}.
  3569. %
  3570. The next instruction is \lstinline{movq x, y} and the live-after set
  3571. is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1 applies, so \ttm{y}
  3572. interferes with \ttm{w} and \ttm{rsp} but not \ttm{x} because \ttm{x}
  3573. is the source of the move and therefore \ttm{x} and \ttm{y} hold the
  3574. same value. Figure~\ref{fig:interference-results} lists the
  3575. interference results for all of the instructions and the resulting
  3576. interference graph is shown in Figure~\ref{fig:interfere}.
  3577. \begin{figure}[tbp]
  3578. \begin{quote}
  3579. \begin{tabular}{ll}
  3580. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  3581. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  3582. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  3583. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  3584. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  3585. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  3586. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  3587. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  3588. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  3589. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  3590. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  3591. \lstinline!jmp conclusion!& no interference.
  3592. \end{tabular}
  3593. \end{quote}
  3594. \caption{Interference results for the running example.}
  3595. \label{fig:interference-results}
  3596. \end{figure}
  3597. \begin{figure}[tbp]
  3598. \large
  3599. \[
  3600. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3601. \node (rax) at (0,0) {$\ttm{rax}$};
  3602. \node (rsp) at (9,2) {$\ttm{rsp}$};
  3603. \node (t1) at (0,2) {$\ttm{t}$};
  3604. \node (z) at (3,2) {$\ttm{z}$};
  3605. \node (x) at (6,2) {$\ttm{x}$};
  3606. \node (y) at (3,0) {$\ttm{y}$};
  3607. \node (w) at (6,0) {$\ttm{w}$};
  3608. \node (v) at (9,0) {$\ttm{v}$};
  3609. \draw (t1) to (rax);
  3610. \draw (t1) to (z);
  3611. \draw (z) to (y);
  3612. \draw (z) to (w);
  3613. \draw (x) to (w);
  3614. \draw (y) to (w);
  3615. \draw (v) to (w);
  3616. \draw (v) to (rsp);
  3617. \draw (w) to (rsp);
  3618. \draw (x) to (rsp);
  3619. \draw (y) to (rsp);
  3620. \path[-.,bend left=15] (z) edge node {} (rsp);
  3621. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3622. \draw (rax) to (rsp);
  3623. \end{tikzpicture}
  3624. \]
  3625. \caption{The interference graph of the example program.}
  3626. \label{fig:interfere}
  3627. \end{figure}
  3628. %% Our next concern is to choose a data structure for representing the
  3629. %% interference graph. There are many choices for how to represent a
  3630. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  3631. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  3632. %% data structure is to study the algorithm that uses the data structure,
  3633. %% determine what operations need to be performed, and then choose the
  3634. %% data structure that provide the most efficient implementations of
  3635. %% those operations. Often times the choice of data structure can have an
  3636. %% effect on the time complexity of the algorithm, as it does here. If
  3637. %% you skim the next section, you will see that the register allocation
  3638. %% algorithm needs to ask the graph for all of its vertices and, given a
  3639. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  3640. %% correct choice of graph representation is that of an adjacency
  3641. %% list. There are helper functions in \code{utilities.rkt} for
  3642. %% representing graphs using the adjacency list representation:
  3643. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  3644. %% (Appendix~\ref{appendix:utilities}).
  3645. %% %
  3646. %% \margincomment{\footnotesize To do: change to use the
  3647. %% Racket graph library. \\ --Jeremy}
  3648. %% %
  3649. %% In particular, those functions use a hash table to map each vertex to
  3650. %% the set of adjacent vertices, and the sets are represented using
  3651. %% Racket's \key{set}, which is also a hash table.
  3652. \begin{exercise}\normalfont
  3653. Implement the compiler pass named \code{build-interference} according
  3654. to the algorithm suggested above. We recommend using the \code{graph}
  3655. package to create and inspect the interference graph. The output
  3656. graph of this pass should be stored in the $\itm{info}$ field of the
  3657. program, under the key \code{conflicts}.
  3658. \end{exercise}
  3659. \section{Graph Coloring via Sudoku}
  3660. \label{sec:graph-coloring}
  3661. \index{subject}{graph coloring}
  3662. \index{subject}{Sudoku}
  3663. \index{subject}{color}
  3664. We come to the main event, mapping variables to registers and stack
  3665. locations. Variables that interfere with each other must be mapped to
  3666. different locations. In terms of the interference graph, this means
  3667. that adjacent vertices must be mapped to different locations. If we
  3668. think of locations as colors, the register allocation problem becomes
  3669. the graph coloring problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  3670. The reader may be more familiar with the graph coloring problem than he
  3671. or she realizes; the popular game of Sudoku is an instance of the
  3672. graph coloring problem. The following describes how to build a graph
  3673. out of an initial Sudoku board.
  3674. \begin{itemize}
  3675. \item There is one vertex in the graph for each Sudoku square.
  3676. \item There is an edge between two vertices if the corresponding squares
  3677. are in the same row, in the same column, or if the squares are in
  3678. the same $3\times 3$ region.
  3679. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  3680. \item Based on the initial assignment of numbers to squares in the
  3681. Sudoku board, assign the corresponding colors to the corresponding
  3682. vertices in the graph.
  3683. \end{itemize}
  3684. If you can color the remaining vertices in the graph with the nine
  3685. colors, then you have also solved the corresponding game of Sudoku.
  3686. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  3687. the corresponding graph with colored vertices. We map the Sudoku
  3688. number 1 to black, 2 to white, and 3 to gray. We only show edges for a
  3689. sampling of the vertices (the colored ones) because showing edges for
  3690. all of the vertices would make the graph unreadable.
  3691. \begin{figure}[tbp]
  3692. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  3693. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  3694. \caption{A Sudoku game board and the corresponding colored graph.}
  3695. \label{fig:sudoku-graph}
  3696. \end{figure}
  3697. Some techniques for playing Sudoku correspond to heuristics used in
  3698. graph coloring algorithms. For example, one of the basic techniques
  3699. for Sudoku is called Pencil Marks. The idea is to use a process of
  3700. elimination to determine what numbers are no longer available for a
  3701. square and write down those numbers in the square (writing very
  3702. small). For example, if the number $1$ is assigned to a square, then
  3703. write the pencil mark $1$ in all the squares in the same row, column,
  3704. and region to indicate that $1$ is no longer an option for those other
  3705. squares.
  3706. %
  3707. The Pencil Marks technique corresponds to the notion of
  3708. \emph{saturation}\index{subject}{saturation} due to \cite{Brelaz:1979eu}. The
  3709. saturation of a vertex, in Sudoku terms, is the set of numbers that
  3710. are no longer available. In graph terminology, we have the following
  3711. definition:
  3712. \begin{equation*}
  3713. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  3714. \text{ and } \mathrm{color}(v) = c \}
  3715. \end{equation*}
  3716. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  3717. edge with $u$.
  3718. Using the Pencil Marks technique leads to a simple strategy for
  3719. filling in numbers: if there is a square with only one possible number
  3720. left, then choose that number! But what if there are no squares with
  3721. only one possibility left? One brute-force approach is to try them
  3722. all: choose the first one and if that ultimately leads to a solution,
  3723. great. If not, backtrack and choose the next possibility. One good
  3724. thing about Pencil Marks is that it reduces the degree of branching in
  3725. the search tree. Nevertheless, backtracking can be terribly time
  3726. consuming. One way to reduce the amount of backtracking is to use the
  3727. most-constrained-first heuristic. That is, when choosing a square,
  3728. always choose one with the fewest possibilities left (the vertex with
  3729. the highest saturation). The idea is that choosing highly constrained
  3730. squares earlier rather than later is better because later on there may
  3731. not be any possibilities left in the highly saturated squares.
  3732. However, register allocation is easier than Sudoku because the
  3733. register allocator can map variables to stack locations when the
  3734. registers run out. Thus, it makes sense to replace backtracking with
  3735. greedy search: make the best choice at the time and keep going. We
  3736. still wish to minimize the number of colors needed, so we use the
  3737. most-constrained-first heuristic in the greedy search.
  3738. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  3739. algorithm for register allocation based on saturation and the
  3740. most-constrained-first heuristic. It is roughly equivalent to the
  3741. DSATUR
  3742. algorithm~\citep{Brelaz:1979eu,Gebremedhin:1999fk,Omari:2006uq}. Just
  3743. as in Sudoku, the algorithm represents colors with integers. The
  3744. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  3745. for register allocation. The integers $k$ and larger correspond to
  3746. stack locations. The registers that are not used for register
  3747. allocation, such as \code{rax}, are assigned to negative integers. In
  3748. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  3749. %% One might wonder why we include registers at all in the liveness
  3750. %% analysis and interference graph. For example, we never allocate a
  3751. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  3752. %% leave them out. As we see in Chapter~\ref{ch:Rvec}, when we begin
  3753. %% to use register for passing arguments to functions, it will be
  3754. %% necessary for those registers to appear in the interference graph
  3755. %% because those registers will also be assigned to variables, and we
  3756. %% don't want those two uses to encroach on each other. Regarding
  3757. %% registers such as \code{rax} and \code{rsp} that are not used for
  3758. %% variables, we could omit them from the interference graph but that
  3759. %% would require adding special cases to our algorithm, which would
  3760. %% complicate the logic for little gain.
  3761. \begin{figure}[btp]
  3762. \centering
  3763. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  3764. Algorithm: DSATUR
  3765. Input: a graph |$G$|
  3766. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  3767. |$W \gets \mathrm{vertices}(G)$|
  3768. while |$W \neq \emptyset$| do
  3769. pick a vertex |$u$| from |$W$| with the highest saturation,
  3770. breaking ties randomly
  3771. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  3772. |$\mathrm{color}[u] \gets c$|
  3773. |$W \gets W - \{u\}$|
  3774. \end{lstlisting}
  3775. \caption{The saturation-based greedy graph coloring algorithm.}
  3776. \label{fig:satur-algo}
  3777. \end{figure}
  3778. With the DSATUR algorithm in hand, let us return to the running
  3779. example and consider how to color the interference graph in
  3780. Figure~\ref{fig:interfere}.
  3781. %
  3782. We start by assigning the register nodes to their own color. For
  3783. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  3784. assigned $-2$. The variables are not yet colored, so they are
  3785. annotated with a dash. We then update the saturation for vertices that
  3786. are adjacent to a register, obtaining the following annotated
  3787. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  3788. it interferes with both \code{rax} and \code{rsp}.
  3789. \[
  3790. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3791. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  3792. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  3793. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  3794. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  3795. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3796. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3797. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3798. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3799. \draw (t1) to (rax);
  3800. \draw (t1) to (z);
  3801. \draw (z) to (y);
  3802. \draw (z) to (w);
  3803. \draw (x) to (w);
  3804. \draw (y) to (w);
  3805. \draw (v) to (w);
  3806. \draw (v) to (rsp);
  3807. \draw (w) to (rsp);
  3808. \draw (x) to (rsp);
  3809. \draw (y) to (rsp);
  3810. \path[-.,bend left=15] (z) edge node {} (rsp);
  3811. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3812. \draw (rax) to (rsp);
  3813. \end{tikzpicture}
  3814. \]
  3815. The algorithm says to select a maximally saturated vertex. So we pick
  3816. $\ttm{t}$ and color it with the first available integer, which is
  3817. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  3818. and \ttm{rsp} because they interfere with $\ttm{t}$.
  3819. \[
  3820. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3821. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3822. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  3823. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  3824. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  3825. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3826. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  3827. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  3828. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3829. \draw (t1) to (rax);
  3830. \draw (t1) to (z);
  3831. \draw (z) to (y);
  3832. \draw (z) to (w);
  3833. \draw (x) to (w);
  3834. \draw (y) to (w);
  3835. \draw (v) to (w);
  3836. \draw (v) to (rsp);
  3837. \draw (w) to (rsp);
  3838. \draw (x) to (rsp);
  3839. \draw (y) to (rsp);
  3840. \path[-.,bend left=15] (z) edge node {} (rsp);
  3841. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3842. \draw (rax) to (rsp);
  3843. \end{tikzpicture}
  3844. \]
  3845. We repeat the process, selecting the next maximally saturated vertex,
  3846. which is \code{z}, and color it with the first available number, which
  3847. is $1$. We add $1$ to the saturation for the neighboring vertices
  3848. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  3849. \[
  3850. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3851. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3852. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3853. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3854. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3855. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  3856. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  3857. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  3858. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  3859. \draw (t1) to (rax);
  3860. \draw (t1) to (z);
  3861. \draw (z) to (y);
  3862. \draw (z) to (w);
  3863. \draw (x) to (w);
  3864. \draw (y) to (w);
  3865. \draw (v) to (w);
  3866. \draw (v) to (rsp);
  3867. \draw (w) to (rsp);
  3868. \draw (x) to (rsp);
  3869. \draw (y) to (rsp);
  3870. \path[-.,bend left=15] (z) edge node {} (rsp);
  3871. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3872. \draw (rax) to (rsp);
  3873. \end{tikzpicture}
  3874. \]
  3875. The most saturated vertices are now \code{w} and \code{y}. We color
  3876. \code{w} with the first available color, which is $0$.
  3877. \[
  3878. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3879. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3880. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  3881. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3882. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  3883. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3884. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  3885. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  3886. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  3887. \draw (t1) to (rax);
  3888. \draw (t1) to (z);
  3889. \draw (z) to (y);
  3890. \draw (z) to (w);
  3891. \draw (x) to (w);
  3892. \draw (y) to (w);
  3893. \draw (v) to (w);
  3894. \draw (v) to (rsp);
  3895. \draw (w) to (rsp);
  3896. \draw (x) to (rsp);
  3897. \draw (y) to (rsp);
  3898. \path[-.,bend left=15] (z) edge node {} (rsp);
  3899. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3900. \draw (rax) to (rsp);
  3901. \end{tikzpicture}
  3902. \]
  3903. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  3904. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  3905. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  3906. and \code{z}, whose colors are $0$ and $1$ respectively.
  3907. \[
  3908. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3909. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3910. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3911. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3912. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3913. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3914. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3915. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3916. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  3917. \draw (t1) to (rax);
  3918. \draw (t1) to (z);
  3919. \draw (z) to (y);
  3920. \draw (z) to (w);
  3921. \draw (x) to (w);
  3922. \draw (y) to (w);
  3923. \draw (v) to (w);
  3924. \draw (v) to (rsp);
  3925. \draw (w) to (rsp);
  3926. \draw (x) to (rsp);
  3927. \draw (y) to (rsp);
  3928. \path[-.,bend left=15] (z) edge node {} (rsp);
  3929. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3930. \draw (rax) to (rsp);
  3931. \end{tikzpicture}
  3932. \]
  3933. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  3934. \[
  3935. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3936. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3937. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3938. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3939. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3940. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  3941. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3942. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3943. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3944. \draw (t1) to (rax);
  3945. \draw (t1) to (z);
  3946. \draw (z) to (y);
  3947. \draw (z) to (w);
  3948. \draw (x) to (w);
  3949. \draw (y) to (w);
  3950. \draw (v) to (w);
  3951. \draw (v) to (rsp);
  3952. \draw (w) to (rsp);
  3953. \draw (x) to (rsp);
  3954. \draw (y) to (rsp);
  3955. \path[-.,bend left=15] (z) edge node {} (rsp);
  3956. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3957. \draw (rax) to (rsp);
  3958. \end{tikzpicture}
  3959. \]
  3960. In the last step of the algorithm, we color \code{x} with $1$.
  3961. \[
  3962. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3963. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  3964. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  3965. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  3966. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  3967. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  3968. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  3969. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  3970. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  3971. \draw (t1) to (rax);
  3972. \draw (t1) to (z);
  3973. \draw (z) to (y);
  3974. \draw (z) to (w);
  3975. \draw (x) to (w);
  3976. \draw (y) to (w);
  3977. \draw (v) to (w);
  3978. \draw (v) to (rsp);
  3979. \draw (w) to (rsp);
  3980. \draw (x) to (rsp);
  3981. \draw (y) to (rsp);
  3982. \path[-.,bend left=15] (z) edge node {} (rsp);
  3983. \path[-.,bend left=10] (t1) edge node {} (rsp);
  3984. \draw (rax) to (rsp);
  3985. \end{tikzpicture}
  3986. \]
  3987. We recommend creating an auxiliary function named \code{color-graph}
  3988. that takes an interference graph and a list of all the variables in
  3989. the program. This function should return a mapping of variables to
  3990. their colors (represented as natural numbers). By creating this helper
  3991. function, you will be able to reuse it in Chapter~\ref{ch:Rfun}
  3992. when we add support for functions.
  3993. To prioritize the processing of highly saturated nodes inside the
  3994. \code{color-graph} function, we recommend using the priority queue
  3995. data structure described in Figure~\ref{fig:priority-queue}. In
  3996. addition, you will need to maintain a mapping from variables to their
  3997. ``handles'' in the priority queue so that you can notify the priority
  3998. queue when their saturation changes.
  3999. \begin{figure}[tp]
  4000. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  4001. \small
  4002. \begin{tcolorbox}[title=Priority Queue]
  4003. A \emph{priority queue} is a collection of items in which the
  4004. removal of items is governed by priority. In a ``min'' queue,
  4005. lower priority items are removed first. An implementation is in
  4006. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  4007. queue} \index{subject}{minimum priority queue}
  4008. \begin{description}
  4009. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  4010. priority queue that uses the $\itm{cmp}$ predicate to determine
  4011. whether its first argument has lower or equal priority to its
  4012. second argument.
  4013. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  4014. items in the queue.
  4015. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  4016. the item into the queue and returns a handle for the item in the
  4017. queue.
  4018. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  4019. the lowest priority.
  4020. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  4021. notifies the queue that the priority has decreased for the item
  4022. associated with the given handle.
  4023. \end{description}
  4024. \end{tcolorbox}
  4025. %\end{wrapfigure}
  4026. \caption{The priority queue data structure.}
  4027. \label{fig:priority-queue}
  4028. \end{figure}
  4029. With the coloring complete, we finalize the assignment of variables to
  4030. registers and stack locations. We map the first $k$ colors to the $k$
  4031. registers and the rest of the colors to stack locations. Suppose for
  4032. the moment that we have just one register to use for register
  4033. allocation, \key{rcx}. Then we have the following map from colors to
  4034. locations.
  4035. \[
  4036. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  4037. \]
  4038. Composing this mapping with the coloring, we arrive at the following
  4039. assignment of variables to locations.
  4040. \begin{gather*}
  4041. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  4042. \ttm{w} \mapsto \key{\%rcx}, \,
  4043. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  4044. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  4045. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  4046. \ttm{t} \mapsto \key{\%rcx} \}
  4047. \end{gather*}
  4048. Adapt the code from the \code{assign-homes} pass
  4049. (Section~\ref{sec:assign-Rvar}) to replace the variables with their
  4050. assigned location. Applying the above assignment to our running
  4051. example, on the left, yields the program on the right.
  4052. % why frame size of 32? -JGS
  4053. \begin{center}
  4054. \begin{minipage}{0.3\textwidth}
  4055. \begin{lstlisting}
  4056. movq $1, v
  4057. movq $42, w
  4058. movq v, x
  4059. addq $7, x
  4060. movq x, y
  4061. movq x, z
  4062. addq w, z
  4063. movq y, t
  4064. negq t
  4065. movq z, %rax
  4066. addq t, %rax
  4067. jmp conclusion
  4068. \end{lstlisting}
  4069. \end{minipage}
  4070. $\Rightarrow\qquad$
  4071. \begin{minipage}{0.45\textwidth}
  4072. \begin{lstlisting}
  4073. movq $1, -8(%rbp)
  4074. movq $42, %rcx
  4075. movq -8(%rbp), -8(%rbp)
  4076. addq $7, -8(%rbp)
  4077. movq -8(%rbp), -16(%rbp)
  4078. movq -8(%rbp), -8(%rbp)
  4079. addq %rcx, -8(%rbp)
  4080. movq -16(%rbp), %rcx
  4081. negq %rcx
  4082. movq -8(%rbp), %rax
  4083. addq %rcx, %rax
  4084. jmp conclusion
  4085. \end{lstlisting}
  4086. \end{minipage}
  4087. \end{center}
  4088. \begin{exercise}\normalfont
  4089. %
  4090. Implement the compiler pass \code{allocate-registers}.
  4091. %
  4092. Create five programs that exercise all of the register allocation
  4093. algorithm, including spilling variables to the stack.
  4094. %
  4095. Replace \code{assign-homes} in the list of \code{passes} in the
  4096. \code{run-tests.rkt} script with the three new passes:
  4097. \code{uncover-live}, \code{build-interference}, and
  4098. \code{allocate-registers}.
  4099. %
  4100. Temporarily remove the \code{print-x86} pass from the list of passes
  4101. and the call to \code{compiler-tests}.
  4102. %
  4103. Run the script to test the register allocator.
  4104. \end{exercise}
  4105. \section{Patch Instructions}
  4106. \label{sec:patch-instructions}
  4107. The remaining step in the compilation to x86 is to ensure that the
  4108. instructions have at most one argument that is a memory access.
  4109. In the running example, the instruction \code{movq -8(\%rbp), -16(\%rbp)}
  4110. is problematic. The fix is to first move \code{-8(\%rbp)}
  4111. into \code{rax} and then move \code{rax} into \code{-16(\%rbp)}.
  4112. %
  4113. The two moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  4114. problematic, but they can be fixed by simply deleting them. In
  4115. general, we recommend deleting all the trivial moves whose source and
  4116. destination are the same location.
  4117. %
  4118. The following is the output of \code{patch-instructions} on the
  4119. running example.
  4120. \begin{center}
  4121. \begin{minipage}{0.4\textwidth}
  4122. \begin{lstlisting}
  4123. movq $1, -8(%rbp)
  4124. movq $42, %rcx
  4125. movq -8(%rbp), -8(%rbp)
  4126. addq $7, -8(%rbp)
  4127. movq -8(%rbp), -16(%rbp)
  4128. movq -8(%rbp), -8(%rbp)
  4129. addq %rcx, -8(%rbp)
  4130. movq -16(%rbp), %rcx
  4131. negq %rcx
  4132. movq -8(%rbp), %rax
  4133. addq %rcx, %rax
  4134. jmp conclusion
  4135. \end{lstlisting}
  4136. \end{minipage}
  4137. $\Rightarrow\qquad$
  4138. \begin{minipage}{0.45\textwidth}
  4139. \begin{lstlisting}
  4140. movq $1, -8(%rbp)
  4141. movq $42, %rcx
  4142. addq $7, -8(%rbp)
  4143. movq -8(%rbp), %rax
  4144. movq %rax, -16(%rbp)
  4145. addq %rcx, -8(%rbp)
  4146. movq -16(%rbp), %rcx
  4147. negq %rcx
  4148. movq -8(%rbp), %rax
  4149. addq %rcx, %rax
  4150. jmp conclusion
  4151. \end{lstlisting}
  4152. \end{minipage}
  4153. \end{center}
  4154. \begin{exercise}\normalfont
  4155. %
  4156. Implement the \code{patch-instructions} compiler pass.
  4157. %
  4158. Insert it after \code{allocate-registers} in the list of \code{passes}
  4159. in the \code{run-tests.rkt} script.
  4160. %
  4161. Run the script to test the \code{patch-instructions} pass.
  4162. \end{exercise}
  4163. \section{Print x86}
  4164. \label{sec:print-x86-reg-alloc}
  4165. \index{subject}{calling conventions}
  4166. \index{subject}{prelude}\index{subject}{conclusion}
  4167. Recall that the \code{print-x86} pass generates the prelude and
  4168. conclusion instructions to satisfy the x86 calling conventions
  4169. (Section~\ref{sec:calling-conventions}). With the addition of the
  4170. register allocator, the callee-saved registers used by the register
  4171. allocator must be saved in the prelude and restored in the conclusion.
  4172. In the \code{allocate-registers} pass, add an entry to the \itm{info}
  4173. of \code{X86Program} named \code{used-callee} that stores the set of
  4174. callee-saved registers that were assigned to variables. The
  4175. \code{print-x86} pass can then access this information to decide which
  4176. callee-saved registers need to be saved and restored.
  4177. %
  4178. When calculating the size of the frame to adjust the \code{rsp} in the
  4179. prelude, make sure to take into account the space used for saving the
  4180. callee-saved registers. Also, don't forget that the frame needs to be
  4181. a multiple of 16 bytes!
  4182. An overview of all of the passes involved in register allocation is
  4183. shown in Figure~\ref{fig:reg-alloc-passes}.
  4184. \begin{figure}[tbp]
  4185. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4186. \node (Rvar) at (0,2) {\large \LangVar{}};
  4187. \node (Rvar-2) at (3,2) {\large \LangVar{}};
  4188. \node (Rvar-3) at (6,2) {\large \LangVar{}};
  4189. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  4190. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  4191. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  4192. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  4193. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  4194. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  4195. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  4196. \path[->,bend left=15] (Rvar) edge [above] node {\ttfamily\footnotesize uniquify} (Rvar-2);
  4197. \path[->,bend left=15] (Rvar-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvar-3);
  4198. \path[->,bend left=15] (Rvar-3) edge [right] node {\ttfamily\footnotesize explicate-control} (Cvar-1);
  4199. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  4200. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  4201. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  4202. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4203. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  4204. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  4205. \end{tikzpicture}
  4206. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  4207. \label{fig:reg-alloc-passes}
  4208. \end{figure}
  4209. \begin{exercise}\normalfont
  4210. Update the \code{print-x86} pass as described in this section.
  4211. %
  4212. In the \code{run-tests.rkt} script, reinstate \code{print-x86} in the
  4213. list of passes and the call to \code{compiler-tests}.
  4214. %
  4215. Run the script to test the complete compiler for \LangVar{} that
  4216. performs register allocation.
  4217. \end{exercise}
  4218. \section{Challenge: Move Biasing}
  4219. \label{sec:move-biasing}
  4220. \index{subject}{move biasing}
  4221. This section describes an enhancement to the register allocator for
  4222. students looking for an extra challenge or who have a deeper interest
  4223. in register allocation.
  4224. To motivate the need for move biasing we return to the running example
  4225. but this time use all of the general purpose registers. So we have
  4226. the following mapping of color numbers to registers.
  4227. \[
  4228. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi} \}
  4229. \]
  4230. Using the same assignment of variables to color numbers that was
  4231. produced by the register allocator described in the last section, we
  4232. get the following program.
  4233. \begin{center}
  4234. \begin{minipage}{0.3\textwidth}
  4235. \begin{lstlisting}
  4236. movq $1, v
  4237. movq $42, w
  4238. movq v, x
  4239. addq $7, x
  4240. movq x, y
  4241. movq x, z
  4242. addq w, z
  4243. movq y, t
  4244. negq t
  4245. movq z, %rax
  4246. addq t, %rax
  4247. jmp conclusion
  4248. \end{lstlisting}
  4249. \end{minipage}
  4250. $\Rightarrow\qquad$
  4251. \begin{minipage}{0.45\textwidth}
  4252. \begin{lstlisting}
  4253. movq $1, %rdx
  4254. movq $42, %rcx
  4255. movq %rdx, %rdx
  4256. addq $7, %rdx
  4257. movq %rdx, %rsi
  4258. movq %rdx, %rdx
  4259. addq %rcx, %rdx
  4260. movq %rsi, %rcx
  4261. negq %rcx
  4262. movq %rdx, %rax
  4263. addq %rcx, %rax
  4264. jmp conclusion
  4265. \end{lstlisting}
  4266. \end{minipage}
  4267. \end{center}
  4268. In the above output code there are two \key{movq} instructions that
  4269. can be removed because their source and target are the same. However,
  4270. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  4271. register, we could instead remove three \key{movq} instructions. We
  4272. can accomplish this by taking into account which variables appear in
  4273. \key{movq} instructions with which other variables.
  4274. We say that two variables $p$ and $q$ are \emph{move
  4275. related}\index{subject}{move related} if they participate together in a
  4276. \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  4277. \key{movq} $q$\key{,} $p$. When the register allocator chooses a color
  4278. for a variable, it should prefer a color that has already been used
  4279. for a move-related variable (assuming that they do not interfere). Of
  4280. course, this preference should not override the preference for
  4281. registers over stack locations. This preference should be used as a
  4282. tie breaker when choosing between registers or when choosing between
  4283. stack locations.
  4284. We recommend representing the move relationships in a graph, similar
  4285. to how we represented interference. The following is the \emph{move
  4286. graph} for our running example.
  4287. \[
  4288. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4289. \node (rax) at (0,0) {$\ttm{rax}$};
  4290. \node (rsp) at (9,2) {$\ttm{rsp}$};
  4291. \node (t) at (0,2) {$\ttm{t}$};
  4292. \node (z) at (3,2) {$\ttm{z}$};
  4293. \node (x) at (6,2) {$\ttm{x}$};
  4294. \node (y) at (3,0) {$\ttm{y}$};
  4295. \node (w) at (6,0) {$\ttm{w}$};
  4296. \node (v) at (9,0) {$\ttm{v}$};
  4297. \draw (v) to (x);
  4298. \draw (x) to (y);
  4299. \draw (x) to (z);
  4300. \draw (y) to (t);
  4301. \end{tikzpicture}
  4302. \]
  4303. Now we replay the graph coloring, pausing to see the coloring of
  4304. \code{y}. Recall the following configuration. The most saturated vertices
  4305. were \code{w} and \code{y}.
  4306. \[
  4307. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4308. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4309. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4310. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  4311. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4312. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4313. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  4314. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  4315. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  4316. \draw (t1) to (rax);
  4317. \draw (t1) to (z);
  4318. \draw (z) to (y);
  4319. \draw (z) to (w);
  4320. \draw (x) to (w);
  4321. \draw (y) to (w);
  4322. \draw (v) to (w);
  4323. \draw (v) to (rsp);
  4324. \draw (w) to (rsp);
  4325. \draw (x) to (rsp);
  4326. \draw (y) to (rsp);
  4327. \path[-.,bend left=15] (z) edge node {} (rsp);
  4328. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4329. \draw (rax) to (rsp);
  4330. \end{tikzpicture}
  4331. \]
  4332. %
  4333. Last time we chose to color \code{w} with $0$. But this time we see
  4334. that \code{w} is not move related to any vertex, but \code{y} is move
  4335. related to \code{t}. So we choose to color \code{y} the same color as
  4336. \code{t}, $0$.
  4337. \[
  4338. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4339. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4340. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4341. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  4342. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4343. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4344. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  4345. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  4346. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  4347. \draw (t1) to (rax);
  4348. \draw (t1) to (z);
  4349. \draw (z) to (y);
  4350. \draw (z) to (w);
  4351. \draw (x) to (w);
  4352. \draw (y) to (w);
  4353. \draw (v) to (w);
  4354. \draw (v) to (rsp);
  4355. \draw (w) to (rsp);
  4356. \draw (x) to (rsp);
  4357. \draw (y) to (rsp);
  4358. \path[-.,bend left=15] (z) edge node {} (rsp);
  4359. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4360. \draw (rax) to (rsp);
  4361. \end{tikzpicture}
  4362. \]
  4363. Now \code{w} is the most saturated, so we color it $2$.
  4364. \[
  4365. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4366. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4367. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4368. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  4369. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4370. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  4371. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  4372. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  4373. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  4374. \draw (t1) to (rax);
  4375. \draw (t1) to (z);
  4376. \draw (z) to (y);
  4377. \draw (z) to (w);
  4378. \draw (x) to (w);
  4379. \draw (y) to (w);
  4380. \draw (v) to (w);
  4381. \draw (v) to (rsp);
  4382. \draw (w) to (rsp);
  4383. \draw (x) to (rsp);
  4384. \draw (y) to (rsp);
  4385. \path[-.,bend left=15] (z) edge node {} (rsp);
  4386. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4387. \draw (rax) to (rsp);
  4388. \end{tikzpicture}
  4389. \]
  4390. At this point, vertices \code{x} and \code{v} are most saturated, but
  4391. \code{x} is move related to \code{y} and \code{z}, so we color
  4392. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  4393. \[
  4394. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4395. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4396. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4397. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  4398. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4399. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  4400. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  4401. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  4402. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  4403. \draw (t1) to (rax);
  4404. \draw (t) to (z);
  4405. \draw (z) to (y);
  4406. \draw (z) to (w);
  4407. \draw (x) to (w);
  4408. \draw (y) to (w);
  4409. \draw (v) to (w);
  4410. \draw (v) to (rsp);
  4411. \draw (w) to (rsp);
  4412. \draw (x) to (rsp);
  4413. \draw (y) to (rsp);
  4414. \path[-.,bend left=15] (z) edge node {} (rsp);
  4415. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4416. \draw (rax) to (rsp);
  4417. \end{tikzpicture}
  4418. \]
  4419. So we have the following assignment of variables to registers.
  4420. \begin{gather*}
  4421. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  4422. \ttm{w} \mapsto \key{\%rsi}, \,
  4423. \ttm{x} \mapsto \key{\%rcx}, \,
  4424. \ttm{y} \mapsto \key{\%rcx}, \,
  4425. \ttm{z} \mapsto \key{\%rdx}, \,
  4426. \ttm{t} \mapsto \key{\%rcx} \}
  4427. \end{gather*}
  4428. We apply this register assignment to the running example, on the left,
  4429. to obtain the code in the middle. The \code{patch-instructions} then
  4430. removes the three trivial moves to obtain the code on the right.
  4431. \begin{minipage}{0.25\textwidth}
  4432. \begin{lstlisting}
  4433. movq $1, v
  4434. movq $42, w
  4435. movq v, x
  4436. addq $7, x
  4437. movq x, y
  4438. movq x, z
  4439. addq w, z
  4440. movq y, t
  4441. negq t
  4442. movq z, %rax
  4443. addq t, %rax
  4444. jmp conclusion
  4445. \end{lstlisting}
  4446. \end{minipage}
  4447. $\Rightarrow\qquad$
  4448. \begin{minipage}{0.25\textwidth}
  4449. \begin{lstlisting}
  4450. movq $1, %rcx
  4451. movq $42, %rsi
  4452. movq %rcx, %rcx
  4453. addq $7, %rcx
  4454. movq %rcx, %rcx
  4455. movq %rcx, %rdx
  4456. addq %rsi, %rdx
  4457. movq %rcx, %rcx
  4458. negq %rcx
  4459. movq %rdx, %rax
  4460. addq %rcx, %rax
  4461. jmp conclusion
  4462. \end{lstlisting}
  4463. \end{minipage}
  4464. $\Rightarrow\qquad$
  4465. \begin{minipage}{0.25\textwidth}
  4466. \begin{lstlisting}
  4467. movq $1, %rcx
  4468. movq $42, %rsi
  4469. addq $7, %rcx
  4470. movq %rcx, %rdx
  4471. addq %rsi, %rdx
  4472. negq %rcx
  4473. movq %rdx, %rax
  4474. addq %rcx, %rax
  4475. jmp conclusion
  4476. \end{lstlisting}
  4477. \end{minipage}
  4478. \begin{exercise}\normalfont
  4479. Change your implementation of \code{allocate-registers} to take move
  4480. biasing into account. Create two new tests that include at least one
  4481. opportunity for move biasing and visually inspect the output x86
  4482. programs to make sure that your move biasing is working properly. Make
  4483. sure that your compiler still passes all of the tests.
  4484. \end{exercise}
  4485. %To do: another neat challenge would be to do
  4486. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  4487. %% \subsection{Output of the Running Example}
  4488. %% \label{sec:reg-alloc-output}
  4489. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  4490. the running example (Figure~\ref{fig:reg-eg}) with register allocation
  4491. and move biasing. To demonstrate both the use of registers and the
  4492. stack, we have limited the register allocator to use just two
  4493. registers: \code{rbx} and \code{rcx}. In the prelude\index{subject}{prelude}
  4494. of the \code{main} function, we push \code{rbx} onto the stack because
  4495. it is a callee-saved register and it was assigned to variable by the
  4496. register allocator. We subtract \code{8} from the \code{rsp} at the
  4497. end of the prelude to reserve space for the one spilled variable.
  4498. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  4499. Moving on the the \code{start} block, we see how the registers were
  4500. allocated. Variables \code{v}, \code{x}, and \code{y} were assigned to
  4501. \code{rbx} and variable \code{z} was assigned to \code{rcx}. Variable
  4502. \code{w} was spilled to the stack location \code{-16(\%rbp)}. Recall
  4503. that the prelude saved the callee-save register \code{rbx} onto the
  4504. stack. The spilled variables must be placed lower on the stack than
  4505. the saved callee-save registers, so in this case \code{w} is placed at
  4506. \code{-16(\%rbp)}.
  4507. In the \code{conclusion}\index{subject}{conclusion}, we undo the work that was
  4508. done in the prelude. We move the stack pointer up by \code{8} bytes
  4509. (the room for spilled variables), then we pop the old values of
  4510. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  4511. \code{retq} to return control to the operating system.
  4512. \begin{figure}[tbp]
  4513. % var_test_28.rkt
  4514. % (use-minimal-set-of-registers! #t)
  4515. % and only rbx rcx
  4516. % tmp 0 rbx
  4517. % z 1 rcx
  4518. % y 0 rbx
  4519. % w 2 16(%rbp)
  4520. % v 0 rbx
  4521. % x 0 rbx
  4522. \begin{lstlisting}
  4523. start:
  4524. movq $1, %rbx
  4525. movq $42, -16(%rbp)
  4526. addq $7, %rbx
  4527. movq %rbx, %rcx
  4528. addq -16(%rbp), %rcx
  4529. negq %rbx
  4530. movq %rcx, %rax
  4531. addq %rbx, %rax
  4532. jmp conclusion
  4533. .globl main
  4534. main:
  4535. pushq %rbp
  4536. movq %rsp, %rbp
  4537. pushq %rbx
  4538. subq $8, %rsp
  4539. jmp start
  4540. conclusion:
  4541. addq $8, %rsp
  4542. popq %rbx
  4543. popq %rbp
  4544. retq
  4545. \end{lstlisting}
  4546. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  4547. \label{fig:running-example-x86}
  4548. \end{figure}
  4549. % challenge: prioritize variables based on execution frequencies
  4550. % and the number of uses of a variable
  4551. % challenge: enhance the coloring algorithm using Chaitin's
  4552. % approach of prioritizing high-degree variables
  4553. % by removing low-degree variables (coloring them later)
  4554. % from the interference graph
  4555. \section{Further Reading}
  4556. \label{sec:register-allocation-further-reading}
  4557. Early register allocation algorithms were developed for Fortran
  4558. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  4559. of graph coloring began in the late 1970s and early 1980s with the
  4560. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  4561. algorithm is based on the following observation of
  4562. \citet{Kempe:1879aa} from the 1870s. If a graph $G$ has a vertex $v$
  4563. with degree lower than $k$, then $G$ is $k$ colorable if the subgraph
  4564. of $G$ with $v$ removed is also $k$ colorable. Suppose that the
  4565. subgraph is $k$ colorable. At worst the neighbors of $v$ are assigned
  4566. different colors, but since there are less than $k$ of them, there
  4567. will be one or more colors left over to use for coloring $v$ in $G$.
  4568. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  4569. less than $k$ from the graph and recursively colors the rest of the
  4570. graph. Upon returning from the recursion, it colors $v$ with one of
  4571. the available colors and returns. \citet{Chaitin:1982vn} augments
  4572. this algorithm to handle spilling as follows. If there are no vertices
  4573. of degree lower than $k$ then pick a vertex at random, spill it,
  4574. remove it from the graph, and proceed recursively to color the rest of
  4575. the graph.
  4576. Prior to coloring, \citet{Chaitin:1981vl} merge variables that are
  4577. move-related and that don't interfere with each other, a process
  4578. called \emph{coalescing}. While coalescing decreases the number of
  4579. moves, it can make the graph more difficult to
  4580. color. \citet{Briggs:1994kx} propose \emph{conservative coalescing} in
  4581. which two variables are merged only if they have fewer than $k$
  4582. neighbors of high degree. \citet{George:1996aa} observe that
  4583. conservative coalescing is sometimes too conservative and make it more
  4584. aggressive by iterating the coalescing with the removal of low-degree
  4585. vertices.
  4586. %
  4587. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  4588. also propose \emph{biased coloring} in which a variable is assigned to
  4589. the same color as another move-related variable if possible, as
  4590. discussed in Section~\ref{sec:move-biasing}.
  4591. %
  4592. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  4593. performs coalescing, graph coloring, and spill code insertion until
  4594. all variables have been assigned a location.
  4595. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  4596. spills variables that don't have to be: a high-degree variable can be
  4597. colorable if many of its neighbors are assigned the same color.
  4598. \citet{Briggs:1994kx} propose \emph{optimistic coloring}, in which a
  4599. high-degree vertex is not immediately spilled. Instead the decision is
  4600. deferred until after the recursive call, at which point it is apparent
  4601. whether there is actually an available color or not. We observe that
  4602. this algorithm is equivalent to the smallest-last ordering
  4603. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  4604. be registers and the rest to be stack locations.
  4605. %% biased coloring
  4606. Earlier editions of the compiler course at Indiana University
  4607. \citep{Dybvig:2010aa} were based on the algorithm of
  4608. \citet{Briggs:1994kx}.
  4609. The smallest-last ordering algorithm is one of many \emph{greedy}
  4610. coloring algorithms. A greedy coloring algorithm visits all the
  4611. vertices in a particular order and assigns each one the first
  4612. available color. An \emph{offline} greedy algorithm chooses the
  4613. ordering up-front, prior to assigning colors. The algorithm of
  4614. \citet{Chaitin:1981vl} should be considered offline because the vertex
  4615. ordering does not depend on the colors assigned, so the algorithm
  4616. could be split into two phases. Other orderings are possible. For
  4617. example, \citet{Chow:1984ys} order variables according an estimate of
  4618. runtime cost.
  4619. An \emph{online} greedy coloring algorithm uses information about the
  4620. current assignment of colors to influence the order in which the
  4621. remaining vertices are colored. The saturation-based algorithm
  4622. described in this chapter is one such algorithm. We choose to use
  4623. saturation-based coloring is because it is fun to introduce graph
  4624. coloring via Sudoku.
  4625. A register allocator may choose to map each variable to just one
  4626. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  4627. variable to one or more locations. The later can be achieved by
  4628. \emph{live range splitting}, where a variable is replaced by several
  4629. variables that each handle part of its live
  4630. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  4631. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  4632. %% replacement algorithm, bottom-up local
  4633. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  4634. %% Cooper: top-down (priority bassed), bottom-up
  4635. %% top-down
  4636. %% order variables by priority (estimated cost)
  4637. %% caveat: split variables into two groups:
  4638. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  4639. %% color the constrained ones first
  4640. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  4641. %% cite J. Cocke for an algorithm that colors variables
  4642. %% in a high-degree first ordering
  4643. %Register Allocation via Usage Counts, Freiburghouse CACM
  4644. \citet{Palsberg:2007si} observe that many of the interference graphs
  4645. that arise from Java programs in the JoeQ compiler are \emph{chordal},
  4646. that is, every cycle with four or more edges has an edge which is not
  4647. part of the cycle but which connects two vertices on the cycle. Such
  4648. graphs can be optimally colored by the greedy algorithm with a vertex
  4649. ordering determined by maximum cardinality search.
  4650. In situations where compile time is of utmost importance, such as in
  4651. just-in-time compilers, graph coloring algorithms can be too expensive
  4652. and the linear scan of \citet{Poletto:1999uq} may be more appropriate.
  4653. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4654. \chapter{Booleans and Control Flow}
  4655. \label{ch:Rif}
  4656. \index{subject}{Boolean}
  4657. \index{subject}{control flow}
  4658. \index{subject}{conditional expression}
  4659. The \LangInt{} and \LangVar{} languages only have a single kind of
  4660. value, integers. In this chapter we add a second kind of value, the
  4661. Booleans, to create the \LangIf{} language. The Boolean values
  4662. \emph{true} and \emph{false} are written \key{\#t} and \key{\#f}
  4663. respectively in Racket. The \LangIf{} language includes several
  4664. operations that involve Booleans (\key{and}, \key{not}, \key{eq?},
  4665. \key{<}, etc.) and the conditional \key{if} expression. With the
  4666. addition of \key{if}, programs can have non-trivial control flow which
  4667. impacts \code{explicate-control} and liveness analysis. Also, because
  4668. we now have two kinds of values, we need to handle programs that apply
  4669. an operation to the wrong kind of value, such as \code{(not 1)}.
  4670. There are two language design options for such situations. One option
  4671. is to signal an error and the other is to provide a wider
  4672. interpretation of the operation. The Racket language uses a mixture of
  4673. these two options, depending on the operation and the kind of
  4674. value. For example, the result of \code{(not 1)} in Racket is
  4675. \code{\#f} because Racket treats non-zero integers as if they were
  4676. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  4677. error in Racket because \code{car} expects a pair.
  4678. Typed Racket makes similar design choices as Racket, except much of
  4679. the error detection happens at compile time instead of run time. Typed
  4680. Racket accepts and runs \code{(not 1)}, producing \code{\#f}. But in
  4681. the case of \code{(car 1)}, Typed Racket reports a compile-time error
  4682. because Typed Racket expects the type of the argument to be of the
  4683. form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  4684. The \LangIf{} language performs type checking during compilation like
  4685. Typed Racket. In Chapter~\ref{ch:type-dynamic} we study the
  4686. alternative choice, that is, a dynamically typed language like Racket.
  4687. The \LangIf{} language is a subset of Typed Racket; for some
  4688. operations we are more restrictive, for example, rejecting
  4689. \code{(not 1)}.
  4690. This chapter is organized as follows. We begin by defining the syntax
  4691. and interpreter for the \LangIf{} language
  4692. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  4693. checking and build a type checker for \LangIf{}
  4694. (Section~\ref{sec:type-check-Rif}). To compile \LangIf{} we need to
  4695. enlarge the intermediate language \LangCVar{} into \LangCIf{}
  4696. (Section~\ref{sec:Cif}) and \LangXInt{} into \LangXIf{}
  4697. (Section~\ref{sec:x86-if}). The remaining sections of this chapter
  4698. discuss how our compiler passes change to accommodate Booleans and
  4699. conditional control flow. There is one new pass, named \code{shrink},
  4700. that translates some operators into others, thereby reducing the
  4701. number of operators that need to be handled in later passes. The
  4702. largest changes occur in \code{explicate-control}, to translate
  4703. \code{if} expressions into control-flow graphs
  4704. (Section~\ref{sec:explicate-control-Rif}). Regarding register
  4705. allocation, the liveness analysis now has multiple basic blocks to
  4706. process and there is the interesting question of how to handle
  4707. conditional jumps.
  4708. \section{The \LangIf{} Language}
  4709. \label{sec:lang-if}
  4710. The concrete syntax of the \LangIf{} language is defined in
  4711. Figure~\ref{fig:Rif-concrete-syntax} and the abstract syntax is defined
  4712. in Figure~\ref{fig:Rif-syntax}. The \LangIf{} language includes all of
  4713. \LangVar{} (shown in gray), the Boolean literals \code{\#t} and
  4714. \code{\#f}, and the conditional \code{if} expression. We expand the
  4715. operators to include
  4716. \begin{enumerate}
  4717. \item subtraction on integers,
  4718. \item the logical operators \key{and}, \key{or} and \key{not},
  4719. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  4720. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  4721. comparing integers.
  4722. \end{enumerate}
  4723. We reorganize the abstract syntax for the primitive operations in
  4724. Figure~\ref{fig:Rif-syntax}, using only one grammar rule for all of
  4725. them. This means that the grammar no longer checks whether the arity
  4726. of an operators matches the number of arguments. That responsibility
  4727. is moved to the type checker for \LangIf{}, which we introduce in
  4728. Section~\ref{sec:type-check-Rif}.
  4729. \begin{figure}[tp]
  4730. \centering
  4731. \fbox{
  4732. \begin{minipage}{0.96\textwidth}
  4733. \[
  4734. \begin{array}{lcl}
  4735. \itm{bool} &::=& \key{\#t} \MID \key{\#f} \\
  4736. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  4737. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp} } \MID \CSUB{\Exp}{\Exp} \\
  4738. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} } \\
  4739. &\MID& \itm{bool}
  4740. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  4741. \MID (\key{not}\;\Exp) \\
  4742. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} \\
  4743. \LangIfM{} &::=& \Exp
  4744. \end{array}
  4745. \]
  4746. \end{minipage}
  4747. }
  4748. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  4749. (Figure~\ref{fig:Rvar-concrete-syntax}) with Booleans and conditionals.}
  4750. \label{fig:Rif-concrete-syntax}
  4751. \end{figure}
  4752. \begin{figure}[tp]
  4753. \centering
  4754. \fbox{
  4755. \begin{minipage}{0.96\textwidth}
  4756. \[
  4757. \begin{array}{lcl}
  4758. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  4759. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  4760. \itm{op} &::= & \itm{cmp} \MID \code{read} \MID \code{+} \MID \code{-}
  4761. \MID \code{and} \MID \code{or} \MID \code{not} \\
  4762. \Exp &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  4763. &\MID& \PRIM{\itm{op}}{\Exp\ldots}\\
  4764. &\MID& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp} \\
  4765. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  4766. \end{array}
  4767. \]
  4768. \end{minipage}
  4769. }
  4770. \caption{The abstract syntax of \LangIf{}.}
  4771. \label{fig:Rif-syntax}
  4772. \end{figure}
  4773. Figure~\ref{fig:interp-Rif} defines the interpreter for \LangIf{},
  4774. which inherits from the interpreter for \LangVar{}
  4775. (Figure~\ref{fig:interp-Rvar}). The literals \code{\#t} and \code{\#f}
  4776. evaluate to the corresponding Boolean values. The conditional
  4777. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  4778. \itm{cnd} and then either evaluates \itm{thn} or \itm{els} depending
  4779. on whether \itm{cnd} produced \code{\#t} or \code{\#f}. The logical
  4780. operations \code{not} and \code{and} behave as you might expect, but
  4781. note that the \code{and} operation is short-circuiting. That is, given
  4782. the expression $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not
  4783. evaluated if $e_1$ evaluates to \code{\#f}.
  4784. With the increase in the number of primitive operations, the
  4785. interpreter would become repetitive without some care. We refactor
  4786. the case for \code{Prim}, moving the code that differs with each
  4787. operation into the \code{interp-op} method shown in in
  4788. Figure~\ref{fig:interp-op-Rif}. We handle the \code{and} operation
  4789. separately because of its short-circuiting behavior.
  4790. \begin{figure}[tbp]
  4791. \begin{lstlisting}
  4792. (define interp-Rif-class
  4793. (class interp-Rvar-class
  4794. (super-new)
  4795. (define/public (interp-op op) ...)
  4796. (define/override ((interp-exp env) e)
  4797. (define recur (interp-exp env))
  4798. (match e
  4799. [(Bool b) b]
  4800. [(If cnd thn els)
  4801. (match (recur cnd)
  4802. [#t (recur thn)]
  4803. [#f (recur els)])]
  4804. [(Prim 'and (list e1 e2))
  4805. (match (recur e1)
  4806. [#t (match (recur e2) [#t #t] [#f #f])]
  4807. [#f #f])]
  4808. [(Prim op args)
  4809. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  4810. [else ((super interp-exp env) e)]))
  4811. ))
  4812. (define (interp-Rif p)
  4813. (send (new interp-Rif-class) interp-program p))
  4814. \end{lstlisting}
  4815. \caption{Interpreter for the \LangIf{} language. (See
  4816. Figure~\ref{fig:interp-op-Rif} for \code{interp-op}.)}
  4817. \label{fig:interp-Rif}
  4818. \end{figure}
  4819. \begin{figure}[tbp]
  4820. \begin{lstlisting}
  4821. (define/public (interp-op op)
  4822. (match op
  4823. ['+ fx+]
  4824. ['- fx-]
  4825. ['read read-fixnum]
  4826. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  4827. ['or (lambda (v1 v2)
  4828. (cond [(and (boolean? v1) (boolean? v2))
  4829. (or v1 v2)]))]
  4830. ['eq? (lambda (v1 v2)
  4831. (cond [(or (and (fixnum? v1) (fixnum? v2))
  4832. (and (boolean? v1) (boolean? v2))
  4833. (and (vector? v1) (vector? v2)))
  4834. (eq? v1 v2)]))]
  4835. ['< (lambda (v1 v2)
  4836. (cond [(and (fixnum? v1) (fixnum? v2))
  4837. (< v1 v2)]))]
  4838. ['<= (lambda (v1 v2)
  4839. (cond [(and (fixnum? v1) (fixnum? v2))
  4840. (<= v1 v2)]))]
  4841. ['> (lambda (v1 v2)
  4842. (cond [(and (fixnum? v1) (fixnum? v2))
  4843. (> v1 v2)]))]
  4844. ['>= (lambda (v1 v2)
  4845. (cond [(and (fixnum? v1) (fixnum? v2))
  4846. (>= v1 v2)]))]
  4847. [else (error 'interp-op "unknown operator")]))
  4848. \end{lstlisting}
  4849. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  4850. \label{fig:interp-op-Rif}
  4851. \end{figure}
  4852. \section{Type Checking \LangIf{} Programs}
  4853. \label{sec:type-check-Rif}
  4854. \index{subject}{type checking}
  4855. \index{subject}{semantic analysis}
  4856. It is helpful to think about type checking in two complementary
  4857. ways. A type checker predicts the type of value that will be produced
  4858. by each expression in the program. For \LangIf{}, we have just two types,
  4859. \key{Integer} and \key{Boolean}. So a type checker should predict that
  4860. \begin{lstlisting}
  4861. (+ 10 (- (+ 12 20)))
  4862. \end{lstlisting}
  4863. produces an \key{Integer} while
  4864. \begin{lstlisting}
  4865. (and (not #f) #t)
  4866. \end{lstlisting}
  4867. produces a \key{Boolean}.
  4868. Another way to think about type checking is that it enforces a set of
  4869. rules about which operators can be applied to which kinds of
  4870. values. For example, our type checker for \LangIf{} signals an error
  4871. for the below expression
  4872. \begin{lstlisting}
  4873. (not (+ 10 (- (+ 12 20))))
  4874. \end{lstlisting}
  4875. The subexpression \code{(+ 10 (- (+ 12 20)))} has type \key{Integer}
  4876. but the type checker enforces the rule that the argument of \code{not}
  4877. must be a \key{Boolean}.
  4878. We implement type checking using classes and methods because they
  4879. provide the open recursion needed to reuse code as we extend the type
  4880. checker in later chapters, analogous to the use of classes and methods
  4881. for the interpreters (Section~\ref{sec:extensible-interp}).
  4882. We separate the type checker for the \LangVar{} fragment into its own
  4883. class, shown in Figure~\ref{fig:type-check-Rvar}. The type checker for
  4884. \LangIf{} is shown in Figure~\ref{fig:type-check-Rif} and it inherits
  4885. from the type checker for \LangVar{}. These type checkers are in the
  4886. files \code{type-check-Rvar.rkt} and \code{type-check-Rif.rkt} of the
  4887. support code.
  4888. %
  4889. Each type checker is a structurally recursive function over the AST.
  4890. Given an input expression \code{e}, the type checker either signals an
  4891. error or returns an expression and its type (\key{Integer} or
  4892. \key{Boolean}). It returns an expression because there are situations
  4893. in which we want to change or update the expression.
  4894. Next we discuss the \code{match} cases in \code{type-check-exp} of
  4895. Figure~\ref{fig:type-check-Rvar}. The type of an integer constant is
  4896. \code{Integer}. To handle variables, the type checker uses the
  4897. environment \code{env} to map variables to types. Consider the case
  4898. for \key{let}. We type check the initializing expression to obtain
  4899. its type \key{T} and then associate type \code{T} with the variable
  4900. \code{x} in the environment used to type check the body of the
  4901. \key{let}. Thus, when the type checker encounters a use of variable
  4902. \code{x}, it can find its type in the environment. Regarding
  4903. primitive operators, we recursively analyze the arguments and then
  4904. invoke \code{type-check-op} to check whether the argument types are
  4905. allowed.
  4906. Several auxiliary methods are used in the type checker. The method
  4907. \code{operator-types} defines a dictionary that maps the operator
  4908. names to their parameter and return types. The \code{type-equal?}
  4909. method determines whether two types are equal, which for now simply
  4910. dispatches to \code{equal?} (deep equality). The
  4911. \code{check-type-equal?} method triggers an error if the two types are
  4912. not equal. The \code{type-check-op} method looks up the operator in
  4913. the \code{operator-types} dictionary and then checks whether the
  4914. argument types are equal to the parameter types. The result is the
  4915. return type of the operator.
  4916. \begin{figure}[tbp]
  4917. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4918. (define type-check-Rvar-class
  4919. (class object%
  4920. (super-new)
  4921. (define/public (operator-types)
  4922. '((+ . ((Integer Integer) . Integer))
  4923. (- . ((Integer) . Integer))
  4924. (read . (() . Integer))))
  4925. (define/public (type-equal? t1 t2) (equal? t1 t2))
  4926. (define/public (check-type-equal? t1 t2 e)
  4927. (unless (type-equal? t1 t2)
  4928. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  4929. (define/public (type-check-op op arg-types e)
  4930. (match (dict-ref (operator-types) op)
  4931. [`(,param-types . ,return-type)
  4932. (for ([at arg-types] [pt param-types])
  4933. (check-type-equal? at pt e))
  4934. return-type]
  4935. [else (error 'type-check-op "unrecognized ~a" op)]))
  4936. (define/public (type-check-exp env)
  4937. (lambda (e)
  4938. (match e
  4939. [(Int n) (values (Int n) 'Integer)]
  4940. [(Var x) (values (Var x) (dict-ref env x))]
  4941. [(Let x e body)
  4942. (define-values (e^ Te) ((type-check-exp env) e))
  4943. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  4944. (values (Let x e^ b) Tb)]
  4945. [(Prim op es)
  4946. (define-values (new-es ts)
  4947. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  4948. (values (Prim op new-es) (type-check-op op ts e))]
  4949. [else (error 'type-check-exp "couldn't match" e)])))
  4950. (define/public (type-check-program e)
  4951. (match e
  4952. [(Program info body)
  4953. (define-values (body^ Tb) ((type-check-exp '()) body))
  4954. (check-type-equal? Tb 'Integer body)
  4955. (Program info body^)]
  4956. [else (error 'type-check-Rvar "couldn't match ~a" e)]))
  4957. ))
  4958. (define (type-check-Rvar p)
  4959. (send (new type-check-Rvar-class) type-check-program p))
  4960. \end{lstlisting}
  4961. \caption{Type checker for the \LangVar{} language.}
  4962. \label{fig:type-check-Rvar}
  4963. \end{figure}
  4964. \begin{figure}[tbp]
  4965. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  4966. (define type-check-Rif-class
  4967. (class type-check-Rvar-class
  4968. (super-new)
  4969. (inherit check-type-equal?)
  4970. (define/override (operator-types)
  4971. (append '((- . ((Integer Integer) . Integer))
  4972. (and . ((Boolean Boolean) . Boolean))
  4973. (or . ((Boolean Boolean) . Boolean))
  4974. (< . ((Integer Integer) . Boolean))
  4975. (<= . ((Integer Integer) . Boolean))
  4976. (> . ((Integer Integer) . Boolean))
  4977. (>= . ((Integer Integer) . Boolean))
  4978. (not . ((Boolean) . Boolean))
  4979. )
  4980. (super operator-types)))
  4981. (define/override (type-check-exp env)
  4982. (lambda (e)
  4983. (match e
  4984. [(Prim 'eq? (list e1 e2))
  4985. (define-values (e1^ T1) ((type-check-exp env) e1))
  4986. (define-values (e2^ T2) ((type-check-exp env) e2))
  4987. (check-type-equal? T1 T2 e)
  4988. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  4989. [(Bool b) (values (Bool b) 'Boolean)]
  4990. [(If cnd thn els)
  4991. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  4992. (define-values (thn^ Tt) ((type-check-exp env) thn))
  4993. (define-values (els^ Te) ((type-check-exp env) els))
  4994. (check-type-equal? Tc 'Boolean e)
  4995. (check-type-equal? Tt Te e)
  4996. (values (If cnd^ thn^ els^) Te)]
  4997. [else ((super type-check-exp env) e)])))
  4998. ))
  4999. (define (type-check-Rif p)
  5000. (send (new type-check-Rif-class) type-check-program p))
  5001. \end{lstlisting}
  5002. \caption{Type checker for the \LangIf{} language.}
  5003. \label{fig:type-check-Rif}
  5004. \end{figure}
  5005. Next we discuss the type checker for \LangIf{} in
  5006. Figure~\ref{fig:type-check-Rif}. The operator \code{eq?} requires the
  5007. two arguments to have the same type. The type of a Boolean constant is
  5008. \code{Boolean}. The condition of an \code{if} must be of
  5009. \code{Boolean} type and the two branches must have the same type. The
  5010. \code{operator-types} function adds dictionary entries for the other
  5011. new operators.
  5012. \begin{exercise}\normalfont
  5013. Create 10 new test programs in \LangIf{}. Half of the programs should
  5014. have a type error. For those programs, create an empty file with the
  5015. same base name but with file extension \code{.tyerr}. For example, if
  5016. the test \code{cond\_test\_14.rkt} is expected to error, then create
  5017. an empty file named \code{cond\_test\_14.tyerr}. This indicates to
  5018. \code{interp-tests} and \code{compiler-tests} that a type error is
  5019. expected. The other half of the test programs should not have type
  5020. errors.
  5021. In the \code{run-tests.rkt} script, change the second argument of
  5022. \code{interp-tests} and \code{compiler-tests} to
  5023. \code{type-check-Rif}, which causes the type checker to run prior to
  5024. the compiler passes. Temporarily change the \code{passes} to an empty
  5025. list and run the script, thereby checking that the new test programs
  5026. either type check or not as intended.
  5027. \end{exercise}
  5028. \section{The \LangCIf{} Intermediate Language}
  5029. \label{sec:Cif}
  5030. Figure~\ref{fig:c1-syntax} defines the abstract syntax of the
  5031. \LangCIf{} intermediate language. (The concrete syntax is in the
  5032. Appendix, Figure~\ref{fig:c1-concrete-syntax}.) Compared to
  5033. \LangCVar{}, the \LangCIf{} language adds logical and comparison
  5034. operators to the \Exp{} non-terminal and the literals \key{\#t} and
  5035. \key{\#f} to the \Arg{} non-terminal.
  5036. Regarding control flow, \LangCIf{} adds \key{goto} and \code{if}
  5037. statements to the \Tail{} non-terminal. The condition of an \code{if}
  5038. statement is a comparison operation and the branches are \code{goto}
  5039. statements, making it straightforward to compile \code{if} statements
  5040. to x86.
  5041. \begin{figure}[tp]
  5042. \fbox{
  5043. \begin{minipage}{0.96\textwidth}
  5044. \small
  5045. \[
  5046. \begin{array}{lcl}
  5047. \Atm &::=& \gray{\INT{\Int} \MID \VAR{\Var}} \MID \BOOL{\itm{bool}} \\
  5048. \itm{cmp} &::= & \key{eq?} \MID \key{<} \\
  5049. \Exp &::= & \gray{ \Atm \MID \READ{} }\\
  5050. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  5051. &\MID& \UNIOP{\key{'not}}{\Atm}
  5052. \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  5053. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  5054. \Tail &::= & \gray{\RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail} }
  5055. \MID \GOTO{\itm{label}} \\
  5056. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  5057. \LangCIfM{} & ::= & \gray{\CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}}
  5058. \end{array}
  5059. \]
  5060. \end{minipage}
  5061. }
  5062. \caption{The abstract syntax of \LangCIf{}, an extension of \LangCVar{}
  5063. (Figure~\ref{fig:c0-syntax}).}
  5064. \label{fig:c1-syntax}
  5065. \end{figure}
  5066. \section{The \LangXIf{} Language}
  5067. \label{sec:x86-if}
  5068. \index{subject}{x86} To implement the new logical operations, the comparison
  5069. operations, and the \key{if} expression, we need to delve further into
  5070. the x86 language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1}
  5071. define the concrete and abstract syntax for the \LangXIf{} subset
  5072. of x86, which includes instructions for logical operations,
  5073. comparisons, and conditional jumps.
  5074. One challenge is that x86 does not provide an instruction that
  5075. directly implements logical negation (\code{not} in \LangIf{} and
  5076. \LangCIf{}). However, the \code{xorq} instruction can be used to
  5077. encode \code{not}. The \key{xorq} instruction takes two arguments,
  5078. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  5079. bit of its arguments, and writes the results into its second argument.
  5080. Recall the truth table for exclusive-or:
  5081. \begin{center}
  5082. \begin{tabular}{l|cc}
  5083. & 0 & 1 \\ \hline
  5084. 0 & 0 & 1 \\
  5085. 1 & 1 & 0
  5086. \end{tabular}
  5087. \end{center}
  5088. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  5089. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  5090. for the bit $1$, the result is the opposite of the second bit. Thus,
  5091. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  5092. the first argument:
  5093. \[
  5094. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  5095. \qquad\Rightarrow\qquad
  5096. \begin{array}{l}
  5097. \key{movq}~ \Arg\key{,} \Var\\
  5098. \key{xorq}~ \key{\$1,} \Var
  5099. \end{array}
  5100. \]
  5101. \begin{figure}[tp]
  5102. \fbox{
  5103. \begin{minipage}{0.96\textwidth}
  5104. \[
  5105. \begin{array}{lcl}
  5106. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  5107. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  5108. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} } \MID \key{\%}\itm{bytereg}\\
  5109. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  5110. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \MID
  5111. \key{subq} \; \Arg\key{,} \Arg \MID
  5112. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID } \\
  5113. && \gray{ \key{callq} \; \itm{label} \MID
  5114. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \MID \key{jmp}\,\itm{label} } \\
  5115. && \gray{ \itm{label}\key{:}\; \Instr }
  5116. \MID \key{xorq}~\Arg\key{,}~\Arg
  5117. \MID \key{cmpq}~\Arg\key{,}~\Arg \MID \\
  5118. && \key{set}cc~\Arg
  5119. \MID \key{movzbq}~\Arg\key{,}~\Arg
  5120. \MID \key{j}cc~\itm{label}
  5121. \\
  5122. \LangXIfM{} &::= & \gray{ \key{.globl main} }\\
  5123. & & \gray{ \key{main:} \; \Instr\ldots }
  5124. \end{array}
  5125. \]
  5126. \end{minipage}
  5127. }
  5128. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  5129. \label{fig:x86-1-concrete}
  5130. \end{figure}
  5131. \begin{figure}[tp]
  5132. \fbox{
  5133. \begin{minipage}{0.98\textwidth}
  5134. \small
  5135. \[
  5136. \begin{array}{lcl}
  5137. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  5138. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  5139. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  5140. \MID \BYTEREG{\itm{bytereg}} \\
  5141. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  5142. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  5143. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  5144. &\MID& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  5145. \MID \UNIINSTR{\code{negq}}{\Arg} } \\
  5146. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  5147. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} } \\
  5148. &\MID& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  5149. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  5150. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  5151. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  5152. &\MID& \JMPIF{\itm{cc}}{\itm{label}} \\
  5153. \Block &::= & \gray{\BLOCK{\itm{info}}{\LP\Instr\ldots\RP}} \\
  5154. \LangXIfM{} &::= & \gray{\XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}}
  5155. \end{array}
  5156. \]
  5157. \end{minipage}
  5158. }
  5159. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  5160. \label{fig:x86-1}
  5161. \end{figure}
  5162. Next we consider the x86 instructions that are relevant for compiling
  5163. the comparison operations. The \key{cmpq} instruction compares its two
  5164. arguments to determine whether one argument is less than, equal, or
  5165. greater than the other argument. The \key{cmpq} instruction is unusual
  5166. regarding the order of its arguments and where the result is
  5167. placed. The argument order is backwards: if you want to test whether
  5168. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  5169. \key{cmpq} is placed in the special EFLAGS register. This register
  5170. cannot be accessed directly but it can be queried by a number of
  5171. instructions, including the \key{set} instruction. The instruction
  5172. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  5173. depending on whether the comparison comes out according to the
  5174. condition code \itm{cc} (\key{e} for equal, \key{l} for less, \key{le}
  5175. for less-or-equal, \key{g} for greater, \key{ge} for
  5176. greater-or-equal). The \key{set} instruction has an annoying quirk in
  5177. that its destination argument must be single byte register, such as
  5178. \code{al} (L for lower bits) or \code{ah} (H for higher bits), which
  5179. are part of the \code{rax} register. Thankfully, the \key{movzbq}
  5180. instruction can be used to move from a single byte register to a
  5181. normal 64-bit register. The abstract syntax for the \code{set}
  5182. instruction differs from the concrete syntax in that it separates the
  5183. instruction name from the condition code.
  5184. The x86 instruction for conditional jump is relevant to the
  5185. compilation of \key{if} expressions. The instruction
  5186. $\key{j}\itm{cc}~\itm{label}$ updates the program counter to point to
  5187. the instruction after \itm{label} depending on whether the result in
  5188. the EFLAGS register matches the condition code \itm{cc}, otherwise the
  5189. jump instruction falls through to the next instruction. Like the
  5190. abstract syntax for \code{set}, the abstract syntax for conditional
  5191. jump separates the instruction name from the condition code. For
  5192. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  5193. the conditional jump instruction relies on the EFLAGS register, it is
  5194. common for it to be immediately preceded by a \key{cmpq} instruction
  5195. to set the EFLAGS register.
  5196. \section{Shrink the \LangIf{} Language}
  5197. \label{sec:shrink-Rif}
  5198. The \LangIf{} language includes several operators that are easily
  5199. expressible with other operators. For example, subtraction is
  5200. expressible using addition and negation.
  5201. \[
  5202. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  5203. \]
  5204. Several of the comparison operations are expressible using less-than
  5205. and logical negation.
  5206. \[
  5207. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  5208. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  5209. \]
  5210. The \key{let} is needed in the above translation to ensure that
  5211. expression $e_1$ is evaluated before $e_2$.
  5212. By performing these translations in the front-end of the compiler, the
  5213. later passes of the compiler do not need to deal with these operators,
  5214. making the passes shorter.
  5215. %% On the other hand, sometimes
  5216. %% these translations make it more difficult to generate the most
  5217. %% efficient code with respect to the number of instructions. However,
  5218. %% these differences typically do not affect the number of accesses to
  5219. %% memory, which is the primary factor that determines execution time on
  5220. %% modern computer architectures.
  5221. \begin{exercise}\normalfont
  5222. Implement the pass \code{shrink} to remove subtraction, \key{and},
  5223. \key{or}, \key{<=}, \key{>}, and \key{>=} from the language by
  5224. translating them to other constructs in \LangIf{}.
  5225. %
  5226. Create six test programs that involve these operators.
  5227. %
  5228. In the \code{run-tests.rkt} script, add the following entry for
  5229. \code{shrink} to the list of passes (it should be the only pass at
  5230. this point).
  5231. \begin{lstlisting}
  5232. (list "shrink" shrink interp-Rif type-check-Rif)
  5233. \end{lstlisting}
  5234. This instructs \code{interp-tests} to run the intepreter
  5235. \code{interp-Rif} and the type checker \code{type-check-Rif} on the
  5236. output of \code{shrink}.
  5237. %
  5238. Run the script to test your compiler on all the test programs.
  5239. \end{exercise}
  5240. \section{Uniquify Variables}
  5241. \label{sec:uniquify-Rif}
  5242. Add cases to \code{uniquify-exp} to handle Boolean constants and
  5243. \code{if} expressions.
  5244. \begin{exercise}\normalfont
  5245. Update the \code{uniquify-exp} for \LangIf{} and add the following
  5246. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  5247. \begin{lstlisting}
  5248. (list "uniquify" uniquify interp-Rif type-check-Rif)
  5249. \end{lstlisting}
  5250. Run the script to test your compiler.
  5251. \end{exercise}
  5252. \section{Remove Complex Operands}
  5253. \label{sec:remove-complex-opera-Rif}
  5254. The output language for this pass is \LangIfANF{}
  5255. (Figure~\ref{fig:Rif-anf-syntax}), the administrative normal form of
  5256. \LangIf{}. The \code{Bool} form is an atomic expressions but
  5257. \code{If} is not. All three sub-expressions of an \code{If} are
  5258. allowed to be complex expressions but the operands of \code{not} and
  5259. the comparisons must be atoms.
  5260. Add cases for \code{Bool} and \code{If} to the \code{rco\_exp} and
  5261. \code{rco\_atom} functions according to whether the output needs to be
  5262. \Exp{} or \Atm{} as specified in the grammar for \LangIfANF{}.
  5263. Regarding \code{If}, it is particularly important to \textbf{not}
  5264. replace its condition with a temporary variable because that would
  5265. interfere with the generation of high-quality output in the
  5266. \code{explicate-control} pass.
  5267. \begin{figure}[tp]
  5268. \centering
  5269. \fbox{
  5270. \begin{minipage}{0.96\textwidth}
  5271. \[
  5272. \begin{array}{rcl}
  5273. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} } \MID \BOOL{\itm{bool}}\\
  5274. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  5275. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  5276. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  5277. &\MID& \UNIOP{\key{not}}{\Atm} \\
  5278. &\MID& \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  5279. R^{\dagger}_2 &::=& \PROGRAM{\code{()}}{\Exp}
  5280. \end{array}
  5281. \]
  5282. \end{minipage}
  5283. }
  5284. \caption{\LangIfANF{} is \LangIf{} in administrative normal form (ANF).}
  5285. \label{fig:Rif-anf-syntax}
  5286. \end{figure}
  5287. \begin{exercise}\normalfont
  5288. %
  5289. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  5290. and \code{rco\_exp} functions in \code{compiler.rkt}.
  5291. %
  5292. Create three new \LangInt{} programs that exercise the interesting
  5293. code in this pass.
  5294. %
  5295. In the \code{run-tests.rkt} script, add the following entry to the
  5296. list of \code{passes} and then run the script to test your compiler.
  5297. \begin{lstlisting}
  5298. (list "remove-complex" remove-complex-opera* interp-Rif type-check-Rif)
  5299. \end{lstlisting}
  5300. \end{exercise}
  5301. \section{Explicate Control}
  5302. \label{sec:explicate-control-Rif}
  5303. Recall that the purpose of \code{explicate-control} is to make the
  5304. order of evaluation explicit in the syntax of the program. With the
  5305. addition of \key{if} this get more interesting.
  5306. As a motivating example, consider the following program that has an
  5307. \key{if} expression nested in the predicate of another \key{if}.
  5308. % cond_test_41.rkt, if_lt_eq.py
  5309. \begin{center}
  5310. \begin{minipage}{0.96\textwidth}
  5311. \begin{lstlisting}
  5312. (let ([x (read)])
  5313. (let ([y (read)])
  5314. (if (if (< x 1) (eq? x 0) (eq? x 2))
  5315. (+ y 2)
  5316. (+ y 10))))
  5317. \end{lstlisting}
  5318. \end{minipage}
  5319. \end{center}
  5320. %
  5321. The naive way to compile \key{if} and the comparison would be to
  5322. handle each of them in isolation, regardless of their context. Each
  5323. comparison would be translated into a \key{cmpq} instruction followed
  5324. by a couple instructions to move the result from the EFLAGS register
  5325. into a general purpose register or stack location. Each \key{if} would
  5326. be translated into a \key{cmpq} instruction followed by a conditional
  5327. jump. The generated code for the inner \key{if} in the above example
  5328. would be as follows.
  5329. \begin{center}
  5330. \begin{minipage}{0.96\textwidth}
  5331. \begin{lstlisting}
  5332. ...
  5333. cmpq $1, x ;; (< x 1)
  5334. setl %al
  5335. movzbq %al, tmp
  5336. cmpq $1, tmp ;; (if ...)
  5337. je then_branch_1
  5338. jmp else_branch_1
  5339. ...
  5340. \end{lstlisting}
  5341. \end{minipage}
  5342. \end{center}
  5343. However, if we take context into account we can do better and reduce
  5344. the use of \key{cmpq} instructions for accessing the EFLAG register.
  5345. Our goal will be compile \key{if} expressions so that the relevant
  5346. comparison instruction appears directly before the conditional jump.
  5347. For example, we want to generate the following code for the inner
  5348. \code{if}.
  5349. \begin{center}
  5350. \begin{minipage}{0.96\textwidth}
  5351. \begin{lstlisting}
  5352. ...
  5353. cmpq $1, x
  5354. je then_branch_1
  5355. jmp else_branch_1
  5356. ...
  5357. \end{lstlisting}
  5358. \end{minipage}
  5359. \end{center}
  5360. One way to achieve this is to reorganize the code at the level of
  5361. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  5362. the following code.
  5363. \begin{center}
  5364. \begin{minipage}{0.96\textwidth}
  5365. \begin{lstlisting}
  5366. (let ([x (read)])
  5367. (let ([y (read)])
  5368. (if (< x 1)
  5369. (if (eq? x 0)
  5370. (+ y 2)
  5371. (+ y 10))
  5372. (if (eq? x 2)
  5373. (+ y 2)
  5374. (+ y 10)))))
  5375. \end{lstlisting}
  5376. \end{minipage}
  5377. \end{center}
  5378. Unfortunately, this approach duplicates the two branches from the
  5379. outer \code{if} and a compiler must never duplicate code!
  5380. We need a way to perform the above transformation but without
  5381. duplicating code. That is, we need a way for different parts of a
  5382. program to refer to the same piece of code. At the level of x86
  5383. assembly this is straightforward because we can label the code for
  5384. each branch and insert jumps in all the places that need to execute
  5385. the branch. In our intermediate language, we need to move away from
  5386. abstract syntax \emph{trees} and instead use \emph{graphs}. In
  5387. particular, we use a standard program representation called a
  5388. \emph{control flow graph} (CFG), due to Frances Elizabeth
  5389. \citet{Allen:1970uq}. \index{subject}{control-flow graph} Each vertex is a
  5390. labeled sequence of code, called a \emph{basic block}, and each edge
  5391. represents a jump to another block. The \key{CProgram} construct of
  5392. \LangCVar{} and \LangCIf{} contains a control flow graph represented
  5393. as an alist mapping labels to basic blocks. Each basic block is
  5394. represented by the $\Tail$ non-terminal.
  5395. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  5396. \code{remove-complex-opera*} pass and then the
  5397. \code{explicate-control} pass on the example program. We walk through
  5398. the output program and then discuss the algorithm.
  5399. %
  5400. Following the order of evaluation in the output of
  5401. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  5402. and then the comparison \lstinline{(< x 1)} in the predicate of the
  5403. inner \key{if}. In the output of \code{explicate-control}, in the
  5404. block labeled \code{start}, is two assignment statements followed by a
  5405. \code{if} statement that branches to \code{block40} or
  5406. \code{block41}. The blocks associated with those labels contain the
  5407. translations of the code \lstinline{(eq? x 0)} and \lstinline{(eq? x 2)},
  5408. respectively. In particular, we start \code{block40} with the
  5409. comparison \lstinline{(eq? x 0)} and then branch to \code{block38} or
  5410. \code{block39}, the two branches of the outer \key{if}, i.e.,
  5411. \lstinline{(+ y 2)} and \lstinline{(+ y 10)}. The story for
  5412. \code{block41} is similar.
  5413. \begin{figure}[tbp]
  5414. \begin{tabular}{lll}
  5415. \begin{minipage}{0.4\textwidth}
  5416. % cond_test_41.rkt
  5417. \begin{lstlisting}
  5418. (let ([x (read)])
  5419. (let ([y (read)])
  5420. (if (if (< x 1)
  5421. (eq? x 0)
  5422. (eq? x 2))
  5423. (+ y 2)
  5424. (+ y 10))))
  5425. \end{lstlisting}
  5426. \hspace{40pt}$\Downarrow$
  5427. \begin{lstlisting}
  5428. (let ([x (read)])
  5429. (let ([y (read)])
  5430. (if (if (< x 1)
  5431. (eq? x 0)
  5432. (eq? x 2))
  5433. (+ y 2)
  5434. (+ y 10))))
  5435. \end{lstlisting}
  5436. \end{minipage}
  5437. &
  5438. $\Rightarrow$
  5439. &
  5440. \begin{minipage}{0.55\textwidth}
  5441. \begin{lstlisting}
  5442. start:
  5443. x = (read);
  5444. y = (read);
  5445. if (< x 1) goto block40;
  5446. else goto block41;
  5447. block40:
  5448. if (eq? x 0) goto block38;
  5449. else goto block39;
  5450. block41:
  5451. if (eq? x 2) goto block38;
  5452. else goto block39;
  5453. block38:
  5454. return (+ y 2);
  5455. block39:
  5456. return (+ y 10);
  5457. \end{lstlisting}
  5458. \end{minipage}
  5459. \end{tabular}
  5460. \caption{Translation from \LangIf{} to \LangCIf{}
  5461. via the \code{explicate-control}.}
  5462. \label{fig:explicate-control-s1-38}
  5463. \end{figure}
  5464. %% The nice thing about the output of \code{explicate-control} is that
  5465. %% there are no unnecessary comparisons and every comparison is part of a
  5466. %% conditional jump.
  5467. %% The down-side of this output is that it includes
  5468. %% trivial blocks, such as the blocks labeled \code{block92} through
  5469. %% \code{block95}, that only jump to another block. We discuss a solution
  5470. %% to this problem in Section~\ref{sec:opt-jumps}.
  5471. Recall that in Section~\ref{sec:explicate-control-Rvar} we implement
  5472. \code{explicate-control} for \LangVar{} using two mutually recursive
  5473. functions, \code{explicate-tail} and \code{explicate-assign}. The
  5474. former function translates expressions in tail position whereas the
  5475. later function translates expressions on the right-hand-side of a
  5476. \key{let}. With the addition of \key{if} expression in \LangIf{} we
  5477. have a new kind of position to deal with: the predicate position of
  5478. the \key{if}. We need another function, \code{explicate-pred}, that
  5479. takes an \LangIf{} expression and two blocks for the then-branch and
  5480. else-branch. The output of \code{explicate-pred} is a block.
  5481. %
  5482. In the following paragraphs we discuss specific cases in the
  5483. \code{explicate-pred} function as well as additions to the
  5484. \code{explicate-tail} and \code{explicate-assign} functions.
  5485. \begin{figure}[tbp]
  5486. \begin{lstlisting}
  5487. (define (explicate-pred cnd thn els)
  5488. (match cnd
  5489. [(Var x) ___]
  5490. [(Let x rhs body) ___]
  5491. [(Prim 'not (list e)) ___]
  5492. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  5493. (IfStmt (Prim op arg*) (force (block->goto thn))
  5494. (force (block->goto els)))]
  5495. [(Bool b) (if b thn els)]
  5496. [(If cnd^ thn^ els^) ___]
  5497. [else (error "explicate-pred unhandled case" cnd)]))
  5498. \end{lstlisting}
  5499. \caption{Skeleton for the \key{explicate-pred} auxiliary function.}
  5500. \label{fig:explicate-pred}
  5501. \end{figure}
  5502. The skeleton for the \code{explicate-pred} function is given in
  5503. Figure~\ref{fig:explicate-pred}. It has a case for every expression
  5504. that can have type \code{Boolean}. We detail a few cases here and
  5505. leave the rest for the reader. The input to this function is an
  5506. expression and two blocks, \code{thn} and \code{els}, for the two
  5507. branches of the enclosing \key{if}.
  5508. %
  5509. Consider the case for Boolean constants in
  5510. Figure~\ref{fig:explicate-pred}. We perform a kind of partial
  5511. evaluation\index{subject}{partial evaluation} and output either the \code{thn}
  5512. or \code{els} branch depending on whether the constant is true or
  5513. false. This case demonstrates that we sometimes discard the \code{thn}
  5514. or \code{els} blocks that are input to \code{explicate-pred}.
  5515. The case for \key{if} in \code{explicate-pred} is particularly
  5516. illuminating because it deals with the challenges we discussed above
  5517. regarding nested \key{if} expressions
  5518. (Figure~\ref{fig:explicate-control-s1-38}). The \lstinline{thn^} and
  5519. \lstinline{els^} branches of the \key{if} inherit their context from
  5520. the current one, that is, predicate context. So you should recursively
  5521. apply \code{explicate-pred} to the \lstinline{thn^} and
  5522. \lstinline{els^} branches. For both of those recursive calls, pass
  5523. \code{thn} and \code{els} as the extra parameters. Thus, \code{thn}
  5524. and \code{els} may get used twice, once inside each recursive call. As
  5525. discussed above, to avoid duplicating code, we need to add them to the
  5526. control-flow graph so that we can instead refer to them by name and
  5527. execute them with a \key{goto}. However, as we saw in the cases above
  5528. for Boolean constants, the blocks \code{thn} and \code{els} may not
  5529. get used at all and we don't want to prematurely add them to the
  5530. control-flow graph if they end up being discarded.
  5531. The solution to this conundrum is to use \emph{lazy
  5532. evaluation}\index{subject}{lazy evaluation}\citep{Friedman:1976aa} to delay
  5533. adding the blocks to the control-flow graph until the points where we
  5534. know they will be used. Racket provides support for lazy evaluation
  5535. with the
  5536. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  5537. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  5538. \index{subject}{delay} creates a \emph{promise}\index{subject}{promise} in which the
  5539. evaluation of the expressions is postponed. When \key{(force}
  5540. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the first
  5541. time, the expressions $e_1 \ldots e_n$ are evaluated and the result of
  5542. $e_n$ is cached in the promise and returned. If \code{force} is
  5543. applied again to the same promise, then the cached result is returned.
  5544. If \code{force} is applied to an argument that is not a promise,
  5545. \code{force} simply returns the argument.
  5546. We use lazy evaluation for the input and output blocks of the
  5547. functions \code{explicate-pred} and \code{explicate-assign} and for
  5548. the output block of \code{explicate-tail}. So instead of taking and
  5549. returning blocks, they take and return promises. Furthermore, when we
  5550. come to a situation in which we a block might be used more than once,
  5551. as in the case for \code{if} in \code{explicate-pred}, we transform
  5552. the promise into a new promise that will add the block to the
  5553. control-flow graph and return a \code{goto}. The following auxiliary
  5554. function named \code{block->goto} accomplishes this task. It begins
  5555. with \code{delay} to create a promise. When forced, this promise will
  5556. force the original promise. If that returns a \code{goto} (because the
  5557. block was already added to the control-flow graph), then we return the
  5558. \code{goto}. Otherwise we add the block to the control-flow graph with
  5559. another auxiliary function named \code{add-node}. That function
  5560. returns the label for the new block, which we use to create a
  5561. \code{goto}.
  5562. \begin{lstlisting}
  5563. (define (block->goto block)
  5564. (delay
  5565. (define b (force block))
  5566. (match b
  5567. [(Goto label) (Goto label)]
  5568. [else (Goto (add-node b))])))
  5569. \end{lstlisting}
  5570. Returning to the discussion of \code{explicate-pred}
  5571. (Figure~\ref{fig:explicate-pred}), consider the case for comparison
  5572. operators. This is one of the base cases of the recursive function so
  5573. we translate the comparison to an \code{if} statement. We apply
  5574. \code{block->goto} to \code{thn} and \code{els} to obtain two promises
  5575. that will add then to the control-flow graph, which we can immediately
  5576. \code{force} to obtain the two goto's that form the branches of the
  5577. \code{if} statement.
  5578. %% Getting back to the case for \code{if} in \code{explicate-pred}, we
  5579. %% make the recursive calls to \code{explicate-pred} on the ``then'' and
  5580. %% ``else'' branches with the arguments \code{(block->goto} $B_1$\code{)}
  5581. %% and \code{(block->goto} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  5582. %% results from the two recursive calls. We complete the case for
  5583. %% \code{if} by recursively apply \code{explicate-pred} to the condition
  5584. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  5585. %% the result $B_5$.
  5586. %% \[
  5587. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  5588. %% \quad\Rightarrow\quad
  5589. %% B_5
  5590. %% \]
  5591. The \code{explicate-tail} and \code{explicate-assign} functions need
  5592. additional cases for Boolean constants and \key{if}.
  5593. %
  5594. In the cases for \code{if}, the two branches inherit the current
  5595. context, so in \code{explicate-tail} they are in tail position and in
  5596. \code{explicate-assign} they are in assignment position. The
  5597. \code{cont} parameter of \code{explicate-assign} is used in both
  5598. recursive calls, so make sure to use \code{block->goto} on it.
  5599. %% In the case for \code{if} in \code{explicate-tail}, the two branches
  5600. %% inherit the current context, so they are in tail position. Thus, the
  5601. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  5602. %% \code{explicate-tail}.
  5603. %% %
  5604. %% We need to pass $B_0$ as the accumulator argument for both of these
  5605. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  5606. %% Thus, we first apply \code{block->goto} to $B_0$ so that it gets added
  5607. %% to the control-flow graph and obtain a promised goto $G_0$.
  5608. %% %
  5609. %% Let $B_1$ be the result of \code{explicate-tail} on the ``then''
  5610. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate-tail}
  5611. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  5612. %% \code{explicate-pred} to the condition of the \key{if}, $B_1$, and
  5613. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  5614. %% \[
  5615. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  5616. %% \]
  5617. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  5618. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  5619. %% should not be confused with the labels for the blocks that appear in
  5620. %% the generated code. We initially construct unlabeled blocks; we only
  5621. %% attach labels to blocks when we add them to the control-flow graph, as
  5622. %% we see in the next case.
  5623. %% Next consider the case for \key{if} in the \code{explicate-assign}
  5624. %% function. The context of the \key{if} is an assignment to some
  5625. %% variable $x$ and then the control continues to some promised block
  5626. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  5627. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  5628. %% apply \code{block->goto} to it and obtain a promised goto $G_1$. The
  5629. %% branches of the \key{if} inherit the current context, so they are in
  5630. %% assignment positions. Let $B_2$ be the result of applying
  5631. %% \code{explicate-assign} to the ``then'' branch, variable $x$, and
  5632. %% $G_1$. Let $B_3$ be the result of applying \code{explicate-assign} to
  5633. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  5634. %% the result of applying \code{explicate-pred} to the predicate
  5635. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  5636. %% translates to the promise $B_4$.
  5637. %% \[
  5638. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  5639. %% \]
  5640. %% This completes the description of \code{explicate-control} for \LangIf{}.
  5641. The way in which the \code{shrink} pass transforms logical operations
  5642. such as \code{and} and \code{or} can impact the quality of code
  5643. generated by \code{explicate-control}. For example, consider the
  5644. following program.
  5645. % cond_test_21.rkt, and_eq_input.py
  5646. \begin{lstlisting}
  5647. (if (and (eq? (read) 0) (eq? (read) 1))
  5648. 0
  5649. 42)
  5650. \end{lstlisting}
  5651. The \code{and} operation should transform into something that the
  5652. \code{explicate-pred} function can still analyze and descend through to
  5653. reach the underlying \code{eq?} conditions. Ideally, your
  5654. \code{explicate-control} pass should generate code similar to the
  5655. following for the above program.
  5656. \begin{center}
  5657. \begin{lstlisting}
  5658. start:
  5659. tmp1 = (read);
  5660. if (eq? tmp1 0) goto block40;
  5661. else goto block39;
  5662. block40:
  5663. tmp2 = (read);
  5664. if (eq? tmp2 1) goto block38;
  5665. else goto block39;
  5666. block38:
  5667. return 0;
  5668. block39:
  5669. return 42;
  5670. \end{lstlisting}
  5671. \end{center}
  5672. \begin{exercise}\normalfont
  5673. Implement the pass \code{explicate-control} by adding the cases for
  5674. Boolean constants and \key{if} to the \code{explicate-tail} and
  5675. \code{explicate-assign}. Implement the auxiliary function
  5676. \code{explicate-pred} for predicate contexts.
  5677. %
  5678. Create test cases that exercise all of the new cases in the code for
  5679. this pass.
  5680. %
  5681. Add the following entry to the list of \code{passes} in
  5682. \code{run-tests.rkt} and then run this script to test your compiler.
  5683. \begin{lstlisting}
  5684. (list "explicate-control" explicate-control interp-Cif type-check-Cif)
  5685. \end{lstlisting}
  5686. \end{exercise}
  5687. \section{Select Instructions}
  5688. \label{sec:select-Rif}
  5689. \index{subject}{instruction selection}
  5690. The \code{select-instructions} pass translate \LangCIf{} to
  5691. \LangXIfVar{}. Recall that we implement this pass using three
  5692. auxiliary functions, one for each of the non-terminals $\Atm$,
  5693. $\Stmt$, and $\Tail$.
  5694. For $\Atm$, we have new cases for the Booleans. We take the usual
  5695. approach of encoding them as integers, with true as 1 and false as 0.
  5696. \[
  5697. \key{\#t} \Rightarrow \key{1}
  5698. \qquad
  5699. \key{\#f} \Rightarrow \key{0}
  5700. \]
  5701. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  5702. be implemented in terms of \code{xorq} as we discussed at the
  5703. beginning of this section. Given an assignment
  5704. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  5705. if the left-hand side $\itm{var}$ is
  5706. the same as $\Atm$, then just the \code{xorq} suffices.
  5707. \[
  5708. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  5709. \quad\Rightarrow\quad
  5710. \key{xorq}~\key{\$}1\key{,}~\Var
  5711. \]
  5712. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  5713. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  5714. x86. Then we have
  5715. \[
  5716. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  5717. \quad\Rightarrow\quad
  5718. \begin{array}{l}
  5719. \key{movq}~\Arg\key{,}~\Var\\
  5720. \key{xorq}~\key{\$}1\key{,}~\Var
  5721. \end{array}
  5722. \]
  5723. Next consider the cases for \code{eq?} and less-than comparison.
  5724. Translating these operations to x86 is slightly involved due to the
  5725. unusual nature of the \key{cmpq} instruction discussed above. We
  5726. recommend translating an assignment from \code{eq?} into the following
  5727. sequence of three instructions. \\
  5728. \begin{tabular}{lll}
  5729. \begin{minipage}{0.4\textwidth}
  5730. \begin{lstlisting}
  5731. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  5732. \end{lstlisting}
  5733. \end{minipage}
  5734. &
  5735. $\Rightarrow$
  5736. &
  5737. \begin{minipage}{0.4\textwidth}
  5738. \begin{lstlisting}
  5739. cmpq |$\Arg_2$|, |$\Arg_1$|
  5740. sete %al
  5741. movzbq %al, |$\Var$|
  5742. \end{lstlisting}
  5743. \end{minipage}
  5744. \end{tabular} \\
  5745. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  5746. and \key{if} statements. Both are straightforward to translate to
  5747. x86. A \key{goto} becomes a jump instruction.
  5748. \[
  5749. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  5750. \]
  5751. An \key{if} statement becomes a compare instruction followed by a
  5752. conditional jump (for the ``then'' branch) and the fall-through is to
  5753. a regular jump (for the ``else'' branch).\\
  5754. \begin{tabular}{lll}
  5755. \begin{minipage}{0.4\textwidth}
  5756. \begin{lstlisting}
  5757. if (eq? |$\Atm_1$| |$\Atm_2$|) goto |$\ell_1$|;
  5758. else goto |$\ell_2$|;
  5759. \end{lstlisting}
  5760. \end{minipage}
  5761. &
  5762. $\Rightarrow$
  5763. &
  5764. \begin{minipage}{0.4\textwidth}
  5765. \begin{lstlisting}
  5766. cmpq |$\Arg_2$|, |$\Arg_1$|
  5767. je |$\ell_1$|
  5768. jmp |$\ell_2$|
  5769. \end{lstlisting}
  5770. \end{minipage}
  5771. \end{tabular} \\
  5772. \begin{exercise}\normalfont
  5773. Expand your \code{select-instructions} pass to handle the new features
  5774. of the \LangIf{} language.
  5775. %
  5776. Add the following entry to the list of \code{passes} in
  5777. \code{run-tests.rkt}
  5778. \begin{lstlisting}
  5779. (list "select-instructions" select-instructions interp-pseudo-x86-1)
  5780. \end{lstlisting}
  5781. %
  5782. Run the script to test your compiler on all the test programs.
  5783. \end{exercise}
  5784. \section{Register Allocation}
  5785. \label{sec:register-allocation-Rif}
  5786. \index{subject}{register allocation}
  5787. The changes required for \LangIf{} affect liveness analysis, building the
  5788. interference graph, and assigning homes, but the graph coloring
  5789. algorithm itself does not change.
  5790. \subsection{Liveness Analysis}
  5791. \label{sec:liveness-analysis-Rif}
  5792. \index{subject}{liveness analysis}
  5793. Recall that for \LangVar{} we implemented liveness analysis for a single
  5794. basic block (Section~\ref{sec:liveness-analysis-Rvar}). With the
  5795. addition of \key{if} expressions to \LangIf{}, \code{explicate-control}
  5796. produces many basic blocks arranged in a control-flow graph. We
  5797. recommend that you create a new auxiliary function named
  5798. \code{uncover-live-CFG} that applies liveness analysis to a
  5799. control-flow graph.
  5800. The first question we is: what order should we process the basic
  5801. blocks in the control-flow graph? Recall that to perform liveness
  5802. analysis on a basic block we need to know its live-after set. If a
  5803. basic block has no successors (i.e. no out-edges in the control flow
  5804. graph), then it has an empty live-after set and we can immediately
  5805. apply liveness analysis to it. If a basic block has some successors,
  5806. then we need to complete liveness analysis on those blocks first. In
  5807. graph theory, a sequence of nodes is in \emph{topological
  5808. order}\index{subject}{topological order} if each vertex comes before its
  5809. successors. We need the opposite, so we can transpose the graph
  5810. before computing a topological order.
  5811. %
  5812. Use the \code{tsort} and \code{transpose} functions of the Racket
  5813. \code{graph} package to accomplish this.
  5814. %
  5815. As an aside, a topological ordering is only guaranteed to exist if the
  5816. graph does not contain any cycles. That is indeed the case for the
  5817. control-flow graphs that we generate from \LangIf{} programs.
  5818. However, in Chapter~\ref{ch:Rwhile} we add loops to \LangLoop{} and
  5819. learn how to handle cycles in the control-flow graph.
  5820. You'll need to construct a directed graph to represent the
  5821. control-flow graph. Do not use the \code{directed-graph} of the
  5822. \code{graph} package because that only allows at most one edge between
  5823. each pair of vertices, but a control-flow graph may have multiple
  5824. edges between a pair of vertices. The \code{multigraph.rkt} file in
  5825. the support code implements a graph representation that allows
  5826. multiple edges between a pair of vertices.
  5827. The next question is how to analyze jump instructions. Recall that in
  5828. Section~\ref{sec:liveness-analysis-Rvar} we maintain an alist named
  5829. \code{label->live} that maps each label to the set of live locations
  5830. at the beginning of its block. We use \code{label->live} to determine
  5831. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  5832. that we have many basic blocks, \code{label->live} needs to be updated
  5833. as we process the blocks. In particular, after performing liveness
  5834. analysis on a block, we take the live-before set of its first
  5835. instruction and associate that with the block's label in the
  5836. \code{label->live}.
  5837. In \LangXIfVar{} we also have the conditional jump
  5838. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  5839. this instruction is particularly interesting because during
  5840. compilation we do not know which way a conditional jump will go. So
  5841. we do not know whether to use the live-before set for the following
  5842. instruction or the live-before set for the $\itm{label}$. However,
  5843. there is no harm to the correctness of the compiler if we classify
  5844. more locations as live than the ones that are truly live during a
  5845. particular execution of the instruction. Thus, we can take the union
  5846. of the live-before sets from the following instruction and from the
  5847. mapping for $\itm{label}$ in \code{label->live}.
  5848. The auxiliary functions for computing the variables in an
  5849. instruction's argument and for computing the variables read-from ($R$)
  5850. or written-to ($W$) by an instruction need to be updated to handle the
  5851. new kinds of arguments and instructions in \LangXIfVar{}.
  5852. \begin{exercise}\normalfont
  5853. Update the \code{uncover-live} pass and implement the
  5854. \code{uncover-live-CFG} auxiliary function to apply liveness analysis
  5855. to the control-flow graph. Add the following entry to the list of
  5856. \code{passes} in the \code{run-tests.rkt} script.
  5857. \begin{lstlisting}
  5858. (list "uncover-live" uncover-live interp-pseudo-x86-1)
  5859. \end{lstlisting}
  5860. \end{exercise}
  5861. \subsection{Build the Interference Graph}
  5862. \label{sec:build-interference-Rif}
  5863. Many of the new instructions in \LangXIfVar{} can be handled in the
  5864. same way as the instructions in \LangXVar{}. Thus, if your code was
  5865. already quite general, it will not need to be changed to handle the
  5866. new instructions. If you code is not general enough, we recommend that
  5867. you change your code to be more general. For example, you can factor
  5868. out the computing of the the read and write sets for each kind of
  5869. instruction into two auxiliary functions.
  5870. Note that the \key{movzbq} instruction requires some special care,
  5871. similar to the \key{movq} instruction. See rule number 1 in
  5872. Section~\ref{sec:build-interference}.
  5873. \begin{exercise}\normalfont
  5874. Update the \code{build-interference} pass for \LangXIfVar{} and add the
  5875. following entries to the list of \code{passes} in the
  5876. \code{run-tests.rkt} script.
  5877. \begin{lstlisting}
  5878. (list "build-interference" build-interference interp-pseudo-x86-1)
  5879. (list "allocate-registers" allocate-registers interp-x86-1)
  5880. \end{lstlisting}
  5881. Run the script to test your compiler on all the \LangIf{} test
  5882. programs.
  5883. \end{exercise}
  5884. \section{Patch Instructions}
  5885. The second argument of the \key{cmpq} instruction must not be an
  5886. immediate value (such as an integer). So if you are comparing two
  5887. immediates, we recommend inserting a \key{movq} instruction to put the
  5888. second argument in \key{rax}. Also, recall that instructions may have
  5889. at most one memory reference.
  5890. %
  5891. The second argument of the \key{movzbq} must be a register.
  5892. %
  5893. There are no special restrictions on the jump instructions.
  5894. \begin{exercise}\normalfont
  5895. %
  5896. Update \code{patch-instructions} pass for \LangXIfVar{}.
  5897. %
  5898. Add the following entry to the list of \code{passes} in
  5899. \code{run-tests.rkt} and then run this script to test your compiler.
  5900. \begin{lstlisting}
  5901. (list "patch-instructions" patch-instructions interp-x86-1)
  5902. \end{lstlisting}
  5903. \end{exercise}
  5904. \begin{figure}[tbp]
  5905. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5906. \node (Rif) at (0,2) {\large \LangIf{}};
  5907. \node (Rif-2) at (3,2) {\large \LangIf{}};
  5908. \node (Rif-3) at (6,2) {\large \LangIf{}};
  5909. \node (Rif-4) at (9,2) {\large \LangIf{}};
  5910. \node (Rif-5) at (12,2) {\large \LangIf{}};
  5911. \node (C1-1) at (3,0) {\large \LangCIf{}};
  5912. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  5913. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  5914. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  5915. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  5916. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  5917. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  5918. \path[->,bend left=15] (Rif) edge [above] node {\ttfamily\footnotesize type-check} (Rif-2);
  5919. \path[->,bend left=15] (Rif-2) edge [above] node {\ttfamily\footnotesize shrink} (Rif-3);
  5920. \path[->,bend left=15] (Rif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Rif-4);
  5921. \path[->,bend left=15] (Rif-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rif-5);
  5922. \path[->,bend left=15] (Rif-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C1-1);
  5923. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select-instructions} (x86-2);
  5924. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  5925. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  5926. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  5927. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  5928. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86 } (x86-5);
  5929. \end{tikzpicture}
  5930. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  5931. \label{fig:Rif-passes}
  5932. \end{figure}
  5933. Figure~\ref{fig:Rif-passes} lists all the passes needed for the
  5934. compilation of \LangIf{}.
  5935. \section{An Example Translation}
  5936. Figure~\ref{fig:if-example-x86} shows a simple example program in
  5937. \LangIf{} translated to x86, showing the results of
  5938. \code{explicate-control}, \code{select-instructions}, and the final
  5939. x86 assembly code.
  5940. \begin{figure}[tbp]
  5941. \begin{tabular}{lll}
  5942. \begin{minipage}{0.4\textwidth}
  5943. % cond_test_20.rkt, eq_input.py
  5944. \begin{lstlisting}
  5945. (if (eq? (read) 1) 42 0)
  5946. \end{lstlisting}
  5947. $\Downarrow$
  5948. \begin{lstlisting}
  5949. start:
  5950. tmp7951 = (read);
  5951. if (eq? tmp7951 1)
  5952. goto block7952;
  5953. else
  5954. goto block7953;
  5955. block7952:
  5956. return 42;
  5957. block7953:
  5958. return 0;
  5959. \end{lstlisting}
  5960. $\Downarrow$
  5961. \begin{lstlisting}
  5962. start:
  5963. callq read_int
  5964. movq %rax, tmp7951
  5965. cmpq $1, tmp7951
  5966. je block7952
  5967. jmp block7953
  5968. block7953:
  5969. movq $0, %rax
  5970. jmp conclusion
  5971. block7952:
  5972. movq $42, %rax
  5973. jmp conclusion
  5974. \end{lstlisting}
  5975. \end{minipage}
  5976. &
  5977. $\Rightarrow\qquad$
  5978. \begin{minipage}{0.4\textwidth}
  5979. \begin{lstlisting}
  5980. start:
  5981. callq read_int
  5982. movq %rax, %rcx
  5983. cmpq $1, %rcx
  5984. je block7952
  5985. jmp block7953
  5986. block7953:
  5987. movq $0, %rax
  5988. jmp conclusion
  5989. block7952:
  5990. movq $42, %rax
  5991. jmp conclusion
  5992. .globl main
  5993. main:
  5994. pushq %rbp
  5995. movq %rsp, %rbp
  5996. pushq %r13
  5997. pushq %r12
  5998. pushq %rbx
  5999. pushq %r14
  6000. subq $0, %rsp
  6001. jmp start
  6002. conclusion:
  6003. addq $0, %rsp
  6004. popq %r14
  6005. popq %rbx
  6006. popq %r12
  6007. popq %r13
  6008. popq %rbp
  6009. retq
  6010. \end{lstlisting}
  6011. \end{minipage}
  6012. \end{tabular}
  6013. \caption{Example compilation of an \key{if} expression to x86.}
  6014. \label{fig:if-example-x86}
  6015. \end{figure}
  6016. \section{Challenge: Remove Jumps}
  6017. \label{sec:opt-jumps}
  6018. %% Recall that in the example output of \code{explicate-control} in
  6019. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  6020. %% \code{block60} are trivial blocks, they do nothing but jump to another
  6021. %% block. The first goal of this challenge assignment is to remove those
  6022. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  6023. %% \code{explicate-control} on the left and shows the result of bypassing
  6024. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  6025. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  6026. %% \code{block55}. The optimized code on the right of
  6027. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  6028. %% \code{then} branch jumping directly to \code{block55}. The story is
  6029. %% similar for the \code{else} branch, as well as for the two branches in
  6030. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  6031. %% have been optimized in this way, there are no longer any jumps to
  6032. %% blocks \code{block57} through \code{block60}, so they can be removed.
  6033. %% \begin{figure}[tbp]
  6034. %% \begin{tabular}{lll}
  6035. %% \begin{minipage}{0.4\textwidth}
  6036. %% \begin{lstlisting}
  6037. %% block62:
  6038. %% tmp54 = (read);
  6039. %% if (eq? tmp54 2) then
  6040. %% goto block59;
  6041. %% else
  6042. %% goto block60;
  6043. %% block61:
  6044. %% tmp53 = (read);
  6045. %% if (eq? tmp53 0) then
  6046. %% goto block57;
  6047. %% else
  6048. %% goto block58;
  6049. %% block60:
  6050. %% goto block56;
  6051. %% block59:
  6052. %% goto block55;
  6053. %% block58:
  6054. %% goto block56;
  6055. %% block57:
  6056. %% goto block55;
  6057. %% block56:
  6058. %% return (+ 700 77);
  6059. %% block55:
  6060. %% return (+ 10 32);
  6061. %% start:
  6062. %% tmp52 = (read);
  6063. %% if (eq? tmp52 1) then
  6064. %% goto block61;
  6065. %% else
  6066. %% goto block62;
  6067. %% \end{lstlisting}
  6068. %% \end{minipage}
  6069. %% &
  6070. %% $\Rightarrow$
  6071. %% &
  6072. %% \begin{minipage}{0.55\textwidth}
  6073. %% \begin{lstlisting}
  6074. %% block62:
  6075. %% tmp54 = (read);
  6076. %% if (eq? tmp54 2) then
  6077. %% goto block55;
  6078. %% else
  6079. %% goto block56;
  6080. %% block61:
  6081. %% tmp53 = (read);
  6082. %% if (eq? tmp53 0) then
  6083. %% goto block55;
  6084. %% else
  6085. %% goto block56;
  6086. %% block56:
  6087. %% return (+ 700 77);
  6088. %% block55:
  6089. %% return (+ 10 32);
  6090. %% start:
  6091. %% tmp52 = (read);
  6092. %% if (eq? tmp52 1) then
  6093. %% goto block61;
  6094. %% else
  6095. %% goto block62;
  6096. %% \end{lstlisting}
  6097. %% \end{minipage}
  6098. %% \end{tabular}
  6099. %% \caption{Optimize jumps by removing trivial blocks.}
  6100. %% \label{fig:optimize-jumps}
  6101. %% \end{figure}
  6102. %% The name of this pass is \code{optimize-jumps}. We recommend
  6103. %% implementing this pass in two phases. The first phrase builds a hash
  6104. %% table that maps labels to possibly improved labels. The second phase
  6105. %% changes the target of each \code{goto} to use the improved label. If
  6106. %% the label is for a trivial block, then the hash table should map the
  6107. %% label to the first non-trivial block that can be reached from this
  6108. %% label by jumping through trivial blocks. If the label is for a
  6109. %% non-trivial block, then the hash table should map the label to itself;
  6110. %% we do not want to change jumps to non-trivial blocks.
  6111. %% The first phase can be accomplished by constructing an empty hash
  6112. %% table, call it \code{short-cut}, and then iterating over the control
  6113. %% flow graph. Each time you encouter a block that is just a \code{goto},
  6114. %% then update the hash table, mapping the block's source to the target
  6115. %% of the \code{goto}. Also, the hash table may already have mapped some
  6116. %% labels to the block's source, to you must iterate through the hash
  6117. %% table and update all of those so that they instead map to the target
  6118. %% of the \code{goto}.
  6119. %% For the second phase, we recommend iterating through the $\Tail$ of
  6120. %% each block in the program, updating the target of every \code{goto}
  6121. %% according to the mapping in \code{short-cut}.
  6122. %% \begin{exercise}\normalfont
  6123. %% Implement the \code{optimize-jumps} pass as a transformation from
  6124. %% \LangCIf{} to \LangCIf{}, coming after the \code{explicate-control} pass.
  6125. %% Check that \code{optimize-jumps} removes trivial blocks in a few
  6126. %% example programs. Then check that your compiler still passes all of
  6127. %% your tests.
  6128. %% \end{exercise}
  6129. There is an opportunity for optimizing jumps that is apparent in the
  6130. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  6131. ends with a jump to \code{block7953} and there are no other jumps to
  6132. \code{block7953} in the rest of the program. In this situation we can
  6133. avoid the runtime overhead of this jump by merging \code{block7953}
  6134. into the preceding block, in this case the \code{start} block.
  6135. Figure~\ref{fig:remove-jumps} shows the output of
  6136. \code{select-instructions} on the left and the result of this
  6137. optimization on the right.
  6138. \begin{figure}[tbp]
  6139. \begin{tabular}{lll}
  6140. \begin{minipage}{0.5\textwidth}
  6141. % cond_test_20.rkt
  6142. \begin{lstlisting}
  6143. start:
  6144. callq read_int
  6145. movq %rax, tmp7951
  6146. cmpq $1, tmp7951
  6147. je block7952
  6148. jmp block7953
  6149. block7953:
  6150. movq $0, %rax
  6151. jmp conclusion
  6152. block7952:
  6153. movq $42, %rax
  6154. jmp conclusion
  6155. \end{lstlisting}
  6156. \end{minipage}
  6157. &
  6158. $\Rightarrow\qquad$
  6159. \begin{minipage}{0.4\textwidth}
  6160. \begin{lstlisting}
  6161. start:
  6162. callq read_int
  6163. movq %rax, tmp7951
  6164. cmpq $1, tmp7951
  6165. je block7952
  6166. movq $0, %rax
  6167. jmp conclusion
  6168. block7952:
  6169. movq $42, %rax
  6170. jmp conclusion
  6171. \end{lstlisting}
  6172. \end{minipage}
  6173. \end{tabular}
  6174. \caption{Merging basic blocks by removing unnecessary jumps.}
  6175. \label{fig:remove-jumps}
  6176. \end{figure}
  6177. \begin{exercise}\normalfont
  6178. %
  6179. Implement a pass named \code{remove-jumps} that merges basic blocks
  6180. into their preceding basic block, when there is only one preceding
  6181. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  6182. %
  6183. In the \code{run-tests.rkt} script, add the following entry to the
  6184. list of \code{passes} between \code{allocate-registers}
  6185. and \code{patch-instructions}.
  6186. \begin{lstlisting}
  6187. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  6188. \end{lstlisting}
  6189. Run this script to test your compiler.
  6190. %
  6191. Check that \code{remove-jumps} accomplishes the goal of merging basic
  6192. blocks on several test programs.
  6193. \end{exercise}
  6194. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6195. \chapter{Tuples and Garbage Collection}
  6196. \label{ch:Rvec}
  6197. \index{subject}{tuple}
  6198. \index{subject}{vector}
  6199. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  6200. %% all the IR grammars are spelled out! \\ --Jeremy}
  6201. %% \margincomment{\scriptsize Be more explicit about how to deal with
  6202. %% the root stack. \\ --Jeremy}
  6203. In this chapter we study the implementation of mutable tuples, called
  6204. vectors in Racket. This language feature is the first to use the
  6205. computer's \emph{heap}\index{subject}{heap} because the lifetime of a Racket
  6206. tuple is indefinite, that is, a tuple lives forever from the
  6207. programmer's viewpoint. Of course, from an implementer's viewpoint, it
  6208. is important to reclaim the space associated with a tuple when it is
  6209. no longer needed, which is why we also study \emph{garbage collection}
  6210. \emph{garbage collection} techniques in this chapter.
  6211. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  6212. interpreter and type checker. The \LangVec{} language extends the \LangIf{}
  6213. language of Chapter~\ref{ch:Rif} with vectors and Racket's
  6214. \code{void} value. The reason for including the later is that the
  6215. \code{vector-set!} operation returns a value of type
  6216. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  6217. called the \code{Unit} type in the programming languages
  6218. literature. Racket's \code{Void} type is inhabited by a single value
  6219. \code{void} which corresponds to \code{unit} or \code{()} in the
  6220. literature~\citep{Pierce:2002hj}.}.
  6221. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  6222. copying live objects back and forth between two halves of the
  6223. heap. The garbage collector requires coordination with the compiler so
  6224. that it can see all of the \emph{root} pointers, that is, pointers in
  6225. registers or on the procedure call stack.
  6226. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  6227. discuss all the necessary changes and additions to the compiler
  6228. passes, including a new compiler pass named \code{expose-allocation}.
  6229. \section{The \LangVec{} Language}
  6230. \label{sec:r3}
  6231. Figure~\ref{fig:Rvec-concrete-syntax} defines the concrete syntax for
  6232. \LangVec{} and Figure~\ref{fig:Rvec-syntax} defines the abstract syntax. The
  6233. \LangVec{} language includes three new forms: \code{vector} for creating a
  6234. tuple, \code{vector-ref} for reading an element of a tuple, and
  6235. \code{vector-set!} for writing to an element of a tuple. The program
  6236. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  6237. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  6238. the 3-tuple, demonstrating that tuples are first-class values. The
  6239. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  6240. of the \key{if} is taken. The element at index $0$ of \code{t} is
  6241. \code{40}, to which we add \code{2}, the element at index $0$ of the
  6242. 1-tuple. So the result of the program is \code{42}.
  6243. \begin{figure}[tbp]
  6244. \centering
  6245. \fbox{
  6246. \begin{minipage}{0.96\textwidth}
  6247. \[
  6248. \begin{array}{lcl}
  6249. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}}
  6250. \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}\\
  6251. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  6252. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  6253. &\MID& \gray{ \key{\#t} \MID \key{\#f}
  6254. \MID \LP\key{and}\;\Exp\;\Exp\RP
  6255. \MID \LP\key{or}\;\Exp\;\Exp\RP
  6256. \MID \LP\key{not}\;\Exp\RP } \\
  6257. &\MID& \gray{ \LP\itm{cmp}\;\Exp\;\Exp\RP
  6258. \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  6259. &\MID& \LP\key{vector}\;\Exp\ldots\RP
  6260. \MID \LP\key{vector-length}\;\Exp\RP \\
  6261. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  6262. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP \\
  6263. &\MID& \LP\key{void}\RP \MID \LP\key{has-type}~\Exp~\Type\RP\\
  6264. \LangVecM{} &::=& \Exp
  6265. \end{array}
  6266. \]
  6267. \end{minipage}
  6268. }
  6269. \caption{The concrete syntax of \LangVec{}, extending \LangIf{}
  6270. (Figure~\ref{fig:Rif-concrete-syntax}).}
  6271. \label{fig:Rvec-concrete-syntax}
  6272. \end{figure}
  6273. \begin{figure}[tbp]
  6274. \begin{lstlisting}
  6275. (let ([t (vector 40 #t (vector 2))])
  6276. (if (vector-ref t 1)
  6277. (+ (vector-ref t 0)
  6278. (vector-ref (vector-ref t 2) 0))
  6279. 44))
  6280. \end{lstlisting}
  6281. \caption{Example program that creates tuples and reads from them.}
  6282. \label{fig:vector-eg}
  6283. \end{figure}
  6284. \begin{figure}[tp]
  6285. \centering
  6286. \fbox{
  6287. \begin{minipage}{0.96\textwidth}
  6288. \[
  6289. \begin{array}{lcl}
  6290. \itm{op} &::=& \ldots \MID \code{vector} \MID \code{vector-length} \\
  6291. \Exp &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  6292. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots}
  6293. \MID \BOOL{\itm{bool}}
  6294. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  6295. &\MID& \VECREF{\Exp}{\INT{\Int}}\\
  6296. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  6297. &\MID& \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP \\
  6298. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  6299. \end{array}
  6300. \]
  6301. \end{minipage}
  6302. }
  6303. \caption{The abstract syntax of \LangVec{}.}
  6304. \label{fig:Rvec-syntax}
  6305. \end{figure}
  6306. \index{subject}{allocate}
  6307. \index{subject}{heap allocate}
  6308. Tuples are our first encounter with heap-allocated data, which raises
  6309. several interesting issues. First, variable binding performs a
  6310. shallow-copy when dealing with tuples, which means that different
  6311. variables can refer to the same tuple, that is, different variables
  6312. can be \emph{aliases} for the same entity. Consider the following
  6313. example in which both \code{t1} and \code{t2} refer to the same tuple.
  6314. Thus, the mutation through \code{t2} is visible when referencing the
  6315. tuple from \code{t1}, so the result of this program is \code{42}.
  6316. \index{subject}{alias}\index{subject}{mutation}
  6317. \begin{center}
  6318. \begin{minipage}{0.96\textwidth}
  6319. \begin{lstlisting}
  6320. (let ([t1 (vector 3 7)])
  6321. (let ([t2 t1])
  6322. (let ([_ (vector-set! t2 0 42)])
  6323. (vector-ref t1 0))))
  6324. \end{lstlisting}
  6325. \end{minipage}
  6326. \end{center}
  6327. The next issue concerns the lifetime of tuples. Of course, they are
  6328. created by the \code{vector} form, but when does their lifetime end?
  6329. Notice that \LangVec{} does not include an operation for deleting
  6330. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  6331. of static scoping. For example, the following program returns
  6332. \code{42} even though the variable \code{w} goes out of scope prior to
  6333. the \code{vector-ref} that reads from the vector it was bound to.
  6334. \begin{center}
  6335. \begin{minipage}{0.96\textwidth}
  6336. \begin{lstlisting}
  6337. (let ([v (vector (vector 44))])
  6338. (let ([x (let ([w (vector 42)])
  6339. (let ([_ (vector-set! v 0 w)])
  6340. 0))])
  6341. (+ x (vector-ref (vector-ref v 0) 0))))
  6342. \end{lstlisting}
  6343. \end{minipage}
  6344. \end{center}
  6345. From the perspective of programmer-observable behavior, tuples live
  6346. forever. Of course, if they really lived forever, then many programs
  6347. would run out of memory.\footnote{The \LangVec{} language does not have
  6348. looping or recursive functions, so it is nigh impossible to write a
  6349. program in \LangVec{} that will run out of memory. However, we add
  6350. recursive functions in the next Chapter!} A Racket implementation
  6351. must therefore perform automatic garbage collection.
  6352. Figure~\ref{fig:interp-Rvec} shows the definitional interpreter for the
  6353. \LangVec{} language. We define the \code{vector}, \code{vector-length},
  6354. \code{vector-ref}, and \code{vector-set!} operations for \LangVec{} in
  6355. terms of the corresponding operations in Racket. One subtle point is
  6356. that the \code{vector-set!} operation returns the \code{\#<void>}
  6357. value. The \code{\#<void>} value can be passed around just like other
  6358. values inside an \LangVec{} program and a \code{\#<void>} value can be
  6359. compared for equality with another \code{\#<void>} value. However,
  6360. there are no other operations specific to the the \code{\#<void>}
  6361. value in \LangVec{}. In contrast, Racket defines the \code{void?} predicate
  6362. that returns \code{\#t} when applied to \code{\#<void>} and \code{\#f}
  6363. otherwise.
  6364. \begin{figure}[tbp]
  6365. \begin{lstlisting}
  6366. (define interp-Rvec-class
  6367. (class interp-Rif-class
  6368. (super-new)
  6369. (define/override (interp-op op)
  6370. (match op
  6371. ['eq? (lambda (v1 v2)
  6372. (cond [(or (and (fixnum? v1) (fixnum? v2))
  6373. (and (boolean? v1) (boolean? v2))
  6374. (and (vector? v1) (vector? v2))
  6375. (and (void? v1) (void? v2)))
  6376. (eq? v1 v2)]))]
  6377. ['vector vector]
  6378. ['vector-length vector-length]
  6379. ['vector-ref vector-ref]
  6380. ['vector-set! vector-set!]
  6381. [else (super interp-op op)]
  6382. ))
  6383. (define/override ((interp-exp env) e)
  6384. (define recur (interp-exp env))
  6385. (match e
  6386. [(HasType e t) (recur e)]
  6387. [(Void) (void)]
  6388. [else ((super interp-exp env) e)]
  6389. ))
  6390. ))
  6391. (define (interp-Rvec p)
  6392. (send (new interp-Rvec-class) interp-program p))
  6393. \end{lstlisting}
  6394. \caption{Interpreter for the \LangVec{} language.}
  6395. \label{fig:interp-Rvec}
  6396. \end{figure}
  6397. Figure~\ref{fig:type-check-Rvec} shows the type checker for \LangVec{}, which
  6398. deserves some explanation. When allocating a vector, we need to know
  6399. which elements of the vector are pointers (i.e. are also vectors). We
  6400. can obtain this information during type checking. The type checker in
  6401. Figure~\ref{fig:type-check-Rvec} not only computes the type of an
  6402. expression, it also wraps every \key{vector} creation with the form
  6403. $(\key{HasType}~e~T)$, where $T$ is the vector's type.
  6404. %
  6405. To create the s-expression for the \code{Vector} type in
  6406. Figure~\ref{fig:type-check-Rvec}, we use the
  6407. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  6408. operator} \code{,@} to insert the list \code{t*} without its usual
  6409. start and end parentheses. \index{subject}{unquote-slicing}
  6410. \begin{figure}[tp]
  6411. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6412. (define type-check-Rvec-class
  6413. (class type-check-Rif-class
  6414. (super-new)
  6415. (inherit check-type-equal?)
  6416. (define/override (type-check-exp env)
  6417. (lambda (e)
  6418. (define recur (type-check-exp env))
  6419. (match e
  6420. [(Void) (values (Void) 'Void)]
  6421. [(Prim 'vector es)
  6422. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  6423. (define t `(Vector ,@t*))
  6424. (values (HasType (Prim 'vector e*) t) t)]
  6425. [(Prim 'vector-ref (list e1 (Int i)))
  6426. (define-values (e1^ t) (recur e1))
  6427. (match t
  6428. [`(Vector ,ts ...)
  6429. (unless (and (0 . <= . i) (i . < . (length ts)))
  6430. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  6431. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  6432. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  6433. [(Prim 'vector-set! (list e1 (Int i) arg) )
  6434. (define-values (e-vec t-vec) (recur e1))
  6435. (define-values (e-arg^ t-arg) (recur arg))
  6436. (match t-vec
  6437. [`(Vector ,ts ...)
  6438. (unless (and (0 . <= . i) (i . < . (length ts)))
  6439. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  6440. (check-type-equal? (list-ref ts i) t-arg e)
  6441. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  6442. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  6443. [(Prim 'vector-length (list e))
  6444. (define-values (e^ t) (recur e))
  6445. (match t
  6446. [`(Vector ,ts ...)
  6447. (values (Prim 'vector-length (list e^)) 'Integer)]
  6448. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  6449. [(Prim 'eq? (list arg1 arg2))
  6450. (define-values (e1 t1) (recur arg1))
  6451. (define-values (e2 t2) (recur arg2))
  6452. (match* (t1 t2)
  6453. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  6454. [(other wise) (check-type-equal? t1 t2 e)])
  6455. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  6456. [(HasType (Prim 'vector es) t)
  6457. ((type-check-exp env) (Prim 'vector es))]
  6458. [(HasType e1 t)
  6459. (define-values (e1^ t^) (recur e1))
  6460. (check-type-equal? t t^ e)
  6461. (values (HasType e1^ t) t)]
  6462. [else ((super type-check-exp env) e)]
  6463. )))
  6464. ))
  6465. (define (type-check-Rvec p)
  6466. (send (new type-check-Rvec-class) type-check-program p))
  6467. \end{lstlisting}
  6468. \caption{Type checker for the \LangVec{} language.}
  6469. \label{fig:type-check-Rvec}
  6470. \end{figure}
  6471. \section{Garbage Collection}
  6472. \label{sec:GC}
  6473. Here we study a relatively simple algorithm for garbage collection
  6474. that is the basis of state-of-the-art garbage
  6475. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  6476. particular, we describe a two-space copying
  6477. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  6478. perform the
  6479. copy~\citep{Cheney:1970aa}.
  6480. \index{subject}{copying collector}
  6481. \index{subject}{two-space copying collector}
  6482. Figure~\ref{fig:copying-collector} gives a
  6483. coarse-grained depiction of what happens in a two-space collector,
  6484. showing two time steps, prior to garbage collection (on the top) and
  6485. after garbage collection (on the bottom). In a two-space collector,
  6486. the heap is divided into two parts named the FromSpace and the
  6487. ToSpace. Initially, all allocations go to the FromSpace until there is
  6488. not enough room for the next allocation request. At that point, the
  6489. garbage collector goes to work to make more room.
  6490. \index{subject}{ToSpace}
  6491. \index{subject}{FromSpace}
  6492. The garbage collector must be careful not to reclaim tuples that will
  6493. be used by the program in the future. Of course, it is impossible in
  6494. general to predict what a program will do, but we can over approximate
  6495. the will-be-used tuples by preserving all tuples that could be
  6496. accessed by \emph{any} program given the current computer state. A
  6497. program could access any tuple whose address is in a register or on
  6498. the procedure call stack. These addresses are called the \emph{root
  6499. set}\index{subject}{root set}. In addition, a program could access any tuple that is
  6500. transitively reachable from the root set. Thus, it is safe for the
  6501. garbage collector to reclaim the tuples that are not reachable in this
  6502. way.
  6503. So the goal of the garbage collector is twofold:
  6504. \begin{enumerate}
  6505. \item preserve all tuple that are reachable from the root set via a
  6506. path of pointers, that is, the \emph{live} tuples, and
  6507. \item reclaim the memory of everything else, that is, the
  6508. \emph{garbage}.
  6509. \end{enumerate}
  6510. A copying collector accomplishes this by copying all of the live
  6511. objects from the FromSpace into the ToSpace and then performs a sleight
  6512. of hand, treating the ToSpace as the new FromSpace and the old
  6513. FromSpace as the new ToSpace. In the example of
  6514. Figure~\ref{fig:copying-collector}, there are three pointers in the
  6515. root set, one in a register and two on the stack. All of the live
  6516. objects have been copied to the ToSpace (the right-hand side of
  6517. Figure~\ref{fig:copying-collector}) in a way that preserves the
  6518. pointer relationships. For example, the pointer in the register still
  6519. points to a 2-tuple whose first element is a 3-tuple and whose second
  6520. element is a 2-tuple. There are four tuples that are not reachable
  6521. from the root set and therefore do not get copied into the ToSpace.
  6522. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  6523. created by a well-typed program in \LangVec{} because it contains a
  6524. cycle. However, creating cycles will be possible once we get to \LangAny{}.
  6525. We design the garbage collector to deal with cycles to begin with so
  6526. we will not need to revisit this issue.
  6527. \begin{figure}[tbp]
  6528. \centering
  6529. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  6530. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  6531. \caption{A copying collector in action.}
  6532. \label{fig:copying-collector}
  6533. \end{figure}
  6534. There are many alternatives to copying collectors (and their bigger
  6535. siblings, the generational collectors) when its comes to garbage
  6536. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  6537. reference counting~\citep{Collins:1960aa}. The strengths of copying
  6538. collectors are that allocation is fast (just a comparison and pointer
  6539. increment), there is no fragmentation, cyclic garbage is collected,
  6540. and the time complexity of collection only depends on the amount of
  6541. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  6542. main disadvantages of a two-space copying collector is that it uses a
  6543. lot of space and takes a long time to perform the copy, though these
  6544. problems are ameliorated in generational collectors. Racket and
  6545. Scheme programs tend to allocate many small objects and generate a lot
  6546. of garbage, so copying and generational collectors are a good fit.
  6547. Garbage collection is an active research topic, especially concurrent
  6548. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  6549. developing new techniques and revisiting old
  6550. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  6551. meet every year at the International Symposium on Memory Management to
  6552. present these findings.
  6553. \subsection{Graph Copying via Cheney's Algorithm}
  6554. \label{sec:cheney}
  6555. \index{subject}{Cheney's algorithm}
  6556. Let us take a closer look at the copying of the live objects. The
  6557. allocated objects and pointers can be viewed as a graph and we need to
  6558. copy the part of the graph that is reachable from the root set. To
  6559. make sure we copy all of the reachable vertices in the graph, we need
  6560. an exhaustive graph traversal algorithm, such as depth-first search or
  6561. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  6562. such algorithms take into account the possibility of cycles by marking
  6563. which vertices have already been visited, so as to ensure termination
  6564. of the algorithm. These search algorithms also use a data structure
  6565. such as a stack or queue as a to-do list to keep track of the vertices
  6566. that need to be visited. We use breadth-first search and a trick
  6567. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  6568. and copying tuples into the ToSpace.
  6569. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  6570. copy progresses. The queue is represented by a chunk of contiguous
  6571. memory at the beginning of the ToSpace, using two pointers to track
  6572. the front and the back of the queue. The algorithm starts by copying
  6573. all tuples that are immediately reachable from the root set into the
  6574. ToSpace to form the initial queue. When we copy a tuple, we mark the
  6575. old tuple to indicate that it has been visited. We discuss how this
  6576. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  6577. pointers inside the copied tuples in the queue still point back to the
  6578. FromSpace. Once the initial queue has been created, the algorithm
  6579. enters a loop in which it repeatedly processes the tuple at the front
  6580. of the queue and pops it off the queue. To process a tuple, the
  6581. algorithm copies all the tuple that are directly reachable from it to
  6582. the ToSpace, placing them at the back of the queue. The algorithm then
  6583. updates the pointers in the popped tuple so they point to the newly
  6584. copied tuples.
  6585. \begin{figure}[tbp]
  6586. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  6587. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  6588. \label{fig:cheney}
  6589. \end{figure}
  6590. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  6591. tuple whose second element is $42$ to the back of the queue. The other
  6592. pointer goes to a tuple that has already been copied, so we do not
  6593. need to copy it again, but we do need to update the pointer to the new
  6594. location. This can be accomplished by storing a \emph{forwarding
  6595. pointer} to the new location in the old tuple, back when we initially
  6596. copied the tuple into the ToSpace. This completes one step of the
  6597. algorithm. The algorithm continues in this way until the front of the
  6598. queue is empty, that is, until the front catches up with the back.
  6599. \subsection{Data Representation}
  6600. \label{sec:data-rep-gc}
  6601. The garbage collector places some requirements on the data
  6602. representations used by our compiler. First, the garbage collector
  6603. needs to distinguish between pointers and other kinds of data. There
  6604. are several ways to accomplish this.
  6605. \begin{enumerate}
  6606. \item Attached a tag to each object that identifies what type of
  6607. object it is~\citep{McCarthy:1960dz}.
  6608. \item Store different types of objects in different
  6609. regions~\citep{Steele:1977ab}.
  6610. \item Use type information from the program to either generate
  6611. type-specific code for collecting or to generate tables that can
  6612. guide the
  6613. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  6614. \end{enumerate}
  6615. Dynamically typed languages, such as Lisp, need to tag objects
  6616. anyways, so option 1 is a natural choice for those languages.
  6617. However, \LangVec{} is a statically typed language, so it would be
  6618. unfortunate to require tags on every object, especially small and
  6619. pervasive objects like integers and Booleans. Option 3 is the
  6620. best-performing choice for statically typed languages, but comes with
  6621. a relatively high implementation complexity. To keep this chapter
  6622. within a 2-week time budget, we recommend a combination of options 1
  6623. and 2, using separate strategies for the stack and the heap.
  6624. Regarding the stack, we recommend using a separate stack for pointers,
  6625. which we call a \emph{root stack}\index{subject}{root stack} (a.k.a. ``shadow
  6626. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  6627. is, when a local variable needs to be spilled and is of type
  6628. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  6629. stack instead of the normal procedure call stack. Furthermore, we
  6630. always spill vector-typed variables if they are live during a call to
  6631. the collector, thereby ensuring that no pointers are in registers
  6632. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  6633. example from Figure~\ref{fig:copying-collector} and contrasts it with
  6634. the data layout using a root stack. The root stack contains the two
  6635. pointers from the regular stack and also the pointer in the second
  6636. register.
  6637. \begin{figure}[tbp]
  6638. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  6639. \caption{Maintaining a root stack to facilitate garbage collection.}
  6640. \label{fig:shadow-stack}
  6641. \end{figure}
  6642. The problem of distinguishing between pointers and other kinds of data
  6643. also arises inside of each tuple on the heap. We solve this problem by
  6644. attaching a tag, an extra 64-bits, to each
  6645. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  6646. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  6647. that we have drawn the bits in a big-endian way, from right-to-left,
  6648. with bit location 0 (the least significant bit) on the far right,
  6649. which corresponds to the direction of the x86 shifting instructions
  6650. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  6651. is dedicated to specifying which elements of the tuple are pointers,
  6652. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  6653. indicates there is a pointer and a 0 bit indicates some other kind of
  6654. data. The pointer mask starts at bit location 7. We have limited
  6655. tuples to a maximum size of 50 elements, so we just need 50 bits for
  6656. the pointer mask. The tag also contains two other pieces of
  6657. information. The length of the tuple (number of elements) is stored in
  6658. bits location 1 through 6. Finally, the bit at location 0 indicates
  6659. whether the tuple has yet to be copied to the ToSpace. If the bit has
  6660. value 1, then this tuple has not yet been copied. If the bit has
  6661. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  6662. of a pointer are always zero anyways because our tuples are 8-byte
  6663. aligned.)
  6664. \begin{figure}[tbp]
  6665. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  6666. \caption{Representation of tuples in the heap.}
  6667. \label{fig:tuple-rep}
  6668. \end{figure}
  6669. \subsection{Implementation of the Garbage Collector}
  6670. \label{sec:organize-gz}
  6671. \index{subject}{prelude}
  6672. An implementation of the copying collector is provided in the
  6673. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  6674. interface to the garbage collector that is used by the compiler. The
  6675. \code{initialize} function creates the FromSpace, ToSpace, and root
  6676. stack and should be called in the prelude of the \code{main}
  6677. function. The arguments of \code{initialize} are the root stack size
  6678. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  6679. good choice for both. The \code{initialize} function puts the address
  6680. of the beginning of the FromSpace into the global variable
  6681. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  6682. the address that is 1-past the last element of the FromSpace. (We use
  6683. half-open intervals to represent chunks of
  6684. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  6685. points to the first element of the root stack.
  6686. As long as there is room left in the FromSpace, your generated code
  6687. can allocate tuples simply by moving the \code{free\_ptr} forward.
  6688. %
  6689. The amount of room left in FromSpace is the difference between the
  6690. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  6691. function should be called when there is not enough room left in the
  6692. FromSpace for the next allocation. The \code{collect} function takes
  6693. a pointer to the current top of the root stack (one past the last item
  6694. that was pushed) and the number of bytes that need to be
  6695. allocated. The \code{collect} function performs the copying collection
  6696. and leaves the heap in a state such that the next allocation will
  6697. succeed.
  6698. \begin{figure}[tbp]
  6699. \begin{lstlisting}
  6700. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  6701. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  6702. int64_t* free_ptr;
  6703. int64_t* fromspace_begin;
  6704. int64_t* fromspace_end;
  6705. int64_t** rootstack_begin;
  6706. \end{lstlisting}
  6707. \caption{The compiler's interface to the garbage collector.}
  6708. \label{fig:gc-header}
  6709. \end{figure}
  6710. %% \begin{exercise}
  6711. %% In the file \code{runtime.c} you will find the implementation of
  6712. %% \code{initialize} and a partial implementation of \code{collect}.
  6713. %% The \code{collect} function calls another function, \code{cheney},
  6714. %% to perform the actual copy, and that function is left to the reader
  6715. %% to implement. The following is the prototype for \code{cheney}.
  6716. %% \begin{lstlisting}
  6717. %% static void cheney(int64_t** rootstack_ptr);
  6718. %% \end{lstlisting}
  6719. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  6720. %% rootstack (which is an array of pointers). The \code{cheney} function
  6721. %% also communicates with \code{collect} through the global
  6722. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  6723. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  6724. %% the ToSpace:
  6725. %% \begin{lstlisting}
  6726. %% static int64_t* tospace_begin;
  6727. %% static int64_t* tospace_end;
  6728. %% \end{lstlisting}
  6729. %% The job of the \code{cheney} function is to copy all the live
  6730. %% objects (reachable from the root stack) into the ToSpace, update
  6731. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  6732. %% update the root stack so that it points to the objects in the
  6733. %% ToSpace, and finally to swap the global pointers for the FromSpace
  6734. %% and ToSpace.
  6735. %% \end{exercise}
  6736. %% \section{Compiler Passes}
  6737. %% \label{sec:code-generation-gc}
  6738. The introduction of garbage collection has a non-trivial impact on our
  6739. compiler passes. We introduce a new compiler pass named
  6740. \code{expose-allocation}. We make
  6741. significant changes to \code{select-instructions},
  6742. \code{build-interference}, \code{allocate-registers}, and
  6743. \code{print-x86} and make minor changes in several more passes. The
  6744. following program will serve as our running example. It creates two
  6745. tuples, one nested inside the other. Both tuples have length one. The
  6746. program accesses the element in the inner tuple tuple via two vector
  6747. references.
  6748. % tests/s2_17.rkt
  6749. \begin{lstlisting}
  6750. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  6751. \end{lstlisting}
  6752. \section{Shrink}
  6753. \label{sec:shrink-Rvec}
  6754. Recall that the \code{shrink} pass translates the primitives operators
  6755. into a smaller set of primitives. Because this pass comes after type
  6756. checking, but before the passes that require the type information in
  6757. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  6758. to wrap \code{HasType} around each AST node that it generates.
  6759. \section{Expose Allocation}
  6760. \label{sec:expose-allocation}
  6761. The pass \code{expose-allocation} lowers the \code{vector} creation
  6762. form into a conditional call to the collector followed by the
  6763. allocation. We choose to place the \code{expose-allocation} pass
  6764. before \code{remove-complex-opera*} because the code generated by
  6765. \code{expose-allocation} contains complex operands. We also place
  6766. \code{expose-allocation} before \code{explicate-control} because
  6767. \code{expose-allocation} introduces new variables using \code{let},
  6768. but \code{let} is gone after \code{explicate-control}.
  6769. The output of \code{expose-allocation} is a language \LangAlloc{} that
  6770. extends \LangVec{} with the three new forms that we use in the translation
  6771. of the \code{vector} form.
  6772. \[
  6773. \begin{array}{lcl}
  6774. \Exp &::=& \cdots
  6775. \MID (\key{collect} \,\itm{int})
  6776. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  6777. \MID (\key{global-value} \,\itm{name})
  6778. \end{array}
  6779. \]
  6780. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  6781. $n$ bytes. It will become a call to the \code{collect} function in
  6782. \code{runtime.c} in \code{select-instructions}. The
  6783. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  6784. \index{subject}{allocate}
  6785. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  6786. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  6787. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  6788. a global variable, such as \code{free\_ptr}.
  6789. In the following, we show the transformation for the \code{vector}
  6790. form into 1) a sequence of let-bindings for the initializing
  6791. expressions, 2) a conditional call to \code{collect}, 3) a call to
  6792. \code{allocate}, and 4) the initialization of the vector. In the
  6793. following, \itm{len} refers to the length of the vector and
  6794. \itm{bytes} is how many total bytes need to be allocated for the
  6795. vector, which is 8 for the tag plus \itm{len} times 8.
  6796. \begin{lstlisting}
  6797. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  6798. |$\Longrightarrow$|
  6799. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  6800. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  6801. (global-value fromspace_end))
  6802. (void)
  6803. (collect |\itm{bytes}|))])
  6804. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  6805. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  6806. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  6807. |$v$|) ... )))) ...)
  6808. \end{lstlisting}
  6809. In the above, we suppressed all of the \code{has-type} forms in the
  6810. output for the sake of readability. The placement of the initializing
  6811. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  6812. sequence of \code{vector-set!} is important, as those expressions may
  6813. trigger garbage collection and we cannot have an allocated but
  6814. uninitialized tuple on the heap during a collection.
  6815. Figure~\ref{fig:expose-alloc-output} shows the output of the
  6816. \code{expose-allocation} pass on our running example.
  6817. \begin{figure}[tbp]
  6818. % tests/s2_17.rkt
  6819. \begin{lstlisting}
  6820. (vector-ref
  6821. (vector-ref
  6822. (let ([vecinit7976
  6823. (let ([vecinit7972 42])
  6824. (let ([collectret7974
  6825. (if (< (+ (global-value free_ptr) 16)
  6826. (global-value fromspace_end))
  6827. (void)
  6828. (collect 16)
  6829. )])
  6830. (let ([alloc7971 (allocate 1 (Vector Integer))])
  6831. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  6832. alloc7971)
  6833. )
  6834. )
  6835. )
  6836. ])
  6837. (let ([collectret7978
  6838. (if (< (+ (global-value free_ptr) 16)
  6839. (global-value fromspace_end))
  6840. (void)
  6841. (collect 16)
  6842. )])
  6843. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  6844. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  6845. alloc7975)
  6846. )
  6847. )
  6848. )
  6849. 0)
  6850. 0)
  6851. \end{lstlisting}
  6852. \caption{Output of the \code{expose-allocation} pass, minus
  6853. all of the \code{has-type} forms.}
  6854. \label{fig:expose-alloc-output}
  6855. \end{figure}
  6856. \section{Remove Complex Operands}
  6857. \label{sec:remove-complex-opera-Rvec}
  6858. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  6859. should all be treated as complex operands.
  6860. %% A new case for
  6861. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  6862. %% handled carefully to prevent the \code{Prim} node from being separated
  6863. %% from its enclosing \code{HasType}.
  6864. Figure~\ref{fig:Rvec-anf-syntax}
  6865. shows the grammar for the output language \LangVecANF{} of this
  6866. pass, which is \LangVec{} in administrative normal form.
  6867. \begin{figure}[tp]
  6868. \centering
  6869. \fbox{
  6870. \begin{minipage}{0.96\textwidth}
  6871. \small
  6872. \[
  6873. \begin{array}{rcl}
  6874. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} }
  6875. \MID \VOID{} \\
  6876. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  6877. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  6878. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  6879. &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  6880. &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  6881. &\MID& \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  6882. \MID \LP\key{GlobalValue}~\Var\RP\\
  6883. % &\MID& \LP\key{HasType}~\Exp~\Type\RP \\
  6884. \LangVecANFM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  6885. \end{array}
  6886. \]
  6887. \end{minipage}
  6888. }
  6889. \caption{\LangVecANF{} is \LangVec{} in administrative normal form (ANF).}
  6890. \label{fig:Rvec-anf-syntax}
  6891. \end{figure}
  6892. \section{Explicate Control and the \LangCVec{} language}
  6893. \label{sec:explicate-control-r3}
  6894. \begin{figure}[tp]
  6895. \fbox{
  6896. \begin{minipage}{0.96\textwidth}
  6897. \small
  6898. \[
  6899. \begin{array}{lcl}
  6900. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} }\\
  6901. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  6902. \Exp &::= & \gray{ \Atm \MID \READ{} } \\
  6903. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} }\\
  6904. &\MID& \gray{ \UNIOP{\key{not}}{\Atm} \MID \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  6905. &\MID& \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  6906. &\MID& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  6907. &\MID& \LP\key{Prim}~\key{'vector-set!}\,\LP\Atm\,\INT{\Int}\,\Atm\RP\RP\\
  6908. &\MID& \LP\key{GlobalValue} \,\Var\RP \MID \LP\key{Void}\RP\\
  6909. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  6910. \MID \LP\key{Collect} \,\itm{int}\RP \\
  6911. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  6912. \MID \GOTO{\itm{label}} } \\
  6913. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  6914. \LangCVecM{} & ::= & \gray{ \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }
  6915. \end{array}
  6916. \]
  6917. \end{minipage}
  6918. }
  6919. \caption{The abstract syntax of \LangCVec{}, extending \LangCIf{}
  6920. (Figure~\ref{fig:c1-syntax}).}
  6921. \label{fig:c2-syntax}
  6922. \end{figure}
  6923. The output of \code{explicate-control} is a program in the
  6924. intermediate language \LangCVec{}, whose abstract syntax is defined in
  6925. Figure~\ref{fig:c2-syntax}. (The concrete syntax is defined in
  6926. Figure~\ref{fig:c2-concrete-syntax} of the Appendix.) The new forms
  6927. of \LangCVec{} include the \key{allocate}, \key{vector-ref}, and
  6928. \key{vector-set!}, and \key{global-value} expressions and the
  6929. \code{collect} statement. The \code{explicate-control} pass can treat
  6930. these new forms much like the other expression forms that we've
  6931. already encoutered.
  6932. \section{Select Instructions and the \LangXGlobal{} Language}
  6933. \label{sec:select-instructions-gc}
  6934. \index{subject}{instruction selection}
  6935. %% void (rep as zero)
  6936. %% allocate
  6937. %% collect (callq collect)
  6938. %% vector-ref
  6939. %% vector-set!
  6940. %% global (postpone)
  6941. In this pass we generate x86 code for most of the new operations that
  6942. were needed to compile tuples, including \code{Allocate},
  6943. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  6944. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  6945. the later has a different concrete syntax (see
  6946. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  6947. \index{subject}{x86}
  6948. The \code{vector-ref} and \code{vector-set!} forms translate into
  6949. \code{movq} instructions. (The plus one in the offset is to get past
  6950. the tag at the beginning of the tuple representation.)
  6951. \begin{lstlisting}
  6952. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  6953. |$\Longrightarrow$|
  6954. movq |$\itm{vec}'$|, %r11
  6955. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  6956. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  6957. |$\Longrightarrow$|
  6958. movq |$\itm{vec}'$|, %r11
  6959. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  6960. movq $0, |$\itm{lhs'}$|
  6961. \end{lstlisting}
  6962. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  6963. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  6964. register \code{r11} ensures that offset expression
  6965. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  6966. removing \code{r11} from consideration by the register allocating.
  6967. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  6968. \code{rax}. Then the generated code for \code{vector-set!} would be
  6969. \begin{lstlisting}
  6970. movq |$\itm{vec}'$|, %rax
  6971. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  6972. movq $0, |$\itm{lhs}'$|
  6973. \end{lstlisting}
  6974. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  6975. \code{patch-instructions} would insert a move through \code{rax}
  6976. as follows.
  6977. \begin{lstlisting}
  6978. movq |$\itm{vec}'$|, %rax
  6979. movq |$\itm{arg}'$|, %rax
  6980. movq %rax, |$8(n+1)$|(%rax)
  6981. movq $0, |$\itm{lhs}'$|
  6982. \end{lstlisting}
  6983. But the above sequence of instructions does not work because we're
  6984. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  6985. $\itm{arg}'$) at the same time!
  6986. We compile the \code{allocate} form to operations on the
  6987. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  6988. is the next free address in the FromSpace, so we copy it into
  6989. \code{r11} and then move it forward by enough space for the tuple
  6990. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  6991. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  6992. initialize the \itm{tag} and finally copy the address in \code{r11} to
  6993. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  6994. tag is organized. We recommend using the Racket operations
  6995. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  6996. during compilation. The type annotation in the \code{vector} form is
  6997. used to determine the pointer mask region of the tag.
  6998. \begin{lstlisting}
  6999. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  7000. |$\Longrightarrow$|
  7001. movq free_ptr(%rip), %r11
  7002. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  7003. movq $|$\itm{tag}$|, 0(%r11)
  7004. movq %r11, |$\itm{lhs}'$|
  7005. \end{lstlisting}
  7006. The \code{collect} form is compiled to a call to the \code{collect}
  7007. function in the runtime. The arguments to \code{collect} are 1) the
  7008. top of the root stack and 2) the number of bytes that need to be
  7009. allocated. We use another dedicated register, \code{r15}, to
  7010. store the pointer to the top of the root stack. So \code{r15} is not
  7011. available for use by the register allocator.
  7012. \begin{lstlisting}
  7013. (collect |$\itm{bytes}$|)
  7014. |$\Longrightarrow$|
  7015. movq %r15, %rdi
  7016. movq $|\itm{bytes}|, %rsi
  7017. callq collect
  7018. \end{lstlisting}
  7019. \begin{figure}[tp]
  7020. \fbox{
  7021. \begin{minipage}{0.96\textwidth}
  7022. \[
  7023. \begin{array}{lcl}
  7024. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)} \\
  7025. \LangXGlobalM{} &::= & \gray{ \key{.globl main} }\\
  7026. & & \gray{ \key{main:} \; \Instr\ldots }
  7027. \end{array}
  7028. \]
  7029. \end{minipage}
  7030. }
  7031. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  7032. \label{fig:x86-2-concrete}
  7033. \end{figure}
  7034. \begin{figure}[tp]
  7035. \fbox{
  7036. \begin{minipage}{0.96\textwidth}
  7037. \small
  7038. \[
  7039. \begin{array}{lcl}
  7040. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  7041. \MID \BYTEREG{\Reg}} \\
  7042. &\MID& (\key{Global}~\Var) \\
  7043. \LangXGlobalM{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  7044. \end{array}
  7045. \]
  7046. \end{minipage}
  7047. }
  7048. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  7049. \label{fig:x86-2}
  7050. \end{figure}
  7051. The concrete and abstract syntax of the \LangXGlobal{} language is
  7052. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  7053. differs from \LangXIf{} just in the addition of the form for global
  7054. variables.
  7055. %
  7056. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  7057. \code{select-instructions} pass on the running example.
  7058. \begin{figure}[tbp]
  7059. \centering
  7060. % tests/s2_17.rkt
  7061. \begin{minipage}[t]{0.5\textwidth}
  7062. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7063. block35:
  7064. movq free_ptr(%rip), alloc9024
  7065. addq $16, free_ptr(%rip)
  7066. movq alloc9024, %r11
  7067. movq $131, 0(%r11)
  7068. movq alloc9024, %r11
  7069. movq vecinit9025, 8(%r11)
  7070. movq $0, initret9026
  7071. movq alloc9024, %r11
  7072. movq 8(%r11), tmp9034
  7073. movq tmp9034, %r11
  7074. movq 8(%r11), %rax
  7075. jmp conclusion
  7076. block36:
  7077. movq $0, collectret9027
  7078. jmp block35
  7079. block38:
  7080. movq free_ptr(%rip), alloc9020
  7081. addq $16, free_ptr(%rip)
  7082. movq alloc9020, %r11
  7083. movq $3, 0(%r11)
  7084. movq alloc9020, %r11
  7085. movq vecinit9021, 8(%r11)
  7086. movq $0, initret9022
  7087. movq alloc9020, vecinit9025
  7088. movq free_ptr(%rip), tmp9031
  7089. movq tmp9031, tmp9032
  7090. addq $16, tmp9032
  7091. movq fromspace_end(%rip), tmp9033
  7092. cmpq tmp9033, tmp9032
  7093. jl block36
  7094. jmp block37
  7095. block37:
  7096. movq %r15, %rdi
  7097. movq $16, %rsi
  7098. callq 'collect
  7099. jmp block35
  7100. block39:
  7101. movq $0, collectret9023
  7102. jmp block38
  7103. \end{lstlisting}
  7104. \end{minipage}
  7105. \begin{minipage}[t]{0.45\textwidth}
  7106. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7107. start:
  7108. movq $42, vecinit9021
  7109. movq free_ptr(%rip), tmp9028
  7110. movq tmp9028, tmp9029
  7111. addq $16, tmp9029
  7112. movq fromspace_end(%rip), tmp9030
  7113. cmpq tmp9030, tmp9029
  7114. jl block39
  7115. jmp block40
  7116. block40:
  7117. movq %r15, %rdi
  7118. movq $16, %rsi
  7119. callq 'collect
  7120. jmp block38
  7121. \end{lstlisting}
  7122. \end{minipage}
  7123. \caption{Output of the \code{select-instructions} pass.}
  7124. \label{fig:select-instr-output-gc}
  7125. \end{figure}
  7126. \clearpage
  7127. \section{Register Allocation}
  7128. \label{sec:reg-alloc-gc}
  7129. \index{subject}{register allocation}
  7130. As discussed earlier in this chapter, the garbage collector needs to
  7131. access all the pointers in the root set, that is, all variables that
  7132. are vectors. It will be the responsibility of the register allocator
  7133. to make sure that:
  7134. \begin{enumerate}
  7135. \item the root stack is used for spilling vector-typed variables, and
  7136. \item if a vector-typed variable is live during a call to the
  7137. collector, it must be spilled to ensure it is visible to the
  7138. collector.
  7139. \end{enumerate}
  7140. The later responsibility can be handled during construction of the
  7141. interference graph, by adding interference edges between the call-live
  7142. vector-typed variables and all the callee-saved registers. (They
  7143. already interfere with the caller-saved registers.) The type
  7144. information for variables is in the \code{Program} form, so we
  7145. recommend adding another parameter to the \code{build-interference}
  7146. function to communicate this alist.
  7147. The spilling of vector-typed variables to the root stack can be
  7148. handled after graph coloring, when choosing how to assign the colors
  7149. (integers) to registers and stack locations. The \code{Program} output
  7150. of this pass changes to also record the number of spills to the root
  7151. stack.
  7152. % build-interference
  7153. %
  7154. % callq
  7155. % extra parameter for var->type assoc. list
  7156. % update 'program' and 'if'
  7157. % allocate-registers
  7158. % allocate spilled vectors to the rootstack
  7159. % don't change color-graph
  7160. \section{Print x86}
  7161. \label{sec:print-x86-gc}
  7162. \index{subject}{prelude}\index{subject}{conclusion}
  7163. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  7164. \code{print-x86} pass on the running example. In the prelude and
  7165. conclusion of the \code{main} function, we treat the root stack very
  7166. much like the regular stack in that we move the root stack pointer
  7167. (\code{r15}) to make room for the spills to the root stack, except
  7168. that the root stack grows up instead of down. For the running
  7169. example, there was just one spill so we increment \code{r15} by 8
  7170. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  7171. One issue that deserves special care is that there may be a call to
  7172. \code{collect} prior to the initializing assignments for all the
  7173. variables in the root stack. We do not want the garbage collector to
  7174. accidentally think that some uninitialized variable is a pointer that
  7175. needs to be followed. Thus, we zero-out all locations on the root
  7176. stack in the prelude of \code{main}. In
  7177. Figure~\ref{fig:print-x86-output-gc}, the instruction
  7178. %
  7179. \lstinline{movq $0, (%r15)}
  7180. %
  7181. accomplishes this task. The garbage collector tests each root to see
  7182. if it is null prior to dereferencing it.
  7183. \begin{figure}[htbp]
  7184. \begin{minipage}[t]{0.5\textwidth}
  7185. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7186. block35:
  7187. movq free_ptr(%rip), %rcx
  7188. addq $16, free_ptr(%rip)
  7189. movq %rcx, %r11
  7190. movq $131, 0(%r11)
  7191. movq %rcx, %r11
  7192. movq -8(%r15), %rax
  7193. movq %rax, 8(%r11)
  7194. movq $0, %rdx
  7195. movq %rcx, %r11
  7196. movq 8(%r11), %rcx
  7197. movq %rcx, %r11
  7198. movq 8(%r11), %rax
  7199. jmp conclusion
  7200. block36:
  7201. movq $0, %rcx
  7202. jmp block35
  7203. block38:
  7204. movq free_ptr(%rip), %rcx
  7205. addq $16, free_ptr(%rip)
  7206. movq %rcx, %r11
  7207. movq $3, 0(%r11)
  7208. movq %rcx, %r11
  7209. movq %rbx, 8(%r11)
  7210. movq $0, %rdx
  7211. movq %rcx, -8(%r15)
  7212. movq free_ptr(%rip), %rcx
  7213. addq $16, %rcx
  7214. movq fromspace_end(%rip), %rdx
  7215. cmpq %rdx, %rcx
  7216. jl block36
  7217. movq %r15, %rdi
  7218. movq $16, %rsi
  7219. callq collect
  7220. jmp block35
  7221. block39:
  7222. movq $0, %rcx
  7223. jmp block38
  7224. \end{lstlisting}
  7225. \end{minipage}
  7226. \begin{minipage}[t]{0.45\textwidth}
  7227. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7228. start:
  7229. movq $42, %rbx
  7230. movq free_ptr(%rip), %rdx
  7231. addq $16, %rdx
  7232. movq fromspace_end(%rip), %rcx
  7233. cmpq %rcx, %rdx
  7234. jl block39
  7235. movq %r15, %rdi
  7236. movq $16, %rsi
  7237. callq collect
  7238. jmp block38
  7239. .globl main
  7240. main:
  7241. pushq %rbp
  7242. movq %rsp, %rbp
  7243. pushq %r13
  7244. pushq %r12
  7245. pushq %rbx
  7246. pushq %r14
  7247. subq $0, %rsp
  7248. movq $16384, %rdi
  7249. movq $16384, %rsi
  7250. callq initialize
  7251. movq rootstack_begin(%rip), %r15
  7252. movq $0, (%r15)
  7253. addq $8, %r15
  7254. jmp start
  7255. conclusion:
  7256. subq $8, %r15
  7257. addq $0, %rsp
  7258. popq %r14
  7259. popq %rbx
  7260. popq %r12
  7261. popq %r13
  7262. popq %rbp
  7263. retq
  7264. \end{lstlisting}
  7265. \end{minipage}
  7266. \caption{Output of the \code{print-x86} pass.}
  7267. \label{fig:print-x86-output-gc}
  7268. \end{figure}
  7269. \begin{figure}[p]
  7270. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7271. \node (Rvec) at (0,2) {\large \LangVec{}};
  7272. \node (Rvec-2) at (3,2) {\large \LangVec{}};
  7273. \node (Rvec-3) at (6,2) {\large \LangVec{}};
  7274. \node (Rvec-4) at (9,2) {\large \LangVec{}};
  7275. \node (Rvec-5) at (12,2) {\large \LangAlloc{}};
  7276. \node (C2-4) at (3,0) {\large \LangCVec{}};
  7277. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  7278. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  7279. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  7280. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  7281. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  7282. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  7283. %\path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize type-check} (Rvec-2);
  7284. \path[->,bend left=15] (Rvec) edge [above] node {\ttfamily\footnotesize shrink} (Rvec-2);
  7285. \path[->,bend left=15] (Rvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Rvec-3);
  7286. \path[->,bend left=15] (Rvec-3) edge [above] node {\ttfamily\footnotesize expose-alloc.} (Rvec-4);
  7287. \path[->,bend left=15] (Rvec-4) edge [above] node {\ttfamily\footnotesize remove-complex.} (Rvec-5);
  7288. \path[->,bend left=20] (Rvec-5) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-4);
  7289. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select-instr.} (x86-2);
  7290. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  7291. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  7292. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7293. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  7294. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  7295. \end{tikzpicture}
  7296. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  7297. \label{fig:Rvec-passes}
  7298. \end{figure}
  7299. Figure~\ref{fig:Rvec-passes} gives an overview of all the passes needed
  7300. for the compilation of \LangVec{}.
  7301. \section{Challenge: Simple Structures}
  7302. \label{sec:simple-structures}
  7303. \index{subject}{struct}
  7304. \index{subject}{structure}
  7305. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  7306. \LangStruct{}, which extends \LangVec{} with support for simple structures.
  7307. Recall that a \code{struct} in Typed Racket is a user-defined data
  7308. type that contains named fields and that is heap allocated, similar to
  7309. a vector. The following is an example of a structure definition, in
  7310. this case the definition of a \code{point} type.
  7311. \begin{lstlisting}
  7312. (struct point ([x : Integer] [y : Integer]) #:mutable)
  7313. \end{lstlisting}
  7314. \begin{figure}[tbp]
  7315. \centering
  7316. \fbox{
  7317. \begin{minipage}{0.96\textwidth}
  7318. \[
  7319. \begin{array}{lcl}
  7320. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  7321. \MID (\key{Vector}\;\Type \ldots) \MID \key{Void} } \MID \Var \\
  7322. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} } \\
  7323. \Exp &::=& \gray{ \Int \MID (\key{read}) \MID (\key{-}\;\Exp) \MID (\key{+} \; \Exp\;\Exp) \MID (\key{-}\;\Exp\;\Exp) } \\
  7324. &\MID& \gray{ \Var \MID (\key{let}~([\Var~\Exp])~\Exp) }\\
  7325. &\MID& \gray{ \key{\#t} \MID \key{\#f}
  7326. \MID (\key{and}\;\Exp\;\Exp)
  7327. \MID (\key{or}\;\Exp\;\Exp)
  7328. \MID (\key{not}\;\Exp) } \\
  7329. &\MID& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  7330. \MID (\key{if}~\Exp~\Exp~\Exp) } \\
  7331. &\MID& \gray{ (\key{vector}\;\Exp \ldots)
  7332. \MID (\key{vector-ref}\;\Exp\;\Int) } \\
  7333. &\MID& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  7334. &\MID& \gray{ (\key{void}) } \MID (\Var\;\Exp \ldots)\\
  7335. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  7336. \LangStruct{} &::=& \Def \ldots \; \Exp
  7337. \end{array}
  7338. \]
  7339. \end{minipage}
  7340. }
  7341. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  7342. (Figure~\ref{fig:Rvec-concrete-syntax}).}
  7343. \label{fig:r3s-concrete-syntax}
  7344. \end{figure}
  7345. An instance of a structure is created using function call syntax, with
  7346. the name of the structure in the function position:
  7347. \begin{lstlisting}
  7348. (point 7 12)
  7349. \end{lstlisting}
  7350. Function-call syntax is also used to read the value in a field of a
  7351. structure. The function name is formed by the structure name, a dash,
  7352. and the field name. The following example uses \code{point-x} and
  7353. \code{point-y} to access the \code{x} and \code{y} fields of two point
  7354. instances.
  7355. \begin{center}
  7356. \begin{lstlisting}
  7357. (let ([pt1 (point 7 12)])
  7358. (let ([pt2 (point 4 3)])
  7359. (+ (- (point-x pt1) (point-x pt2))
  7360. (- (point-y pt1) (point-y pt2)))))
  7361. \end{lstlisting}
  7362. \end{center}
  7363. Similarly, to write to a field of a structure, use its set function,
  7364. whose name starts with \code{set-}, followed by the structure name,
  7365. then a dash, then the field name, and concluded with an exclamation
  7366. mark. The following example uses \code{set-point-x!} to change the
  7367. \code{x} field from \code{7} to \code{42}.
  7368. \begin{center}
  7369. \begin{lstlisting}
  7370. (let ([pt (point 7 12)])
  7371. (let ([_ (set-point-x! pt 42)])
  7372. (point-x pt)))
  7373. \end{lstlisting}
  7374. \end{center}
  7375. \begin{exercise}\normalfont
  7376. Extend your compiler with support for simple structures, compiling
  7377. \LangStruct{} to x86 assembly code. Create five new test cases that use
  7378. structures and test your compiler.
  7379. \end{exercise}
  7380. \section{Challenge: Generational Collection}
  7381. The copying collector described in Section~\ref{sec:GC} can incur
  7382. significant runtime overhead because the call to \code{collect} takes
  7383. time proportional to all of the live data. One way to reduce this
  7384. overhead is to reduce how much data is inspected in each call to
  7385. \code{collect}. In particular, researchers have observed that recently
  7386. allocated data is more likely to become garbage then data that has
  7387. survived one or more previous calls to \code{collect}. This insight
  7388. motivated the creation of \emph{generational garbage collectors}
  7389. \index{subject}{generational garbage collector} that
  7390. 1) segregates data according to its age into two or more generations,
  7391. 2) allocates less space for younger generations, so collecting them is
  7392. faster, and more space for the older generations, and 3) performs
  7393. collection on the younger generations more frequently then for older
  7394. generations~\citep{Wilson:1992fk}.
  7395. For this challenge assignment, the goal is to adapt the copying
  7396. collector implemented in \code{runtime.c} to use two generations, one
  7397. for young data and one for old data. Each generation consists of a
  7398. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  7399. \code{collect} function to use the two generations.
  7400. \begin{enumerate}
  7401. \item Copy the young generation's FromSpace to its ToSpace then switch
  7402. the role of the ToSpace and FromSpace
  7403. \item If there is enough space for the requested number of bytes in
  7404. the young FromSpace, then return from \code{collect}.
  7405. \item If there is not enough space in the young FromSpace for the
  7406. requested bytes, then move the data from the young generation to the
  7407. old one with the following steps:
  7408. \begin{enumerate}
  7409. \item If there is enough room in the old FromSpace, copy the young
  7410. FromSpace to the old FromSpace and then return.
  7411. \item If there is not enough room in the old FromSpace, then collect
  7412. the old generation by copying the old FromSpace to the old ToSpace
  7413. and swap the roles of the old FromSpace and ToSpace.
  7414. \item If there is enough room now, copy the young FromSpace to the
  7415. old FromSpace and return. Otherwise, allocate a larger FromSpace
  7416. and ToSpace for the old generation. Copy the young FromSpace and
  7417. the old FromSpace into the larger FromSpace for the old
  7418. generation and then return.
  7419. \end{enumerate}
  7420. \end{enumerate}
  7421. We recommend that you generalize the \code{cheney} function so that it
  7422. can be used for all the copies mentioned above: between the young
  7423. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  7424. between the young FromSpace and old FromSpace. This can be
  7425. accomplished by adding parameters to \code{cheney} that replace its
  7426. use of the global variables \code{fromspace\_begin},
  7427. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  7428. Note that the collection of the young generation does not traverse the
  7429. old generation. This introduces a potential problem: there may be
  7430. young data that is only reachable through pointers in the old
  7431. generation. If these pointers are not taken into account, the
  7432. collector could throw away young data that is live! One solution,
  7433. called \emph{pointer recording}, is to maintain a set of all the
  7434. pointers from the old generation into the new generation and consider
  7435. this set as part of the root set. To maintain this set, the compiler
  7436. must insert extra instructions around every \code{vector-set!}. If the
  7437. vector being modified is in the old generation, and if the value being
  7438. written is a pointer into the new generation, than that pointer must
  7439. be added to the set. Also, if the value being overwritten was a
  7440. pointer into the new generation, then that pointer should be removed
  7441. from the set.
  7442. \begin{exercise}\normalfont
  7443. Adapt the \code{collect} function in \code{runtime.c} to implement
  7444. generational garbage collection, as outlined in this section.
  7445. Update the code generation for \code{vector-set!} to implement
  7446. pointer recording. Make sure that your new compiler and runtime
  7447. passes your test suite.
  7448. \end{exercise}
  7449. % Further Reading
  7450. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7451. \chapter{Functions}
  7452. \label{ch:Rfun}
  7453. \index{subject}{function}
  7454. This chapter studies the compilation of functions similar to those
  7455. found in the C language. This corresponds to a subset of Typed Racket
  7456. in which only top-level function definitions are allowed. This kind of
  7457. function is an important stepping stone to implementing
  7458. lexically-scoped functions, that is, \key{lambda} abstractions, which
  7459. is the topic of Chapter~\ref{ch:Rlam}.
  7460. \section{The \LangFun{} Language}
  7461. The concrete and abstract syntax for function definitions and function
  7462. application is shown in Figures~\ref{fig:Rfun-concrete-syntax} and
  7463. \ref{fig:Rfun-syntax}, where we define the \LangFun{} language. Programs in
  7464. \LangFun{} begin with zero or more function definitions. The function
  7465. names from these definitions are in-scope for the entire program,
  7466. including all other function definitions (so the ordering of function
  7467. definitions does not matter). The concrete syntax for function
  7468. application\index{subject}{function application} is $(\Exp \; \Exp \ldots)$
  7469. where the first expression must
  7470. evaluate to a function and the rest are the arguments.
  7471. The abstract syntax for function application is
  7472. $\APPLY{\Exp}{\Exp\ldots}$.
  7473. %% The syntax for function application does not include an explicit
  7474. %% keyword, which is error prone when using \code{match}. To alleviate
  7475. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  7476. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  7477. Functions are first-class in the sense that a function pointer
  7478. \index{subject}{function pointer} is data and can be stored in memory or passed
  7479. as a parameter to another function. Thus, we introduce a function
  7480. type, written
  7481. \begin{lstlisting}
  7482. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  7483. \end{lstlisting}
  7484. for a function whose $n$ parameters have the types $\Type_1$ through
  7485. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  7486. these functions (with respect to Racket functions) is that they are
  7487. not lexically scoped. That is, the only external entities that can be
  7488. referenced from inside a function body are other globally-defined
  7489. functions. The syntax of \LangFun{} prevents functions from being nested
  7490. inside each other.
  7491. \begin{figure}[tp]
  7492. \centering
  7493. \fbox{
  7494. \begin{minipage}{0.96\textwidth}
  7495. \small
  7496. \[
  7497. \begin{array}{lcl}
  7498. \Type &::=& \gray{ \key{Integer} \MID \key{Boolean}
  7499. \MID (\key{Vector}\;\Type\ldots) \MID \key{Void} } \MID (\Type \ldots \; \key{->}\; \Type) \\
  7500. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} } \\
  7501. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  7502. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  7503. &\MID& \gray{ \key{\#t} \MID \key{\#f}
  7504. \MID (\key{and}\;\Exp\;\Exp)
  7505. \MID (\key{or}\;\Exp\;\Exp)
  7506. \MID (\key{not}\;\Exp)} \\
  7507. &\MID& \gray{(\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  7508. &\MID& \gray{(\key{vector}\;\Exp\ldots) \MID
  7509. (\key{vector-ref}\;\Exp\;\Int)} \\
  7510. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  7511. \MID \LP\key{has-type}~\Exp~\Type\RP } \\
  7512. &\MID& \LP\Exp \; \Exp \ldots\RP \\
  7513. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  7514. \LangFunM{} &::=& \Def \ldots \; \Exp
  7515. \end{array}
  7516. \]
  7517. \end{minipage}
  7518. }
  7519. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-concrete-syntax}).}
  7520. \label{fig:Rfun-concrete-syntax}
  7521. \end{figure}
  7522. \begin{figure}[tp]
  7523. \centering
  7524. \fbox{
  7525. \begin{minipage}{0.96\textwidth}
  7526. \small
  7527. \[
  7528. \begin{array}{lcl}
  7529. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  7530. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  7531. &\MID& \gray{ \BOOL{\itm{bool}}
  7532. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  7533. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP }
  7534. \MID \APPLY{\Exp}{\Exp\ldots}\\
  7535. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}\\
  7536. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  7537. \end{array}
  7538. \]
  7539. \end{minipage}
  7540. }
  7541. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Rvec-syntax}).}
  7542. \label{fig:Rfun-syntax}
  7543. \end{figure}
  7544. The program in Figure~\ref{fig:Rfun-function-example} is a
  7545. representative example of defining and using functions in \LangFun{}. We
  7546. define a function \code{map-vec} that applies some other function
  7547. \code{f} to both elements of a vector and returns a new
  7548. vector containing the results. We also define a function \code{add1}.
  7549. The program applies
  7550. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  7551. \code{(vector 1 42)}, from which we return the \code{42}.
  7552. \begin{figure}[tbp]
  7553. \begin{lstlisting}
  7554. (define (map-vec [f : (Integer -> Integer)]
  7555. [v : (Vector Integer Integer)])
  7556. : (Vector Integer Integer)
  7557. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  7558. (define (add1 [x : Integer]) : Integer
  7559. (+ x 1))
  7560. (vector-ref (map-vec add1 (vector 0 41)) 1)
  7561. \end{lstlisting}
  7562. \caption{Example of using functions in \LangFun{}.}
  7563. \label{fig:Rfun-function-example}
  7564. \end{figure}
  7565. The definitional interpreter for \LangFun{} is in
  7566. Figure~\ref{fig:interp-Rfun}. The case for the \code{ProgramDefsExp} form is
  7567. responsible for setting up the mutual recursion between the top-level
  7568. function definitions. We use the classic back-patching \index{subject}{back-patching}
  7569. approach that uses mutable variables and makes two passes over the function
  7570. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  7571. top-level environment using a mutable cons cell for each function
  7572. definition. Note that the \code{lambda} value for each function is
  7573. incomplete; it does not yet include the environment. Once the
  7574. top-level environment is constructed, we then iterate over it and
  7575. update the \code{lambda} values to use the top-level environment.
  7576. \begin{figure}[tp]
  7577. \begin{lstlisting}
  7578. (define interp-Rfun-class
  7579. (class interp-Rvec-class
  7580. (super-new)
  7581. (define/override ((interp-exp env) e)
  7582. (define recur (interp-exp env))
  7583. (match e
  7584. [(Var x) (unbox (dict-ref env x))]
  7585. [(Let x e body)
  7586. (define new-env (dict-set env x (box (recur e))))
  7587. ((interp-exp new-env) body)]
  7588. [(Apply fun args)
  7589. (define fun-val (recur fun))
  7590. (define arg-vals (for/list ([e args]) (recur e)))
  7591. (match fun-val
  7592. [`(function (,xs ...) ,body ,fun-env)
  7593. (define params-args (for/list ([x xs] [arg arg-vals])
  7594. (cons x (box arg))))
  7595. (define new-env (append params-args fun-env))
  7596. ((interp-exp new-env) body)]
  7597. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  7598. [else ((super interp-exp env) e)]
  7599. ))
  7600. (define/public (interp-def d)
  7601. (match d
  7602. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  7603. (cons f (box `(function ,xs ,body ())))]))
  7604. (define/override (interp-program p)
  7605. (match p
  7606. [(ProgramDefsExp info ds body)
  7607. (let ([top-level (for/list ([d ds]) (interp-def d))])
  7608. (for/list ([f (in-dict-values top-level)])
  7609. (set-box! f (match (unbox f)
  7610. [`(function ,xs ,body ())
  7611. `(function ,xs ,body ,top-level)])))
  7612. ((interp-exp top-level) body))]))
  7613. ))
  7614. (define (interp-Rfun p)
  7615. (send (new interp-Rfun-class) interp-program p))
  7616. \end{lstlisting}
  7617. \caption{Interpreter for the \LangFun{} language.}
  7618. \label{fig:interp-Rfun}
  7619. \end{figure}
  7620. %\margincomment{TODO: explain type checker}
  7621. The type checker for \LangFun{} is in Figure~\ref{fig:type-check-Rfun}.
  7622. \begin{figure}[tp]
  7623. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7624. (define type-check-Rfun-class
  7625. (class type-check-Rvec-class
  7626. (super-new)
  7627. (inherit check-type-equal?)
  7628. (define/public (type-check-apply env e es)
  7629. (define-values (e^ ty) ((type-check-exp env) e))
  7630. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  7631. ((type-check-exp env) e)))
  7632. (match ty
  7633. [`(,ty^* ... -> ,rt)
  7634. (for ([arg-ty ty*] [param-ty ty^*])
  7635. (check-type-equal? arg-ty param-ty (Apply e es)))
  7636. (values e^ e* rt)]))
  7637. (define/override (type-check-exp env)
  7638. (lambda (e)
  7639. (match e
  7640. [(FunRef f)
  7641. (values (FunRef f) (dict-ref env f))]
  7642. [(Apply e es)
  7643. (define-values (e^ es^ rt) (type-check-apply env e es))
  7644. (values (Apply e^ es^) rt)]
  7645. [(Call e es)
  7646. (define-values (e^ es^ rt) (type-check-apply env e es))
  7647. (values (Call e^ es^) rt)]
  7648. [else ((super type-check-exp env) e)])))
  7649. (define/public (type-check-def env)
  7650. (lambda (e)
  7651. (match e
  7652. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  7653. (define new-env (append (map cons xs ps) env))
  7654. (define-values (body^ ty^) ((type-check-exp new-env) body))
  7655. (check-type-equal? ty^ rt body)
  7656. (Def f p:t* rt info body^)])))
  7657. (define/public (fun-def-type d)
  7658. (match d
  7659. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  7660. (define/override (type-check-program e)
  7661. (match e
  7662. [(ProgramDefsExp info ds body)
  7663. (define new-env (for/list ([d ds])
  7664. (cons (Def-name d) (fun-def-type d))))
  7665. (define ds^ (for/list ([d ds]) ((type-check-def new-env) d)))
  7666. (define-values (body^ ty) ((type-check-exp new-env) body))
  7667. (check-type-equal? ty 'Integer body)
  7668. (ProgramDefsExp info ds^ body^)]))))
  7669. (define (type-check-Rfun p)
  7670. (send (new type-check-Rfun-class) type-check-program p))
  7671. \end{lstlisting}
  7672. \caption{Type checker for the \LangFun{} language.}
  7673. \label{fig:type-check-Rfun}
  7674. \end{figure}
  7675. \section{Functions in x86}
  7676. \label{sec:fun-x86}
  7677. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  7678. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  7679. %% \margincomment{\tiny Talk about the return address on the
  7680. %% stack and what callq and retq does.\\ --Jeremy }
  7681. The x86 architecture provides a few features to support the
  7682. implementation of functions. We have already seen that x86 provides
  7683. labels so that one can refer to the location of an instruction, as is
  7684. needed for jump instructions. Labels can also be used to mark the
  7685. beginning of the instructions for a function. Going further, we can
  7686. obtain the address of a label by using the \key{leaq} instruction and
  7687. PC-relative addressing. For example, the following puts the
  7688. address of the \code{add1} label into the \code{rbx} register.
  7689. \begin{lstlisting}
  7690. leaq add1(%rip), %rbx
  7691. \end{lstlisting}
  7692. The instruction pointer register \key{rip} (aka. the program counter
  7693. \index{subject}{program counter}) always points to the next instruction to be
  7694. executed. When combined with an label, as in \code{add1(\%rip)}, the
  7695. linker computes the distance $d$ between the address of \code{add1}
  7696. and where the \code{rip} would be at that moment and then changes
  7697. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  7698. the address of \code{add1}.
  7699. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  7700. jump to a function whose location is given by a label. To support
  7701. function calls in this chapter we instead will be jumping to a
  7702. function whose location is given by an address in a register, that is,
  7703. we need to make an \emph{indirect function call}. The x86 syntax for
  7704. this is a \code{callq} instruction but with an asterisk before the
  7705. register name.\index{subject}{indirect function call}
  7706. \begin{lstlisting}
  7707. callq *%rbx
  7708. \end{lstlisting}
  7709. \subsection{Calling Conventions}
  7710. \index{subject}{calling conventions}
  7711. The \code{callq} instruction provides partial support for implementing
  7712. functions: it pushes the return address on the stack and it jumps to
  7713. the target. However, \code{callq} does not handle
  7714. \begin{enumerate}
  7715. \item parameter passing,
  7716. \item pushing frames on the procedure call stack and popping them off,
  7717. or
  7718. \item determining how registers are shared by different functions.
  7719. \end{enumerate}
  7720. Regarding (1) parameter passing, recall that the following six
  7721. registers are used to pass arguments to a function, in this order.
  7722. \begin{lstlisting}
  7723. rdi rsi rdx rcx r8 r9
  7724. \end{lstlisting}
  7725. If there are
  7726. more than six arguments, then the convention is to use space on the
  7727. frame of the caller for the rest of the arguments. However, to ease
  7728. the implementation of efficient tail calls
  7729. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  7730. arguments.
  7731. %
  7732. Also recall that the register \code{rax} is for the return value of
  7733. the function.
  7734. \index{subject}{prelude}\index{subject}{conclusion}
  7735. Regarding (2) frames \index{subject}{frame} and the procedure call stack,
  7736. \index{subject}{procedure call stack} recall from Section~\ref{sec:x86} that
  7737. the stack grows down, with each function call using a chunk of space
  7738. called a frame. The caller sets the stack pointer, register
  7739. \code{rsp}, to the last data item in its frame. The callee must not
  7740. change anything in the caller's frame, that is, anything that is at or
  7741. above the stack pointer. The callee is free to use locations that are
  7742. below the stack pointer.
  7743. Recall that we are storing variables of vector type on the root stack.
  7744. So the prelude needs to move the root stack pointer \code{r15} up and
  7745. the conclusion needs to move the root stack pointer back down. Also,
  7746. the prelude must initialize to \code{0} this frame's slots in the root
  7747. stack to signal to the garbage collector that those slots do not yet
  7748. contain a pointer to a vector. Otherwise the garbage collector will
  7749. interpret the garbage bits in those slots as memory addresses and try
  7750. to traverse them, causing serious mayhem!
  7751. Regarding (3) the sharing of registers between different functions,
  7752. recall from Section~\ref{sec:calling-conventions} that the registers
  7753. are divided into two groups, the caller-saved registers and the
  7754. callee-saved registers. The caller should assume that all the
  7755. caller-saved registers get overwritten with arbitrary values by the
  7756. callee. That is why we recommend in
  7757. Section~\ref{sec:calling-conventions} that variables that are live
  7758. during a function call should not be assigned to caller-saved
  7759. registers.
  7760. On the flip side, if the callee wants to use a callee-saved register,
  7761. the callee must save the contents of those registers on their stack
  7762. frame and then put them back prior to returning to the caller. That
  7763. is why we recommended in Section~\ref{sec:calling-conventions} that if
  7764. the register allocator assigns a variable to a callee-saved register,
  7765. then the prelude of the \code{main} function must save that register
  7766. to the stack and the conclusion of \code{main} must restore it. This
  7767. recommendation now generalizes to all functions.
  7768. Also recall that the base pointer, register \code{rbp}, is used as a
  7769. point-of-reference within a frame, so that each local variable can be
  7770. accessed at a fixed offset from the base pointer
  7771. (Section~\ref{sec:x86}).
  7772. %
  7773. Figure~\ref{fig:call-frames} shows the general layout of the caller
  7774. and callee frames.
  7775. \begin{figure}[tbp]
  7776. \centering
  7777. \begin{tabular}{r|r|l|l} \hline
  7778. Caller View & Callee View & Contents & Frame \\ \hline
  7779. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  7780. 0(\key{\%rbp}) & & old \key{rbp} \\
  7781. -8(\key{\%rbp}) & & callee-saved $1$ \\
  7782. \ldots & & \ldots \\
  7783. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  7784. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  7785. \ldots & & \ldots \\
  7786. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  7787. %% & & \\
  7788. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  7789. %% & \ldots & \ldots \\
  7790. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  7791. \hline
  7792. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  7793. & 0(\key{\%rbp}) & old \key{rbp} \\
  7794. & -8(\key{\%rbp}) & callee-saved $1$ \\
  7795. & \ldots & \ldots \\
  7796. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  7797. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  7798. & \ldots & \ldots \\
  7799. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  7800. \end{tabular}
  7801. \caption{Memory layout of caller and callee frames.}
  7802. \label{fig:call-frames}
  7803. \end{figure}
  7804. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  7805. %% local variables and for storing the values of callee-saved registers
  7806. %% (we shall refer to all of these collectively as ``locals''), and that
  7807. %% at the beginning of a function we move the stack pointer \code{rsp}
  7808. %% down to make room for them.
  7809. %% We recommend storing the local variables
  7810. %% first and then the callee-saved registers, so that the local variables
  7811. %% can be accessed using \code{rbp} the same as before the addition of
  7812. %% functions.
  7813. %% To make additional room for passing arguments, we shall
  7814. %% move the stack pointer even further down. We count how many stack
  7815. %% arguments are needed for each function call that occurs inside the
  7816. %% body of the function and find their maximum. Adding this number to the
  7817. %% number of locals gives us how much the \code{rsp} should be moved at
  7818. %% the beginning of the function. In preparation for a function call, we
  7819. %% offset from \code{rsp} to set up the stack arguments. We put the first
  7820. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  7821. %% so on.
  7822. %% Upon calling the function, the stack arguments are retrieved by the
  7823. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  7824. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  7825. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  7826. %% the layout of the caller and callee frames. Notice how important it is
  7827. %% that we correctly compute the maximum number of arguments needed for
  7828. %% function calls; if that number is too small then the arguments and
  7829. %% local variables will smash into each other!
  7830. \subsection{Efficient Tail Calls}
  7831. \label{sec:tail-call}
  7832. In general, the amount of stack space used by a program is determined
  7833. by the longest chain of nested function calls. That is, if function
  7834. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  7835. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  7836. $n$ can grow quite large in the case of recursive or mutually
  7837. recursive functions. However, in some cases we can arrange to use only
  7838. constant space, i.e. $O(1)$, instead of $O(n)$.
  7839. If a function call is the last action in a function body, then that
  7840. call is said to be a \emph{tail call}\index{subject}{tail call}.
  7841. For example, in the following
  7842. program, the recursive call to \code{tail-sum} is a tail call.
  7843. \begin{center}
  7844. \begin{lstlisting}
  7845. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  7846. (if (eq? n 0)
  7847. r
  7848. (tail-sum (- n 1) (+ n r))))
  7849. (+ (tail-sum 5 0) 27)
  7850. \end{lstlisting}
  7851. \end{center}
  7852. At a tail call, the frame of the caller is no longer needed, so we
  7853. can pop the caller's frame before making the tail call. With this
  7854. approach, a recursive function that only makes tail calls will only
  7855. use $O(1)$ stack space. Functional languages like Racket typically
  7856. rely heavily on recursive functions, so they typically guarantee that
  7857. all tail calls will be optimized in this way.
  7858. \index{subject}{frame}
  7859. However, some care is needed with regards to argument passing in tail
  7860. calls. As mentioned above, for arguments beyond the sixth, the
  7861. convention is to use space in the caller's frame for passing
  7862. arguments. But for a tail call we pop the caller's frame and can no
  7863. longer use it. Another alternative is to use space in the callee's
  7864. frame for passing arguments. However, this option is also problematic
  7865. because the caller and callee's frame overlap in memory. As we begin
  7866. to copy the arguments from their sources in the caller's frame, the
  7867. target locations in the callee's frame might overlap with the sources
  7868. for later arguments! We solve this problem by not using the stack for
  7869. passing more than six arguments but instead using the heap, as we
  7870. describe in the Section~\ref{sec:limit-functions-r4}.
  7871. As mentioned above, for a tail call we pop the caller's frame prior to
  7872. making the tail call. The instructions for popping a frame are the
  7873. instructions that we usually place in the conclusion of a
  7874. function. Thus, we also need to place such code immediately before
  7875. each tail call. These instructions include restoring the callee-saved
  7876. registers, so it is good that the argument passing registers are all
  7877. caller-saved registers.
  7878. One last note regarding which instruction to use to make the tail
  7879. call. When the callee is finished, it should not return to the current
  7880. function, but it should return to the function that called the current
  7881. one. Thus, the return address that is already on the stack is the
  7882. right one, and we should not use \key{callq} to make the tail call, as
  7883. that would unnecessarily overwrite the return address. Instead we can
  7884. simply use the \key{jmp} instruction. Like the indirect function call,
  7885. we write an \emph{indirect jump}\index{subject}{indirect jump} with a register
  7886. prefixed with an asterisk. We recommend using \code{rax} to hold the
  7887. jump target because the preceding conclusion overwrites just about
  7888. everything else.
  7889. \begin{lstlisting}
  7890. jmp *%rax
  7891. \end{lstlisting}
  7892. \section{Shrink \LangFun{}}
  7893. \label{sec:shrink-r4}
  7894. The \code{shrink} pass performs a minor modification to ease the
  7895. later passes. This pass introduces an explicit \code{main} function
  7896. and changes the top \code{ProgramDefsExp} form to
  7897. \code{ProgramDefs} as follows.
  7898. \begin{lstlisting}
  7899. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  7900. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  7901. \end{lstlisting}
  7902. where $\itm{mainDef}$ is
  7903. \begin{lstlisting}
  7904. (Def 'main '() 'Integer '() |$\Exp'$|)
  7905. \end{lstlisting}
  7906. \section{Reveal Functions and the \LangFunRef{} language}
  7907. \label{sec:reveal-functions-r4}
  7908. The syntax of \LangFun{} is inconvenient for purposes of compilation in one
  7909. respect: it conflates the use of function names and local
  7910. variables. This is a problem because we need to compile the use of a
  7911. function name differently than the use of a local variable; we need to
  7912. use \code{leaq} to convert the function name (a label in x86) to an
  7913. address in a register. Thus, it is a good idea to create a new pass
  7914. that changes function references from just a symbol $f$ to
  7915. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  7916. output language, \LangFunRef{}, is defined in Figure~\ref{fig:f1-syntax}.
  7917. The concrete syntax for a function reference is $\CFUNREF{f}$.
  7918. \begin{figure}[tp]
  7919. \centering
  7920. \fbox{
  7921. \begin{minipage}{0.96\textwidth}
  7922. \[
  7923. \begin{array}{lcl}
  7924. \Exp &::=& \ldots \MID \FUNREF{\Var}\\
  7925. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  7926. \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  7927. \end{array}
  7928. \]
  7929. \end{minipage}
  7930. }
  7931. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  7932. (Figure~\ref{fig:Rfun-syntax}).}
  7933. \label{fig:f1-syntax}
  7934. \end{figure}
  7935. %% Distinguishing between calls in tail position and non-tail position
  7936. %% requires the pass to have some notion of context. We recommend using
  7937. %% two mutually recursive functions, one for processing expressions in
  7938. %% tail position and another for the rest.
  7939. Placing this pass after \code{uniquify} will make sure that there are
  7940. no local variables and functions that share the same name. On the
  7941. other hand, \code{reveal-functions} needs to come before the
  7942. \code{explicate-control} pass because that pass helps us compile
  7943. \code{FunRef} forms into assignment statements.
  7944. \section{Limit Functions}
  7945. \label{sec:limit-functions-r4}
  7946. Recall that we wish to limit the number of function parameters to six
  7947. so that we do not need to use the stack for argument passing, which
  7948. makes it easier to implement efficient tail calls. However, because
  7949. the input language \LangFun{} supports arbitrary numbers of function
  7950. arguments, we have some work to do!
  7951. This pass transforms functions and function calls that involve more
  7952. than six arguments to pass the first five arguments as usual, but it
  7953. packs the rest of the arguments into a vector and passes it as the
  7954. sixth argument.
  7955. Each function definition with too many parameters is transformed as
  7956. follows.
  7957. \begin{lstlisting}
  7958. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  7959. |$\Rightarrow$|
  7960. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  7961. \end{lstlisting}
  7962. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  7963. the occurrences of the later parameters with vector references.
  7964. \begin{lstlisting}
  7965. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  7966. \end{lstlisting}
  7967. For function calls with too many arguments, the \code{limit-functions}
  7968. pass transforms them in the following way.
  7969. \begin{tabular}{lll}
  7970. \begin{minipage}{0.2\textwidth}
  7971. \begin{lstlisting}
  7972. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  7973. \end{lstlisting}
  7974. \end{minipage}
  7975. &
  7976. $\Rightarrow$
  7977. &
  7978. \begin{minipage}{0.4\textwidth}
  7979. \begin{lstlisting}
  7980. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  7981. \end{lstlisting}
  7982. \end{minipage}
  7983. \end{tabular}
  7984. \section{Remove Complex Operands}
  7985. \label{sec:rco-r4}
  7986. The primary decisions to make for this pass is whether to classify
  7987. \code{FunRef} and \code{Apply} as either atomic or complex
  7988. expressions. Recall that a simple expression will eventually end up as
  7989. just an immediate argument of an x86 instruction. Function
  7990. application will be translated to a sequence of instructions, so
  7991. \code{Apply} must be classified as complex expression.
  7992. On the other hand, the arguments of \code{Apply} should be
  7993. atomic expressions.
  7994. %
  7995. Regarding \code{FunRef}, as discussed above, the function label needs
  7996. to be converted to an address using the \code{leaq} instruction. Thus,
  7997. even though \code{FunRef} seems rather simple, it needs to be
  7998. classified as a complex expression so that we generate an assignment
  7999. statement with a left-hand side that can serve as the target of the
  8000. \code{leaq}. Figure~\ref{fig:Rfun-anf-syntax} defines the
  8001. output language \LangFunANF{} of this pass.
  8002. \begin{figure}[tp]
  8003. \centering
  8004. \fbox{
  8005. \begin{minipage}{0.96\textwidth}
  8006. \small
  8007. \[
  8008. \begin{array}{rcl}
  8009. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  8010. \MID \VOID{} } \\
  8011. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  8012. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  8013. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  8014. &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  8015. &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  8016. &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  8017. \MID \LP\key{GlobalValue}~\Var\RP }\\
  8018. &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  8019. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  8020. R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  8021. \end{array}
  8022. \]
  8023. \end{minipage}
  8024. }
  8025. \caption{\LangFunANF{} is \LangFun{} in administrative normal form (ANF).}
  8026. \label{fig:Rfun-anf-syntax}
  8027. \end{figure}
  8028. \section{Explicate Control and the \LangCFun{} language}
  8029. \label{sec:explicate-control-r4}
  8030. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  8031. output of \key{explicate-control}. (The concrete syntax is given in
  8032. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.) The auxiliary
  8033. functions for assignment and tail contexts should be updated with
  8034. cases for \code{Apply} and \code{FunRef} and the function for
  8035. predicate context should be updated for \code{Apply} but not
  8036. \code{FunRef}. (A \code{FunRef} can't be a Boolean.) In assignment
  8037. and predicate contexts, \code{Apply} becomes \code{Call}, whereas in
  8038. tail position \code{Apply} becomes \code{TailCall}. We recommend
  8039. defining a new auxiliary function for processing function definitions.
  8040. This code is similar to the case for \code{Program} in \LangVec{}. The
  8041. top-level \code{explicate-control} function that handles the
  8042. \code{ProgramDefs} form of \LangFun{} can then apply this new function to
  8043. all the function definitions.
  8044. \begin{figure}[tp]
  8045. \fbox{
  8046. \begin{minipage}{0.96\textwidth}
  8047. \small
  8048. \[
  8049. \begin{array}{lcl}
  8050. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} }\\
  8051. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  8052. \Exp &::= & \gray{ \Atm \MID \READ{} } \\
  8053. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} }\\
  8054. &\MID& \gray{ \UNIOP{\key{not}}{\Atm} \MID \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  8055. &\MID& \gray{ \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP } \\
  8056. &\MID& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  8057. &\MID& \gray{ \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP }\\
  8058. &\MID& \gray{ \LP\key{GlobalValue} \,\Var\RP \MID \LP\key{Void}\RP }\\
  8059. &\MID& \FUNREF{\itm{label}} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  8060. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  8061. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  8062. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  8063. \MID \GOTO{\itm{label}} } \\
  8064. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  8065. &\MID& \TAILCALL{\Atm}{\Atm\ldots} \\
  8066. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  8067. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  8068. \end{array}
  8069. \]
  8070. \end{minipage}
  8071. }
  8072. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  8073. \label{fig:c3-syntax}
  8074. \end{figure}
  8075. \section{Select Instructions and the \LangXIndCall{} Language}
  8076. \label{sec:select-r4}
  8077. \index{subject}{instruction selection}
  8078. The output of select instructions is a program in the \LangXIndCall{}
  8079. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  8080. \index{subject}{x86}
  8081. \begin{figure}[tp]
  8082. \fbox{
  8083. \begin{minipage}{0.96\textwidth}
  8084. \small
  8085. \[
  8086. \begin{array}{lcl}
  8087. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)}
  8088. \MID \LP\key{fun-ref}\; \itm{label}\RP\\
  8089. \itm{cc} & ::= & \gray{ \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} } \\
  8090. \Instr &::=& \ldots
  8091. \MID \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  8092. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  8093. \Block &::= & \Instr\ldots \\
  8094. \Def &::= & \LP\key{define} \; \LP\itm{label}\RP \;\LP\LP\itm{label} \,\key{.}\, \Block\RP\ldots\RP\RP\\
  8095. \LangXIndCallM{} &::= & \Def\ldots
  8096. \end{array}
  8097. \]
  8098. \end{minipage}
  8099. }
  8100. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  8101. \label{fig:x86-3-concrete}
  8102. \end{figure}
  8103. \begin{figure}[tp]
  8104. \fbox{
  8105. \begin{minipage}{0.96\textwidth}
  8106. \small
  8107. \[
  8108. \begin{array}{lcl}
  8109. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  8110. \MID \BYTEREG{\Reg} } \\
  8111. &\MID& \gray{ (\key{Global}~\Var) } \MID \FUNREF{\itm{label}} \\
  8112. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  8113. \MID \TAILJMP{\Arg}{\itm{int}}\\
  8114. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  8115. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  8116. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  8117. \LangXIndCallM{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  8118. \end{array}
  8119. \]
  8120. \end{minipage}
  8121. }
  8122. \caption{The abstract syntax of \LangXIndCall{} (extends
  8123. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  8124. \label{fig:x86-3}
  8125. \end{figure}
  8126. An assignment of a function reference to a variable becomes a
  8127. load-effective-address instruction as follows: \\
  8128. \begin{tabular}{lcl}
  8129. \begin{minipage}{0.35\textwidth}
  8130. \begin{lstlisting}
  8131. |$\itm{lhs}$| = (fun-ref |$f$|);
  8132. \end{lstlisting}
  8133. \end{minipage}
  8134. &
  8135. $\Rightarrow$\qquad\qquad
  8136. &
  8137. \begin{minipage}{0.3\textwidth}
  8138. \begin{lstlisting}
  8139. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  8140. \end{lstlisting}
  8141. \end{minipage}
  8142. \end{tabular} \\
  8143. Regarding function definitions, we need to remove the parameters and
  8144. instead perform parameter passing using the conventions discussed in
  8145. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  8146. registers. We recommend turning the parameters into local variables
  8147. and generating instructions at the beginning of the function to move
  8148. from the argument passing registers to these local variables.
  8149. \begin{lstlisting}
  8150. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  8151. |$\Rightarrow$|
  8152. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  8153. \end{lstlisting}
  8154. The $G'$ control-flow graph is the same as $G$ except that the
  8155. \code{start} block is modified to add the instructions for moving from
  8156. the argument registers to the parameter variables. So the \code{start}
  8157. block of $G$ shown on the left is changed to the code on the right.
  8158. \begin{center}
  8159. \begin{minipage}{0.3\textwidth}
  8160. \begin{lstlisting}
  8161. start:
  8162. |$\itm{instr}_1$|
  8163. |$\vdots$|
  8164. |$\itm{instr}_n$|
  8165. \end{lstlisting}
  8166. \end{minipage}
  8167. $\Rightarrow$
  8168. \begin{minipage}{0.3\textwidth}
  8169. \begin{lstlisting}
  8170. start:
  8171. movq %rdi, |$x_1$|
  8172. movq %rsi, |$x_2$|
  8173. |$\vdots$|
  8174. |$\itm{instr}_1$|
  8175. |$\vdots$|
  8176. |$\itm{instr}_n$|
  8177. \end{lstlisting}
  8178. \end{minipage}
  8179. \end{center}
  8180. By changing the parameters to local variables, we are giving the
  8181. register allocator control over which registers or stack locations to
  8182. use for them. If you implemented the move-biasing challenge
  8183. (Section~\ref{sec:move-biasing}), the register allocator will try to
  8184. assign the parameter variables to the corresponding argument register,
  8185. in which case the \code{patch-instructions} pass will remove the
  8186. \code{movq} instruction. This happens in the example translation in
  8187. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  8188. the \code{add} function.
  8189. %
  8190. Also, note that the register allocator will perform liveness analysis
  8191. on this sequence of move instructions and build the interference
  8192. graph. So, for example, $x_1$ will be marked as interfering with
  8193. \code{rsi} and that will prevent the assignment of $x_1$ to
  8194. \code{rsi}, which is good, because that would overwrite the argument
  8195. that needs to move into $x_2$.
  8196. Next, consider the compilation of function calls. In the mirror image
  8197. of handling the parameters of function definitions, the arguments need
  8198. to be moved to the argument passing registers. The function call
  8199. itself is performed with an indirect function call. The return value
  8200. from the function is stored in \code{rax}, so it needs to be moved
  8201. into the \itm{lhs}.
  8202. \begin{lstlisting}
  8203. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  8204. |$\Rightarrow$|
  8205. movq |$\itm{arg}_1$|, %rdi
  8206. movq |$\itm{arg}_2$|, %rsi
  8207. |$\vdots$|
  8208. callq *|\itm{fun}|
  8209. movq %rax, |\itm{lhs}|
  8210. \end{lstlisting}
  8211. The \code{IndirectCallq} AST node includes an integer for the arity of
  8212. the function, i.e., the number of parameters. That information is
  8213. useful in the \code{uncover-live} pass for determining which
  8214. argument-passing registers are potentially read during the call.
  8215. For tail calls, the parameter passing is the same as non-tail calls:
  8216. generate instructions to move the arguments into to the argument
  8217. passing registers. After that we need to pop the frame from the
  8218. procedure call stack. However, we do not yet know how big the frame
  8219. is; that gets determined during register allocation. So instead of
  8220. generating those instructions here, we invent a new instruction that
  8221. means ``pop the frame and then do an indirect jump'', which we name
  8222. \code{TailJmp}. The abstract syntax for this instruction includes an
  8223. argument that specifies where to jump and an integer that represents
  8224. the arity of the function being called.
  8225. Recall that in Section~\ref{sec:explicate-control-Rvar} we recommended
  8226. using the label \code{start} for the initial block of a program, and
  8227. in Section~\ref{sec:select-Rvar} we recommended labeling the conclusion
  8228. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  8229. can be compiled to an assignment to \code{rax} followed by a jump to
  8230. \code{conclusion}. With the addition of function definitions, we will
  8231. have a starting block and conclusion for each function, but their
  8232. labels need to be unique. We recommend prepending the function's name
  8233. to \code{start} and \code{conclusion}, respectively, to obtain unique
  8234. labels. (Alternatively, one could \code{gensym} labels for the start
  8235. and conclusion and store them in the $\itm{info}$ field of the
  8236. function definition.)
  8237. \section{Register Allocation}
  8238. \label{sec:register-allocation-r4}
  8239. \subsection{Liveness Analysis}
  8240. \label{sec:liveness-analysis-r4}
  8241. \index{subject}{liveness analysis}
  8242. %% The rest of the passes need only minor modifications to handle the new
  8243. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  8244. %% \code{leaq}.
  8245. The \code{IndirectCallq} instruction should be treated like
  8246. \code{Callq} regarding its written locations $W$, in that they should
  8247. include all the caller-saved registers. Recall that the reason for
  8248. that is to force call-live variables to be assigned to callee-saved
  8249. registers or to be spilled to the stack.
  8250. Regarding the set of read locations $R$ the arity field of
  8251. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  8252. argument-passing registers should be considered as read by those
  8253. instructions.
  8254. \subsection{Build Interference Graph}
  8255. \label{sec:build-interference-r4}
  8256. With the addition of function definitions, we compute an interference
  8257. graph for each function (not just one for the whole program).
  8258. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  8259. spill vector-typed variables that are live during a call to the
  8260. \code{collect}. With the addition of functions to our language, we
  8261. need to revisit this issue. Many functions perform allocation and
  8262. therefore have calls to the collector inside of them. Thus, we should
  8263. not only spill a vector-typed variable when it is live during a call
  8264. to \code{collect}, but we should spill the variable if it is live
  8265. during any function call. Thus, in the \code{build-interference} pass,
  8266. we recommend adding interference edges between call-live vector-typed
  8267. variables and the callee-saved registers (in addition to the usual
  8268. addition of edges between call-live variables and the caller-saved
  8269. registers).
  8270. \subsection{Allocate Registers}
  8271. The primary change to the \code{allocate-registers} pass is adding an
  8272. auxiliary function for handling definitions (the \Def{} non-terminal
  8273. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  8274. logic is the same as described in
  8275. Chapter~\ref{ch:register-allocation-Rvar}, except now register
  8276. allocation is performed many times, once for each function definition,
  8277. instead of just once for the whole program.
  8278. \section{Patch Instructions}
  8279. In \code{patch-instructions}, you should deal with the x86
  8280. idiosyncrasy that the destination argument of \code{leaq} must be a
  8281. register. Additionally, you should ensure that the argument of
  8282. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  8283. code generation more convenient, because we trample many registers
  8284. before the tail call (as explained in the next section).
  8285. \section{Print x86}
  8286. For the \code{print-x86} pass, the cases for \code{FunRef} and
  8287. \code{IndirectCallq} are straightforward: output their concrete
  8288. syntax.
  8289. \begin{lstlisting}
  8290. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  8291. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  8292. \end{lstlisting}
  8293. The \code{TailJmp} node requires a bit work. A straightforward
  8294. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  8295. before the jump we need to pop the current frame. This sequence of
  8296. instructions is the same as the code for the conclusion of a function,
  8297. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  8298. Regarding function definitions, you will need to generate a prelude
  8299. and conclusion for each one. This code is similar to the prelude and
  8300. conclusion that you generated for the \code{main} function in
  8301. Chapter~\ref{ch:Rvec}. To review, the prelude of every function
  8302. should carry out the following steps.
  8303. \begin{enumerate}
  8304. \item Start with \code{.global} and \code{.align} directives followed
  8305. by the label for the function. (See Figure~\ref{fig:add-fun} for an
  8306. example.)
  8307. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  8308. pointer.
  8309. \item Push to the stack all of the callee-saved registers that were
  8310. used for register allocation.
  8311. \item Move the stack pointer \code{rsp} down by the size of the stack
  8312. frame for this function, which depends on the number of regular
  8313. spills. (Aligned to 16 bytes.)
  8314. \item Move the root stack pointer \code{r15} up by the size of the
  8315. root-stack frame for this function, which depends on the number of
  8316. spilled vectors. \label{root-stack-init}
  8317. \item Initialize to zero all of the entries in the root-stack frame.
  8318. \item Jump to the start block.
  8319. \end{enumerate}
  8320. The prelude of the \code{main} function has one additional task: call
  8321. the \code{initialize} function to set up the garbage collector and
  8322. move the value of the global \code{rootstack\_begin} in
  8323. \code{r15}. This should happen before step \ref{root-stack-init}
  8324. above, which depends on \code{r15}.
  8325. The conclusion of every function should do the following.
  8326. \begin{enumerate}
  8327. \item Move the stack pointer back up by the size of the stack frame
  8328. for this function.
  8329. \item Restore the callee-saved registers by popping them from the
  8330. stack.
  8331. \item Move the root stack pointer back down by the size of the
  8332. root-stack frame for this function.
  8333. \item Restore \code{rbp} by popping it from the stack.
  8334. \item Return to the caller with the \code{retq} instruction.
  8335. \end{enumerate}
  8336. \begin{exercise}\normalfont
  8337. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  8338. Create 5 new programs that use functions, including examples that pass
  8339. functions and return functions from other functions, recursive
  8340. functions, functions that create vectors, and functions that make tail
  8341. calls. Test your compiler on these new programs and all of your
  8342. previously created test programs.
  8343. \end{exercise}
  8344. \begin{figure}[tbp]
  8345. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8346. \node (Rfun) at (0,2) {\large \LangFun{}};
  8347. \node (Rfun-1) at (3,2) {\large \LangFun{}};
  8348. \node (Rfun-2) at (6,2) {\large \LangFun{}};
  8349. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  8350. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  8351. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  8352. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  8353. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  8354. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  8355. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  8356. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  8357. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  8358. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  8359. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  8360. \path[->,bend left=15] (Rfun) edge [above] node
  8361. {\ttfamily\footnotesize shrink} (Rfun-1);
  8362. \path[->,bend left=15] (Rfun-1) edge [above] node
  8363. {\ttfamily\footnotesize uniquify} (Rfun-2);
  8364. \path[->,bend left=15] (Rfun-2) edge [right] node
  8365. {\ttfamily\footnotesize ~~reveal-functions} (F1-1);
  8366. \path[->,bend left=15] (F1-1) edge [below] node
  8367. {\ttfamily\footnotesize limit-functions} (F1-2);
  8368. \path[->,bend right=15] (F1-2) edge [above] node
  8369. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  8370. \path[->,bend right=15] (F1-3) edge [above] node
  8371. {\ttfamily\footnotesize remove-complex.} (F1-4);
  8372. \path[->,bend left=15] (F1-4) edge [right] node
  8373. {\ttfamily\footnotesize explicate-control} (C3-2);
  8374. \path[->,bend right=15] (C3-2) edge [left] node
  8375. {\ttfamily\footnotesize select-instr.} (x86-2);
  8376. \path[->,bend left=15] (x86-2) edge [left] node
  8377. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  8378. \path[->,bend right=15] (x86-2-1) edge [below] node
  8379. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  8380. \path[->,bend right=15] (x86-2-2) edge [left] node
  8381. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  8382. \path[->,bend left=15] (x86-3) edge [above] node
  8383. {\ttfamily\footnotesize patch-instr.} (x86-4);
  8384. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  8385. \end{tikzpicture}
  8386. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  8387. \label{fig:Rfun-passes}
  8388. \end{figure}
  8389. Figure~\ref{fig:Rfun-passes} gives an overview of the passes for
  8390. compiling \LangFun{} to x86.
  8391. \section{An Example Translation}
  8392. \label{sec:functions-example}
  8393. Figure~\ref{fig:add-fun} shows an example translation of a simple
  8394. function in \LangFun{} to x86. The figure also includes the results of the
  8395. \code{explicate-control} and \code{select-instructions} passes.
  8396. \begin{figure}[htbp]
  8397. \begin{tabular}{ll}
  8398. \begin{minipage}{0.5\textwidth}
  8399. % s3_2.rkt
  8400. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  8401. (define (add [x : Integer] [y : Integer])
  8402. : Integer
  8403. (+ x y))
  8404. (add 40 2)
  8405. \end{lstlisting}
  8406. $\Downarrow$
  8407. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  8408. (define (add86 [x87 : Integer]
  8409. [y88 : Integer]) : Integer
  8410. add86start:
  8411. return (+ x87 y88);
  8412. )
  8413. (define (main) : Integer ()
  8414. mainstart:
  8415. tmp89 = (fun-ref add86);
  8416. (tail-call tmp89 40 2)
  8417. )
  8418. \end{lstlisting}
  8419. \end{minipage}
  8420. &
  8421. $\Rightarrow$
  8422. \begin{minipage}{0.5\textwidth}
  8423. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  8424. (define (add86) : Integer
  8425. add86start:
  8426. movq %rdi, x87
  8427. movq %rsi, y88
  8428. movq x87, %rax
  8429. addq y88, %rax
  8430. jmp add11389conclusion
  8431. )
  8432. (define (main) : Integer
  8433. mainstart:
  8434. leaq (fun-ref add86), tmp89
  8435. movq $40, %rdi
  8436. movq $2, %rsi
  8437. tail-jmp tmp89
  8438. )
  8439. \end{lstlisting}
  8440. $\Downarrow$
  8441. \end{minipage}
  8442. \end{tabular}
  8443. \begin{tabular}{ll}
  8444. \begin{minipage}{0.3\textwidth}
  8445. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  8446. .globl add86
  8447. .align 16
  8448. add86:
  8449. pushq %rbp
  8450. movq %rsp, %rbp
  8451. jmp add86start
  8452. add86start:
  8453. movq %rdi, %rax
  8454. addq %rsi, %rax
  8455. jmp add86conclusion
  8456. add86conclusion:
  8457. popq %rbp
  8458. retq
  8459. \end{lstlisting}
  8460. \end{minipage}
  8461. &
  8462. \begin{minipage}{0.5\textwidth}
  8463. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  8464. .globl main
  8465. .align 16
  8466. main:
  8467. pushq %rbp
  8468. movq %rsp, %rbp
  8469. movq $16384, %rdi
  8470. movq $16384, %rsi
  8471. callq initialize
  8472. movq rootstack_begin(%rip), %r15
  8473. jmp mainstart
  8474. mainstart:
  8475. leaq add86(%rip), %rcx
  8476. movq $40, %rdi
  8477. movq $2, %rsi
  8478. movq %rcx, %rax
  8479. popq %rbp
  8480. jmp *%rax
  8481. mainconclusion:
  8482. popq %rbp
  8483. retq
  8484. \end{lstlisting}
  8485. \end{minipage}
  8486. \end{tabular}
  8487. \caption{Example compilation of a simple function to x86.}
  8488. \label{fig:add-fun}
  8489. \end{figure}
  8490. % Challenge idea: inlining! (simple version)
  8491. % Further Reading
  8492. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8493. \chapter{Lexically Scoped Functions}
  8494. \label{ch:Rlam}
  8495. \index{subject}{lambda}
  8496. \index{subject}{lexical scoping}
  8497. This chapter studies lexically scoped functions as they appear in
  8498. functional languages such as Racket. By lexical scoping we mean that a
  8499. function's body may refer to variables whose binding site is outside
  8500. of the function, in an enclosing scope.
  8501. %
  8502. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  8503. \LangLam{}, which extends \LangFun{} with anonymous functions using the
  8504. \key{lambda} form. The body of the \key{lambda}, refers to three
  8505. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  8506. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  8507. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  8508. parameter of function \code{f}. The \key{lambda} is returned from the
  8509. function \code{f}. The main expression of the program includes two
  8510. calls to \code{f} with different arguments for \code{x}, first
  8511. \code{5} then \code{3}. The functions returned from \code{f} are bound
  8512. to variables \code{g} and \code{h}. Even though these two functions
  8513. were created by the same \code{lambda}, they are really different
  8514. functions because they use different values for \code{x}. Applying
  8515. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  8516. \code{15} produces \code{22}. The result of this program is \code{42}.
  8517. \begin{figure}[btp]
  8518. % s4_6.rkt
  8519. \begin{lstlisting}
  8520. (define (f [x : Integer]) : (Integer -> Integer)
  8521. (let ([y 4])
  8522. (lambda: ([z : Integer]) : Integer
  8523. (+ x (+ y z)))))
  8524. (let ([g (f 5)])
  8525. (let ([h (f 3)])
  8526. (+ (g 11) (h 15))))
  8527. \end{lstlisting}
  8528. \caption{Example of a lexically scoped function.}
  8529. \label{fig:lexical-scoping}
  8530. \end{figure}
  8531. The approach that we take for implementing lexically scoped
  8532. functions is to compile them into top-level function definitions,
  8533. translating from \LangLam{} into \LangFun{}. However, the compiler will need to
  8534. provide special treatment for variable occurrences such as \code{x}
  8535. and \code{y} in the body of the \code{lambda} of
  8536. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function may not
  8537. refer to variables defined outside of it. To identify such variable
  8538. occurrences, we review the standard notion of free variable.
  8539. \begin{definition}
  8540. A variable is \emph{free in expression} $e$ if the variable occurs
  8541. inside $e$ but does not have an enclosing binding in $e$.\index{subject}{free
  8542. variable}
  8543. \end{definition}
  8544. For example, in the expression \code{(+ x (+ y z))} the variables
  8545. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  8546. only \code{x} and \code{y} are free in the following expression
  8547. because \code{z} is bound by the \code{lambda}.
  8548. \begin{lstlisting}
  8549. (lambda: ([z : Integer]) : Integer
  8550. (+ x (+ y z)))
  8551. \end{lstlisting}
  8552. So the free variables of a \code{lambda} are the ones that will need
  8553. special treatment. We need to arrange for some way to transport, at
  8554. runtime, the values of those variables from the point where the
  8555. \code{lambda} was created to the point where the \code{lambda} is
  8556. applied. An efficient solution to the problem, due to
  8557. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  8558. free variables together with the function pointer for the lambda's
  8559. code, an arrangement called a \emph{flat closure} (which we shorten to
  8560. just ``closure''). \index{subject}{closure}\index{subject}{flat closure} Fortunately,
  8561. we have all the ingredients to make closures, Chapter~\ref{ch:Rvec}
  8562. gave us vectors and Chapter~\ref{ch:Rfun} gave us function
  8563. pointers. The function pointer resides at index $0$ and the
  8564. values for the free variables will fill in the rest of the vector.
  8565. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  8566. how closures work. It's a three-step dance. The program first calls
  8567. function \code{f}, which creates a closure for the \code{lambda}. The
  8568. closure is a vector whose first element is a pointer to the top-level
  8569. function that we will generate for the \code{lambda}, the second
  8570. element is the value of \code{x}, which is \code{5}, and the third
  8571. element is \code{4}, the value of \code{y}. The closure does not
  8572. contain an element for \code{z} because \code{z} is not a free
  8573. variable of the \code{lambda}. Creating the closure is step 1 of the
  8574. dance. The closure is returned from \code{f} and bound to \code{g}, as
  8575. shown in Figure~\ref{fig:closures}.
  8576. %
  8577. The second call to \code{f} creates another closure, this time with
  8578. \code{3} in the second slot (for \code{x}). This closure is also
  8579. returned from \code{f} but bound to \code{h}, which is also shown in
  8580. Figure~\ref{fig:closures}.
  8581. \begin{figure}[tbp]
  8582. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  8583. \caption{Example closure representation for the \key{lambda}'s
  8584. in Figure~\ref{fig:lexical-scoping}.}
  8585. \label{fig:closures}
  8586. \end{figure}
  8587. Continuing with the example, consider the application of \code{g} to
  8588. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  8589. obtain the function pointer in the first element of the closure and
  8590. call it, passing in the closure itself and then the regular arguments,
  8591. in this case \code{11}. This technique for applying a closure is step
  8592. 2 of the dance.
  8593. %
  8594. But doesn't this \code{lambda} only take 1 argument, for parameter
  8595. \code{z}? The third and final step of the dance is generating a
  8596. top-level function for a \code{lambda}. We add an additional
  8597. parameter for the closure and we insert a \code{let} at the beginning
  8598. of the function for each free variable, to bind those variables to the
  8599. appropriate elements from the closure parameter.
  8600. %
  8601. This three-step dance is known as \emph{closure conversion}. We
  8602. discuss the details of closure conversion in
  8603. Section~\ref{sec:closure-conversion} and the code generated from the
  8604. example in Section~\ref{sec:example-lambda}. But first we define the
  8605. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  8606. \section{The \LangLam{} Language}
  8607. \label{sec:r5}
  8608. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  8609. functions and lexical scoping, is defined in
  8610. Figures~\ref{fig:Rlam-concrete-syntax} and ~\ref{fig:Rlam-syntax}. It adds
  8611. the \key{lambda} form to the grammar for \LangFun{}, which already has
  8612. syntax for function application.
  8613. \begin{figure}[tp]
  8614. \centering
  8615. \fbox{
  8616. \begin{minipage}{0.96\textwidth}
  8617. \small
  8618. \[
  8619. \begin{array}{lcl}
  8620. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  8621. \MID (\key{Vector}\;\Type\ldots) \MID \key{Void}
  8622. \MID (\Type\ldots \; \key{->}\; \Type)} \\
  8623. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  8624. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  8625. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  8626. &\MID& \gray{\key{\#t} \MID \key{\#f}
  8627. \MID (\key{and}\;\Exp\;\Exp)
  8628. \MID (\key{or}\;\Exp\;\Exp)
  8629. \MID (\key{not}\;\Exp) } \\
  8630. &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  8631. &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  8632. (\key{vector-ref}\;\Exp\;\Int)} \\
  8633. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  8634. \MID (\Exp \; \Exp\ldots) } \\
  8635. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  8636. &\MID& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  8637. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  8638. \LangLamM{} &::=& \gray{\Def\ldots \; \Exp}
  8639. \end{array}
  8640. \]
  8641. \end{minipage}
  8642. }
  8643. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-concrete-syntax})
  8644. with \key{lambda}.}
  8645. \label{fig:Rlam-concrete-syntax}
  8646. \end{figure}
  8647. \begin{figure}[tp]
  8648. \centering
  8649. \fbox{
  8650. \begin{minipage}{0.96\textwidth}
  8651. \small
  8652. \[
  8653. \begin{array}{lcl}
  8654. \itm{op} &::=& \ldots \MID \code{procedure-arity} \\
  8655. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  8656. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  8657. &\MID& \gray{ \BOOL{\itm{bool}}
  8658. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  8659. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  8660. \MID \APPLY{\Exp}{\Exp\ldots} }\\
  8661. &\MID& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  8662. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  8663. \LangLamM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  8664. \end{array}
  8665. \]
  8666. \end{minipage}
  8667. }
  8668. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-syntax}).}
  8669. \label{fig:Rlam-syntax}
  8670. \end{figure}
  8671. \index{subject}{interpreter}
  8672. \label{sec:interp-Rlambda}
  8673. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  8674. \LangLam{}. The case for \key{lambda} saves the current environment
  8675. inside the returned \key{lambda}. Then the case for \key{Apply} uses
  8676. the environment from the \key{lambda}, the \code{lam-env}, when
  8677. interpreting the body of the \key{lambda}. The \code{lam-env}
  8678. environment is extended with the mapping of parameters to argument
  8679. values.
  8680. \begin{figure}[tbp]
  8681. \begin{lstlisting}
  8682. (define interp-Rlambda-class
  8683. (class interp-Rfun-class
  8684. (super-new)
  8685. (define/override (interp-op op)
  8686. (match op
  8687. ['procedure-arity
  8688. (lambda (v)
  8689. (match v
  8690. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  8691. [else (error 'interp-op "expected a function, not ~a" v)]))]
  8692. [else (super interp-op op)]))
  8693. (define/override ((interp-exp env) e)
  8694. (define recur (interp-exp env))
  8695. (match e
  8696. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  8697. `(function ,xs ,body ,env)]
  8698. [else ((super interp-exp env) e)]))
  8699. ))
  8700. (define (interp-Rlambda p)
  8701. (send (new interp-Rlambda-class) interp-program p))
  8702. \end{lstlisting}
  8703. \caption{Interpreter for \LangLam{}.}
  8704. \label{fig:interp-Rlambda}
  8705. \end{figure}
  8706. \label{sec:type-check-r5}
  8707. \index{subject}{type checking}
  8708. Figure~\ref{fig:type-check-Rlambda} shows how to type check the new
  8709. \key{lambda} form. The body of the \key{lambda} is checked in an
  8710. environment that includes the current environment (because it is
  8711. lexically scoped) and also includes the \key{lambda}'s parameters. We
  8712. require the body's type to match the declared return type.
  8713. \begin{figure}[tbp]
  8714. \begin{lstlisting}
  8715. (define (type-check-Rlambda env)
  8716. (lambda (e)
  8717. (match e
  8718. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  8719. (define-values (new-body bodyT)
  8720. ((type-check-exp (append (map cons xs Ts) env)) body))
  8721. (define ty `(,@Ts -> ,rT))
  8722. (cond
  8723. [(equal? rT bodyT)
  8724. (values (HasType (Lambda params rT new-body) ty) ty)]
  8725. [else
  8726. (error "mismatch in return type" bodyT rT)])]
  8727. ...
  8728. )))
  8729. \end{lstlisting}
  8730. \caption{Type checking the \key{lambda}'s in \LangLam{}.}
  8731. \label{fig:type-check-Rlambda}
  8732. \end{figure}
  8733. \section{Reveal Functions and the $F_2$ language}
  8734. \label{sec:reveal-functions-r5}
  8735. To support the \code{procedure-arity} operator we need to communicate
  8736. the arity of a function to the point of closure creation. We can
  8737. accomplish this by replacing the $\FUNREF{\Var}$ struct with one that
  8738. has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$. The
  8739. output of this pass is the language $F_2$, whose syntax is defined in
  8740. Figure~\ref{fig:f2-syntax}.
  8741. \begin{figure}[tp]
  8742. \centering
  8743. \fbox{
  8744. \begin{minipage}{0.96\textwidth}
  8745. \[
  8746. \begin{array}{lcl}
  8747. \Exp &::=& \ldots \MID \FUNREFARITY{\Var}{\Int}\\
  8748. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  8749. F_2 &::=& \gray{\PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}}
  8750. \end{array}
  8751. \]
  8752. \end{minipage}
  8753. }
  8754. \caption{The abstract syntax $F_2$, an extension of \LangLam{}
  8755. (Figure~\ref{fig:Rlam-syntax}).}
  8756. \label{fig:f2-syntax}
  8757. \end{figure}
  8758. \section{Closure Conversion}
  8759. \label{sec:closure-conversion}
  8760. \index{subject}{closure conversion}
  8761. The compiling of lexically-scoped functions into top-level function
  8762. definitions is accomplished in the pass \code{convert-to-closures}
  8763. that comes after \code{reveal-functions} and before
  8764. \code{limit-functions}.
  8765. As usual, we implement the pass as a recursive function over the
  8766. AST. All of the action is in the cases for \key{Lambda} and
  8767. \key{Apply}. We transform a \key{Lambda} expression into an expression
  8768. that creates a closure, that is, a vector whose first element is a
  8769. function pointer and the rest of the elements are the free variables
  8770. of the \key{Lambda}. We use the struct \code{Closure} here instead of
  8771. using \code{vector} so that we can distinguish closures from vectors
  8772. in Section~\ref{sec:optimize-closures} and to record the arity. In
  8773. the generated code below, the \itm{name} is a unique symbol generated
  8774. to identify the function and the \itm{arity} is the number of
  8775. parameters (the length of \itm{ps}).
  8776. \begin{lstlisting}
  8777. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  8778. |$\Rightarrow$|
  8779. (Closure |\itm{arity}| (cons (FunRef |\itm{name}|) |\itm{fvs}|))
  8780. \end{lstlisting}
  8781. In addition to transforming each \key{Lambda} into a \key{Closure}, we
  8782. create a top-level function definition for each \key{Lambda}, as
  8783. shown below.\\
  8784. \begin{minipage}{0.8\textwidth}
  8785. \begin{lstlisting}
  8786. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  8787. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  8788. ...
  8789. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  8790. |\itm{body'}|)...))
  8791. \end{lstlisting}
  8792. \end{minipage}\\
  8793. The \code{clos} parameter refers to the closure. Translate the type
  8794. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  8795. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The types
  8796. $\itm{fvts}$ are the types of the free variables in the lambda and the
  8797. underscore \code{\_} is a dummy type that we use because it is rather
  8798. difficult to give a type to the function in the closure's
  8799. type.\footnote{To give an accurate type to a closure, we would need to
  8800. add existential types to the type checker~\citep{Minamide:1996ys}.}
  8801. The dummy type is considered to be equal to any other type during type
  8802. checking. The sequence of \key{Let} forms bind the free variables to
  8803. their values obtained from the closure.
  8804. Closure conversion turns functions into vectors, so the type
  8805. annotations in the program must also be translated. We recommend
  8806. defining a auxiliary recursive function for this purpose. Function
  8807. types should be translated as follows.
  8808. \begin{lstlisting}
  8809. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  8810. |$\Rightarrow$|
  8811. (Vector ((Vector _) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  8812. \end{lstlisting}
  8813. The above type says that the first thing in the vector is a function
  8814. pointer. The first parameter of the function pointer is a vector (a
  8815. closure) and the rest of the parameters are the ones from the original
  8816. function, with types $T'_1, \ldots, T'_n$. The \code{Vector} type for
  8817. the closure omits the types of the free variables because 1) those
  8818. types are not available in this context and 2) we do not need them in
  8819. the code that is generated for function application.
  8820. We transform function application into code that retrieves the
  8821. function pointer from the closure and then calls the function, passing
  8822. in the closure as the first argument. We bind $e'$ to a temporary
  8823. variable to avoid code duplication.
  8824. \begin{lstlisting}
  8825. (Apply |$e$| |\itm{es}|)
  8826. |$\Rightarrow$|
  8827. (Let |\itm{tmp}| |$e'$|
  8828. (Apply (Prim 'vector-ref (list (Var |\itm{tmp}|) (Int 0))) (cons |\itm{tmp}| |\itm{es'}|)))
  8829. \end{lstlisting}
  8830. There is also the question of what to do with references top-level
  8831. function definitions. To maintain a uniform translation of function
  8832. application, we turn function references into closures.
  8833. \begin{tabular}{lll}
  8834. \begin{minipage}{0.3\textwidth}
  8835. \begin{lstlisting}
  8836. (FunRefArity |$f$| |$n$|)
  8837. \end{lstlisting}
  8838. \end{minipage}
  8839. &
  8840. $\Rightarrow$
  8841. &
  8842. \begin{minipage}{0.5\textwidth}
  8843. \begin{lstlisting}
  8844. (Closure |$n$| (FunRef |$f$|) '())
  8845. \end{lstlisting}
  8846. \end{minipage}
  8847. \end{tabular} \\
  8848. %
  8849. The top-level function definitions need to be updated as well to take
  8850. an extra closure parameter.
  8851. \section{An Example Translation}
  8852. \label{sec:example-lambda}
  8853. Figure~\ref{fig:lexical-functions-example} shows the result of
  8854. \code{reveal-functions} and \code{convert-to-closures} for the example
  8855. program demonstrating lexical scoping that we discussed at the
  8856. beginning of this chapter.
  8857. \begin{figure}[tbp]
  8858. \begin{minipage}{0.8\textwidth}
  8859. % tests/lambda_test_6.rkt
  8860. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8861. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  8862. (let ([y8 4])
  8863. (lambda: ([z9 : Integer]) : Integer
  8864. (+ x7 (+ y8 z9)))))
  8865. (define (main) : Integer
  8866. (let ([g0 ((fun-ref-arity f6 1) 5)])
  8867. (let ([h1 ((fun-ref-arity f6 1) 3)])
  8868. (+ (g0 11) (h1 15)))))
  8869. \end{lstlisting}
  8870. $\Rightarrow$
  8871. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8872. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  8873. (let ([y8 4])
  8874. (closure 1 (list (fun-ref lambda2) x7 y8))))
  8875. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  8876. (let ([x7 (vector-ref fvs3 1)])
  8877. (let ([y8 (vector-ref fvs3 2)])
  8878. (+ x7 (+ y8 z9)))))
  8879. (define (main) : Integer
  8880. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6)))])
  8881. ((vector-ref clos5 0) clos5 5))])
  8882. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6)))])
  8883. ((vector-ref clos6 0) clos6 3))])
  8884. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  8885. \end{lstlisting}
  8886. \end{minipage}
  8887. \caption{Example of closure conversion.}
  8888. \label{fig:lexical-functions-example}
  8889. \end{figure}
  8890. \begin{exercise}\normalfont
  8891. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  8892. Create 5 new programs that use \key{lambda} functions and make use of
  8893. lexical scoping. Test your compiler on these new programs and all of
  8894. your previously created test programs.
  8895. \end{exercise}
  8896. \section{Expose Allocation}
  8897. \label{sec:expose-allocation-r5}
  8898. Compile the $\CLOSURE{\itm{arity}}{\LP\Exp\ldots\RP}$ form into code
  8899. that allocates and initializes a vector, similar to the translation of
  8900. the \code{vector} operator in Section~\ref{sec:expose-allocation}.
  8901. The only difference is replacing the use of
  8902. \ALLOC{\itm{len}}{\itm{type}} with
  8903. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  8904. \section{Explicate Control and \LangCLam{}}
  8905. \label{sec:explicate-r5}
  8906. The output language of \code{explicate-control} is \LangCLam{} whose
  8907. abstract syntax is defined in Figure~\ref{fig:c4-syntax}. The only
  8908. difference with respect to \LangCFun{} is the addition of the
  8909. \code{AllocateClosure} form to the grammar for $\Exp$. The handling
  8910. of \code{AllocateClosure} in the \code{explicate-control} pass is
  8911. similar to the handling of other expressions such as primitive
  8912. operators.
  8913. \begin{figure}[tp]
  8914. \fbox{
  8915. \begin{minipage}{0.96\textwidth}
  8916. \small
  8917. \[
  8918. \begin{array}{lcl}
  8919. \Exp &::= & \ldots
  8920. \MID \ALLOCCLOS{\Int}{\Type}{\Int} \\
  8921. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  8922. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  8923. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  8924. \MID \GOTO{\itm{label}} } \\
  8925. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  8926. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  8927. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  8928. \LangCLamM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  8929. \end{array}
  8930. \]
  8931. \end{minipage}
  8932. }
  8933. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  8934. \label{fig:c4-syntax}
  8935. \end{figure}
  8936. \section{Select Instructions}
  8937. \label{sec:select-instructions-Rlambda}
  8938. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  8939. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  8940. (Section~\ref{sec:select-instructions-gc}). The only difference is
  8941. that you should place the \itm{arity} in the tag that is stored at
  8942. position $0$ of the vector. Recall that in
  8943. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  8944. was not used. We store the arity in the $5$ bits starting at position
  8945. $58$.
  8946. Compile the \code{procedure-arity} operator into a sequence of
  8947. instructions that access the tag from position $0$ of the vector and
  8948. extract the $5$-bits starting at position $58$ from the tag.
  8949. \begin{figure}[p]
  8950. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8951. \node (Rfun) at (0,2) {\large \LangFun{}};
  8952. \node (Rfun-2) at (3,2) {\large \LangFun{}};
  8953. \node (Rfun-3) at (6,2) {\large \LangFun{}};
  8954. \node (F1-1) at (12,0) {\large \LangFunRef{}};
  8955. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  8956. \node (F1-3) at (6,0) {\large $F_1$};
  8957. \node (F1-4) at (3,0) {\large $F_1$};
  8958. \node (F1-5) at (0,0) {\large $F_1$};
  8959. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  8960. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  8961. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  8962. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  8963. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  8964. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  8965. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  8966. \path[->,bend left=15] (Rfun) edge [above] node
  8967. {\ttfamily\footnotesize shrink} (Rfun-2);
  8968. \path[->,bend left=15] (Rfun-2) edge [above] node
  8969. {\ttfamily\footnotesize uniquify} (Rfun-3);
  8970. \path[->,bend left=15] (Rfun-3) edge [right] node
  8971. {\ttfamily\footnotesize reveal-functions} (F1-1);
  8972. \path[->,bend left=15] (F1-1) edge [below] node
  8973. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  8974. \path[->,bend right=15] (F1-2) edge [above] node
  8975. {\ttfamily\footnotesize limit-fun.} (F1-3);
  8976. \path[->,bend right=15] (F1-3) edge [above] node
  8977. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  8978. \path[->,bend right=15] (F1-4) edge [above] node
  8979. {\ttfamily\footnotesize remove-complex.} (F1-5);
  8980. \path[->,bend right=15] (F1-5) edge [right] node
  8981. {\ttfamily\footnotesize explicate-control} (C3-2);
  8982. \path[->,bend left=15] (C3-2) edge [left] node
  8983. {\ttfamily\footnotesize select-instr.} (x86-2);
  8984. \path[->,bend right=15] (x86-2) edge [left] node
  8985. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  8986. \path[->,bend right=15] (x86-2-1) edge [below] node
  8987. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  8988. \path[->,bend right=15] (x86-2-2) edge [left] node
  8989. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  8990. \path[->,bend left=15] (x86-3) edge [above] node
  8991. {\ttfamily\footnotesize patch-instr.} (x86-4);
  8992. \path[->,bend left=15] (x86-4) edge [right] node
  8993. {\ttfamily\footnotesize print-x86} (x86-5);
  8994. \end{tikzpicture}
  8995. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  8996. functions.}
  8997. \label{fig:Rlambda-passes}
  8998. \end{figure}
  8999. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  9000. for the compilation of \LangLam{}.
  9001. \clearpage
  9002. \section{Challenge: Optimize Closures}
  9003. \label{sec:optimize-closures}
  9004. In this chapter we compiled lexically-scoped functions into a
  9005. relatively efficient representation: flat closures. However, even this
  9006. representation comes with some overhead. For example, consider the
  9007. following program with a function \code{tail-sum} that does not have
  9008. any free variables and where all the uses of \code{tail-sum} are in
  9009. applications where we know that only \code{tail-sum} is being applied
  9010. (and not any other functions).
  9011. \begin{center}
  9012. \begin{minipage}{0.95\textwidth}
  9013. \begin{lstlisting}
  9014. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  9015. (if (eq? n 0)
  9016. r
  9017. (tail-sum (- n 1) (+ n r))))
  9018. (+ (tail-sum 5 0) 27)
  9019. \end{lstlisting}
  9020. \end{minipage}
  9021. \end{center}
  9022. As described in this chapter, we uniformly apply closure conversion to
  9023. all functions, obtaining the following output for this program.
  9024. \begin{center}
  9025. \begin{minipage}{0.95\textwidth}
  9026. \begin{lstlisting}
  9027. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [r3 : Integer]) : Integer
  9028. (if (eq? n2 0)
  9029. r3
  9030. (let ([clos4 (closure (list (fun-ref tail_sum1)))])
  9031. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 r3)))))
  9032. (define (main) : Integer
  9033. (+ (let ([clos6 (closure (list (fun-ref tail_sum1)))])
  9034. ((vector-ref clos6 0) clos6 5 0)) 27))
  9035. \end{lstlisting}
  9036. \end{minipage}
  9037. \end{center}
  9038. In the previous Chapter, there would be no allocation in the program
  9039. and the calls to \code{tail-sum} would be direct calls. In contrast,
  9040. the above program allocates memory for each \code{closure} and the
  9041. calls to \code{tail-sum} are indirect. These two differences incur
  9042. considerable overhead in a program such as this one, where the
  9043. allocations and indirect calls occur inside a tight loop.
  9044. One might think that this problem is trivial to solve: can't we just
  9045. recognize calls of the form \code{((fun-ref $f$) $e_1 \ldots e_n$)}
  9046. and compile them to direct calls \code{((fun-ref $f$) $e'_1 \ldots
  9047. e'_n$)} instead of treating it like a call to a closure? We would
  9048. also drop the \code{fvs5} parameter of \code{tail\_sum1}.
  9049. %
  9050. However, this problem is not so trivial because a global function may
  9051. ``escape'' and become involved in applications that also involve
  9052. closures. Consider the following example in which the application
  9053. \code{(f 41)} needs to be compiled into a closure application, because
  9054. the \code{lambda} may get bound to \code{f}, but the \code{add1}
  9055. function might also get bound to \code{f}.
  9056. \begin{lstlisting}
  9057. (define (add1 [x : Integer]) : Integer
  9058. (+ x 1))
  9059. (let ([y (read)])
  9060. (let ([f (if (eq? (read) 0)
  9061. add1
  9062. (lambda: ([x : Integer]) : Integer (- x y)))])
  9063. (f 41)))
  9064. \end{lstlisting}
  9065. If a global function name is used in any way other than as the
  9066. operator in a direct call, then we say that the function
  9067. \emph{escapes}. If a global function does not escape, then we do not
  9068. need to perform closure conversion on the function.
  9069. \begin{exercise}\normalfont
  9070. Implement an auxiliary function for detecting which global
  9071. functions escape. Using that function, implement an improved version
  9072. of closure conversion that does not apply closure conversion to
  9073. global functions that do not escape but instead compiles them as
  9074. regular functions. Create several new test cases that check whether
  9075. you properly detect whether global functions escape or not.
  9076. \end{exercise}
  9077. So far we have reduced the overhead of calling global functions, but
  9078. it would also be nice to reduce the overhead of calling a
  9079. \code{lambda} when we can determine at compile time which
  9080. \code{lambda} will be called. We refer to such calls as \emph{known
  9081. calls}. Consider the following example in which a \code{lambda} is
  9082. bound to \code{f} and then applied.
  9083. \begin{lstlisting}
  9084. (let ([y (read)])
  9085. (let ([f (lambda: ([x : Integer]) : Integer
  9086. (+ x y))])
  9087. (f 21)))
  9088. \end{lstlisting}
  9089. Closure conversion compiles \code{(f 21)} into an indirect call:
  9090. \begin{lstlisting}
  9091. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  9092. (let ([y2 (vector-ref fvs6 1)])
  9093. (+ x3 y2)))
  9094. (define (main) : Integer
  9095. (let ([y2 (read)])
  9096. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  9097. ((vector-ref f4 0) f4 21))))
  9098. \end{lstlisting}
  9099. but we can instead compile the application \code{(f 21)} into a direct call
  9100. to \code{lambda5}:
  9101. \begin{lstlisting}
  9102. (define (main) : Integer
  9103. (let ([y2 (read)])
  9104. (let ([f4 (Closure 1 (list (fun-ref lambda5) y2))])
  9105. ((fun-ref lambda5) f4 21))))
  9106. \end{lstlisting}
  9107. The problem of determining which lambda will be called from a
  9108. particular application is quite challenging in general and the topic
  9109. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  9110. following exercise we recommend that you compile an application to a
  9111. direct call when the operator is a variable and the variable is
  9112. \code{let}-bound to a closure. This can be accomplished by maintaining
  9113. an environment mapping \code{let}-bound variables to function names.
  9114. Extend the environment whenever you encounter a closure on the
  9115. right-hand side of a \code{let}, mapping the \code{let}-bound variable
  9116. to the name of the global function for the closure. This pass should
  9117. come after closure conversion.
  9118. \begin{exercise}\normalfont
  9119. Implement a compiler pass, named \code{optimize-known-calls}, that
  9120. compiles known calls into direct calls. Verify that your compiler is
  9121. successful in this regard on several example programs.
  9122. \end{exercise}
  9123. These exercises only scratches the surface of optimizing of
  9124. closures. A good next step for the interested reader is to look at the
  9125. work of \citet{Keep:2012ab}.
  9126. \section{Further Reading}
  9127. The notion of lexically scoped anonymous functions predates modern
  9128. computers by about a decade. They were invented by
  9129. \citet{Church:1932aa}, who proposed the $\lambda$ calculus as a
  9130. foundation for logic. Anonymous functions were included in the
  9131. LISP~\citep{McCarthy:1960dz} programming language but were initially
  9132. dynamically scoped. The Scheme dialect of LISP adopted lexical scoping
  9133. and \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently
  9134. compile Scheme programs. However, environments were represented as
  9135. linked lists, so variable lookup was linear in the size of the
  9136. environment. In this chapter we represent environments using flat
  9137. closures, which were invented by
  9138. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  9139. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  9140. closures, variable lookup is constant time but the time to create a
  9141. closure is proportional to the number of its free variables. Flat
  9142. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  9143. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  9144. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9145. \chapter{Dynamic Typing}
  9146. \label{ch:Rdyn}
  9147. \index{subject}{dynamic typing}
  9148. In this chapter we discuss the compilation of \LangDyn{}, a dynamically
  9149. typed language that is a subset of Racket. This is in contrast to the
  9150. previous chapters, which have studied the compilation of Typed
  9151. Racket. In dynamically typed languages such as \LangDyn{}, a given
  9152. expression may produce a value of a different type each time it is
  9153. executed. Consider the following example with a conditional \code{if}
  9154. expression that may return a Boolean or an integer depending on the
  9155. input to the program.
  9156. % part of dynamic_test_25.rkt
  9157. \begin{lstlisting}
  9158. (not (if (eq? (read) 1) #f 0))
  9159. \end{lstlisting}
  9160. Languages that allow expressions to produce different kinds of values
  9161. are called \emph{polymorphic}, a word composed of the Greek roots
  9162. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  9163. are several kinds of polymorphism in programming languages, such as
  9164. subtype polymorphism and parametric
  9165. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  9166. study in this chapter does not have a special name but it is the kind
  9167. that arises in dynamically typed languages.
  9168. Another characteristic of dynamically typed languages is that
  9169. primitive operations, such as \code{not}, are often defined to operate
  9170. on many different types of values. In fact, in Racket, the \code{not}
  9171. operator produces a result for any kind of value: given \code{\#f} it
  9172. returns \code{\#t} and given anything else it returns \code{\#f}.
  9173. Furthermore, even when primitive operations restrict their inputs to
  9174. values of a certain type, this restriction is enforced at runtime
  9175. instead of during compilation. For example, the following vector
  9176. reference results in a run-time contract violation because the index
  9177. must be in integer, not a Boolean such as \code{\#t}.
  9178. \begin{lstlisting}
  9179. (vector-ref (vector 42) #t)
  9180. \end{lstlisting}
  9181. \begin{figure}[tp]
  9182. \centering
  9183. \fbox{
  9184. \begin{minipage}{0.97\textwidth}
  9185. \[
  9186. \begin{array}{rcl}
  9187. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  9188. \Exp &::=& \Int \MID \CREAD{} \MID \CNEG{\Exp}
  9189. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} \\
  9190. &\MID& \Var \MID \CLET{\Var}{\Exp}{\Exp} \\
  9191. &\MID& \key{\#t} \MID \key{\#f}
  9192. \MID \CBINOP{\key{and}}{\Exp}{\Exp}
  9193. \MID \CBINOP{\key{or}}{\Exp}{\Exp}
  9194. \MID \CUNIOP{\key{not}}{\Exp} \\
  9195. &\MID& \LP\itm{cmp}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} \\
  9196. &\MID& \LP\key{vector}\;\Exp\ldots\RP \MID
  9197. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  9198. &\MID& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \MID \LP\key{void}\RP \\
  9199. &\MID& \LP\Exp \; \Exp\ldots\RP
  9200. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  9201. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  9202. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  9203. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  9204. \LangDynM{} &::=& \Def\ldots\; \Exp
  9205. \end{array}
  9206. \]
  9207. \end{minipage}
  9208. }
  9209. \caption{Syntax of \LangDyn{}, an untyped language (a subset of Racket).}
  9210. \label{fig:r7-concrete-syntax}
  9211. \end{figure}
  9212. \begin{figure}[tp]
  9213. \centering
  9214. \fbox{
  9215. \begin{minipage}{0.96\textwidth}
  9216. \small
  9217. \[
  9218. \begin{array}{lcl}
  9219. \Exp &::=& \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} \\
  9220. &\MID& \PRIM{\itm{op}}{\Exp\ldots} \\
  9221. &\MID& \BOOL{\itm{bool}}
  9222. \MID \IF{\Exp}{\Exp}{\Exp} \\
  9223. &\MID& \VOID{} \MID \APPLY{\Exp}{\Exp\ldots} \\
  9224. &\MID& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  9225. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  9226. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  9227. \end{array}
  9228. \]
  9229. \end{minipage}
  9230. }
  9231. \caption{The abstract syntax of \LangDyn{}.}
  9232. \label{fig:r7-syntax}
  9233. \end{figure}
  9234. The concrete and abstract syntax of \LangDyn{}, our subset of Racket, is
  9235. defined in Figures~\ref{fig:r7-concrete-syntax} and
  9236. \ref{fig:r7-syntax}.
  9237. %
  9238. There is no type checker for \LangDyn{} because it is not a statically
  9239. typed language (it's dynamically typed!).
  9240. The definitional interpreter for \LangDyn{} is presented in
  9241. Figure~\ref{fig:interp-Rdyn} and its auxiliary functions are defined i
  9242. Figure~\ref{fig:interp-Rdyn-aux}. Consider the match case for
  9243. \code{(Int n)}. Instead of simply returning the integer \code{n} (as
  9244. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Rvar}), the
  9245. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  9246. value} that combines an underlying value with a tag that identifies
  9247. what kind of value it is. We define the following struct
  9248. to represented tagged values.
  9249. \begin{lstlisting}
  9250. (struct Tagged (value tag) #:transparent)
  9251. \end{lstlisting}
  9252. The tags are \code{Integer}, \code{Boolean}, \code{Void},
  9253. \code{Vector}, and \code{Procedure}. Tags are closely related to types
  9254. but don't always capture all the information that a type does. For
  9255. example, a vector of type \code{(Vector Any Any)} is tagged with
  9256. \code{Vector} and a procedure of type \code{(Any Any -> Any)}
  9257. is tagged with \code{Procedure}.
  9258. Next consider the match case for \code{vector-ref}. The
  9259. \code{check-tag} auxiliary function (Figure~\ref{fig:interp-Rdyn-aux})
  9260. is used to ensure that the first argument is a vector and the second
  9261. is an integer. If they are not, a \code{trapped-error} is raised.
  9262. Recall from Section~\ref{sec:interp_Rint} that when a definition
  9263. interpreter raises a \code{trapped-error} error, the compiled code
  9264. must also signal an error by exiting with return code \code{255}. A
  9265. \code{trapped-error} is also raised if the index is not less than
  9266. length of the vector.
  9267. \begin{figure}[tbp]
  9268. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9269. (define ((interp-Rdyn-exp env) ast)
  9270. (define recur (interp-Rdyn-exp env))
  9271. (match ast
  9272. [(Var x) (lookup x env)]
  9273. [(Int n) (Tagged n 'Integer)]
  9274. [(Bool b) (Tagged b 'Boolean)]
  9275. [(Lambda xs rt body)
  9276. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  9277. [(Prim 'vector es)
  9278. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  9279. [(Prim 'vector-ref (list e1 e2))
  9280. (define vec (recur e1)) (define i (recur e2))
  9281. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  9282. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  9283. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  9284. (vector-ref (Tagged-value vec) (Tagged-value i))]
  9285. [(Prim 'vector-set! (list e1 e2 e3))
  9286. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  9287. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  9288. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  9289. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  9290. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  9291. (Tagged (void) 'Void)]
  9292. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  9293. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  9294. [(Prim 'or (list e1 e2))
  9295. (define v1 (recur e1))
  9296. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  9297. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  9298. [(Prim op (list e1))
  9299. #:when (set-member? type-predicates op)
  9300. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  9301. [(Prim op es)
  9302. (define args (map recur es))
  9303. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  9304. (unless (for/or ([expected-tags (op-tags op)])
  9305. (equal? expected-tags tags))
  9306. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  9307. (tag-value
  9308. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  9309. [(If q t f)
  9310. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  9311. [(Apply f es)
  9312. (define new-f (recur f)) (define args (map recur es))
  9313. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  9314. (match f-val
  9315. [`(function ,xs ,body ,lam-env)
  9316. (unless (eq? (length xs) (length args))
  9317. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  9318. (define new-env (append (map cons xs args) lam-env))
  9319. ((interp-Rdyn-exp new-env) body)]
  9320. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  9321. \end{lstlisting}
  9322. \caption{Interpreter for the \LangDyn{} language.}
  9323. \label{fig:interp-Rdyn}
  9324. \end{figure}
  9325. \begin{figure}[tbp]
  9326. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9327. (define (interp-op op)
  9328. (match op
  9329. ['+ fx+]
  9330. ['- fx-]
  9331. ['read read-fixnum]
  9332. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  9333. ['< (lambda (v1 v2)
  9334. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  9335. ['<= (lambda (v1 v2)
  9336. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  9337. ['> (lambda (v1 v2)
  9338. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  9339. ['>= (lambda (v1 v2)
  9340. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  9341. ['boolean? boolean?]
  9342. ['integer? fixnum?]
  9343. ['void? void?]
  9344. ['vector? vector?]
  9345. ['vector-length vector-length]
  9346. ['procedure? (match-lambda
  9347. [`(functions ,xs ,body ,env) #t] [else #f])]
  9348. [else (error 'interp-op "unknown operator" op)]))
  9349. (define (op-tags op)
  9350. (match op
  9351. ['+ '((Integer Integer))]
  9352. ['- '((Integer Integer) (Integer))]
  9353. ['read '(())]
  9354. ['not '((Boolean))]
  9355. ['< '((Integer Integer))]
  9356. ['<= '((Integer Integer))]
  9357. ['> '((Integer Integer))]
  9358. ['>= '((Integer Integer))]
  9359. ['vector-length '((Vector))]))
  9360. (define type-predicates
  9361. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  9362. (define (tag-value v)
  9363. (cond [(boolean? v) (Tagged v 'Boolean)]
  9364. [(fixnum? v) (Tagged v 'Integer)]
  9365. [(procedure? v) (Tagged v 'Procedure)]
  9366. [(vector? v) (Tagged v 'Vector)]
  9367. [(void? v) (Tagged v 'Void)]
  9368. [else (error 'tag-value "unidentified value ~a" v)]))
  9369. (define (check-tag val expected ast)
  9370. (define tag (Tagged-tag val))
  9371. (unless (eq? tag expected)
  9372. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  9373. \end{lstlisting}
  9374. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  9375. \label{fig:interp-Rdyn-aux}
  9376. \end{figure}
  9377. \clearpage
  9378. \section{Representation of Tagged Values}
  9379. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  9380. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  9381. values at the bit level. Because almost every operation in \LangDyn{}
  9382. involves manipulating tagged values, the representation must be
  9383. efficient. Recall that all of our values are 64 bits. We shall steal
  9384. the 3 right-most bits to encode the tag. We use $001$ to identify
  9385. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  9386. and $101$ for the void value. We define the following auxiliary
  9387. function for mapping types to tag codes.
  9388. \begin{align*}
  9389. \itm{tagof}(\key{Integer}) &= 001 \\
  9390. \itm{tagof}(\key{Boolean}) &= 100 \\
  9391. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  9392. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  9393. \itm{tagof}(\key{Void}) &= 101
  9394. \end{align*}
  9395. This stealing of 3 bits comes at some price: our integers are reduced
  9396. to ranging from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  9397. affect vectors and procedures because those values are addresses, and
  9398. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  9399. they are always $000$. Thus, we do not lose information by overwriting
  9400. the rightmost 3 bits with the tag and we can simply zero-out the tag
  9401. to recover the original address.
  9402. To make tagged values into first-class entities, we can give them a
  9403. type, called \code{Any}, and define operations such as \code{Inject}
  9404. and \code{Project} for creating and using them, yielding the \LangAny{}
  9405. intermediate language. We describe how to compile \LangDyn{} to \LangAny{} in
  9406. Section~\ref{sec:compile-r7} but first we describe the \LangAny{} language
  9407. in greater detail.
  9408. \section{The \LangAny{} Language}
  9409. \label{sec:Rany-lang}
  9410. \begin{figure}[tp]
  9411. \centering
  9412. \fbox{
  9413. \begin{minipage}{0.96\textwidth}
  9414. \small
  9415. \[
  9416. \begin{array}{lcl}
  9417. \Type &::= & \ldots \MID \key{Any} \\
  9418. \itm{op} &::= & \ldots \MID \code{any-vector-length}
  9419. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  9420. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  9421. \MID \code{procedure?} \MID \code{void?} \\
  9422. \Exp &::=& \ldots
  9423. \MID \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  9424. &\MID& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  9425. \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  9426. \LangAnyM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  9427. \end{array}
  9428. \]
  9429. \end{minipage}
  9430. }
  9431. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Rlam-syntax}).}
  9432. \label{fig:Rany-syntax}
  9433. \end{figure}
  9434. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Rany-syntax}.
  9435. (The concrete syntax of \LangAny{} is in the Appendix,
  9436. Figure~\ref{fig:Rany-concrete-syntax}.) The $\INJECT{e}{T}$ form
  9437. converts the value produced by expression $e$ of type $T$ into a
  9438. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  9439. produced by expression $e$ into a value of type $T$ or else halts the
  9440. program if the type tag is not equivalent to $T$.
  9441. %
  9442. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  9443. restricted to a flat type $\FType$, which simplifies the
  9444. implementation and corresponds with what is needed for compiling \LangDyn{}.
  9445. The \code{any-vector} operators adapt the vector operations so that
  9446. they can be applied to a value of type \code{Any}. They also
  9447. generalize the vector operations in that the index is not restricted
  9448. to be a literal integer in the grammar but is allowed to be any
  9449. expression.
  9450. The type predicates such as \key{boolean?} expect their argument to
  9451. produce a tagged value; they return \key{\#t} if the tag corresponds
  9452. to the predicate and they return \key{\#f} otherwise.
  9453. The type checker for \LangAny{} is shown in
  9454. Figures~\ref{fig:type-check-Rany-part-1} and
  9455. \ref{fig:type-check-Rany-part-2} and uses the auxiliary functions in
  9456. Figure~\ref{fig:type-check-Rany-aux}.
  9457. %
  9458. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Rany} and the
  9459. auxiliary functions \code{apply-inject} and \code{apply-project} are
  9460. in Figure~\ref{fig:apply-project}.
  9461. \begin{figure}[btp]
  9462. \begin{lstlisting}[basicstyle=\ttfamily\small]
  9463. (define type-check-Rany-class
  9464. (class type-check-Rlambda-class
  9465. (super-new)
  9466. (inherit check-type-equal?)
  9467. (define/override (type-check-exp env)
  9468. (lambda (e)
  9469. (define recur (type-check-exp env))
  9470. (match e
  9471. [(Inject e1 ty)
  9472. (unless (flat-ty? ty)
  9473. (error 'type-check "may only inject from flat type, not ~a" ty))
  9474. (define-values (new-e1 e-ty) (recur e1))
  9475. (check-type-equal? e-ty ty e)
  9476. (values (Inject new-e1 ty) 'Any)]
  9477. [(Project e1 ty)
  9478. (unless (flat-ty? ty)
  9479. (error 'type-check "may only project to flat type, not ~a" ty))
  9480. (define-values (new-e1 e-ty) (recur e1))
  9481. (check-type-equal? e-ty 'Any e)
  9482. (values (Project new-e1 ty) ty)]
  9483. [(Prim 'any-vector-length (list e1))
  9484. (define-values (e1^ t1) (recur e1))
  9485. (check-type-equal? t1 'Any e)
  9486. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  9487. [(Prim 'any-vector-ref (list e1 e2))
  9488. (define-values (e1^ t1) (recur e1))
  9489. (define-values (e2^ t2) (recur e2))
  9490. (check-type-equal? t1 'Any e)
  9491. (check-type-equal? t2 'Integer e)
  9492. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  9493. [(Prim 'any-vector-set! (list e1 e2 e3))
  9494. (define-values (e1^ t1) (recur e1))
  9495. (define-values (e2^ t2) (recur e2))
  9496. (define-values (e3^ t3) (recur e3))
  9497. (check-type-equal? t1 'Any e)
  9498. (check-type-equal? t2 'Integer e)
  9499. (check-type-equal? t3 'Any e)
  9500. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  9501. \end{lstlisting}
  9502. \caption{Type checker for the \LangAny{} language, part 1.}
  9503. \label{fig:type-check-Rany-part-1}
  9504. \end{figure}
  9505. \begin{figure}[btp]
  9506. \begin{lstlisting}[basicstyle=\ttfamily\small]
  9507. [(ValueOf e ty)
  9508. (define-values (new-e e-ty) (recur e))
  9509. (values (ValueOf new-e ty) ty)]
  9510. [(Prim pred (list e1))
  9511. #:when (set-member? (type-predicates) pred)
  9512. (define-values (new-e1 e-ty) (recur e1))
  9513. (check-type-equal? e-ty 'Any e)
  9514. (values (Prim pred (list new-e1)) 'Boolean)]
  9515. [(If cnd thn els)
  9516. (define-values (cnd^ Tc) (recur cnd))
  9517. (define-values (thn^ Tt) (recur thn))
  9518. (define-values (els^ Te) (recur els))
  9519. (check-type-equal? Tc 'Boolean cnd)
  9520. (check-type-equal? Tt Te e)
  9521. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  9522. [(Exit) (values (Exit) '_)]
  9523. [(Prim 'eq? (list arg1 arg2))
  9524. (define-values (e1 t1) (recur arg1))
  9525. (define-values (e2 t2) (recur arg2))
  9526. (match* (t1 t2)
  9527. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  9528. [(other wise) (check-type-equal? t1 t2 e)])
  9529. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  9530. [else ((super type-check-exp env) e)])))
  9531. ))
  9532. \end{lstlisting}
  9533. \caption{Type checker for the \LangAny{} language, part 2.}
  9534. \label{fig:type-check-Rany-part-2}
  9535. \end{figure}
  9536. \begin{figure}[tbp]
  9537. \begin{lstlisting}
  9538. (define/override (operator-types)
  9539. (append
  9540. '((integer? . ((Any) . Boolean))
  9541. (vector? . ((Any) . Boolean))
  9542. (procedure? . ((Any) . Boolean))
  9543. (void? . ((Any) . Boolean))
  9544. (tag-of-any . ((Any) . Integer))
  9545. (make-any . ((_ Integer) . Any))
  9546. )
  9547. (super operator-types)))
  9548. (define/public (type-predicates)
  9549. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  9550. (define/public (combine-types t1 t2)
  9551. (match (list t1 t2)
  9552. [(list '_ t2) t2]
  9553. [(list t1 '_) t1]
  9554. [(list `(Vector ,ts1 ...)
  9555. `(Vector ,ts2 ...))
  9556. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  9557. (combine-types t1 t2)))]
  9558. [(list `(,ts1 ... -> ,rt1)
  9559. `(,ts2 ... -> ,rt2))
  9560. `(,@(for/list ([t1 ts1] [t2 ts2])
  9561. (combine-types t1 t2))
  9562. -> ,(combine-types rt1 rt2))]
  9563. [else t1]))
  9564. (define/public (flat-ty? ty)
  9565. (match ty
  9566. [(or `Integer `Boolean '_ `Void) #t]
  9567. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  9568. [`(,ts ... -> ,rt)
  9569. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  9570. [else #f]))
  9571. \end{lstlisting}
  9572. \caption{Auxiliary methods for type checking \LangAny{}.}
  9573. \label{fig:type-check-Rany-aux}
  9574. \end{figure}
  9575. \begin{figure}[btp]
  9576. \begin{lstlisting}
  9577. (define interp-Rany-class
  9578. (class interp-Rlambda-class
  9579. (super-new)
  9580. (define/override (interp-op op)
  9581. (match op
  9582. ['boolean? (match-lambda
  9583. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  9584. [else #f])]
  9585. ['integer? (match-lambda
  9586. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  9587. [else #f])]
  9588. ['vector? (match-lambda
  9589. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  9590. [else #f])]
  9591. ['procedure? (match-lambda
  9592. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  9593. [else #f])]
  9594. ['eq? (match-lambda*
  9595. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  9596. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  9597. [ls (apply (super interp-op op) ls)])]
  9598. ['any-vector-ref (lambda (v i)
  9599. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  9600. ['any-vector-set! (lambda (v i a)
  9601. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  9602. ['any-vector-length (lambda (v)
  9603. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  9604. [else (super interp-op op)]))
  9605. (define/override ((interp-exp env) e)
  9606. (define recur (interp-exp env))
  9607. (match e
  9608. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  9609. [(Project e ty2) (apply-project (recur e) ty2)]
  9610. [else ((super interp-exp env) e)]))
  9611. ))
  9612. (define (interp-Rany p)
  9613. (send (new interp-Rany-class) interp-program p))
  9614. \end{lstlisting}
  9615. \caption{Interpreter for \LangAny{}.}
  9616. \label{fig:interp-Rany}
  9617. \end{figure}
  9618. \begin{figure}[tbp]
  9619. \begin{lstlisting}
  9620. (define/public (apply-inject v tg) (Tagged v tg))
  9621. (define/public (apply-project v ty2)
  9622. (define tag2 (any-tag ty2))
  9623. (match v
  9624. [(Tagged v1 tag1)
  9625. (cond
  9626. [(eq? tag1 tag2)
  9627. (match ty2
  9628. [`(Vector ,ts ...)
  9629. (define l1 ((interp-op 'vector-length) v1))
  9630. (cond
  9631. [(eq? l1 (length ts)) v1]
  9632. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  9633. l1 (length ts))])]
  9634. [`(,ts ... -> ,rt)
  9635. (match v1
  9636. [`(function ,xs ,body ,env)
  9637. (cond [(eq? (length xs) (length ts)) v1]
  9638. [else
  9639. (error 'apply-project "arity mismatch ~a != ~a"
  9640. (length xs) (length ts))])]
  9641. [else (error 'apply-project "expected function not ~a" v1)])]
  9642. [else v1])]
  9643. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  9644. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  9645. \end{lstlisting}
  9646. \caption{Auxiliary functions for injection and projection.}
  9647. \label{fig:apply-project}
  9648. \end{figure}
  9649. \clearpage
  9650. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  9651. \label{sec:compile-r7}
  9652. The \code{cast-insert} pass compiles from \LangDyn{} to \LangAny{}.
  9653. Figure~\ref{fig:compile-r7-Rany} shows the compilation of many of the
  9654. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  9655. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  9656. an expression $e'$ in \LangAny{} that has type \key{Any}. For example, the
  9657. first row in Figure~\ref{fig:compile-r7-Rany} shows the compilation of
  9658. the Boolean \code{\#t}, which must be injected to produce an
  9659. expression of type \key{Any}.
  9660. %
  9661. The second row of Figure~\ref{fig:compile-r7-Rany}, the compilation of
  9662. addition, is representative of compilation for many primitive
  9663. operations: the arguments have type \key{Any} and must be projected to
  9664. \key{Integer} before the addition can be performed.
  9665. The compilation of \key{lambda} (third row of
  9666. Figure~\ref{fig:compile-r7-Rany}) shows what happens when we need to
  9667. produce type annotations: we simply use \key{Any}.
  9668. %
  9669. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  9670. has to account for some differences in behavior between \LangDyn{} and
  9671. \LangAny{}. The \LangDyn{} language is more permissive than \LangAny{} regarding what
  9672. kind of values can be used in various places. For example, the
  9673. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  9674. the arguments need not be of the same type (in that case the
  9675. result is \code{\#f}).
  9676. \begin{figure}[btp]
  9677. \centering
  9678. \begin{tabular}{|lll|} \hline
  9679. \begin{minipage}{0.27\textwidth}
  9680. \begin{lstlisting}
  9681. #t
  9682. \end{lstlisting}
  9683. \end{minipage}
  9684. &
  9685. $\Rightarrow$
  9686. &
  9687. \begin{minipage}{0.65\textwidth}
  9688. \begin{lstlisting}
  9689. (inject #t Boolean)
  9690. \end{lstlisting}
  9691. \end{minipage}
  9692. \\[2ex]\hline
  9693. \begin{minipage}{0.27\textwidth}
  9694. \begin{lstlisting}
  9695. (+ |$e_1$| |$e_2$|)
  9696. \end{lstlisting}
  9697. \end{minipage}
  9698. &
  9699. $\Rightarrow$
  9700. &
  9701. \begin{minipage}{0.65\textwidth}
  9702. \begin{lstlisting}
  9703. (inject
  9704. (+ (project |$e'_1$| Integer)
  9705. (project |$e'_2$| Integer))
  9706. Integer)
  9707. \end{lstlisting}
  9708. \end{minipage}
  9709. \\[2ex]\hline
  9710. \begin{minipage}{0.27\textwidth}
  9711. \begin{lstlisting}
  9712. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  9713. \end{lstlisting}
  9714. \end{minipage}
  9715. &
  9716. $\Rightarrow$
  9717. &
  9718. \begin{minipage}{0.65\textwidth}
  9719. \begin{lstlisting}
  9720. (inject
  9721. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  9722. (Any|$\ldots$|Any -> Any))
  9723. \end{lstlisting}
  9724. \end{minipage}
  9725. \\[2ex]\hline
  9726. \begin{minipage}{0.27\textwidth}
  9727. \begin{lstlisting}
  9728. (|$e_0$| |$e_1 \ldots e_n$|)
  9729. \end{lstlisting}
  9730. \end{minipage}
  9731. &
  9732. $\Rightarrow$
  9733. &
  9734. \begin{minipage}{0.65\textwidth}
  9735. \begin{lstlisting}
  9736. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  9737. \end{lstlisting}
  9738. \end{minipage}
  9739. \\[2ex]\hline
  9740. \begin{minipage}{0.27\textwidth}
  9741. \begin{lstlisting}
  9742. (vector-ref |$e_1$| |$e_2$|)
  9743. \end{lstlisting}
  9744. \end{minipage}
  9745. &
  9746. $\Rightarrow$
  9747. &
  9748. \begin{minipage}{0.65\textwidth}
  9749. \begin{lstlisting}
  9750. (any-vector-ref |$e_1'$| |$e_2'$|)
  9751. \end{lstlisting}
  9752. \end{minipage}
  9753. \\[2ex]\hline
  9754. \begin{minipage}{0.27\textwidth}
  9755. \begin{lstlisting}
  9756. (if |$e_1$| |$e_2$| |$e_3$|)
  9757. \end{lstlisting}
  9758. \end{minipage}
  9759. &
  9760. $\Rightarrow$
  9761. &
  9762. \begin{minipage}{0.65\textwidth}
  9763. \begin{lstlisting}
  9764. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  9765. \end{lstlisting}
  9766. \end{minipage}
  9767. \\[2ex]\hline
  9768. \begin{minipage}{0.27\textwidth}
  9769. \begin{lstlisting}
  9770. (eq? |$e_1$| |$e_2$|)
  9771. \end{lstlisting}
  9772. \end{minipage}
  9773. &
  9774. $\Rightarrow$
  9775. &
  9776. \begin{minipage}{0.65\textwidth}
  9777. \begin{lstlisting}
  9778. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  9779. \end{lstlisting}
  9780. \end{minipage}
  9781. \\[2ex]\hline
  9782. \begin{minipage}{0.27\textwidth}
  9783. \begin{lstlisting}
  9784. (not |$e_1$|)
  9785. \end{lstlisting}
  9786. \end{minipage}
  9787. &
  9788. $\Rightarrow$
  9789. &
  9790. \begin{minipage}{0.65\textwidth}
  9791. \begin{lstlisting}
  9792. (if (eq? |$e'_1$| (inject #f Boolean))
  9793. (inject #t Boolean) (inject #f Boolean))
  9794. \end{lstlisting}
  9795. \end{minipage}
  9796. \\[2ex]\hline
  9797. \end{tabular}
  9798. \caption{Cast Insertion}
  9799. \label{fig:compile-r7-Rany}
  9800. \end{figure}
  9801. \section{Reveal Casts}
  9802. \label{sec:reveal-casts-Rany}
  9803. % TODO: define R'_6
  9804. In the \code{reveal-casts} pass we recommend compiling \code{project}
  9805. into an \code{if} expression that checks whether the value's tag
  9806. matches the target type; if it does, the value is converted to a value
  9807. of the target type by removing the tag; if it does not, the program
  9808. exits. To perform these actions we need a new primitive operation,
  9809. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  9810. The \code{tag-of-any} operation retrieves the type tag from a tagged
  9811. value of type \code{Any}. The \code{ValueOf} form retrieves the
  9812. underlying value from a tagged value. The \code{ValueOf} form
  9813. includes the type for the underlying value which is used by the type
  9814. checker. Finally, the \code{Exit} form ends the execution of the
  9815. program.
  9816. If the target type of the projection is \code{Boolean} or
  9817. \code{Integer}, then \code{Project} can be translated as follows.
  9818. \begin{center}
  9819. \begin{minipage}{1.0\textwidth}
  9820. \begin{lstlisting}
  9821. (Project |$e$| |$\FType$|)
  9822. |$\Rightarrow$|
  9823. (Let |$\itm{tmp}$| |$e'$|
  9824. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  9825. (Int |$\itm{tagof}(\FType)$|)))
  9826. (ValueOf |$\itm{tmp}$| |$\FType$|)
  9827. (Exit)))
  9828. \end{lstlisting}
  9829. \end{minipage}
  9830. \end{center}
  9831. If the target type of the projection is a vector or function type,
  9832. then there is a bit more work to do. For vectors, check that the
  9833. length of the vector type matches the length of the vector (using the
  9834. \code{vector-length} primitive). For functions, check that the number
  9835. of parameters in the function type matches the function's arity (using
  9836. \code{procedure-arity}).
  9837. Regarding \code{inject}, we recommend compiling it to a slightly
  9838. lower-level primitive operation named \code{make-any}. This operation
  9839. takes a tag instead of a type.
  9840. \begin{center}
  9841. \begin{minipage}{1.0\textwidth}
  9842. \begin{lstlisting}
  9843. (Inject |$e$| |$\FType$|)
  9844. |$\Rightarrow$|
  9845. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  9846. \end{lstlisting}
  9847. \end{minipage}
  9848. \end{center}
  9849. The type predicates (\code{boolean?}, etc.) can be translated into
  9850. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  9851. translation of \code{Project}.
  9852. The \code{any-vector-ref} and \code{any-vector-set!} operations
  9853. combine the projection action with the vector operation. Also, the
  9854. read and write operations allow arbitrary expressions for the index so
  9855. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany-part-1})
  9856. cannot guarantee that the index is within bounds. Thus, we insert code
  9857. to perform bounds checking at runtime. The translation for
  9858. \code{any-vector-ref} is as follows and the other two operations are
  9859. translated in a similar way.
  9860. \begin{lstlisting}
  9861. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  9862. |$\Rightarrow$|
  9863. (Let |$v$| |$e'_1$|
  9864. (Let |$i$| |$e'_2$|
  9865. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  9866. (If (Prim '< (list (Var |$i$|)
  9867. (Prim 'any-vector-length (list (Var |$v$|)))))
  9868. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  9869. (Exit))))
  9870. \end{lstlisting}
  9871. \section{Remove Complex Operands}
  9872. \label{sec:rco-Rany}
  9873. The \code{ValueOf} and \code{Exit} forms are both complex expressions.
  9874. The subexpression of \code{ValueOf} must be atomic.
  9875. \section{Explicate Control and \LangCAny{}}
  9876. \label{sec:explicate-Rany}
  9877. The output of \code{explicate-control} is the \LangCAny{} language whose
  9878. syntax is defined in Figure~\ref{fig:c5-syntax}. The \code{ValueOf}
  9879. form that we added to \LangAny{} remains an expression and the \code{Exit}
  9880. expression becomes a $\Tail$. Also, note that the index argument of
  9881. \code{vector-ref} and \code{vector-set!} is an $\Atm$ instead
  9882. of an integer, as in \LangCVec{} (Figure~\ref{fig:c2-syntax}).
  9883. \begin{figure}[tp]
  9884. \fbox{
  9885. \begin{minipage}{0.96\textwidth}
  9886. \small
  9887. \[
  9888. \begin{array}{lcl}
  9889. \Exp &::= & \ldots
  9890. \MID \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  9891. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  9892. &\MID& \VALUEOF{\Exp}{\FType} \\
  9893. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  9894. \MID \LP\key{Collect} \,\itm{int}\RP }\\
  9895. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  9896. \MID \GOTO{\itm{label}} } \\
  9897. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  9898. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  9899. \MID \LP\key{Exit}\RP \\
  9900. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  9901. \LangCAnyM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  9902. \end{array}
  9903. \]
  9904. \end{minipage}
  9905. }
  9906. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  9907. \label{fig:c5-syntax}
  9908. \end{figure}
  9909. \section{Select Instructions}
  9910. \label{sec:select-Rany}
  9911. In the \code{select-instructions} pass we translate the primitive
  9912. operations on the \code{Any} type to x86 instructions that involve
  9913. manipulating the 3 tag bits of the tagged value.
  9914. \paragraph{Make-any}
  9915. We recommend compiling the \key{make-any} primitive as follows if the
  9916. tag is for \key{Integer} or \key{Boolean}. The \key{salq} instruction
  9917. shifts the destination to the left by the number of bits specified its
  9918. source argument (in this case $3$, the length of the tag) and it
  9919. preserves the sign of the integer. We use the \key{orq} instruction to
  9920. combine the tag and the value to form the tagged value. \\
  9921. \begin{lstlisting}
  9922. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  9923. |$\Rightarrow$|
  9924. movq |$e'$|, |\itm{lhs'}|
  9925. salq $3, |\itm{lhs'}|
  9926. orq $|$\itm{tag}$|, |\itm{lhs'}|
  9927. \end{lstlisting}
  9928. The instruction selection for vectors and procedures is different
  9929. because their is no need to shift them to the left. The rightmost 3
  9930. bits are already zeros as described at the beginning of this
  9931. chapter. So we just combine the value and the tag using \key{orq}. \\
  9932. \begin{lstlisting}
  9933. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  9934. |$\Rightarrow$|
  9935. movq |$e'$|, |\itm{lhs'}|
  9936. orq $|$\itm{tag}$|, |\itm{lhs'}|
  9937. \end{lstlisting}
  9938. \paragraph{Tag-of-any}
  9939. Recall that the \code{tag-of-any} operation extracts the type tag from
  9940. a value of type \code{Any}. The type tag is the bottom three bits, so
  9941. we obtain the tag by taking the bitwise-and of the value with $111$
  9942. ($7$ in decimal).
  9943. \begin{lstlisting}
  9944. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  9945. |$\Rightarrow$|
  9946. movq |$e'$|, |\itm{lhs'}|
  9947. andq $7, |\itm{lhs'}|
  9948. \end{lstlisting}
  9949. \paragraph{ValueOf}
  9950. Like \key{make-any}, the instructions for \key{ValueOf} are different
  9951. depending on whether the type $T$ is a pointer (vector or procedure)
  9952. or not (Integer or Boolean). The following shows the instruction
  9953. selection for Integer and Boolean. We produce an untagged value by
  9954. shifting it to the right by 3 bits.
  9955. \begin{lstlisting}
  9956. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  9957. |$\Rightarrow$|
  9958. movq |$e'$|, |\itm{lhs'}|
  9959. sarq $3, |\itm{lhs'}|
  9960. \end{lstlisting}
  9961. %
  9962. In the case for vectors and procedures, there is no need to
  9963. shift. Instead we just need to zero-out the rightmost 3 bits. We
  9964. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  9965. decimal) and apply \code{bitwise-not} to obtain $\ldots 11111000$ (-8
  9966. in decimal) which we \code{movq} into the destination $\itm{lhs}$. We
  9967. then apply \code{andq} with the tagged value to get the desired
  9968. result. \\
  9969. \begin{lstlisting}
  9970. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  9971. |$\Rightarrow$|
  9972. movq $|$-8$|, |\itm{lhs'}|
  9973. andq |$e'$|, |\itm{lhs'}|
  9974. \end{lstlisting}
  9975. %% \paragraph{Type Predicates} We leave it to the reader to
  9976. %% devise a sequence of instructions to implement the type predicates
  9977. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  9978. \paragraph{Any-vector-length}
  9979. \begin{lstlisting}
  9980. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$a_1$|)))
  9981. |$\Longrightarrow$|
  9982. movq |$\neg 111$|, %r11
  9983. andq |$a_1'$|, %r11
  9984. movq 0(%r11), %r11
  9985. andq $126, %r11
  9986. sarq $1, %r11
  9987. movq %r11, |$\itm{lhs'}$|
  9988. \end{lstlisting}
  9989. \paragraph{Any-vector-ref}
  9990. The index may be an arbitrary atom so instead of computing the offset
  9991. at compile time, instructions need to be generated to compute the
  9992. offset at runtime as follows. Note the use of the new instruction
  9993. \code{imulq}.
  9994. \begin{center}
  9995. \begin{minipage}{0.96\textwidth}
  9996. \begin{lstlisting}
  9997. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$a_1$| |$a_2$|)))
  9998. |$\Longrightarrow$|
  9999. movq |$\neg 111$|, %r11
  10000. andq |$a_1'$|, %r11
  10001. movq |$a_2'$|, %rax
  10002. addq $1, %rax
  10003. imulq $8, %rax
  10004. addq %rax, %r11
  10005. movq 0(%r11) |$\itm{lhs'}$|
  10006. \end{lstlisting}
  10007. \end{minipage}
  10008. \end{center}
  10009. \paragraph{Any-vector-set!}
  10010. The code generation for \code{any-vector-set!} is similar to the other
  10011. \code{any-vector} operations.
  10012. \section{Register Allocation for \LangAny{}}
  10013. \label{sec:register-allocation-Rany}
  10014. \index{subject}{register allocation}
  10015. There is an interesting interaction between tagged values and garbage
  10016. collection that has an impact on register allocation. A variable of
  10017. type \code{Any} might refer to a vector and therefore it might be a
  10018. root that needs to be inspected and copied during garbage
  10019. collection. Thus, we need to treat variables of type \code{Any} in a
  10020. similar way to variables of type \code{Vector} for purposes of
  10021. register allocation. In particular,
  10022. \begin{itemize}
  10023. \item If a variable of type \code{Any} is live during a function call,
  10024. then it must be spilled. This can be accomplished by changing
  10025. \code{build-interference} to mark all variables of type \code{Any}
  10026. that are live after a \code{callq} as interfering with all the
  10027. registers.
  10028. \item If a variable of type \code{Any} is spilled, it must be spilled
  10029. to the root stack instead of the normal procedure call stack.
  10030. \end{itemize}
  10031. Another concern regarding the root stack is that the garbage collector
  10032. needs to differentiate between (1) plain old pointers to tuples, (2) a
  10033. tagged value that points to a tuple, and (3) a tagged value that is
  10034. not a tuple. We enable this differentiation by choosing not to use the
  10035. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  10036. reserved for identifying plain old pointers to tuples. That way, if
  10037. one of the first three bits is set, then we have a tagged value and
  10038. inspecting the tag can differentiation between vectors ($010$) and the
  10039. other kinds of values.
  10040. \begin{exercise}\normalfont
  10041. Expand your compiler to handle \LangAny{} as discussed in the last few
  10042. sections. Create 5 new programs that use the \code{Any} type and the
  10043. new operations (\code{inject}, \code{project}, \code{boolean?},
  10044. etc.). Test your compiler on these new programs and all of your
  10045. previously created test programs.
  10046. \end{exercise}
  10047. \begin{exercise}\normalfont
  10048. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  10049. Create tests for \LangDyn{} by adapting ten of your previous test programs
  10050. by removing type annotations. Add 5 more tests programs that
  10051. specifically rely on the language being dynamically typed. That is,
  10052. they should not be legal programs in a statically typed language, but
  10053. nevertheless, they should be valid \LangDyn{} programs that run to
  10054. completion without error.
  10055. \end{exercise}
  10056. \begin{figure}[p]
  10057. \begin{tikzpicture}[baseline=(current bounding box.center)]
  10058. \node (Rfun) at (0,4) {\large \LangDyn{}};
  10059. \node (Rfun-2) at (3,4) {\large \LangDyn{}};
  10060. \node (Rfun-3) at (6,4) {\large \LangDyn{}};
  10061. \node (Rfun-4) at (9,4) {\large \LangDynFunRef{}};
  10062. \node (Rfun-5) at (9,2) {\large \LangAnyFunRef{}};
  10063. \node (Rfun-6) at (12,2) {\large \LangAnyFunRef{}};
  10064. \node (Rfun-7) at (12,0) {\large \LangAnyFunRef{}};
  10065. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  10066. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  10067. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  10068. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  10069. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  10070. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  10071. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  10072. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  10073. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  10074. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  10075. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  10076. \path[->,bend left=15] (Rfun) edge [above] node
  10077. {\ttfamily\footnotesize shrink} (Rfun-2);
  10078. \path[->,bend left=15] (Rfun-2) edge [above] node
  10079. {\ttfamily\footnotesize uniquify} (Rfun-3);
  10080. \path[->,bend left=15] (Rfun-3) edge [above] node
  10081. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  10082. \path[->,bend right=15] (Rfun-4) edge [left] node
  10083. {\ttfamily\footnotesize cast-insert} (Rfun-5);
  10084. \path[->,bend left=15] (Rfun-5) edge [above] node
  10085. {\ttfamily\footnotesize check-bounds} (Rfun-6);
  10086. \path[->,bend left=15] (Rfun-6) edge [left] node
  10087. {\ttfamily\footnotesize reveal-casts} (Rfun-7);
  10088. \path[->,bend left=15] (Rfun-7) edge [below] node
  10089. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  10090. \path[->,bend right=15] (F1-2) edge [above] node
  10091. {\ttfamily\footnotesize limit-fun.} (F1-3);
  10092. \path[->,bend right=15] (F1-3) edge [above] node
  10093. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  10094. \path[->,bend right=15] (F1-4) edge [above] node
  10095. {\ttfamily\footnotesize remove-complex.} (F1-5);
  10096. \path[->,bend right=15] (F1-5) edge [right] node
  10097. {\ttfamily\footnotesize explicate-control} (C3-2);
  10098. \path[->,bend left=15] (C3-2) edge [left] node
  10099. {\ttfamily\footnotesize select-instr.} (x86-2);
  10100. \path[->,bend right=15] (x86-2) edge [left] node
  10101. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  10102. \path[->,bend right=15] (x86-2-1) edge [below] node
  10103. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  10104. \path[->,bend right=15] (x86-2-2) edge [left] node
  10105. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  10106. \path[->,bend left=15] (x86-3) edge [above] node
  10107. {\ttfamily\footnotesize patch-instr.} (x86-4);
  10108. \path[->,bend left=15] (x86-4) edge [right] node
  10109. {\ttfamily\footnotesize print-x86} (x86-5);
  10110. \end{tikzpicture}
  10111. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  10112. \label{fig:Rdyn-passes}
  10113. \end{figure}
  10114. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  10115. for the compilation of \LangDyn{}.
  10116. % Further Reading
  10117. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10118. \chapter{Loops and Assignment}
  10119. \label{ch:Rwhile}
  10120. % TODO: define R'_8
  10121. % TODO: multi-graph
  10122. In this chapter we study two features that are the hallmarks of
  10123. imperative programming languages: loops and assignments to local
  10124. variables. The following example demonstrates these new features by
  10125. computing the sum of the first five positive integers.
  10126. % similar to loop_test_1.rkt
  10127. \begin{lstlisting}
  10128. (let ([sum 0])
  10129. (let ([i 5])
  10130. (begin
  10131. (while (> i 0)
  10132. (begin
  10133. (set! sum (+ sum i))
  10134. (set! i (- i 1))))
  10135. sum)))
  10136. \end{lstlisting}
  10137. The \code{while} loop consists of a condition and a body.
  10138. %
  10139. The \code{set!} consists of a variable and a right-hand-side expression.
  10140. %
  10141. The primary purpose of both the \code{while} loop and \code{set!} is
  10142. to cause side effects, so it is convenient to also include in a
  10143. language feature for sequencing side effects: the \code{begin}
  10144. expression. It consists of one or more subexpressions that are
  10145. evaluated left-to-right.
  10146. \section{The \LangLoop{} Language}
  10147. \begin{figure}[tp]
  10148. \centering
  10149. \fbox{
  10150. \begin{minipage}{0.96\textwidth}
  10151. \small
  10152. \[
  10153. \begin{array}{lcl}
  10154. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  10155. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  10156. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  10157. &\MID& \gray{\key{\#t} \MID \key{\#f}
  10158. \MID (\key{and}\;\Exp\;\Exp)
  10159. \MID (\key{or}\;\Exp\;\Exp)
  10160. \MID (\key{not}\;\Exp) } \\
  10161. &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  10162. &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  10163. (\key{vector-ref}\;\Exp\;\Int)} \\
  10164. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  10165. \MID (\Exp \; \Exp\ldots) } \\
  10166. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP
  10167. \MID \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  10168. &\MID& \CSETBANG{\Var}{\Exp}
  10169. \MID \CBEGIN{\Exp\ldots}{\Exp}
  10170. \MID \CWHILE{\Exp}{\Exp} \\
  10171. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  10172. \LangLoopM{} &::=& \gray{\Def\ldots \; \Exp}
  10173. \end{array}
  10174. \]
  10175. \end{minipage}
  10176. }
  10177. \caption{The concrete syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-concrete-syntax}).}
  10178. \label{fig:Rwhile-concrete-syntax}
  10179. \end{figure}
  10180. \begin{figure}[tp]
  10181. \centering
  10182. \fbox{
  10183. \begin{minipage}{0.96\textwidth}
  10184. \small
  10185. \[
  10186. \begin{array}{lcl}
  10187. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  10188. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  10189. &\MID& \gray{ \BOOL{\itm{bool}}
  10190. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  10191. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  10192. \MID \APPLY{\Exp}{\Exp\ldots} }\\
  10193. &\MID& \gray{ \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp} }\\
  10194. &\MID& \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  10195. \MID \WHILE{\Exp}{\Exp} \\
  10196. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  10197. \LangLoopM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  10198. \end{array}
  10199. \]
  10200. \end{minipage}
  10201. }
  10202. \caption{The abstract syntax of \LangLoop{}, extending \LangAny{} (Figure~\ref{fig:Rany-syntax}).}
  10203. \label{fig:Rwhile-syntax}
  10204. \end{figure}
  10205. The concrete syntax of \LangLoop{} is defined in
  10206. Figure~\ref{fig:Rwhile-concrete-syntax} and its abstract syntax is defined
  10207. in Figure~\ref{fig:Rwhile-syntax}.
  10208. %
  10209. The definitional interpreter for \LangLoop{} is shown in
  10210. Figure~\ref{fig:interp-Rwhile}. We add three new cases for \code{SetBang},
  10211. \code{WhileLoop}, and \code{Begin} and we make changes to the cases
  10212. for \code{Var}, \code{Let}, and \code{Apply} regarding variables. To
  10213. support assignment to variables and to make their lifetimes indefinite
  10214. (see the second example in Section~\ref{sec:assignment-scoping}), we
  10215. box the value that is bound to each variable (in \code{Let}) and
  10216. function parameter (in \code{Apply}). The case for \code{Var} unboxes
  10217. the value.
  10218. %
  10219. Now to discuss the new cases. For \code{SetBang}, we lookup the
  10220. variable in the environment to obtain a boxed value and then we change
  10221. it using \code{set-box!} to the result of evaluating the right-hand
  10222. side. The result value of a \code{SetBang} is \code{void}.
  10223. %
  10224. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  10225. if the result is true, 2) evaluate the body.
  10226. The result value of a \code{while} loop is also \code{void}.
  10227. %
  10228. Finally, the $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  10229. subexpressions \itm{es} for their effects and then evaluates
  10230. and returns the result from \itm{body}.
  10231. \begin{figure}[tbp]
  10232. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10233. (define interp-Rwhile-class
  10234. (class interp-Rany-class
  10235. (super-new)
  10236. (define/override ((interp-exp env) e)
  10237. (define recur (interp-exp env))
  10238. (match e
  10239. [(SetBang x rhs)
  10240. (set-box! (lookup x env) (recur rhs))]
  10241. [(WhileLoop cnd body)
  10242. (define (loop)
  10243. (cond [(recur cnd) (recur body) (loop)]
  10244. [else (void)]))
  10245. (loop)]
  10246. [(Begin es body)
  10247. (for ([e es]) (recur e))
  10248. (recur body)]
  10249. [else ((super interp-exp env) e)]))
  10250. ))
  10251. (define (interp-Rwhile p)
  10252. (send (new interp-Rwhile-class) interp-program p))
  10253. \end{lstlisting}
  10254. \caption{Interpreter for \LangLoop{}.}
  10255. \label{fig:interp-Rwhile}
  10256. \end{figure}
  10257. The type checker for \LangLoop{} is define in
  10258. Figure~\ref{fig:type-check-Rwhile}. For \code{SetBang}, the type of the
  10259. variable and the right-hand-side must agree. The result type is
  10260. \code{Void}. For the \code{WhileLoop}, the condition must be a
  10261. \code{Boolean}. The result type is also \code{Void}. For
  10262. \code{Begin}, the result type is the type of its last subexpression.
  10263. \begin{figure}[tbp]
  10264. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10265. (define type-check-Rwhile-class
  10266. (class type-check-Rany-class
  10267. (super-new)
  10268. (inherit check-type-equal?)
  10269. (define/override (type-check-exp env)
  10270. (lambda (e)
  10271. (define recur (type-check-exp env))
  10272. (match e
  10273. [(SetBang x rhs)
  10274. (define-values (rhs^ rhsT) (recur rhs))
  10275. (define varT (dict-ref env x))
  10276. (check-type-equal? rhsT varT e)
  10277. (values (SetBang x rhs^) 'Void)]
  10278. [(WhileLoop cnd body)
  10279. (define-values (cnd^ Tc) (recur cnd))
  10280. (check-type-equal? Tc 'Boolean e)
  10281. (define-values (body^ Tbody) ((type-check-exp env) body))
  10282. (values (WhileLoop cnd^ body^) 'Void)]
  10283. [(Begin es body)
  10284. (define-values (es^ ts)
  10285. (for/lists (l1 l2) ([e es]) (recur e)))
  10286. (define-values (body^ Tbody) (recur body))
  10287. (values (Begin es^ body^) Tbody)]
  10288. [else ((super type-check-exp env) e)])))
  10289. ))
  10290. (define (type-check-Rwhile p)
  10291. (send (new type-check-Rwhile-class) type-check-program p))
  10292. \end{lstlisting}
  10293. \caption{Type checking \key{SetBang}, \key{WhileLoop},
  10294. and \code{Begin} in \LangLoop{}.}
  10295. \label{fig:type-check-Rwhile}
  10296. \end{figure}
  10297. At first glance, the translation of these language features to x86
  10298. seems straightforward because the \LangCFun{} intermediate language already
  10299. supports all of the ingredients that we need: assignment, \code{goto},
  10300. conditional branching, and sequencing. However, there are two
  10301. complications that arise which we discuss in the next two
  10302. sections. After that we introduce one new compiler pass and the
  10303. changes necessary to the existing passes.
  10304. \section{Assignment and Lexically Scoped Functions}
  10305. \label{sec:assignment-scoping}
  10306. The addition of assignment raises a problem with our approach to
  10307. implementing lexically-scoped functions. Consider the following
  10308. example in which function \code{f} has a free variable \code{x} that
  10309. is changed after \code{f} is created but before the call to \code{f}.
  10310. % loop_test_11.rkt
  10311. \begin{lstlisting}
  10312. (let ([x 0])
  10313. (let ([y 0])
  10314. (let ([z 20])
  10315. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  10316. (begin
  10317. (set! x 10)
  10318. (set! y 12)
  10319. (f y))))))
  10320. \end{lstlisting}
  10321. The correct output for this example is \code{42} because the call to
  10322. \code{f} is required to use the current value of \code{x} (which is
  10323. \code{10}). Unfortunately, the closure conversion pass
  10324. (Section~\ref{sec:closure-conversion}) generates code for the
  10325. \code{lambda} that copies the old value of \code{x} into a
  10326. closure. Thus, if we naively add support for assignment to our current
  10327. compiler, the output of this program would be \code{32}.
  10328. A first attempt at solving this problem would be to save a pointer to
  10329. \code{x} in the closure and change the occurrences of \code{x} inside
  10330. the lambda to dereference the pointer. Of course, this would require
  10331. assigning \code{x} to the stack and not to a register. However, the
  10332. problem goes a bit deeper. Consider the following example in which we
  10333. create a counter abstraction by creating a pair of functions that
  10334. share the free variable \code{x}.
  10335. % similar to loop_test_10.rkt
  10336. \begin{lstlisting}
  10337. (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  10338. (vector
  10339. (lambda: () : Integer x)
  10340. (lambda: () : Void (set! x (+ 1 x)))))
  10341. (let ([counter (f 0)])
  10342. (let ([get (vector-ref counter 0)])
  10343. (let ([inc (vector-ref counter 1)])
  10344. (begin
  10345. (inc)
  10346. (get)))))
  10347. \end{lstlisting}
  10348. In this example, the lifetime of \code{x} extends beyond the lifetime
  10349. of the call to \code{f}. Thus, if we were to store \code{x} on the
  10350. stack frame for the call to \code{f}, it would be gone by the time we
  10351. call \code{inc} and \code{get}, leaving us with dangling pointers for
  10352. \code{x}. This example demonstrates that when a variable occurs free
  10353. inside a \code{lambda}, its lifetime becomes indefinite. Thus, the
  10354. value of the variable needs to live on the heap. The verb ``box'' is
  10355. often used for allocating a single value on the heap, producing a
  10356. pointer, and ``unbox'' for dereferencing the pointer.
  10357. We recommend solving these problems by ``boxing'' the local variables
  10358. that are in the intersection of 1) variables that appear on the
  10359. left-hand-side of a \code{set!} and 2) variables that occur free
  10360. inside a \code{lambda}. We shall introduce a new pass named
  10361. \code{convert-assignments} in Section~\ref{sec:convert-assignments} to
  10362. perform this translation. But before diving into the compiler passes,
  10363. we one more problem to discuss.
  10364. \section{Cyclic Control Flow and Dataflow Analysis}
  10365. \label{sec:dataflow-analysis}
  10366. Up until this point the control-flow graphs generated in
  10367. \code{explicate-control} were guaranteed to be acyclic. However, each
  10368. \code{while} loop introduces a cycle in the control-flow graph.
  10369. But does that matter?
  10370. %
  10371. Indeed it does. Recall that for register allocation, the compiler
  10372. performs liveness analysis to determine which variables can share the
  10373. same register. In Section~\ref{sec:liveness-analysis-Rif} we analyze
  10374. the control-flow graph in reverse topological order, but topological
  10375. order is only well-defined for acyclic graphs.
  10376. Let us return to the example of computing the sum of the first five
  10377. positive integers. Here is the program after instruction selection but
  10378. before register allocation.
  10379. \begin{center}
  10380. \begin{minipage}{0.45\textwidth}
  10381. \begin{lstlisting}
  10382. (define (main) : Integer
  10383. mainstart:
  10384. movq $0, sum1
  10385. movq $5, i2
  10386. jmp block5
  10387. block5:
  10388. movq i2, tmp3
  10389. cmpq tmp3, $0
  10390. jl block7
  10391. jmp block8
  10392. \end{lstlisting}
  10393. \end{minipage}
  10394. \begin{minipage}{0.45\textwidth}
  10395. \begin{lstlisting}
  10396. block7:
  10397. addq i2, sum1
  10398. movq $1, tmp4
  10399. negq tmp4
  10400. addq tmp4, i2
  10401. jmp block5
  10402. block8:
  10403. movq $27, %rax
  10404. addq sum1, %rax
  10405. jmp mainconclusion
  10406. )
  10407. \end{lstlisting}
  10408. \end{minipage}
  10409. \end{center}
  10410. Recall that liveness analysis works backwards, starting at the end
  10411. of each function. For this example we could start with \code{block8}
  10412. because we know what is live at the beginning of the conclusion,
  10413. just \code{rax} and \code{rsp}. So the live-before set
  10414. for \code{block8} is $\{\ttm{rsp},\ttm{sum1}\}$.
  10415. %
  10416. Next we might try to analyze \code{block5} or \code{block7}, but
  10417. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  10418. we are stuck.
  10419. The way out of this impasse comes from the realization that one can
  10420. perform liveness analysis starting with an empty live-after set to
  10421. compute an under-approximation of the live-before set. By
  10422. \emph{under-approximation}, we mean that the set only contains
  10423. variables that are really live, but it may be missing some. Next, the
  10424. under-approximations for each block can be improved by 1) updating the
  10425. live-after set for each block using the approximate live-before sets
  10426. from the other blocks and 2) perform liveness analysis again on each
  10427. block. In fact, by iterating this process, the under-approximations
  10428. eventually become the correct solutions!
  10429. %
  10430. This approach of iteratively analyzing a control-flow graph is
  10431. applicable to many static analysis problems and goes by the name
  10432. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  10433. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  10434. Washington.
  10435. Let us apply this approach to the above example. We use the empty set
  10436. for the initial live-before set for each block. Let $m_0$ be the
  10437. following mapping from label names to sets of locations (variables and
  10438. registers).
  10439. \begin{center}
  10440. \begin{lstlisting}
  10441. mainstart: {}
  10442. block5: {}
  10443. block7: {}
  10444. block8: {}
  10445. \end{lstlisting}
  10446. \end{center}
  10447. Using the above live-before approximations, we determine the
  10448. live-after for each block and then apply liveness analysis to each
  10449. block. This produces our next approximation $m_1$ of the live-before
  10450. sets.
  10451. \begin{center}
  10452. \begin{lstlisting}
  10453. mainstart: {}
  10454. block5: {i2}
  10455. block7: {i2, sum1}
  10456. block8: {rsp, sum1}
  10457. \end{lstlisting}
  10458. \end{center}
  10459. For the second round, the live-after for \code{mainstart} is the
  10460. current live-before for \code{block5}, which is \code{\{i2\}}. So the
  10461. liveness analysis for \code{mainstart} computes the empty set. The
  10462. live-after for \code{block5} is the union of the live-before sets for
  10463. \code{block7} and \code{block8}, which is \code{\{i2 , rsp, sum1\}}.
  10464. So the liveness analysis for \code{block5} computes \code{\{i2 , rsp,
  10465. sum1\}}. The live-after for \code{block7} is the live-before for
  10466. \code{block5} (from the previous iteration), which is \code{\{i2\}}.
  10467. So the liveness analysis for \code{block7} remains \code{\{i2,
  10468. sum1\}}. Together these yield the following approximation $m_2$ of
  10469. the live-before sets.
  10470. \begin{center}
  10471. \begin{lstlisting}
  10472. mainstart: {}
  10473. block5: {i2, rsp, sum1}
  10474. block7: {i2, sum1}
  10475. block8: {rsp, sum1}
  10476. \end{lstlisting}
  10477. \end{center}
  10478. In the preceding iteration, only \code{block5} changed, so we can
  10479. limit our attention to \code{mainstart} and \code{block7}, the two
  10480. blocks that jump to \code{block5}. As a result, the live-before sets
  10481. for \code{mainstart} and \code{block7} are updated to include
  10482. \code{rsp}, yielding the following approximation $m_3$.
  10483. \begin{center}
  10484. \begin{lstlisting}
  10485. mainstart: {rsp}
  10486. block5: {i2, rsp, sum1}
  10487. block7: {i2, rsp, sum1}
  10488. block8: {rsp, sum1}
  10489. \end{lstlisting}
  10490. \end{center}
  10491. Because \code{block7} changed, we analyze \code{block5} once more, but
  10492. its live-before set remains \code{\{ i2, rsp, sum1 \}}. At this point
  10493. our approximations have converged, so $m_3$ is the solution.
  10494. This iteration process is guaranteed to converge to a solution by the
  10495. Kleene Fixed-Point Theorem, a general theorem about functions on
  10496. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  10497. any collection that comes with a partial ordering $\sqsubseteq$ on its
  10498. elements, a least element $\bot$ (pronounced bottom), and a join
  10499. operator $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  10500. ordering}\index{subject}{join}\footnote{Technically speaking, we will be
  10501. working with join semi-lattices.} When two elements are ordered $m_i
  10502. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  10503. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  10504. approximation than $m_i$. The bottom element $\bot$ represents the
  10505. complete lack of information, i.e., the worst approximation. The join
  10506. operator takes two lattice elements and combines their information,
  10507. i.e., it produces the least upper bound of the two.\index{subject}{least upper
  10508. bound}
  10509. A dataflow analysis typically involves two lattices: one lattice to
  10510. represent abstract states and another lattice that aggregates the
  10511. abstract states of all the blocks in the control-flow graph. For
  10512. liveness analysis, an abstract state is a set of locations. We form
  10513. the lattice $L$ by taking its elements to be sets of locations, the
  10514. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  10515. set, and the join operator to be set union.
  10516. %
  10517. We form a second lattice $M$ by taking its elements to be mappings
  10518. from the block labels to sets of locations (elements of $L$). We
  10519. order the mappings point-wise, using the ordering of $L$. So given any
  10520. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  10521. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  10522. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  10523. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  10524. We can think of one iteration of liveness analysis as being a function
  10525. $f$ on the lattice $M$. It takes a mapping as input and computes a new
  10526. mapping.
  10527. \[
  10528. f(m_i) = m_{i+1}
  10529. \]
  10530. Next let us think for a moment about what a final solution $m_s$
  10531. should look like. If we perform liveness analysis using the solution
  10532. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  10533. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  10534. \[
  10535. f(m_s) = m_s
  10536. \]
  10537. Furthermore, the solution should only include locations that are
  10538. forced to be there by performing liveness analysis on the program, so
  10539. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  10540. The Kleene Fixed-Point Theorem states that if a function $f$ is
  10541. monotone (better inputs produce better outputs), then the least fixed
  10542. point of $f$ is the least upper bound of the \emph{ascending Kleene
  10543. chain} obtained by starting at $\bot$ and iterating $f$ as
  10544. follows.\index{subject}{Kleene Fixed-Point Theorem}
  10545. \[
  10546. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10547. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  10548. \]
  10549. When a lattice contains only finitely-long ascending chains, then
  10550. every Kleene chain tops out at some fixed point after a number of
  10551. iterations of $f$. So that fixed point is also a least upper
  10552. bound of the chain.
  10553. \[
  10554. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10555. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  10556. \]
  10557. The liveness analysis is indeed a monotone function and the lattice
  10558. $M$ only has finitely-long ascending chains because there are only a
  10559. finite number of variables and blocks in the program. Thus we are
  10560. guaranteed that iteratively applying liveness analysis to all blocks
  10561. in the program will eventually produce the least fixed point solution.
  10562. Next let us consider dataflow analysis in general and discuss the
  10563. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  10564. %
  10565. The algorithm has four parameters: the control-flow graph \code{G}, a
  10566. function \code{transfer} that applies the analysis to one block, the
  10567. \code{bottom} and \code{join} operator for the lattice of abstract
  10568. states. The algorithm begins by creating the bottom mapping,
  10569. represented by a hash table. It then pushes all of the nodes in the
  10570. control-flow graph onto the work list (a queue). The algorithm repeats
  10571. the \code{while} loop as long as there are items in the work list. In
  10572. each iteration, a node is popped from the work list and processed. The
  10573. \code{input} for the node is computed by taking the join of the
  10574. abstract states of all the predecessor nodes. The \code{transfer}
  10575. function is then applied to obtain the \code{output} abstract
  10576. state. If the output differs from the previous state for this block,
  10577. the mapping for this block is updated and its successor nodes are
  10578. pushed onto the work list.
  10579. \begin{figure}[tb]
  10580. \begin{lstlisting}
  10581. (define (analyze-dataflow G transfer bottom join)
  10582. (define mapping (make-hash))
  10583. (for ([v (in-vertices G)])
  10584. (dict-set! mapping v bottom))
  10585. (define worklist (make-queue))
  10586. (for ([v (in-vertices G)])
  10587. (enqueue! worklist v))
  10588. (define trans-G (transpose G))
  10589. (while (not (queue-empty? worklist))
  10590. (define node (dequeue! worklist))
  10591. (define input (for/fold ([state bottom])
  10592. ([pred (in-neighbors trans-G node)])
  10593. (join state (dict-ref mapping pred))))
  10594. (define output (transfer node input))
  10595. (cond [(not (equal? output (dict-ref mapping node)))
  10596. (dict-set! mapping node output)
  10597. (for ([v (in-neighbors G node)])
  10598. (enqueue! worklist v))]))
  10599. mapping)
  10600. \end{lstlisting}
  10601. \caption{Generic work list algorithm for dataflow analysis}
  10602. \label{fig:generic-dataflow}
  10603. \end{figure}
  10604. Having discussed the two complications that arise from adding support
  10605. for assignment and loops, we turn to discussing the one new compiler
  10606. pass and the significant changes to existing passes.
  10607. \section{Convert Assignments}
  10608. \label{sec:convert-assignments}
  10609. Recall that in Section~\ref{sec:assignment-scoping} we learned that
  10610. the combination of assignments and lexically-scoped functions requires
  10611. that we box those variables that are both assigned-to and that appear
  10612. free inside a \code{lambda}. The purpose of the
  10613. \code{convert-assignments} pass is to carry out that transformation.
  10614. We recommend placing this pass after \code{uniquify} but before
  10615. \code{reveal-functions}.
  10616. Consider again the first example from
  10617. Section~\ref{sec:assignment-scoping}:
  10618. \begin{lstlisting}
  10619. (let ([x 0])
  10620. (let ([y 0])
  10621. (let ([z 20])
  10622. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  10623. (begin
  10624. (set! x 10)
  10625. (set! y 12)
  10626. (f y))))))
  10627. \end{lstlisting}
  10628. The variables \code{x} and \code{y} are assigned-to. The variables
  10629. \code{x} and \code{z} occur free inside the \code{lambda}. Thus,
  10630. variable \code{x} needs to be boxed but not \code{y} and \code{z}.
  10631. The boxing of \code{x} consists of three transformations: initialize
  10632. \code{x} with a vector, replace reads from \code{x} with
  10633. \code{vector-ref}'s, and replace each \code{set!} on \code{x} with a
  10634. \code{vector-set!}. The output of \code{convert-assignments} for this
  10635. example is as follows.
  10636. \begin{lstlisting}
  10637. (define (main) : Integer
  10638. (let ([x0 (vector 0)])
  10639. (let ([y1 0])
  10640. (let ([z2 20])
  10641. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  10642. (+ a3 (+ (vector-ref x0 0) z2)))])
  10643. (begin
  10644. (vector-set! x0 0 10)
  10645. (set! y1 12)
  10646. (f4 y1)))))))
  10647. \end{lstlisting}
  10648. \paragraph{Assigned \& Free}
  10649. We recommend defining an auxiliary function named
  10650. \code{assigned\&free} that takes an expression and simultaneously
  10651. computes 1) a set of assigned variables $A$, 2) a set $F$ of variables
  10652. that occur free within lambda's, and 3) a new version of the
  10653. expression that records which bound variables occurred in the
  10654. intersection of $A$ and $F$. You can use the struct
  10655. \code{AssignedFree} to do this. Consider the case for
  10656. $\LET{x}{\itm{rhs}}{\itm{body}}$. Suppose the the recursive call on
  10657. $\itm{rhs}$ produces $\itm{rhs}'$, $A_r$, and $F_r$ and the recursive
  10658. call on the $\itm{body}$ produces $\itm{body}'$, $A_b$, and $F_b$. If
  10659. $x$ is in $A_b\cap F_b$, then transforms the \code{Let} as follows.
  10660. \begin{lstlisting}
  10661. (Let |$x$| |$rhs$| |$body$|)
  10662. |$\Rightarrow$|
  10663. (Let (AssignedFree |$x$|) |$rhs'$| |$body'$|)
  10664. \end{lstlisting}
  10665. If $x$ is not in $A_b\cap F_b$ then omit the use of \code{AssignedFree}.
  10666. The set of assigned variables for this \code{Let} is
  10667. $A_r \cup (A_b - \{x\})$
  10668. and the set of variables free in lambda's is
  10669. $F_r \cup (F_b - \{x\})$.
  10670. The case for $\SETBANG{x}{\itm{rhs}}$ is straightforward but
  10671. important. Recursively process \itm{rhs} to obtain \itm{rhs'}, $A_r$,
  10672. and $F_r$. The result is $\SETBANG{x}{\itm{rhs'}}$, $\{x\} \cup A_r$,
  10673. and $F_r$.
  10674. The case for $\LAMBDA{\itm{params}}{T}{\itm{body}}$ is a bit more
  10675. involved. Let \itm{body'}, $A_b$, and $F_b$ be the result of
  10676. recursively processing \itm{body}. Wrap each of parameter that occurs
  10677. in $A_b \cap F_b$ with \code{AssignedFree} to produce \itm{params'}.
  10678. Let $P$ be the set of parameter names in \itm{params}. The result is
  10679. $\LAMBDA{\itm{params'}}{T}{\itm{body'}}$, $A_b - P$, and $(F_b \cup
  10680. \mathrm{FV}(\itm{body})) - P$, where $\mathrm{FV}$ computes the free
  10681. variables of an expression (see Chapter~\ref{ch:Rlam}).
  10682. \paragraph{Convert Assignments}
  10683. Next we discuss the \code{convert-assignment} pass with its auxiliary
  10684. functions for expressions and definitions. The function for
  10685. expressions, \code{cnvt-assign-exp}, should take an expression and a
  10686. set of assigned-and-free variables (obtained from the result of
  10687. \code{assigned\&free}. In the case for $\VAR{x}$, if $x$ is
  10688. assigned-and-free, then unbox it by translating $\VAR{x}$ to a
  10689. \code{vector-ref}.
  10690. \begin{lstlisting}
  10691. (Var |$x$|)
  10692. |$\Rightarrow$|
  10693. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  10694. \end{lstlisting}
  10695. %
  10696. In the case for $\LET{\LP\code{AssignedFree}\,
  10697. x\RP}{\itm{rhs}}{\itm{body}}$, recursively process \itm{rhs} to
  10698. obtain \itm{rhs'}. Next, recursively process \itm{body} to obtain
  10699. \itm{body'} but with $x$ added to the set of assigned-and-free
  10700. variables. Translate the let-expression as follows to bind $x$ to a
  10701. boxed value.
  10702. \begin{lstlisting}
  10703. (Let (AssignedFree |$x$|) |$rhs$| |$body$|)
  10704. |$\Rightarrow$|
  10705. (Let |$x$| (Prim 'vector (list |$rhs'$|)) |$body'$|)
  10706. \end{lstlisting}
  10707. %
  10708. In the case for $\SETBANG{x}{\itm{rhs}}$, recursively process
  10709. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in the assigned-and-free
  10710. variables, translate the \code{set!} into a \code{vector-set!}
  10711. as follows.
  10712. \begin{lstlisting}
  10713. (SetBang |$x$| |$\itm{rhs}$|)
  10714. |$\Rightarrow$|
  10715. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  10716. \end{lstlisting}
  10717. %
  10718. The case for \code{Lambda} is non-trivial, but it is similar to the
  10719. case for function definitions, which we discuss next.
  10720. The auxiliary function for definitions, \code{cnvt-assign-def},
  10721. applies assignment conversion to function definitions.
  10722. We translate a function definition as follows.
  10723. \begin{lstlisting}
  10724. (Def |$f$| |$\itm{params}$| |$T$| |$\itm{info}$| |$\itm{body_1}$|)
  10725. |$\Rightarrow$|
  10726. (Def |$f$| |$\itm{params'}$| |$T$| |$\itm{info}$| |$\itm{body_4}$|)
  10727. \end{lstlisting}
  10728. So it remains to explain \itm{params'} and $\itm{body}_4$.
  10729. Let \itm{body_2}, $A_b$, and $F_b$ be the result of
  10730. \code{assigned\&free} on $\itm{body_1}$.
  10731. Let $P$ be the parameter names in \itm{params}.
  10732. We then apply \code{cnvt-assign-exp} to $\itm{body_2}$ to
  10733. obtain \itm{body_3}, passing $A_b \cap F_b \cap P$
  10734. as the set of assigned-and-free variables.
  10735. Finally, we obtain \itm{body_4} by wrapping \itm{body_3}
  10736. in a sequence of let-expressions that box the parameters
  10737. that are in $A_b \cap F_b$.
  10738. %
  10739. Regarding \itm{params'}, change the names of the parameters that are
  10740. in $A_b \cap F_b$ to maintain uniqueness (and so the let-bound
  10741. variables can retain the original names). Recall the second example in
  10742. Section~\ref{sec:assignment-scoping} involving a counter
  10743. abstraction. The following is the output of assignment version for
  10744. function \code{f}.
  10745. \begin{lstlisting}
  10746. (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  10747. (vector
  10748. (lambda: () : Integer x1)
  10749. (lambda: () : Void (set! x1 (+ 1 x1)))))
  10750. |$\Rightarrow$|
  10751. (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  10752. (let ([x1 (vector param_x1)])
  10753. (vector (lambda: () : Integer (vector-ref x1 0))
  10754. (lambda: () : Void
  10755. (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  10756. \end{lstlisting}
  10757. \section{Remove Complex Operands}
  10758. \label{sec:rco-loop}
  10759. The three new language forms, \code{while}, \code{set!}, and
  10760. \code{begin} are all complex expressions and their subexpressions are
  10761. allowed to be complex. Figure~\ref{fig:Rfun-anf-syntax} defines the
  10762. output language \LangFunANF{} of this pass.
  10763. \begin{figure}[tp]
  10764. \centering
  10765. \fbox{
  10766. \begin{minipage}{0.96\textwidth}
  10767. \small
  10768. \[
  10769. \begin{array}{rcl}
  10770. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  10771. \MID \VOID{} } \\
  10772. \Exp &::=& \ldots \MID \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  10773. &\MID& \WHILE{\Exp}{\Exp} \MID \SETBANG{\Var}{\Exp}
  10774. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  10775. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  10776. R^{\dagger}_8 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  10777. \end{array}
  10778. \]
  10779. \end{minipage}
  10780. }
  10781. \caption{\LangLoopANF{} is \LangLoop{} in administrative normal form (ANF).}
  10782. \label{fig:Rwhile-anf-syntax}
  10783. \end{figure}
  10784. As usual, when a complex expression appears in a grammar position that
  10785. needs to be atomic, such as the argument of a primitive operator, we
  10786. must introduce a temporary variable and bind it to the complex
  10787. expression. This approach applies, unchanged, to handle the new
  10788. language forms. For example, in the following code there are two
  10789. \code{begin} expressions appearing as arguments to \code{+}. The
  10790. output of \code{rco-exp} is shown below, in which the \code{begin}
  10791. expressions have been bound to temporary variables. Recall that
  10792. \code{let} expressions in \LangLoopANF{} are allowed to have
  10793. arbitrary expressions in their right-hand-side expression, so it is
  10794. fine to place \code{begin} there.
  10795. \begin{lstlisting}
  10796. (let ([x0 10])
  10797. (let ([y1 0])
  10798. (+ (+ (begin (set! y1 (read)) x0)
  10799. (begin (set! x0 (read)) y1))
  10800. x0)))
  10801. |$\Rightarrow$|
  10802. (let ([x0 10])
  10803. (let ([y1 0])
  10804. (let ([tmp2 (begin (set! y1 (read)) x0)])
  10805. (let ([tmp3 (begin (set! x0 (read)) y1)])
  10806. (let ([tmp4 (+ tmp2 tmp3)])
  10807. (+ tmp4 x0))))))
  10808. \end{lstlisting}
  10809. \section{Explicate Control and \LangCLoop{}}
  10810. \label{sec:explicate-loop}
  10811. Recall that in the \code{explicate-control} pass we define one helper
  10812. function for each kind of position in the program. For the \LangVar{}
  10813. language of integers and variables we needed kinds of positions:
  10814. assignment and tail. The \code{if} expressions of \LangIf{} introduced
  10815. predicate positions. For \LangLoop{}, the \code{begin} expression introduces
  10816. yet another kind of position: effect position. Except for the last
  10817. subexpression, the subexpressions inside a \code{begin} are evaluated
  10818. only for their effect. Their result values are discarded. We can
  10819. generate better code by taking this fact into account.
  10820. The output language of \code{explicate-control} is \LangCLoop{}
  10821. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  10822. \LangCLam{}. The only syntactic difference is that \code{Call},
  10823. \code{vector-set!}, and \code{read} may also appear as statements.
  10824. The most significant difference between \LangCLam{} and \LangCLoop{}
  10825. is that the control-flow graphs of the later may contain cycles.
  10826. \begin{figure}[tp]
  10827. \fbox{
  10828. \begin{minipage}{0.96\textwidth}
  10829. \small
  10830. \[
  10831. \begin{array}{lcl}
  10832. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  10833. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  10834. &\MID& \CALL{\Atm}{\LP\Atm\ldots\RP} \MID \READ{}\\
  10835. &\MID& \LP\key{Prim}~\key{'vector-set!}\,\LP\key{list}\,\Atm\,\INT{\Int}\,\Atm\RP\RP \\
  10836. \Def &::=& \DEF{\itm{label}}{\LP\LS\Var\key{:}\Type\RS\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}\\
  10837. \LangCLoopM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  10838. \end{array}
  10839. \]
  10840. \end{minipage}
  10841. }
  10842. \caption{The abstract syntax of \LangCLoop{}, extending \LangCLam{} (Figure~\ref{fig:c4-syntax}).}
  10843. \label{fig:c7-syntax}
  10844. \end{figure}
  10845. The new auxiliary function \code{explicate-effect} takes an expression
  10846. (in an effect position) and a promise of a continuation block. The
  10847. function returns a promise for a $\Tail$ that includes the generated
  10848. code for the input expression followed by the continuation block. If
  10849. the expression is obviously pure, that is, never causes side effects,
  10850. then the expression can be removed, so the result is just the
  10851. continuation block.
  10852. %
  10853. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  10854. case. First, you will need a fresh label $\itm{loop}$ for the top of
  10855. the loop. Recursively process the \itm{body} (in effect position)
  10856. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  10857. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  10858. \itm{body'} as the then-branch and the continuation block as the
  10859. else-branch. The result should be added to the control-flow graph with
  10860. the label \itm{loop}. The result for the whole \code{while} loop is a
  10861. \code{goto} to the \itm{loop} label. Note that the loop should only be
  10862. added to the control-flow graph if the loop is indeed used, which can
  10863. be accomplished using \code{delay}.
  10864. The auxiliary functions for tail, assignment, and predicate positions
  10865. need to be updated. The three new language forms, \code{while},
  10866. \code{set!}, and \code{begin}, can appear in assignment and tail
  10867. positions. Only \code{begin} may appear in predicate positions; the
  10868. other two have result type \code{Void}.
  10869. \section{Select Instructions}
  10870. \label{sec:select-instructions-loop}
  10871. Only three small additions are needed in the
  10872. \code{select-instructions} pass to handle the changes to \LangCLoop{}. That
  10873. is, \code{Call}, \code{read}, and \code{vector-set!} may now appear as
  10874. stand-alone statements instead of only appearing on the right-hand
  10875. side of an assignment statement. The code generation is nearly
  10876. identical; just leave off the instruction for moving the result into
  10877. the left-hand side.
  10878. \section{Register Allocation}
  10879. \label{sec:register-allocation-loop}
  10880. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  10881. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  10882. which complicates the liveness analysis needed for register
  10883. allocation.
  10884. \subsection{Liveness Analysis}
  10885. \label{sec:liveness-analysis-r8}
  10886. We recommend using the generic \code{analyze-dataflow} function that
  10887. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  10888. perform liveness analysis, replacing the code in
  10889. \code{uncover-live-CFG} that processed the basic blocks in topological
  10890. order (Section~\ref{sec:liveness-analysis-Rif}).
  10891. The \code{analyze-dataflow} function has four parameters.
  10892. \begin{enumerate}
  10893. \item The first parameter \code{G} should be a directed graph from the
  10894. \code{racket/graph} package (see the sidebar in
  10895. Section~\ref{sec:build-interference}) that represents the
  10896. control-flow graph.
  10897. \item The second parameter \code{transfer} is a function that applies
  10898. liveness analysis to a basic block. It takes two parameters: the
  10899. label for the block to analyze and the live-after set for that
  10900. block. The transfer function should return the live-before set for
  10901. the block. Also, as a side-effect, it should update the block's
  10902. $\itm{info}$ with the liveness information for each instruction. To
  10903. implement the \code{transfer} function, you should be able to reuse
  10904. the code you already have for analyzing basic blocks.
  10905. \item The third and fourth parameters of \code{analyze-dataflow} are
  10906. \code{bottom} and \code{join} for the lattice of abstract states,
  10907. i.e. sets of locations. The bottom of the lattice is the empty set
  10908. \code{(set)} and the join operator is \code{set-union}.
  10909. \end{enumerate}
  10910. \begin{figure}[p]
  10911. \begin{tikzpicture}[baseline=(current bounding box.center)]
  10912. \node (Rfun) at (0,2) {\large \LangLoop{}};
  10913. \node (Rfun-2) at (3,2) {\large \LangLoop{}};
  10914. \node (Rfun-3) at (6,2) {\large \LangLoop{}};
  10915. \node (Rfun-4) at (9,2) {\large \LangLoopFunRef{}};
  10916. \node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  10917. \node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  10918. \node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  10919. \node (F1-4) at (3,0) {\large \LangLoopAlloc{}};
  10920. \node (F1-5) at (0,0) {\large \LangLoopAlloc{}};
  10921. \node (C3-2) at (3,-2) {\large \LangCLoop{}};
  10922. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  10923. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  10924. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  10925. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  10926. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  10927. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  10928. %% \path[->,bend left=15] (Rfun) edge [above] node
  10929. %% {\ttfamily\footnotesize type-check} (Rfun-2);
  10930. \path[->,bend left=15] (Rfun) edge [above] node
  10931. {\ttfamily\footnotesize shrink} (Rfun-2);
  10932. \path[->,bend left=15] (Rfun-2) edge [above] node
  10933. {\ttfamily\footnotesize uniquify} (Rfun-3);
  10934. \path[->,bend left=15] (Rfun-3) edge [above] node
  10935. {\ttfamily\footnotesize reveal-functions} (Rfun-4);
  10936. \path[->,bend left=15] (Rfun-4) edge [right] node
  10937. {\ttfamily\footnotesize convert-assignments} (F1-1);
  10938. \path[->,bend left=15] (F1-1) edge [below] node
  10939. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  10940. \path[->,bend right=15] (F1-2) edge [above] node
  10941. {\ttfamily\footnotesize limit-fun.} (F1-3);
  10942. \path[->,bend right=15] (F1-3) edge [above] node
  10943. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  10944. \path[->,bend right=15] (F1-4) edge [above] node
  10945. {\ttfamily\footnotesize remove-complex.} (F1-5);
  10946. \path[->,bend right=15] (F1-5) edge [right] node
  10947. {\ttfamily\footnotesize explicate-control} (C3-2);
  10948. \path[->,bend left=15] (C3-2) edge [left] node
  10949. {\ttfamily\footnotesize select-instr.} (x86-2);
  10950. \path[->,bend right=15] (x86-2) edge [left] node
  10951. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  10952. \path[->,bend right=15] (x86-2-1) edge [below] node
  10953. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  10954. \path[->,bend right=15] (x86-2-2) edge [left] node
  10955. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  10956. \path[->,bend left=15] (x86-3) edge [above] node
  10957. {\ttfamily\footnotesize patch-instr.} (x86-4);
  10958. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  10959. \end{tikzpicture}
  10960. \caption{Diagram of the passes for \LangLoop{} (loops and assignment).}
  10961. \label{fig:Rwhile-passes}
  10962. \end{figure}
  10963. Figure~\ref{fig:Rwhile-passes} provides an overview of all the passes needed
  10964. for the compilation of \LangLoop{}.
  10965. \section{Challenge: Arrays}
  10966. \label{sec:arrays}
  10967. In Chapter~\ref{ch:Rvec} we studied tuples, that is, sequences of
  10968. elements whose length is determined at compile-time and where each
  10969. element of a tuple may have a different type (they are
  10970. heterogeous). This challenge is also about sequences, but this time
  10971. the length is determined at run-time and all the elements have the same
  10972. type (they are homogeneous). We use the term ``array'' for this later
  10973. kind of sequence.
  10974. The Racket language does not distinguish between tuples and arrays,
  10975. they are both represented by vectors. However, Typed Racket
  10976. distinguishes between tuples and arrays: the \code{Vector} type is for
  10977. tuples and the \code{Vectorof} type is for arrays.
  10978. %
  10979. Figure~\ref{fig:Rvecof-concrete-syntax} defines the concrete syntax
  10980. for \LangArray{}, extending \LangLoop{} with the \code{Vectorof} type
  10981. and the \code{make-vector} primitive operator for creating an array,
  10982. whose arguments are the length of the array and an initial value for
  10983. all the elements in the array. The \code{vector-length},
  10984. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  10985. for tuples become overloaded for use with arrays.
  10986. %
  10987. We also include integer multiplication in \LangArray{}, as it is
  10988. useful in many examples involving arrays such as computing the
  10989. inner-product of two arrays (Figure~\ref{fig:inner-product}).
  10990. \begin{figure}[tp]
  10991. \centering
  10992. \fbox{
  10993. \begin{minipage}{0.96\textwidth}
  10994. \small
  10995. \[
  10996. \begin{array}{lcl}
  10997. \Type &::=& \ldots \MID \LP \key{Vectorof}~\Type \RP \\
  10998. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  10999. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \MID \CMUL{\Exp}{\Exp}\\
  11000. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  11001. &\MID& \gray{\key{\#t} \MID \key{\#f}
  11002. \MID \LP\key{and}\;\Exp\;\Exp\RP
  11003. \MID \LP\key{or}\;\Exp\;\Exp\RP
  11004. \MID \LP\key{not}\;\Exp\RP } \\
  11005. &\MID& \gray{ \LP\key{eq?}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  11006. &\MID& \gray{ \LP\key{vector}\;\Exp\ldots\RP \MID
  11007. \LP\key{vector-ref}\;\Exp\;\Int\RP} \\
  11008. &\MID& \gray{\LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP\MID \LP\key{void}\RP
  11009. \MID \LP\Exp \; \Exp\ldots\RP } \\
  11010. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP
  11011. \MID \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  11012. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  11013. \MID \CBEGIN{\Exp\ldots}{\Exp}
  11014. \MID \CWHILE{\Exp}{\Exp} } \\
  11015. &\MID& \CMAKEVEC{\Exp}{\Exp} \\
  11016. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  11017. \LangArray{} &::=& \gray{\Def\ldots \; \Exp}
  11018. \end{array}
  11019. \]
  11020. \end{minipage}
  11021. }
  11022. \caption{The concrete syntax of \LangArray{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  11023. \label{fig:Rvecof-concrete-syntax}
  11024. \end{figure}
  11025. \begin{figure}[tp]
  11026. \begin{lstlisting}
  11027. (define (inner-product [A : (Vectorof Integer)] [B : (Vectorof Integer)]
  11028. [n : Integer]) : Integer
  11029. (let ([i 0])
  11030. (let ([prod 0])
  11031. (begin
  11032. (while (< i n)
  11033. (begin
  11034. (set! prod (+ prod (* (vector-ref A i)
  11035. (vector-ref B i))))
  11036. (set! i (+ i 1))
  11037. ))
  11038. prod))))
  11039. (let ([A (make-vector 2 2)])
  11040. (let ([B (make-vector 2 3)])
  11041. (+ (inner-product A B 2)
  11042. 30)))
  11043. \end{lstlisting}
  11044. \caption{Example program that computes the inner-product.}
  11045. \label{fig:inner-product}
  11046. \end{figure}
  11047. The type checker for \LangArray{} is define in
  11048. Figure~\ref{fig:type-check-Rvecof}. The result type of
  11049. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  11050. of the intializing expression. The length expression is required to
  11051. have type \code{Integer}. The type checking of the operators
  11052. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  11053. updated to handle the situation where the vector has type
  11054. \code{Vectorof}. In these cases we translate the operators to their
  11055. \code{vectorof} form so that later passes can easily distinguish
  11056. between operations on tuples versus arrays. We override the
  11057. \code{operator-types} method to provide the type signature for
  11058. multiplication: it takes two integers and returns an integer. To
  11059. support injection and projection of arrays to the \code{Any} type
  11060. (Section~\ref{sec:Rany-lang}), we also override the \code{flat-ty?}
  11061. predicate.
  11062. \begin{figure}[tbp]
  11063. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11064. (define type-check-Rvecof-class
  11065. (class type-check-Rwhile-class
  11066. (super-new)
  11067. (inherit check-type-equal?)
  11068. (define/override (flat-ty? ty)
  11069. (match ty
  11070. ['(Vectorof Any) #t]
  11071. [else (super flat-ty? ty)]))
  11072. (define/override (operator-types)
  11073. (append '((* . ((Integer Integer) . Integer)))
  11074. (super operator-types)))
  11075. (define/override (type-check-exp env)
  11076. (lambda (e)
  11077. (define recur (type-check-exp env))
  11078. (match e
  11079. [(Prim 'make-vector (list e1 e2))
  11080. (define-values (e1^ t1) (recur e1))
  11081. (define-values (e2^ elt-type) (recur e2))
  11082. (define vec-type `(Vectorof ,elt-type))
  11083. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  11084. vec-type)]
  11085. [(Prim 'vector-ref (list e1 e2))
  11086. (define-values (e1^ t1) (recur e1))
  11087. (define-values (e2^ t2) (recur e2))
  11088. (match* (t1 t2)
  11089. [(`(Vectorof ,elt-type) 'Integer)
  11090. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  11091. [(other wise) ((super type-check-exp env) e)])]
  11092. [(Prim 'vector-set! (list e1 e2 e3) )
  11093. (define-values (e-vec t-vec) (recur e1))
  11094. (define-values (e2^ t2) (recur e2))
  11095. (define-values (e-arg^ t-arg) (recur e3))
  11096. (match t-vec
  11097. [`(Vectorof ,elt-type)
  11098. (check-type-equal? elt-type t-arg e)
  11099. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  11100. [else ((super type-check-exp env) e)])]
  11101. [(Prim 'vector-length (list e1))
  11102. (define-values (e1^ t1) (recur e1))
  11103. (match t1
  11104. [`(Vectorof ,t)
  11105. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  11106. [else ((super type-check-exp env) e)])]
  11107. [else ((super type-check-exp env) e)])))
  11108. ))
  11109. (define (type-check-Rvecof p)
  11110. (send (new type-check-Rvecof-class) type-check-program p))
  11111. \end{lstlisting}
  11112. \caption{Type checker for the \LangArray{} language.}
  11113. \label{fig:type-check-Rvecof}
  11114. \end{figure}
  11115. The interpreter for \LangArray{} is defined in
  11116. Figure~\ref{fig:interp-Rvecof}. The \code{make-vector} operator is
  11117. implemented with Racket's \code{make-vector} function and
  11118. multiplication is \code{fx*}, multiplication for \code{fixnum}
  11119. integers.
  11120. \begin{figure}[tbp]
  11121. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11122. (define interp-Rvecof-class
  11123. (class interp-Rwhile-class
  11124. (super-new)
  11125. (define/override (interp-op op)
  11126. (verbose "Rvecof/interp-op" op)
  11127. (match op
  11128. ['make-vector make-vector]
  11129. ['* fx*]
  11130. [else (super interp-op op)]))
  11131. ))
  11132. (define (interp-Rvecof p)
  11133. (send (new interp-Rvecof-class) interp-program p))
  11134. \end{lstlisting}
  11135. \caption{Interpreter for \LangArray{}.}
  11136. \label{fig:interp-Rvecof}
  11137. \end{figure}
  11138. \subsection{Data Representation}
  11139. \label{sec:array-rep}
  11140. Just like tuples, we store arrays on the heap which means that the
  11141. garbage collector will need to inspect arrays. An immediate thought is
  11142. to use the same representation for arrays that we use for tuples.
  11143. However, we limit tuples to a length of $50$ so that their length and
  11144. pointer mask can fit into the 64-bit tag at the beginning of each
  11145. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  11146. millions of elements, so we need more bits to store the length.
  11147. However, because arrays are homogeneous, we only need $1$ bit for the
  11148. pointer mask instead of one bit per array elements. Finally, the
  11149. garbage collector will need to be able to distinguish between tuples
  11150. and arrays, so we need to reserve $1$ bit for that purpose. So we
  11151. arrive at the following layout for the 64-bit tag at the beginning of
  11152. an array:
  11153. \begin{itemize}
  11154. \item The right-most bit is the forwarding bit, just like in a tuple.
  11155. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  11156. it is not.
  11157. \item The next bit to the left is the pointer mask. A $0$ indicates
  11158. that none of the elements are pointers to the heap and a $1$
  11159. indicates that all of the elements are pointers.
  11160. \item The next $61$ bits store the length of the array.
  11161. \item The left-most bit distinguishes between a tuple ($0$) versus an
  11162. array ($1$).
  11163. \end{itemize}
  11164. Recall that in Chapter~\ref{ch:Rdyn}, we use a $3$-bit tag to
  11165. differentiate the kinds of values that have been injected into the
  11166. \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  11167. to indicate that the value is an array.
  11168. In the following subsections we provide hints regarding how to update
  11169. the passes to handle arrays.
  11170. \subsection{Reveal Casts}
  11171. The array-access operators \code{vectorof-ref} and
  11172. \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  11173. \code{any-vector-set!} operators of Chapter~\ref{ch:Rdyn} in
  11174. that the type checker cannot tell whether the index will be in bounds,
  11175. so the bounds check must be performed at run time. Recall that the
  11176. \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  11177. an \code{If} arround a vector reference for update to check whether
  11178. the index is less than the length. You should do the same for
  11179. \code{vectorof-ref} and \code{vectorof-set!} .
  11180. In addition, the handling of the \code{any-vector} operators in
  11181. \code{reveal-casts} needs to be updated to account for arrays that are
  11182. injected to \code{Any}. For the \code{any-vector-length} operator, the
  11183. generated code should test whether the tag is for tuples (\code{010})
  11184. or arrays (\code{110}) and then dispatch to either
  11185. \code{any-vector-length} or \code{any-vectorof-length}. For the later
  11186. we add a case in \code{select-instructions} to generate the
  11187. appropriate instructions for accessing the array length from the
  11188. header of an array.
  11189. For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  11190. the generated code needs to check that the index is less than the
  11191. vector length, so like the code for \code{any-vector-length}, check
  11192. the tag to determine whether to use \code{any-vector-length} or
  11193. \code{any-vectorof-length} for this purpose. Once the bounds checking
  11194. is complete, the generated code can use \code{any-vector-ref} and
  11195. \code{any-vector-set!} for both tuples and arrays because the
  11196. instructions used for those operators do not look at the tag at the
  11197. front of the tuple or array.
  11198. \subsection{Expose Allocation}
  11199. This pass should translate the \code{make-vector} operator into
  11200. lower-level operations. In particular, the new AST node
  11201. $\LP\key{AllocateArray}~\Exp~\Type\RP$ allocates an array of the
  11202. length specified by the $\Exp$, but does not initialize the elements
  11203. of the array. (Analogous to the \code{Allocate} AST node for tuples.)
  11204. The $\Type$ argument must be $\LP\key{Vectorof}~T\RP$ where $T$ is the
  11205. element type for the array. Regarding the initialization of the array,
  11206. we recommend generated a \code{while} loop that uses
  11207. \code{vector-set!} to put the initializing value into every element of
  11208. the array.
  11209. \subsection{Remove Complex Operands}
  11210. Add cases in the \code{rco-atom} and \code{rco-exp} for
  11211. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  11212. complex and its subexpression must be atomic.
  11213. \subsection{Explicate Control}
  11214. Add cases for \code{AllocateArray} to \code{explicate-tail} and
  11215. \code{explicate-assign}.
  11216. \subsection{Select Instructions}
  11217. Generate instructions for \code{AllocateArray} similar to those for
  11218. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  11219. that the tag at the front of the array should instead use the
  11220. representation discussed in Section~\ref{sec:array-rep}.
  11221. Regarding \code{vectorof-length}, extract the length from the tag
  11222. according to the representation discussed in
  11223. Section~\ref{sec:array-rep}.
  11224. The instructions generated for \code{vectorof-ref} differ from those
  11225. for \code{vector-ref} (Section~\ref{sec:select-instructions-gc}) in
  11226. that the index is not a constant so the offset must be computed at
  11227. runtime, similar to the instructions generated for
  11228. \code{any-vector-of-ref} (Section~\ref{sec:select-Rany}). The same is
  11229. true for \code{vectorof-set!}. Also, the \code{vectorof-set!} may
  11230. appear in an assignment and as a stand-alone statement, so make sure
  11231. to handle both situations in this pass.
  11232. Finally, the instructions for \code{any-vectorof-length} should be
  11233. similar to those for \code{vectorof-length}, except that one must
  11234. first project the array by writing zeroes into the $3$-bit tag
  11235. \begin{exercise}\normalfont
  11236. Implement a compiler for the \LangArray{} language by extending your
  11237. compiler for \LangLoop{}. Test your compiler on a half dozen new
  11238. programs, including the one in Figure~\ref{fig:inner-product} and also
  11239. a program that multiplies two matrices. Note that matrices are
  11240. 2-dimensional arrays, but those can be encoded into 1-dimensional
  11241. arrays by laying out each row in the array, one after the next.
  11242. \end{exercise}
  11243. % Further Reading: dataflow analysis
  11244. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11245. \chapter{Gradual Typing}
  11246. \label{ch:Rgrad}
  11247. \index{subject}{gradual typing}
  11248. This chapter studies a language, \LangGrad{}, in which the programmer
  11249. can choose between static and dynamic type checking in different parts
  11250. of a program, thereby mixing the statically typed \LangLoop{} language
  11251. with the dynamically typed \LangDyn{}. There are several approaches to
  11252. mixing static and dynamic typing, including multi-language
  11253. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  11254. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  11255. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  11256. programmer controls the amount of static versus dynamic checking by
  11257. adding or removing type annotations on parameters and
  11258. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  11259. %
  11260. The concrete syntax of \LangGrad{} is defined in
  11261. Figure~\ref{fig:Rgrad-concrete-syntax} and its abstract syntax is defined
  11262. in Figure~\ref{fig:Rgrad-syntax}. The main syntactic difference between
  11263. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  11264. non-terminals that make type annotations optional. The return types
  11265. are not optional in the abstract syntax; the parser fills in
  11266. \code{Any} when the return type is not specified in the concrete
  11267. syntax.
  11268. \begin{figure}[tp]
  11269. \centering
  11270. \fbox{
  11271. \begin{minipage}{0.96\textwidth}
  11272. \small
  11273. \[
  11274. \begin{array}{lcl}
  11275. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  11276. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  11277. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  11278. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  11279. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  11280. &\MID& \gray{\key{\#t} \MID \key{\#f}
  11281. \MID (\key{and}\;\Exp\;\Exp)
  11282. \MID (\key{or}\;\Exp\;\Exp)
  11283. \MID (\key{not}\;\Exp) } \\
  11284. &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  11285. &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  11286. (\key{vector-ref}\;\Exp\;\Int)} \\
  11287. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  11288. \MID (\Exp \; \Exp\ldots) } \\
  11289. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  11290. \MID \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  11291. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  11292. \MID \CBEGIN{\Exp\ldots}{\Exp}
  11293. \MID \CWHILE{\Exp}{\Exp} } \\
  11294. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  11295. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  11296. \end{array}
  11297. \]
  11298. \end{minipage}
  11299. }
  11300. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  11301. \label{fig:Rgrad-concrete-syntax}
  11302. \end{figure}
  11303. \begin{figure}[tp]
  11304. \centering
  11305. \fbox{
  11306. \begin{minipage}{0.96\textwidth}
  11307. \small
  11308. \[
  11309. \begin{array}{lcl}
  11310. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  11311. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  11312. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  11313. &\MID& \gray{ \BOOL{\itm{bool}}
  11314. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  11315. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  11316. \MID \APPLY{\Exp}{\Exp\ldots} }\\
  11317. &\MID& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  11318. &\MID& \gray{ \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  11319. &\MID& \gray{ \WHILE{\Exp}{\Exp} } \\
  11320. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  11321. \LangGradM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11322. \end{array}
  11323. \]
  11324. \end{minipage}
  11325. }
  11326. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  11327. \label{fig:Rgrad-syntax}
  11328. \end{figure}
  11329. Both the type checker and the interpreter for \LangGrad{} require some
  11330. interesting changes to enable gradual typing, which we discuss in the
  11331. next two sections in the context of the \code{map-vec} example from
  11332. Chapter~\ref{ch:Rfun}. In Figure~\ref{fig:gradual-map-vec} we
  11333. revised the \code{map-vec} example, omitting the type annotations from
  11334. the \code{add1} function.
  11335. \begin{figure}[btp]
  11336. % gradual_test_9.rkt
  11337. \begin{lstlisting}
  11338. (define (map-vec [f : (Integer -> Integer)]
  11339. [v : (Vector Integer Integer)])
  11340. : (Vector Integer Integer)
  11341. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11342. (define (add1 x) (+ x 1))
  11343. (vector-ref (map-vec add1 (vector 0 41)) 1)
  11344. \end{lstlisting}
  11345. \caption{A partially-typed version of the \code{map-vec} example.}
  11346. \label{fig:gradual-map-vec}
  11347. \end{figure}
  11348. \section{Type Checking \LangGrad{} and \LangCast{}}
  11349. \label{sec:gradual-type-check}
  11350. The type checker for \LangGrad{} uses the \code{Any} type for missing
  11351. parameter and return types. For example, the \code{x} parameter of
  11352. \code{add1} in Figure~\ref{fig:gradual-map-vec} is given the type
  11353. \code{Any} and the return type of \code{add1} is \code{Any}. Next
  11354. consider the \code{+} operator inside \code{add1}. It expects both
  11355. arguments to have type \code{Integer}, but its first argument \code{x}
  11356. has type \code{Any}. In a gradually typed language, such differences
  11357. are allowed so long as the types are \emph{consistent}, that is, they
  11358. are equal except in places where there is an \code{Any} type. The type
  11359. \code{Any} is consistent with every other type.
  11360. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  11361. \begin{figure}[tbp]
  11362. \begin{lstlisting}
  11363. (define/public (consistent? t1 t2)
  11364. (match* (t1 t2)
  11365. [('Integer 'Integer) #t]
  11366. [('Boolean 'Boolean) #t]
  11367. [('Void 'Void) #t]
  11368. [('Any t2) #t]
  11369. [(t1 'Any) #t]
  11370. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11371. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  11372. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11373. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  11374. (consistent? rt1 rt2))]
  11375. [(other wise) #f]))
  11376. \end{lstlisting}
  11377. \caption{The consistency predicate on types.}
  11378. \label{fig:consistent}
  11379. \end{figure}
  11380. Returning to the \code{map-vec} example of
  11381. Figure~\ref{fig:gradual-map-vec}, the \code{add1} function has type
  11382. \code{(Any -> Any)} but parameter \code{f} of \code{map-vec} has type
  11383. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  11384. because the two types are consistent. In particular, \code{->} is
  11385. equal to \code{->} and because \code{Any} is consistent with
  11386. \code{Integer}.
  11387. Next consider a program with an error, such as applying the
  11388. \code{map-vec} to a function that sometimes returns a Boolean, as
  11389. shown in Figure~\ref{fig:map-vec-maybe-add1}. The type checker for
  11390. \LangGrad{} accepts this program because the type of \code{maybe-add1} is
  11391. consistent with the type of parameter \code{f} of \code{map-vec}, that
  11392. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  11393. Integer)}. One might say that a gradual type checker is optimistic
  11394. in that it accepts programs that might execute without a runtime type
  11395. error.
  11396. %
  11397. Unfortunately, running this program with input \code{1} triggers an
  11398. error when the \code{maybe-add1} function returns \code{\#t}. \LangGrad{}
  11399. performs checking at runtime to ensure the integrity of the static
  11400. types, such as the \code{(Integer -> Integer)} annotation on parameter
  11401. \code{f} of \code{map-vec}. This runtime checking is carried out by a
  11402. new \code{Cast} form that is inserted by the type checker. Thus, the
  11403. output of the type checker is a program in the \LangCast{} language, which
  11404. adds \code{Cast} to \LangLoop{}, as shown in
  11405. Figure~\ref{fig:Rgrad-prime-syntax}.
  11406. \begin{figure}[tp]
  11407. \centering
  11408. \fbox{
  11409. \begin{minipage}{0.96\textwidth}
  11410. \small
  11411. \[
  11412. \begin{array}{lcl}
  11413. \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  11414. \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  11415. \end{array}
  11416. \]
  11417. \end{minipage}
  11418. }
  11419. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:Rwhile-syntax}).}
  11420. \label{fig:Rgrad-prime-syntax}
  11421. \end{figure}
  11422. \begin{figure}[tbp]
  11423. \begin{lstlisting}
  11424. (define (map-vec [f : (Integer -> Integer)]
  11425. [v : (Vector Integer Integer)])
  11426. : (Vector Integer Integer)
  11427. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11428. (define (add1 x) (+ x 1))
  11429. (define (true) #t)
  11430. (define (maybe-add1 x) (if (eq? 0 (read)) (add1 x) (true)))
  11431. (vector-ref (map-vec maybe-add1 (vector 0 41)) 0)
  11432. \end{lstlisting}
  11433. \caption{A variant of the \code{map-vec} example with an error.}
  11434. \label{fig:map-vec-maybe-add1}
  11435. \end{figure}
  11436. Figure~\ref{fig:map-vec-cast} shows the output of the type checker for
  11437. \code{map-vec} and \code{maybe-add1}. The idea is that \code{Cast} is
  11438. inserted every time the type checker sees two types that are
  11439. consistent but not equal. In the \code{add1} function, \code{x} is
  11440. cast to \code{Integer} and the result of the \code{+} is cast to
  11441. \code{Any}. In the call to \code{map-vec}, the \code{add1} argument
  11442. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  11443. \begin{figure}[btp]
  11444. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11445. (define (map-vec [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  11446. : (Vector Integer Integer)
  11447. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11448. (define (add1 [x : Any]) : Any
  11449. (cast (+ (cast x Any Integer) 1) Integer Any))
  11450. (define (true) : Any (cast #t Boolean Any))
  11451. (define (maybe-add1 [x : Any]) : Any
  11452. (if (eq? 0 (read)) (add1 x) (true)))
  11453. (vector-ref (map-vec (cast maybe-add1 (Any -> Any) (Integer -> Integer))
  11454. (vector 0 41)) 0)
  11455. \end{lstlisting}
  11456. \caption{Output of type checking \code{map-vec}
  11457. and \code{maybe-add1}.}
  11458. \label{fig:map-vec-cast}
  11459. \end{figure}
  11460. The type checker for \LangGrad{} is defined in
  11461. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  11462. and \ref{fig:type-check-Rgradual-3}.
  11463. \begin{figure}[tbp]
  11464. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11465. (define type-check-gradual-class
  11466. (class type-check-Rwhile-class
  11467. (super-new)
  11468. (inherit operator-types type-predicates)
  11469. (define/override (type-check-exp env)
  11470. (lambda (e)
  11471. (define recur (type-check-exp env))
  11472. (match e
  11473. [(Prim 'vector-length (list e1))
  11474. (define-values (e1^ t) (recur e1))
  11475. (match t
  11476. [`(Vector ,ts ...)
  11477. (values (Prim 'vector-length (list e1^)) 'Integer)]
  11478. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  11479. [(Prim 'vector-ref (list e1 e2))
  11480. (define-values (e1^ t1) (recur e1))
  11481. (define-values (e2^ t2) (recur e2))
  11482. (check-consistent? t2 'Integer e)
  11483. (match t1
  11484. [`(Vector ,ts ...)
  11485. (match e2^
  11486. [(Int i)
  11487. (unless (and (0 . <= . i) (i . < . (length ts)))
  11488. (error 'type-check "invalid index ~a in ~a" i e))
  11489. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  11490. [else (define e1^^ (make-cast e1^ t1 'Any))
  11491. (define e2^^ (make-cast e2^ t2 'Integer))
  11492. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  11493. ['Any
  11494. (define e2^^ (make-cast e2^ t2 'Integer))
  11495. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  11496. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  11497. [(Prim 'vector-set! (list e1 e2 e3) )
  11498. (define-values (e1^ t1) (recur e1))
  11499. (define-values (e2^ t2) (recur e2))
  11500. (define-values (e3^ t3) (recur e3))
  11501. (check-consistent? t2 'Integer e)
  11502. (match t1
  11503. [`(Vector ,ts ...)
  11504. (match e2^
  11505. [(Int i)
  11506. (unless (and (0 . <= . i) (i . < . (length ts)))
  11507. (error 'type-check "invalid index ~a in ~a" i e))
  11508. (check-consistent? (list-ref ts i) t3 e)
  11509. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  11510. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  11511. [else
  11512. (define e1^^ (make-cast e1^ t1 'Any))
  11513. (define e2^^ (make-cast e2^ t2 'Integer))
  11514. (define e3^^ (make-cast e3^ t3 'Any))
  11515. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  11516. ['Any
  11517. (define e2^^ (make-cast e2^ t2 'Integer))
  11518. (define e3^^ (make-cast e3^ t3 'Any))
  11519. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  11520. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  11521. \end{lstlisting}
  11522. \caption{Type checker for the \LangGrad{} language, part 1.}
  11523. \label{fig:type-check-Rgradual-1}
  11524. \end{figure}
  11525. \begin{figure}[tbp]
  11526. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11527. [(Prim 'eq? (list e1 e2))
  11528. (define-values (e1^ t1) (recur e1))
  11529. (define-values (e2^ t2) (recur e2))
  11530. (check-consistent? t1 t2 e)
  11531. (define T (meet t1 t2))
  11532. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  11533. 'Boolean)]
  11534. [(Prim 'not (list e1))
  11535. (define-values (e1^ t1) (recur e1))
  11536. (match t1
  11537. ['Any
  11538. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  11539. (Bool #t) (Bool #f)))]
  11540. [else
  11541. (define-values (t-ret new-es^)
  11542. (type-check-op 'not (list t1) (list e1^) e))
  11543. (values (Prim 'not new-es^) t-ret)])]
  11544. [(Prim 'and (list e1 e2))
  11545. (recur (If e1 e2 (Bool #f)))]
  11546. [(Prim 'or (list e1 e2))
  11547. (define tmp (gensym 'tmp))
  11548. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  11549. [(Prim op es)
  11550. #:when (not (set-member? explicit-prim-ops op))
  11551. (define-values (new-es ts)
  11552. (for/lists (exprs types) ([e es])
  11553. (recur e)))
  11554. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  11555. (values (Prim op new-es^) t-ret)]
  11556. [(If e1 e2 e3)
  11557. (define-values (e1^ T1) (recur e1))
  11558. (define-values (e2^ T2) (recur e2))
  11559. (define-values (e3^ T3) (recur e3))
  11560. (check-consistent? T2 T3 e)
  11561. (match T1
  11562. ['Boolean
  11563. (define Tif (join T2 T3))
  11564. (values (If e1^ (make-cast e2^ T2 Tif)
  11565. (make-cast e3^ T3 Tif)) Tif)]
  11566. ['Any
  11567. (define Tif (meet T2 T3))
  11568. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  11569. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  11570. Tif)]
  11571. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  11572. [(HasType e1 T)
  11573. (define-values (e1^ T1) (recur e1))
  11574. (check-consistent? T1 T)
  11575. (values (make-cast e1^ T1 T) T)]
  11576. [(SetBang x e1)
  11577. (define-values (e1^ T1) (recur e1))
  11578. (define varT (dict-ref env x))
  11579. (check-consistent? T1 varT e)
  11580. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  11581. [(WhileLoop e1 e2)
  11582. (define-values (e1^ T1) (recur e1))
  11583. (check-consistent? T1 'Boolean e)
  11584. (define-values (e2^ T2) ((type-check-exp env) e2))
  11585. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  11586. \end{lstlisting}
  11587. \caption{Type checker for the \LangGrad{} language, part 2.}
  11588. \label{fig:type-check-Rgradual-2}
  11589. \end{figure}
  11590. \begin{figure}[tbp]
  11591. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11592. [(Apply e1 e2s)
  11593. (define-values (e1^ T1) (recur e1))
  11594. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  11595. (match T1
  11596. [`(,T1ps ... -> ,T1rt)
  11597. (for ([T2 T2s] [Tp T1ps])
  11598. (check-consistent? T2 Tp e))
  11599. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  11600. (make-cast e2 src tgt)))
  11601. (values (Apply e1^ e2s^^) T1rt)]
  11602. [`Any
  11603. (define e1^^ (make-cast e1^ 'Any
  11604. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  11605. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  11606. (make-cast e2 src 'Any)))
  11607. (values (Apply e1^^ e2s^^) 'Any)]
  11608. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  11609. [(Lambda params Tr e1)
  11610. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  11611. (match p
  11612. [`[,x : ,T] (values x T)]
  11613. [(? symbol? x) (values x 'Any)])))
  11614. (define-values (e1^ T1)
  11615. ((type-check-exp (append (map cons xs Ts) env)) e1))
  11616. (check-consistent? Tr T1 e)
  11617. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  11618. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  11619. [else ((super type-check-exp env) e)]
  11620. )))
  11621. \end{lstlisting}
  11622. \caption{Type checker for the \LangGrad{} language, part 3.}
  11623. \label{fig:type-check-Rgradual-3}
  11624. \end{figure}
  11625. \begin{figure}[tbp]
  11626. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11627. (define/public (join t1 t2)
  11628. (match* (t1 t2)
  11629. [('Integer 'Integer) 'Integer]
  11630. [('Boolean 'Boolean) 'Boolean]
  11631. [('Void 'Void) 'Void]
  11632. [('Any t2) t2]
  11633. [(t1 'Any) t1]
  11634. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11635. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  11636. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11637. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  11638. -> ,(join rt1 rt2))]))
  11639. (define/public (meet t1 t2)
  11640. (match* (t1 t2)
  11641. [('Integer 'Integer) 'Integer]
  11642. [('Boolean 'Boolean) 'Boolean]
  11643. [('Void 'Void) 'Void]
  11644. [('Any t2) 'Any]
  11645. [(t1 'Any) 'Any]
  11646. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11647. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  11648. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11649. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  11650. -> ,(meet rt1 rt2))]))
  11651. (define/public (make-cast e src tgt)
  11652. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  11653. (define/public (check-consistent? t1 t2 e)
  11654. (unless (consistent? t1 t2)
  11655. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  11656. (define/override (type-check-op op arg-types args e)
  11657. (match (dict-ref (operator-types) op)
  11658. [`(,param-types . ,return-type)
  11659. (for ([at arg-types] [pt param-types])
  11660. (check-consistent? at pt e))
  11661. (values return-type
  11662. (for/list ([e args] [s arg-types] [t param-types])
  11663. (make-cast e s t)))]
  11664. [else (error 'type-check-op "unrecognized ~a" op)]))
  11665. (define explicit-prim-ops
  11666. (set-union
  11667. (type-predicates)
  11668. (set 'procedure-arity 'eq?
  11669. 'vector 'vector-length 'vector-ref 'vector-set!
  11670. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  11671. (define/override (fun-def-type d)
  11672. (match d
  11673. [(Def f params rt info body)
  11674. (define ps
  11675. (for/list ([p params])
  11676. (match p
  11677. [`[,x : ,T] T]
  11678. [(? symbol?) 'Any]
  11679. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  11680. `(,@ps -> ,rt)]
  11681. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  11682. \end{lstlisting}
  11683. \caption{Auxiliary functions for type checking \LangGrad{}.}
  11684. \label{fig:type-check-Rgradual-aux}
  11685. \end{figure}
  11686. \clearpage
  11687. \section{Interpreting \LangCast{}}
  11688. \label{sec:interp-casts}
  11689. The runtime behavior of first-order casts is straightforward, that is,
  11690. casts involving simple types such as \code{Integer} and
  11691. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  11692. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  11693. puts the integer into a tagged value
  11694. (Figure~\ref{fig:interp-Rany}). Similarly, a cast from \code{Any} to
  11695. \code{Integer} is accomplished with the \code{Project} operator, that
  11696. is, by checking the value's tag and either retrieving the underlying
  11697. integer or signaling an error if it the tag is not the one for
  11698. integers (Figure~\ref{fig:apply-project}).
  11699. %
  11700. Things get more interesting for higher-order casts, that is, casts
  11701. involving function or vector types.
  11702. Consider the cast of the function \code{maybe-add1} from \code{(Any ->
  11703. Any)} to \code{(Integer -> Integer)}. When a function flows through
  11704. this cast at runtime, we can't know in general whether the function
  11705. will always return an integer.\footnote{Predicting the return value of
  11706. a function is equivalent to the halting problem, which is
  11707. undecidable.} The \LangCast{} interpreter therefore delays the checking
  11708. of the cast until the function is applied. This is accomplished by
  11709. wrapping \code{maybe-add1} in a new function that casts its parameter
  11710. from \code{Integer} to \code{Any}, applies \code{maybe-add1}, and then
  11711. casts the return value from \code{Any} to \code{Integer}.
  11712. Turning our attention to casts involving vector types, we consider the
  11713. example in Figure~\ref{fig:map-vec-bang} that defines a
  11714. partially-typed version of \code{map-vec} whose parameter \code{v} has
  11715. type \code{(Vector Any Any)} and that updates \code{v} in place
  11716. instead of returning a new vector. So we name this function
  11717. \code{map-vec!}. We apply \code{map-vec!} to a vector of integers, so
  11718. the type checker inserts a cast from \code{(Vector Integer Integer)}
  11719. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  11720. cast between vector types would be a build a new vector whose elements
  11721. are the result of casting each of the original elements to the
  11722. appropriate target type. However, this approach is only valid for
  11723. immutable vectors; and our vectors are mutable. In the example of
  11724. Figure~\ref{fig:map-vec-bang}, if the cast created a new vector, then
  11725. the updates inside of \code{map-vec!} would happen to the new vector
  11726. and not the original one.
  11727. \begin{figure}[tbp]
  11728. % gradual_test_11.rkt
  11729. \begin{lstlisting}
  11730. (define (map-vec! [f : (Any -> Any)]
  11731. [v : (Vector Any Any)]) : Void
  11732. (begin
  11733. (vector-set! v 0 (f (vector-ref v 0)))
  11734. (vector-set! v 1 (f (vector-ref v 1)))))
  11735. (define (add1 x) (+ x 1))
  11736. (let ([v (vector 0 41)])
  11737. (begin (map-vec! add1 v) (vector-ref v 1)))
  11738. \end{lstlisting}
  11739. \caption{An example involving casts on vectors.}
  11740. \label{fig:map-vec-bang}
  11741. \end{figure}
  11742. Instead the interpreter needs to create a new kind of value, a
  11743. \emph{vector proxy}, that intercepts every vector operation. On a
  11744. read, the proxy reads from the underlying vector and then applies a
  11745. cast to the resulting value. On a write, the proxy casts the argument
  11746. value and then performs the write to the underlying vector. For the
  11747. first \code{(vector-ref v 0)} in \code{map-vec!}, the proxy casts
  11748. \code{0} from \code{Integer} to \code{Any}. For the first
  11749. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  11750. to \code{Integer}.
  11751. The final category of cast that we need to consider are casts between
  11752. the \code{Any} type and either a function or a vector
  11753. type. Figure~\ref{fig:map-vec-any} shows a variant of \code{map-vec!}
  11754. in which parameter \code{v} does not have a type annotation, so it is
  11755. given type \code{Any}. In the call to \code{map-vec!}, the vector has
  11756. type \code{(Vector Integer Integer)} so the type checker inserts a
  11757. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  11758. thought is to use \code{Inject}, but that doesn't work because
  11759. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  11760. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  11761. to \code{Any}.
  11762. \begin{figure}[tbp]
  11763. \begin{lstlisting}
  11764. (define (map-vec! [f : (Any -> Any)] v) : Void
  11765. (begin
  11766. (vector-set! v 0 (f (vector-ref v 0)))
  11767. (vector-set! v 1 (f (vector-ref v 1)))))
  11768. (define (add1 x) (+ x 1))
  11769. (let ([v (vector 0 41)])
  11770. (begin (map-vec! add1 v) (vector-ref v 1)))
  11771. \end{lstlisting}
  11772. \caption{Casting a vector to \code{Any}.}
  11773. \label{fig:map-vec-any}
  11774. \end{figure}
  11775. The \LangCast{} interpreter uses an auxiliary function named
  11776. \code{apply-cast} to cast a value from a source type to a target type,
  11777. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  11778. of the kinds of casts that we've discussed in this section.
  11779. \begin{figure}[tbp]
  11780. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11781. (define/public (apply-cast v s t)
  11782. (match* (s t)
  11783. [(t1 t2) #:when (equal? t1 t2) v]
  11784. [('Any t2)
  11785. (match t2
  11786. [`(,ts ... -> ,rt)
  11787. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  11788. (define v^ (apply-project v any->any))
  11789. (apply-cast v^ any->any `(,@ts -> ,rt))]
  11790. [`(Vector ,ts ...)
  11791. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  11792. (define v^ (apply-project v vec-any))
  11793. (apply-cast v^ vec-any `(Vector ,@ts))]
  11794. [else (apply-project v t2)])]
  11795. [(t1 'Any)
  11796. (match t1
  11797. [`(,ts ... -> ,rt)
  11798. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  11799. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  11800. (apply-inject v^ (any-tag any->any))]
  11801. [`(Vector ,ts ...)
  11802. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  11803. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  11804. (apply-inject v^ (any-tag vec-any))]
  11805. [else (apply-inject v (any-tag t1))])]
  11806. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  11807. (define x (gensym 'x))
  11808. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  11809. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  11810. (define cast-writes
  11811. (for/list ([t1 ts1] [t2 ts2])
  11812. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  11813. `(vector-proxy ,(vector v (apply vector cast-reads)
  11814. (apply vector cast-writes)))]
  11815. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  11816. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  11817. `(function ,xs ,(Cast
  11818. (Apply (Value v)
  11819. (for/list ([x xs][t1 ts1][t2 ts2])
  11820. (Cast (Var x) t2 t1)))
  11821. rt1 rt2) ())]
  11822. ))
  11823. \end{lstlisting}
  11824. \caption{The \code{apply-cast} auxiliary method.}
  11825. \label{fig:apply-cast}
  11826. \end{figure}
  11827. The interpreter for \LangCast{} is defined in
  11828. Figure~\ref{fig:interp-Rcast}, with the case for \code{Cast}
  11829. dispatching to \code{apply-cast}. To handle the addition of vector
  11830. proxies, we update the vector primitives in \code{interp-op} using the
  11831. functions in Figure~\ref{fig:guarded-vector}.
  11832. \begin{figure}[tbp]
  11833. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11834. (define interp-Rcast-class
  11835. (class interp-Rwhile-class
  11836. (super-new)
  11837. (inherit apply-fun apply-inject apply-project)
  11838. (define/override (interp-op op)
  11839. (match op
  11840. ['vector-length guarded-vector-length]
  11841. ['vector-ref guarded-vector-ref]
  11842. ['vector-set! guarded-vector-set!]
  11843. ['any-vector-ref (lambda (v i)
  11844. (match v [`(tagged ,v^ ,tg)
  11845. (guarded-vector-ref v^ i)]))]
  11846. ['any-vector-set! (lambda (v i a)
  11847. (match v [`(tagged ,v^ ,tg)
  11848. (guarded-vector-set! v^ i a)]))]
  11849. ['any-vector-length (lambda (v)
  11850. (match v [`(tagged ,v^ ,tg)
  11851. (guarded-vector-length v^)]))]
  11852. [else (super interp-op op)]
  11853. ))
  11854. (define/override ((interp-exp env) e)
  11855. (define (recur e) ((interp-exp env) e))
  11856. (match e
  11857. [(Value v) v]
  11858. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  11859. [else ((super interp-exp env) e)]))
  11860. ))
  11861. (define (interp-Rcast p)
  11862. (send (new interp-Rcast-class) interp-program p))
  11863. \end{lstlisting}
  11864. \caption{The interpreter for \LangCast{}.}
  11865. \label{fig:interp-Rcast}
  11866. \end{figure}
  11867. \begin{figure}[tbp]
  11868. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11869. (define (guarded-vector-ref vec i)
  11870. (match vec
  11871. [`(vector-proxy ,proxy)
  11872. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  11873. (define rd (vector-ref (vector-ref proxy 1) i))
  11874. (apply-fun rd (list val) 'guarded-vector-ref)]
  11875. [else (vector-ref vec i)]))
  11876. (define (guarded-vector-set! vec i arg)
  11877. (match vec
  11878. [`(vector-proxy ,proxy)
  11879. (define wr (vector-ref (vector-ref proxy 2) i))
  11880. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  11881. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  11882. [else (vector-set! vec i arg)]))
  11883. (define (guarded-vector-length vec)
  11884. (match vec
  11885. [`(vector-proxy ,proxy)
  11886. (guarded-vector-length (vector-ref proxy 0))]
  11887. [else (vector-length vec)]))
  11888. \end{lstlisting}
  11889. \caption{The guarded-vector auxiliary functions.}
  11890. \label{fig:guarded-vector}
  11891. \end{figure}
  11892. \section{Lower Casts}
  11893. \label{sec:lower-casts}
  11894. The next step in the journey towards x86 is the \code{lower-casts}
  11895. pass that translates the casts in \LangCast{} to the lower-level
  11896. \code{Inject} and \code{Project} operators and a new operator for
  11897. creating vector proxies, extending the \LangLoop{} language to create
  11898. \LangProxy{}. We recommend creating an auxiliary function named
  11899. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  11900. and a target type, and translates it to expression in \LangProxy{} that has
  11901. the same behavior as casting the expression from the source to the
  11902. target type in the interpreter.
  11903. The \code{lower-cast} function can follow a code structure similar to
  11904. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  11905. the interpreter for \LangCast{} because it must handle the same cases as
  11906. \code{apply-cast} and it needs to mimic the behavior of
  11907. \code{apply-cast}. The most interesting cases are those concerning the
  11908. casts between two vector types and between two function types.
  11909. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  11910. type to another vector type is accomplished by creating a proxy that
  11911. intercepts the operations on the underlying vector. Here we make the
  11912. creation of the proxy explicit with the \code{vector-proxy} primitive
  11913. operation. It takes three arguments, the first is an expression for
  11914. the vector, the second is a vector of functions for casting an element
  11915. that is being read from the vector, and the third is a vector of
  11916. functions for casting an element that is being written to the vector.
  11917. You can create the functions using \code{Lambda}. Also, as we shall
  11918. see in the next section, we need to differentiate these vectors from
  11919. the user-created ones, so we recommend using a new primitive operator
  11920. named \code{raw-vector} instead of \code{vector} to create these
  11921. vectors of functions. Figure~\ref{fig:map-vec-bang-lower-cast} shows
  11922. the output of \code{lower-casts} on the example in
  11923. Figure~\ref{fig:map-vec-bang} that involved casting a vector of
  11924. integers to a vector of \code{Any}.
  11925. \begin{figure}[tbp]
  11926. \begin{lstlisting}
  11927. (define (map-vec! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  11928. (begin
  11929. (vector-set! v 0 (f (vector-ref v 0)))
  11930. (vector-set! v 1 (f (vector-ref v 1)))))
  11931. (define (add1 [x : Any]) : Any
  11932. (inject (+ (project x Integer) 1) Integer))
  11933. (let ([v (vector 0 41)])
  11934. (begin
  11935. (map-vec! add1 (vector-proxy v
  11936. (raw-vector (lambda: ([x9 : Integer]) : Any
  11937. (inject x9 Integer))
  11938. (lambda: ([x9 : Integer]) : Any
  11939. (inject x9 Integer)))
  11940. (raw-vector (lambda: ([x9 : Any]) : Integer
  11941. (project x9 Integer))
  11942. (lambda: ([x9 : Any]) : Integer
  11943. (project x9 Integer)))))
  11944. (vector-ref v 1)))
  11945. \end{lstlisting}
  11946. \caption{Output of \code{lower-casts} on the example in
  11947. Figure~\ref{fig:map-vec-bang}.}
  11948. \label{fig:map-vec-bang-lower-cast}
  11949. \end{figure}
  11950. A cast from one function type to another function type is accomplished
  11951. by generating a \code{Lambda} whose parameter and return types match
  11952. the target function type. The body of the \code{Lambda} should cast
  11953. the parameters from the target type to the source type (yes,
  11954. backwards! functions are contravariant\index{subject}{contravariant} in the
  11955. parameters), then call the underlying function, and finally cast the
  11956. result from the source return type to the target return type.
  11957. Figure~\ref{fig:map-vec-lower-cast} shows the output of the
  11958. \code{lower-casts} pass on the \code{map-vec} example in
  11959. Figure~\ref{fig:gradual-map-vec}. Note that the \code{add1} argument
  11960. in the call to \code{map-vec} is wrapped in a \code{lambda}.
  11961. \begin{figure}[tbp]
  11962. \begin{lstlisting}
  11963. (define (map-vec [f : (Integer -> Integer)]
  11964. [v : (Vector Integer Integer)])
  11965. : (Vector Integer Integer)
  11966. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  11967. (define (add1 [x : Any]) : Any
  11968. (inject (+ (project x Integer) 1) Integer))
  11969. (vector-ref (map-vec (lambda: ([x9 : Integer]) : Integer
  11970. (project (add1 (inject x9 Integer)) Integer))
  11971. (vector 0 41)) 1)
  11972. \end{lstlisting}
  11973. \caption{Output of \code{lower-casts} on the example in
  11974. Figure~\ref{fig:gradual-map-vec}.}
  11975. \label{fig:map-vec-lower-cast}
  11976. \end{figure}
  11977. \section{Differentiate Proxies}
  11978. \label{sec:differentiate-proxies}
  11979. So far the job of differentiating vectors and vector proxies has been
  11980. the job of the interpreter. For example, the interpreter for \LangCast{}
  11981. implements \code{vector-ref} using the \code{guarded-vector-ref}
  11982. function in Figure~\ref{fig:guarded-vector}. In the
  11983. \code{differentiate-proxies} pass we shift this responsibility to the
  11984. generated code.
  11985. We begin by designing the output language $R^p_8$. In
  11986. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  11987. proxies. In $R^p_8$ we return the \code{Vector} type to
  11988. its original meaning, as the type of real vectors, and we introduce a
  11989. new type, \code{PVector}, whose values can be either real vectors or
  11990. vector proxies. This new type comes with a suite of new primitive
  11991. operations for creating and using values of type \code{PVector}. We
  11992. don't need to introduce a new type to represent vector proxies. A
  11993. proxy is represented by a vector containing three things: 1) the
  11994. underlying vector, 2) a vector of functions for casting elements that
  11995. are read from the vector, and 3) a vector of functions for casting
  11996. values to be written to the vector. So we define the following
  11997. abbreviation for the type of a vector proxy:
  11998. \[
  11999. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  12000. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  12001. \to (\key{PVector}~ T' \ldots)
  12002. \]
  12003. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  12004. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  12005. %
  12006. Next we describe each of the new primitive operations.
  12007. \begin{description}
  12008. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  12009. (\key{PVector} $T \ldots$)]\ \\
  12010. %
  12011. This operation brands a vector as a value of the \code{PVector} type.
  12012. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  12013. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  12014. %
  12015. This operation brands a vector proxy as value of the \code{PVector} type.
  12016. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  12017. \code{Boolean}] \ \\
  12018. %
  12019. returns true if the value is a vector proxy and false if it is a
  12020. real vector.
  12021. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  12022. (\key{Vector} $T \ldots$)]\ \\
  12023. %
  12024. Assuming that the input is a vector (and not a proxy), this
  12025. operation returns the vector.
  12026. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  12027. $\to$ \code{Boolean}]\ \\
  12028. %
  12029. Given a vector proxy, this operation returns the length of the
  12030. underlying vector.
  12031. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  12032. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  12033. %
  12034. Given a vector proxy, this operation returns the $i$th element of
  12035. the underlying vector.
  12036. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  12037. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  12038. proxy, this operation writes a value to the $i$th element of the
  12039. underlying vector.
  12040. \end{description}
  12041. Now to discuss the translation that differentiates vectors from
  12042. proxies. First, every type annotation in the program must be
  12043. translated (recursively) to replace \code{Vector} with \code{PVector}.
  12044. Next, we must insert uses of \code{PVector} operations in the
  12045. appropriate places. For example, we wrap every vector creation with an
  12046. \code{inject-vector}.
  12047. \begin{lstlisting}
  12048. (vector |$e_1 \ldots e_n$|)
  12049. |$\Rightarrow$|
  12050. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  12051. \end{lstlisting}
  12052. The \code{raw-vector} operator that we introduced in the previous
  12053. section does not get injected.
  12054. \begin{lstlisting}
  12055. (raw-vector |$e_1 \ldots e_n$|)
  12056. |$\Rightarrow$|
  12057. (vector |$e'_1 \ldots e'_n$|)
  12058. \end{lstlisting}
  12059. The \code{vector-proxy} primitive translates as follows.
  12060. \begin{lstlisting}
  12061. (vector-proxy |$e_1~e_2~e_3$|)
  12062. |$\Rightarrow$|
  12063. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  12064. \end{lstlisting}
  12065. We translate the vector operations into conditional expressions that
  12066. check whether the value is a proxy and then dispatch to either the
  12067. appropriate proxy vector operation or the regular vector operation.
  12068. For example, the following is the translation for \code{vector-ref}.
  12069. \begin{lstlisting}
  12070. (vector-ref |$e_1$| |$i$|)
  12071. |$\Rightarrow$|
  12072. (let ([|$v~e_1$|])
  12073. (if (proxy? |$v$|)
  12074. (proxy-vector-ref |$v$| |$i$|)
  12075. (vector-ref (project-vector |$v$|) |$i$|)
  12076. \end{lstlisting}
  12077. Note in the case of a real vector, we must apply \code{project-vector}
  12078. before the \code{vector-ref}.
  12079. \section{Reveal Casts}
  12080. \label{sec:reveal-casts-gradual}
  12081. Recall that the \code{reveal-casts} pass
  12082. (Section~\ref{sec:reveal-casts-Rany}) is responsible for lowering
  12083. \code{Inject} and \code{Project} into lower-level operations. In
  12084. particular, \code{Project} turns into a conditional expression that
  12085. inspects the tag and retrieves the underlying value. Here we need to
  12086. augment the translation of \code{Project} to handle the situation when
  12087. the target type is \code{PVector}. Instead of using
  12088. \code{vector-length} we need to use \code{proxy-vector-length}.
  12089. \begin{lstlisting}
  12090. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  12091. |$\Rightarrow$|
  12092. (let |$\itm{tmp}$| |$e'$|
  12093. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  12094. (let |$\itm{vec}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  12095. (if (eq? (proxy-vector-length |$\itm{vec}$|) |$n$|) |$\itm{vec}$| (exit)))
  12096. (exit)))
  12097. \end{lstlisting}
  12098. \section{Closure Conversion}
  12099. \label{sec:closure-conversion-gradual}
  12100. The closure conversion pass only requires one minor adjustment. The
  12101. auxiliary function that translates type annotations needs to be
  12102. updated to handle the \code{PVector} type.
  12103. \section{Explicate Control}
  12104. \label{sec:explicate-control-gradual}
  12105. Update the \code{explicate-control} pass to handle the new primitive
  12106. operations on the \code{PVector} type.
  12107. \section{Select Instructions}
  12108. \label{sec:select-instructions-gradual}
  12109. Recall that the \code{select-instructions} pass is responsible for
  12110. lowering the primitive operations into x86 instructions. So we need
  12111. to translate the new \code{PVector} operations to x86. To do so, the
  12112. first question we need to answer is how will we differentiate the two
  12113. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  12114. We need just one bit to accomplish this, and use the bit in position
  12115. $57$ of the 64-bit tag at the front of every vector (see
  12116. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  12117. for \code{inject-vector} we leave it that way.
  12118. \begin{lstlisting}
  12119. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  12120. |$\Rightarrow$|
  12121. movq |$e'_1$|, |$\itm{lhs'}$|
  12122. \end{lstlisting}
  12123. On the other hand, \code{inject-proxy} sets bit $57$ to $1$.
  12124. \begin{lstlisting}
  12125. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  12126. |$\Rightarrow$|
  12127. movq |$e'_1$|, %r11
  12128. movq |$(1 << 57)$|, %rax
  12129. orq 0(%r11), %rax
  12130. movq %rax, 0(%r11)
  12131. movq %r11, |$\itm{lhs'}$|
  12132. \end{lstlisting}
  12133. The \code{proxy?} operation consumes the information so carefully
  12134. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  12135. isolates the $57$th bit to tell whether the value is a real vector or
  12136. a proxy.
  12137. \begin{lstlisting}
  12138. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  12139. |$\Rightarrow$|
  12140. movq |$e_1'$|, %r11
  12141. movq 0(%r11), %rax
  12142. sarq $57, %rax
  12143. andq $1, %rax
  12144. movq %rax, |$\itm{lhs'}$|
  12145. \end{lstlisting}
  12146. The \code{project-vector} operation is straightforward to translate,
  12147. so we leave it up to the reader.
  12148. Regarding the \code{proxy-vector} operations, the runtime provides
  12149. procedures that implement them (they are recursive functions!) so
  12150. here we simply need to translate these vector operations into the
  12151. appropriate function call. For example, here is the translation for
  12152. \code{proxy-vector-ref}.
  12153. \begin{lstlisting}
  12154. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  12155. |$\Rightarrow$|
  12156. movq |$e_1'$|, %rdi
  12157. movq |$e_2'$|, %rsi
  12158. callq proxy_vector_ref
  12159. movq %rax, |$\itm{lhs'}$|
  12160. \end{lstlisting}
  12161. We have another batch of vector operations to deal with, those for the
  12162. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  12163. \code{any-vector-ref} when there is a \code{vector-ref} on something
  12164. of type \code{Any}, and similarly for \code{any-vector-set!} and
  12165. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  12166. Section~\ref{sec:select-Rany} we selected instructions for these
  12167. operations based on the idea that the underlying value was a real
  12168. vector. But in the current setting, the underlying value is of type
  12169. \code{PVector}. So \code{any-vector-ref} can be translates to
  12170. pseudo-x86 as follows. We begin by projecting the underlying value out
  12171. of the tagged value and then call the \code{proxy\_vector\_ref}
  12172. procedure in the runtime.
  12173. \begin{lstlisting}
  12174. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  12175. movq |$\neg 111$|, %rdi
  12176. andq |$e_1'$|, %rdi
  12177. movq |$e_2'$|, %rsi
  12178. callq proxy_vector_ref
  12179. movq %rax, |$\itm{lhs'}$|
  12180. \end{lstlisting}
  12181. The \code{any-vector-set!} and \code{any-vector-length} operators can
  12182. be translated in a similar way.
  12183. \begin{exercise}\normalfont
  12184. Implement a compiler for the gradually-typed \LangGrad{} language by
  12185. extending and adapting your compiler for \LangLoop{}. Create 10 new
  12186. partially-typed test programs. In addition to testing with these
  12187. new programs, also test your compiler on all the tests for \LangLoop{}
  12188. and tests for \LangDyn{}. Sometimes you may get a type checking error
  12189. on the \LangDyn{} programs but you can adapt them by inserting
  12190. a cast to the \code{Any} type around each subexpression
  12191. causing a type error. While \LangDyn{} doesn't have explicit casts,
  12192. you can induce one by wrapping the subexpression \code{e}
  12193. with a call to an un-annotated identity function, like this:
  12194. \code{((lambda (x) x) e)}.
  12195. \end{exercise}
  12196. \begin{figure}[p]
  12197. \begin{tikzpicture}[baseline=(current bounding box.center)]
  12198. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  12199. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  12200. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  12201. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  12202. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  12203. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  12204. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  12205. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  12206. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  12207. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  12208. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  12209. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  12210. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  12211. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  12212. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  12213. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  12214. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  12215. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  12216. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  12217. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  12218. \path[->,bend right=15] (Rgradual) edge [above] node
  12219. {\ttfamily\footnotesize type-check} (Rgradualp);
  12220. \path[->,bend right=15] (Rgradualp) edge [above] node
  12221. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  12222. \path[->,bend right=15] (Rwhilepp) edge [right] node
  12223. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  12224. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  12225. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  12226. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  12227. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  12228. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  12229. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  12230. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  12231. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  12232. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  12233. {\ttfamily\footnotesize convert-assignments} (F1-1);
  12234. \path[->,bend left=15] (F1-1) edge [below] node
  12235. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  12236. \path[->,bend right=15] (F1-2) edge [above] node
  12237. {\ttfamily\footnotesize limit-fun.} (F1-3);
  12238. \path[->,bend right=15] (F1-3) edge [above] node
  12239. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  12240. \path[->,bend right=15] (F1-4) edge [above] node
  12241. {\ttfamily\footnotesize remove-complex.} (F1-5);
  12242. \path[->,bend right=15] (F1-5) edge [right] node
  12243. {\ttfamily\footnotesize explicate-control} (C3-2);
  12244. \path[->,bend left=15] (C3-2) edge [left] node
  12245. {\ttfamily\footnotesize select-instr.} (x86-2);
  12246. \path[->,bend right=15] (x86-2) edge [left] node
  12247. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  12248. \path[->,bend right=15] (x86-2-1) edge [below] node
  12249. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  12250. \path[->,bend right=15] (x86-2-2) edge [left] node
  12251. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  12252. \path[->,bend left=15] (x86-3) edge [above] node
  12253. {\ttfamily\footnotesize patch-instr.} (x86-4);
  12254. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  12255. \end{tikzpicture}
  12256. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  12257. \label{fig:Rgradual-passes}
  12258. \end{figure}
  12259. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  12260. for the compilation of \LangGrad{}.
  12261. \section{Further Reading}
  12262. This chapter just scratches the surface of gradual typing. The basic
  12263. approach described here is missing two key ingredients that one would
  12264. want in a implementation of gradual typing: blame
  12265. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  12266. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  12267. problem addressed by blame tracking is that when a cast on a
  12268. higher-order value fails, it often does so at a point in the program
  12269. that is far removed from the original cast. Blame tracking is a
  12270. technique for propagating extra information through casts and proxies
  12271. so that when a cast fails, the error message can point back to the
  12272. original location of the cast in the source program.
  12273. The problem addressed by space-efficient casts also relates to
  12274. higher-order casts. It turns out that in partially typed programs, a
  12275. function or vector can flow through very-many casts at runtime. With
  12276. the approach described in this chapter, each cast adds another
  12277. \code{lambda} wrapper or a vector proxy. Not only does this take up
  12278. considerable space, but it also makes the function calls and vector
  12279. operations slow. For example, a partially-typed version of quicksort
  12280. could, in the worst case, build a chain of proxies of length $O(n)$
  12281. around the vector, changing the overall time complexity of the
  12282. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  12283. solution to this problem by representing casts using the coercion
  12284. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  12285. long chains of proxies by compressing them into a concise normal
  12286. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  12287. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  12288. the Grift compiler.
  12289. \begin{center}
  12290. \url{https://github.com/Gradual-Typing/Grift}
  12291. \end{center}
  12292. There are also interesting interactions between gradual typing and
  12293. other language features, such as parametetric polymorphism,
  12294. information-flow types, and type inference, to name a few. We
  12295. recommend the reader to the online gradual typing bibliography:
  12296. \begin{center}
  12297. \url{http://samth.github.io/gradual-typing-bib/}
  12298. \end{center}
  12299. % TODO: challenge problem:
  12300. % type analysis and type specialization?
  12301. % coercions?
  12302. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12303. \chapter{Parametric Polymorphism}
  12304. \label{ch:Rpoly}
  12305. \index{subject}{parametric polymorphism}
  12306. \index{subject}{generics}
  12307. This chapter studies the compilation of parametric
  12308. polymorphism\index{subject}{parametric polymorphism}
  12309. (aka. generics\index{subject}{generics}) in the subset \LangPoly{} of Typed
  12310. Racket. Parametric polymorphism enables improved code reuse by
  12311. parameterizing functions and data structures with respect to the types
  12312. that they operate on. For example, Figure~\ref{fig:map-vec-poly}
  12313. revisits the \code{map-vec} example but this time gives it a more
  12314. fitting type. This \code{map-vec} function is parameterized with
  12315. respect to the element type of the vector. The type of \code{map-vec}
  12316. is the following polymorphic type as specified by the \code{All} and
  12317. the type parameter \code{a}.
  12318. \begin{lstlisting}
  12319. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  12320. \end{lstlisting}
  12321. The idea is that \code{map-vec} can be used at \emph{all} choices of a
  12322. type for parameter \code{a}. In Figure~\ref{fig:map-vec-poly} we apply
  12323. \code{map-vec} to a vector of integers, a choice of \code{Integer} for
  12324. \code{a}, but we could have just as well applied \code{map-vec} to a
  12325. vector of Booleans (and a function on Booleans).
  12326. \begin{figure}[tbp]
  12327. % poly_test_2.rkt
  12328. \begin{lstlisting}
  12329. (: map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  12330. (define (map-vec f v)
  12331. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12332. (define (add1 [x : Integer]) : Integer (+ x 1))
  12333. (vector-ref (map-vec add1 (vector 0 41)) 1)
  12334. \end{lstlisting}
  12335. \caption{The \code{map-vec} example using parametric polymorphism.}
  12336. \label{fig:map-vec-poly}
  12337. \end{figure}
  12338. Figure~\ref{fig:Rpoly-concrete-syntax} defines the concrete syntax of
  12339. \LangPoly{} and Figure~\ref{fig:Rpoly-syntax} defines the abstract
  12340. syntax. We add a second form for function definitions in which a type
  12341. declaration comes before the \code{define}. In the abstract syntax,
  12342. the return type in the \code{Def} is \code{Any}, but that should be
  12343. ignored in favor of the return type in the type declaration. (The
  12344. \code{Any} comes from using the same parser as in
  12345. Chapter~\ref{ch:Rdyn}.) The presence of a type declaration
  12346. enables the use of an \code{All} type for a function, thereby making
  12347. it polymorphic. The grammar for types is extended to include
  12348. polymorphic types and type variables.
  12349. \begin{figure}[tp]
  12350. \centering
  12351. \fbox{
  12352. \begin{minipage}{0.96\textwidth}
  12353. \small
  12354. \[
  12355. \begin{array}{lcl}
  12356. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  12357. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  12358. &\MID& \LP\key{:}~\Var~\Type\RP \\
  12359. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  12360. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  12361. \end{array}
  12362. \]
  12363. \end{minipage}
  12364. }
  12365. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  12366. (Figure~\ref{fig:Rwhile-concrete-syntax}).}
  12367. \label{fig:Rpoly-concrete-syntax}
  12368. \end{figure}
  12369. \begin{figure}[tp]
  12370. \centering
  12371. \fbox{
  12372. \begin{minipage}{0.96\textwidth}
  12373. \small
  12374. \[
  12375. \begin{array}{lcl}
  12376. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  12377. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  12378. &\MID& \DECL{\Var}{\Type} \\
  12379. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  12380. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  12381. \end{array}
  12382. \]
  12383. \end{minipage}
  12384. }
  12385. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  12386. (Figure~\ref{fig:Rwhile-syntax}).}
  12387. \label{fig:Rpoly-syntax}
  12388. \end{figure}
  12389. By including polymorphic types in the $\Type$ non-terminal we choose
  12390. to make them first-class which has interesting repercussions on the
  12391. compiler. Many languages with polymorphism, such as
  12392. C++~\citep{stroustrup88:_param_types} and Standard
  12393. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  12394. it is useful to see an example of first-class polymorphism. In
  12395. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  12396. whose parameter is a polymorphic function. The occurrence of a
  12397. polymorphic type underneath a function type is enabled by the normal
  12398. recursive structure of the grammar for $\Type$ and the categorization
  12399. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  12400. applies the polymorphic function to a Boolean and to an integer.
  12401. \begin{figure}[tbp]
  12402. \begin{lstlisting}
  12403. (: apply-twice ((All (b) (b -> b)) -> Integer))
  12404. (define (apply-twice f)
  12405. (if (f #t) (f 42) (f 777)))
  12406. (: id (All (a) (a -> a)))
  12407. (define (id x) x)
  12408. (apply-twice id)
  12409. \end{lstlisting}
  12410. \caption{An example illustrating first-class polymorphism.}
  12411. \label{fig:apply-twice}
  12412. \end{figure}
  12413. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Rvar0} has
  12414. three new responsibilities (compared to \LangLoop{}). The type checking of
  12415. function application is extended to handle the case where the operator
  12416. expression is a polymorphic function. In that case the type arguments
  12417. are deduced by matching the type of the parameters with the types of
  12418. the arguments.
  12419. %
  12420. The \code{match-types} auxiliary function carries out this deduction
  12421. by recursively descending through a parameter type \code{pt} and the
  12422. corresponding argument type \code{at}, making sure that they are equal
  12423. except when there is a type parameter on the left (in the parameter
  12424. type). If it's the first time that the type parameter has been
  12425. encountered, then the algorithm deduces an association of the type
  12426. parameter to the corresponding type on the right (in the argument
  12427. type). If it's not the first time that the type parameter has been
  12428. encountered, the algorithm looks up its deduced type and makes sure
  12429. that it is equal to the type on the right.
  12430. %
  12431. Once the type arguments are deduced, the operator expression is
  12432. wrapped in an \code{Inst} AST node (for instantiate) that records the
  12433. type of the operator, but more importantly, records the deduced type
  12434. arguments. The return type of the application is the return type of
  12435. the polymorphic function, but with the type parameters replaced by the
  12436. deduced type arguments, using the \code{subst-type} function.
  12437. The second responsibility of the type checker is extending the
  12438. function \code{type-equal?} to handle the \code{All} type. This is
  12439. not quite a simple as equal on other types, such as function and
  12440. vector types, because two polymorphic types can be syntactically
  12441. different even though they are equivalent types. For example,
  12442. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  12443. Two polymorphic types should be considered equal if they differ only
  12444. in the choice of the names of the type parameters. The
  12445. \code{type-equal?} function in Figure~\ref{fig:type-check-Rvar0-aux}
  12446. renames the type parameters of the first type to match the type
  12447. parameters of the second type.
  12448. The third responsibility of the type checker is making sure that only
  12449. defined type variables appear in type annotations. The
  12450. \code{check-well-formed} function defined in
  12451. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  12452. sure that each type variable has been defined.
  12453. The output language of the type checker is \LangInst{}, defined in
  12454. Figure~\ref{fig:Rpoly-prime-syntax}. The type checker combines the type
  12455. declaration and polymorphic function into a single definition, using
  12456. the \code{Poly} form, to make polymorphic functions more convenient to
  12457. process in next pass of the compiler.
  12458. \begin{figure}[tp]
  12459. \centering
  12460. \fbox{
  12461. \begin{minipage}{0.96\textwidth}
  12462. \small
  12463. \[
  12464. \begin{array}{lcl}
  12465. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  12466. \Exp &::=& \ldots \MID \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  12467. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  12468. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  12469. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  12470. \end{array}
  12471. \]
  12472. \end{minipage}
  12473. }
  12474. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  12475. (Figure~\ref{fig:Rwhile-syntax}).}
  12476. \label{fig:Rpoly-prime-syntax}
  12477. \end{figure}
  12478. The output of the type checker on the polymorphic \code{map-vec}
  12479. example is listed in Figure~\ref{fig:map-vec-type-check}.
  12480. \begin{figure}[tbp]
  12481. % poly_test_2.rkt
  12482. \begin{lstlisting}
  12483. (poly (a) (define (map-vec [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  12484. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  12485. (define (add1 [x : Integer]) : Integer (+ x 1))
  12486. (vector-ref ((inst map-vec (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  12487. (Integer))
  12488. add1 (vector 0 41)) 1)
  12489. \end{lstlisting}
  12490. \caption{Output of the type checker on the \code{map-vec} example.}
  12491. \label{fig:map-vec-type-check}
  12492. \end{figure}
  12493. \begin{figure}[tbp]
  12494. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12495. (define type-check-poly-class
  12496. (class type-check-Rwhile-class
  12497. (super-new)
  12498. (inherit check-type-equal?)
  12499. (define/override (type-check-apply env e1 es)
  12500. (define-values (e^ ty) ((type-check-exp env) e1))
  12501. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  12502. ((type-check-exp env) e)))
  12503. (match ty
  12504. [`(,ty^* ... -> ,rt)
  12505. (for ([arg-ty ty*] [param-ty ty^*])
  12506. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  12507. (values e^ es^ rt)]
  12508. [`(All ,xs (,tys ... -> ,rt))
  12509. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  12510. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  12511. (match-types env^^ param-ty arg-ty)))
  12512. (define targs
  12513. (for/list ([x xs])
  12514. (match (dict-ref env^^ x (lambda () #f))
  12515. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  12516. x (Apply e1 es))]
  12517. [ty ty])))
  12518. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  12519. [else (error 'type-check "expected a function, not ~a" ty)]))
  12520. (define/override ((type-check-exp env) e)
  12521. (match e
  12522. [(Lambda `([,xs : ,Ts] ...) rT body)
  12523. (for ([T Ts]) ((check-well-formed env) T))
  12524. ((check-well-formed env) rT)
  12525. ((super type-check-exp env) e)]
  12526. [(HasType e1 ty)
  12527. ((check-well-formed env) ty)
  12528. ((super type-check-exp env) e)]
  12529. [else ((super type-check-exp env) e)]))
  12530. (define/override ((type-check-def env) d)
  12531. (verbose 'type-check "poly/def" d)
  12532. (match d
  12533. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  12534. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  12535. (for ([p ps]) ((check-well-formed ts-env) p))
  12536. ((check-well-formed ts-env) rt)
  12537. (define new-env (append ts-env (map cons xs ps) env))
  12538. (define-values (body^ ty^) ((type-check-exp new-env) body))
  12539. (check-type-equal? ty^ rt body)
  12540. (Generic ts (Def f p:t* rt info body^))]
  12541. [else ((super type-check-def env) d)]))
  12542. (define/override (type-check-program p)
  12543. (match p
  12544. [(Program info body)
  12545. (type-check-program (ProgramDefsExp info '() body))]
  12546. [(ProgramDefsExp info ds body)
  12547. (define ds^ (combine-decls-defs ds))
  12548. (define new-env (for/list ([d ds^])
  12549. (cons (def-name d) (fun-def-type d))))
  12550. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  12551. (define-values (body^ ty) ((type-check-exp new-env) body))
  12552. (check-type-equal? ty 'Integer body)
  12553. (ProgramDefsExp info ds^^ body^)]))
  12554. ))
  12555. \end{lstlisting}
  12556. \caption{Type checker for the \LangPoly{} language.}
  12557. \label{fig:type-check-Rvar0}
  12558. \end{figure}
  12559. \begin{figure}[tbp]
  12560. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12561. (define/override (type-equal? t1 t2)
  12562. (match* (t1 t2)
  12563. [(`(All ,xs ,T1) `(All ,ys ,T2))
  12564. (define env (map cons xs ys))
  12565. (type-equal? (subst-type env T1) T2)]
  12566. [(other wise)
  12567. (super type-equal? t1 t2)]))
  12568. (define/public (match-types env pt at)
  12569. (match* (pt at)
  12570. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  12571. [('Void 'Void) env] [('Any 'Any) env]
  12572. [(`(Vector ,pts ...) `(Vector ,ats ...))
  12573. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  12574. (match-types env^ pt1 at1))]
  12575. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  12576. (define env^ (match-types env prt art))
  12577. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  12578. (match-types env^^ pt1 at1))]
  12579. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  12580. (define env^ (append (map cons pxs axs) env))
  12581. (match-types env^ pt1 at1)]
  12582. [((? symbol? x) at)
  12583. (match (dict-ref env x (lambda () #f))
  12584. [#f (error 'type-check "undefined type variable ~a" x)]
  12585. ['Type (cons (cons x at) env)]
  12586. [t^ (check-type-equal? at t^ 'matching) env])]
  12587. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  12588. (define/public (subst-type env pt)
  12589. (match pt
  12590. ['Integer 'Integer] ['Boolean 'Boolean]
  12591. ['Void 'Void] ['Any 'Any]
  12592. [`(Vector ,ts ...)
  12593. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  12594. [`(,ts ... -> ,rt)
  12595. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  12596. [`(All ,xs ,t)
  12597. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  12598. [(? symbol? x) (dict-ref env x)]
  12599. [else (error 'type-check "expected a type not ~a" pt)]))
  12600. (define/public (combine-decls-defs ds)
  12601. (match ds
  12602. ['() '()]
  12603. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  12604. (unless (equal? name f)
  12605. (error 'type-check "name mismatch, ~a != ~a" name f))
  12606. (match type
  12607. [`(All ,xs (,ps ... -> ,rt))
  12608. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  12609. (cons (Generic xs (Def name params^ rt info body))
  12610. (combine-decls-defs ds^))]
  12611. [`(,ps ... -> ,rt)
  12612. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  12613. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  12614. [else (error 'type-check "expected a function type, not ~a" type) ])]
  12615. [`(,(Def f params rt info body) . ,ds^)
  12616. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  12617. \end{lstlisting}
  12618. \caption{Auxiliary functions for type checking \LangPoly{}.}
  12619. \label{fig:type-check-Rvar0-aux}
  12620. \end{figure}
  12621. \begin{figure}[tbp]
  12622. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  12623. (define/public ((check-well-formed env) ty)
  12624. (match ty
  12625. ['Integer (void)]
  12626. ['Boolean (void)]
  12627. ['Void (void)]
  12628. [(? symbol? a)
  12629. (match (dict-ref env a (lambda () #f))
  12630. ['Type (void)]
  12631. [else (error 'type-check "undefined type variable ~a" a)])]
  12632. [`(Vector ,ts ...)
  12633. (for ([t ts]) ((check-well-formed env) t))]
  12634. [`(,ts ... -> ,t)
  12635. (for ([t ts]) ((check-well-formed env) t))
  12636. ((check-well-formed env) t)]
  12637. [`(All ,xs ,t)
  12638. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  12639. ((check-well-formed env^) t)]
  12640. [else (error 'type-check "unrecognized type ~a" ty)]))
  12641. \end{lstlisting}
  12642. \caption{Well-formed types.}
  12643. \label{fig:well-formed-types}
  12644. \end{figure}
  12645. % TODO: interpreter for R'_10
  12646. \section{Compiling Polymorphism}
  12647. \label{sec:compiling-poly}
  12648. Broadly speaking, there are four approaches to compiling parametric
  12649. polymorphism, which we describe below.
  12650. \begin{description}
  12651. \item[Monomorphization] generates a different version of a polymorphic
  12652. function for each set of type arguments that it is used with,
  12653. producing type-specialized code. This approach results in the most
  12654. efficient code but requires whole-program compilation (no separate
  12655. compilation) and increases code size. For our current purposes
  12656. monomorphization is a non-starter because, with first-class
  12657. polymorphism, it is sometimes not possible to determine which
  12658. generic functions are used with which type arguments during
  12659. compilation. (It can be done at runtime, with just-in-time
  12660. compilation.) This approach is used to compile C++
  12661. templates~\citep{stroustrup88:_param_types} and polymorphic
  12662. functions in NESL~\citep{Blelloch:1993aa} and
  12663. ML~\citep{Weeks:2006aa}.
  12664. \item[Uniform representation] generates one version of each
  12665. polymorphic function but requires all values have a common ``boxed''
  12666. format, such as the tagged values of type \code{Any} in
  12667. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  12668. similarly to code in a dynamically typed language (like \LangDyn{}),
  12669. in which primitive operators require their arguments to be projected
  12670. from \code{Any} and their results are injected into \code{Any}. (In
  12671. object-oriented languages, the projection is accomplished via
  12672. virtual method dispatch.) The uniform representation approach is
  12673. compatible with separate compilation and with first-class
  12674. polymorphism. However, it produces the least-efficient code because
  12675. it introduces overhead in the entire program, including
  12676. non-polymorphic code. This approach is used in implementations of
  12677. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  12678. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  12679. Java~\citep{Bracha:1998fk}.
  12680. \item[Mixed representation] generates one version of each polymorphic
  12681. function, using a boxed representation for type
  12682. variables. Monomorphic code is compiled as usual (as in \LangLoop{})
  12683. and conversions are performed at the boundaries between monomorphic
  12684. and polymorphic (e.g. when a polymorphic function is instantiated
  12685. and called). This approach is compatible with separate compilation
  12686. and first-class polymorphism and maintains the efficiency of
  12687. monomorphic code. The tradeoff is increased overhead at the boundary
  12688. between monomorphic and polymorphic code. This approach is used in
  12689. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  12690. Java 5 with the addition of autoboxing.
  12691. \item[Type passing] uses the unboxed representation in both
  12692. monomorphic and polymorphic code. Each polymorphic function is
  12693. compiled to a single function with extra parameters that describe
  12694. the type arguments. The type information is used by the generated
  12695. code to know how to access the unboxed values at runtime. This
  12696. approach is used in implementation of the Napier88
  12697. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. Type
  12698. passing is compatible with separate compilation and first-class
  12699. polymorphism and maintains the efficiency for monomorphic
  12700. code. There is runtime overhead in polymorphic code from dispatching
  12701. on type information.
  12702. \end{description}
  12703. In this chapter we use the mixed representation approach, partly
  12704. because of its favorable attributes, and partly because it is
  12705. straightforward to implement using the tools that we have already
  12706. built to support gradual typing. To compile polymorphic functions, we
  12707. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  12708. \LangCast{}.
  12709. \section{Erase Types}
  12710. \label{sec:erase-types}
  12711. We use the \code{Any} type from Chapter~\ref{ch:Rdyn} to
  12712. represent type variables. For example, Figure~\ref{fig:map-vec-erase}
  12713. shows the output of the \code{erase-types} pass on the polymorphic
  12714. \code{map-vec} (Figure~\ref{fig:map-vec-poly}). The occurrences of
  12715. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  12716. \code{All} types are removed from the type of \code{map-vec}.
  12717. \begin{figure}[tbp]
  12718. \begin{lstlisting}
  12719. (define (map-vec [f : (Any -> Any)] [v : (Vector Any Any)])
  12720. : (Vector Any Any)
  12721. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12722. (define (add1 [x : Integer]) : Integer (+ x 1))
  12723. (vector-ref ((cast map-vec
  12724. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  12725. ((Integer -> Integer) (Vector Integer Integer)
  12726. -> (Vector Integer Integer)))
  12727. add1 (vector 0 41)) 1)
  12728. \end{lstlisting}
  12729. \caption{The polymorphic \code{map-vec} example after type erasure.}
  12730. \label{fig:map-vec-erase}
  12731. \end{figure}
  12732. This process of type erasure creates a challenge at points of
  12733. instantiation. For example, consider the instantiation of
  12734. \code{map-vec} in Figure~\ref{fig:map-vec-type-check}.
  12735. The type of \code{map-vec} is
  12736. \begin{lstlisting}
  12737. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  12738. \end{lstlisting}
  12739. and it is instantiated to
  12740. \begin{lstlisting}
  12741. ((Integer -> Integer) (Vector Integer Integer)
  12742. -> (Vector Integer Integer))
  12743. \end{lstlisting}
  12744. After erasure, the type of \code{map-vec} is
  12745. \begin{lstlisting}
  12746. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  12747. \end{lstlisting}
  12748. but we need to convert it to the instantiated type. This is easy to
  12749. do in the target language \LangCast{} with a single \code{cast}. In
  12750. Figure~\ref{fig:map-vec-erase}, the instantiation of \code{map-vec}
  12751. has been compiled to a \code{cast} from the type of \code{map-vec} to
  12752. the instantiated type. The source and target type of a cast must be
  12753. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  12754. because both the source and target are obtained from the same
  12755. polymorphic type of \code{map-vec}, replacing the type parameters with
  12756. \code{Any} in the former and with the deduced type arguments in the
  12757. later. (Recall that the \code{Any} type is consistent with any type.)
  12758. To implement the \code{erase-types} pass, we recommend defining a
  12759. recursive auxiliary function named \code{erase-type} that applies the
  12760. following two transformations. It replaces type variables with
  12761. \code{Any}
  12762. \begin{lstlisting}
  12763. |$x$|
  12764. |$\Rightarrow$|
  12765. Any
  12766. \end{lstlisting}
  12767. and it removes the polymorphic \code{All} types.
  12768. \begin{lstlisting}
  12769. (All |$xs$| |$T_1$|)
  12770. |$\Rightarrow$|
  12771. |$T'_1$|
  12772. \end{lstlisting}
  12773. Apply the \code{erase-type} function to all of the type annotations in
  12774. the program.
  12775. Regarding the translation of expressions, the case for \code{Inst} is
  12776. the interesting one. We translate it into a \code{Cast}, as shown
  12777. below. The type of the subexpression $e$ is the polymorphic type
  12778. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  12779. $T$, the type $T'$. The target type $T''$ is the result of
  12780. substituting the arguments types $ts$ for the type parameters $xs$ in
  12781. $T$ followed by doing type erasure.
  12782. \begin{lstlisting}
  12783. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  12784. |$\Rightarrow$|
  12785. (Cast |$e'$| |$T'$| |$T''$|)
  12786. \end{lstlisting}
  12787. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  12788. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  12789. Finally, each polymorphic function is translated to a regular
  12790. functions in which type erasure has been applied to all the type
  12791. annotations and the body.
  12792. \begin{lstlisting}
  12793. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  12794. |$\Rightarrow$|
  12795. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  12796. \end{lstlisting}
  12797. \begin{exercise}\normalfont
  12798. Implement a compiler for the polymorphic language \LangPoly{} by
  12799. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  12800. programs that use polymorphic functions. Some of them should make
  12801. use of first-class polymorphism.
  12802. \end{exercise}
  12803. \begin{figure}[p]
  12804. \begin{tikzpicture}[baseline=(current bounding box.center)]
  12805. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  12806. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  12807. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  12808. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  12809. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  12810. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  12811. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  12812. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  12813. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  12814. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  12815. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  12816. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  12817. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  12818. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  12819. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  12820. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  12821. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  12822. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  12823. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  12824. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  12825. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  12826. \path[->,bend right=15] (Rpoly) edge [above] node
  12827. {\ttfamily\footnotesize type-check} (Rpolyp);
  12828. \path[->,bend right=15] (Rpolyp) edge [above] node
  12829. {\ttfamily\footnotesize erase-types} (Rgradualp);
  12830. \path[->,bend right=15] (Rgradualp) edge [above] node
  12831. {\ttfamily\footnotesize lower-casts} (Rwhilepp);
  12832. \path[->,bend right=15] (Rwhilepp) edge [right] node
  12833. {\ttfamily\footnotesize differentiate-proxies} (Rwhileproxy);
  12834. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  12835. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  12836. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  12837. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  12838. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  12839. {\ttfamily\footnotesize reveal-functions} (Rwhileproxy-4);
  12840. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  12841. {\ttfamily\footnotesize reveal-casts} (Rwhileproxy-5);
  12842. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  12843. {\ttfamily\footnotesize convert-assignments} (F1-1);
  12844. \path[->,bend left=15] (F1-1) edge [below] node
  12845. {\ttfamily\footnotesize convert-to-clos.} (F1-2);
  12846. \path[->,bend right=15] (F1-2) edge [above] node
  12847. {\ttfamily\footnotesize limit-fun.} (F1-3);
  12848. \path[->,bend right=15] (F1-3) edge [above] node
  12849. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  12850. \path[->,bend right=15] (F1-4) edge [above] node
  12851. {\ttfamily\footnotesize remove-complex.} (F1-5);
  12852. \path[->,bend right=15] (F1-5) edge [right] node
  12853. {\ttfamily\footnotesize explicate-control} (C3-2);
  12854. \path[->,bend left=15] (C3-2) edge [left] node
  12855. {\ttfamily\footnotesize select-instr.} (x86-2);
  12856. \path[->,bend right=15] (x86-2) edge [left] node
  12857. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  12858. \path[->,bend right=15] (x86-2-1) edge [below] node
  12859. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  12860. \path[->,bend right=15] (x86-2-2) edge [left] node
  12861. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  12862. \path[->,bend left=15] (x86-3) edge [above] node
  12863. {\ttfamily\footnotesize patch-instr.} (x86-4);
  12864. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  12865. \end{tikzpicture}
  12866. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  12867. \label{fig:Rpoly-passes}
  12868. \end{figure}
  12869. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  12870. for the compilation of \LangPoly{}.
  12871. % TODO: challenge problem: specialization of instantiations
  12872. % Further Reading
  12873. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12874. \clearpage
  12875. \appendix
  12876. \chapter{Appendix}
  12877. \section{Interpreters}
  12878. \label{appendix:interp}
  12879. \index{subject}{interpreter}
  12880. We provide interpreters for each of the source languages \LangInt{},
  12881. \LangVar{}, $\ldots$ in the files \code{interp\_Rint.rkt},
  12882. \code{interp-Rvar.rkt}, etc. The interpreters for the intermediate
  12883. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  12884. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  12885. and x86 are in the \key{interp.rkt} file.
  12886. \section{Utility Functions}
  12887. \label{appendix:utilities}
  12888. The utility functions described in this section are in the
  12889. \key{utilities.rkt} file of the support code.
  12890. \paragraph{\code{interp-tests}}
  12891. The \key{interp-tests} function runs the compiler passes and the
  12892. interpreters on each of the specified tests to check whether each pass
  12893. is correct. The \key{interp-tests} function has the following
  12894. parameters:
  12895. \begin{description}
  12896. \item[name (a string)] a name to identify the compiler,
  12897. \item[typechecker] a function of exactly one argument that either
  12898. raises an error using the \code{error} function when it encounters a
  12899. type error, or returns \code{\#f} when it encounters a type
  12900. error. If there is no type error, the type checker returns the
  12901. program.
  12902. \item[passes] a list with one entry per pass. An entry is a list with
  12903. four things:
  12904. \begin{enumerate}
  12905. \item a string giving the name of the pass,
  12906. \item the function that implements the pass (a translator from AST
  12907. to AST),
  12908. \item a function that implements the interpreter (a function from
  12909. AST to result value) for the output language,
  12910. \item and a type checker for the output language. Type checkers for
  12911. the $R$ and $C$ languages are provided in the support code. For
  12912. example, the type checkers for \LangVar{} and \LangCVar{} are in
  12913. \code{type-check-Rvar.rkt} and \code{type-check-Cvar.rkt}. The
  12914. type checker entry is optional. The support code does not provide
  12915. type checkers for the x86 languages.
  12916. \end{enumerate}
  12917. \item[source-interp] an interpreter for the source language. The
  12918. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  12919. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  12920. \item[tests] a list of test numbers that specifies which tests to
  12921. run. (see below)
  12922. \end{description}
  12923. %
  12924. The \key{interp-tests} function assumes that the subdirectory
  12925. \key{tests} has a collection of Racket programs whose names all start
  12926. with the family name, followed by an underscore and then the test
  12927. number, ending with the file extension \key{.rkt}. Also, for each test
  12928. program that calls \code{read} one or more times, there is a file with
  12929. the same name except that the file extension is \key{.in} that
  12930. provides the input for the Racket program. If the test program is
  12931. expected to fail type checking, then there should be an empty file of
  12932. the same name but with extension \key{.tyerr}.
  12933. \paragraph{\code{compiler-tests}}
  12934. runs the compiler passes to generate x86 (a \key{.s} file) and then
  12935. runs the GNU C compiler (gcc) to generate machine code. It runs the
  12936. machine code and checks that the output is $42$. The parameters to the
  12937. \code{compiler-tests} function are similar to those of the
  12938. \code{interp-tests} function, and consist of
  12939. \begin{itemize}
  12940. \item a compiler name (a string),
  12941. \item a type checker,
  12942. \item description of the passes,
  12943. \item name of a test-family, and
  12944. \item a list of test numbers.
  12945. \end{itemize}
  12946. \paragraph{\code{compile-file}}
  12947. takes a description of the compiler passes (see the comment for
  12948. \key{interp-tests}) and returns a function that, given a program file
  12949. name (a string ending in \key{.rkt}), applies all of the passes and
  12950. writes the output to a file whose name is the same as the program file
  12951. name but with \key{.rkt} replaced with \key{.s}.
  12952. \paragraph{\code{read-program}}
  12953. takes a file path and parses that file (it must be a Racket program)
  12954. into an abstract syntax tree.
  12955. \paragraph{\code{parse-program}}
  12956. takes an S-expression representation of an abstract syntax tree and converts it into
  12957. the struct-based representation.
  12958. \paragraph{\code{assert}}
  12959. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  12960. and displays the message \key{msg} if the Boolean \key{bool} is false.
  12961. \paragraph{\code{lookup}}
  12962. % remove discussion of lookup? -Jeremy
  12963. takes a key and an alist, and returns the first value that is
  12964. associated with the given key, if there is one. If not, an error is
  12965. triggered. The alist may contain both immutable pairs (built with
  12966. \key{cons}) and mutable pairs (built with \key{mcons}).
  12967. %The \key{map2} function ...
  12968. \section{x86 Instruction Set Quick-Reference}
  12969. \label{sec:x86-quick-reference}
  12970. \index{subject}{x86}
  12971. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  12972. do. We write $A \to B$ to mean that the value of $A$ is written into
  12973. location $B$. Address offsets are given in bytes. The instruction
  12974. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  12975. registers (such as \code{\%rax}), or memory references (such as
  12976. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  12977. reference per instruction. Other operands must be immediates or
  12978. registers.
  12979. \begin{table}[tbp]
  12980. \centering
  12981. \begin{tabular}{l|l}
  12982. \textbf{Instruction} & \textbf{Operation} \\ \hline
  12983. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  12984. \texttt{negq} $A$ & $- A \to A$ \\
  12985. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  12986. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  12987. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  12988. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  12989. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  12990. \texttt{retq} & Pops the return address and jumps to it \\
  12991. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  12992. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  12993. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  12994. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  12995. be an immediate) \\
  12996. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  12997. matches the condition code of the instruction, otherwise go to the
  12998. next instructions. The condition codes are \key{e} for ``equal'',
  12999. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  13000. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  13001. \texttt{jl} $L$ & \\
  13002. \texttt{jle} $L$ & \\
  13003. \texttt{jg} $L$ & \\
  13004. \texttt{jge} $L$ & \\
  13005. \texttt{jmp} $L$ & Jump to label $L$ \\
  13006. \texttt{movq} $A$, $B$ & $A \to B$ \\
  13007. \texttt{movzbq} $A$, $B$ &
  13008. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  13009. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  13010. and the extra bytes of $B$ are set to zero.} \\
  13011. & \\
  13012. & \\
  13013. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  13014. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  13015. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  13016. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  13017. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  13018. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  13019. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  13020. description of the condition codes. $A$ must be a single byte register
  13021. (e.g., \texttt{al} or \texttt{cl}).} \\
  13022. \texttt{setl} $A$ & \\
  13023. \texttt{setle} $A$ & \\
  13024. \texttt{setg} $A$ & \\
  13025. \texttt{setge} $A$ &
  13026. \end{tabular}
  13027. \vspace{5pt}
  13028. \caption{Quick-reference for the x86 instructions used in this book.}
  13029. \label{tab:x86-instr}
  13030. \end{table}
  13031. \cleardoublepage
  13032. \section{Concrete Syntax for Intermediate Languages}
  13033. The concrete syntax of \LangAny{} is defined in
  13034. Figure~\ref{fig:Rany-concrete-syntax}.
  13035. \begin{figure}[tp]
  13036. \centering
  13037. \fbox{
  13038. \begin{minipage}{0.97\textwidth}\small
  13039. \[
  13040. \begin{array}{lcl}
  13041. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  13042. \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}} \\
  13043. &\MID& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \MID \key{Any} \\
  13044. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  13045. \MID \LP\key{Vector}\; \key{Any}\ldots\RP \\
  13046. &\MID& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  13047. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \MID \CPROJECT{\Exp}{\FType}\\
  13048. &\MID& \LP\key{any-vector-length}\;\Exp\RP
  13049. \MID \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  13050. &\MID& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  13051. &\MID& \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP
  13052. \MID \LP\key{void?}\;\Exp\RP \\
  13053. &\MID& \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \\
  13054. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  13055. \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  13056. \end{array}
  13057. \]
  13058. \end{minipage}
  13059. }
  13060. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  13061. (Figure~\ref{fig:Rlam-syntax}).}
  13062. \label{fig:Rany-concrete-syntax}
  13063. \end{figure}
  13064. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and \LangCFun{} is
  13065. defined in Figures~\ref{fig:c0-concrete-syntax},
  13066. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax},
  13067. and \ref{fig:c3-concrete-syntax}, respectively.
  13068. \begin{figure}[tbp]
  13069. \fbox{
  13070. \begin{minipage}{0.96\textwidth}
  13071. \[
  13072. \begin{array}{lcl}
  13073. \Atm &::=& \Int \MID \Var \\
  13074. \Exp &::=& \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)}\\
  13075. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  13076. \Tail &::= & \key{return}~\Exp\key{;} \MID \Stmt~\Tail \\
  13077. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  13078. \end{array}
  13079. \]
  13080. \end{minipage}
  13081. }
  13082. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  13083. \label{fig:c0-concrete-syntax}
  13084. \end{figure}
  13085. \begin{figure}[tbp]
  13086. \fbox{
  13087. \begin{minipage}{0.96\textwidth}
  13088. \small
  13089. \[
  13090. \begin{array}{lcl}
  13091. \Atm &::=& \gray{ \Int \MID \Var } \MID \itm{bool} \\
  13092. \itm{cmp} &::= & \key{eq?} \MID \key{<} \\
  13093. \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  13094. &\MID& \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  13095. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  13096. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  13097. \MID \key{goto}~\itm{label}\key{;}\\
  13098. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  13099. \LangCIfM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  13100. \end{array}
  13101. \]
  13102. \end{minipage}
  13103. }
  13104. \caption{The concrete syntax of the \LangCIf{} intermediate language.}
  13105. \label{fig:c1-concrete-syntax}
  13106. \end{figure}
  13107. \begin{figure}[tbp]
  13108. \fbox{
  13109. \begin{minipage}{0.96\textwidth}
  13110. \small
  13111. \[
  13112. \begin{array}{lcl}
  13113. \Atm &::=& \gray{ \Int \MID \Var \MID \itm{bool} } \\
  13114. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  13115. \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  13116. &\MID& \gray{ \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP } \\
  13117. &\MID& \LP \key{allocate}~\Int~\Type \RP \\
  13118. &\MID& (\key{vector-ref}\;\Atm\;\Int) \MID (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  13119. &\MID& \LP \key{global-value}~\Var \RP \MID \LP \key{void} \RP \\
  13120. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \MID \LP\key{collect}~\Int \RP\\
  13121. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  13122. \MID \gray{ \key{goto}~\itm{label}\key{;} }\\
  13123. &\MID& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  13124. \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  13125. \end{array}
  13126. \]
  13127. \end{minipage}
  13128. }
  13129. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  13130. \label{fig:c2-concrete-syntax}
  13131. \end{figure}
  13132. \begin{figure}[tp]
  13133. \fbox{
  13134. \begin{minipage}{0.96\textwidth}
  13135. \small
  13136. \[
  13137. \begin{array}{lcl}
  13138. \Atm &::=& \gray{ \Int \MID \Var \MID \key{\#t} \MID \key{\#f} }
  13139. \\
  13140. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  13141. \Exp &::= & \gray{ \Atm \MID \LP\key{read}\RP \MID \LP\key{-}\;\Atm\RP \MID \LP\key{+} \; \Atm\;\Atm\RP
  13142. \MID \LP\key{not}\;\Atm\RP \MID \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  13143. &\MID& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  13144. \MID \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  13145. &\MID& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \MID \LP\key{global-value} \,\itm{name}\RP \MID \LP\key{void}\RP } \\
  13146. &\MID& \LP\key{fun-ref}~\itm{label}\RP \MID \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  13147. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \MID \RETURN{\Exp}
  13148. \MID \LP\key{collect} \,\itm{int}\RP }\\
  13149. \Tail &::= & \gray{\RETURN{\Exp} \MID \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  13150. &\MID& \gray{\LP\key{goto}\,\itm{label}\RP
  13151. \MID \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  13152. &\MID& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  13153. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  13154. \LangCFunM{} & ::= & \Def\ldots
  13155. \end{array}
  13156. \]
  13157. \end{minipage}
  13158. }
  13159. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  13160. \label{fig:c3-concrete-syntax}
  13161. \end{figure}
  13162. \backmatter
  13163. \addtocontents{toc}{\vspace{11pt}}
  13164. %% \addtocontents{toc}{\vspace{11pt}}
  13165. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  13166. \nocite{*}\let\bibname\refname
  13167. \addcontentsline{toc}{fmbm}{\refname}
  13168. \printbibliography
  13169. \printindex{authors}{Author Index}
  13170. \printindex{subject}{Subject Index}
  13171. \end{document}