book.tex 355 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466
  1. % Why direct style instead of continuation passing style?
  2. %% Student project ideas:
  3. %% * high-level optimizations like procedure inlining, etc.
  4. %% * closure optimization
  5. %% * adding letrec to the language
  6. %% (Thought: in the book and regular course, replace top-level defines
  7. %% with letrec.)
  8. %% * alternative back ends (ARM, LLVM)
  9. %% * alternative calling convention (a la Dybvig)
  10. %% * lazy evaluation
  11. %% * gradual typing
  12. %% * continuations (frames in heap a la SML or segmented stack a la Dybvig)
  13. %% * exceptions
  14. %% * self hosting
  15. %% * I/O
  16. %% * foreign function interface
  17. %% * quasi-quote and unquote
  18. %% * macros (too difficult?)
  19. %% * alternative garbage collector
  20. %% * alternative register allocator
  21. %% * parametric polymorphism
  22. %% * type classes (too difficulty?)
  23. %% * loops (too easy? combine with something else?)
  24. %% * loop optimization (fusion, etc.)
  25. %% * deforestation
  26. %% * records and subtyping
  27. %% * object-oriented features
  28. %% - objects, object types, and structural subtyping (e.g. Abadi & Cardelli)
  29. %% - class-based objects and nominal subtyping (e.g. Featherweight Java)
  30. %% * multi-threading, fork join, futures, implicit parallelism
  31. %% * dataflow analysis, type analysis and specialization
  32. \documentclass[11pt]{book}
  33. \usepackage[T1]{fontenc}
  34. \usepackage[utf8]{inputenc}
  35. \usepackage{lmodern}
  36. \usepackage{hyperref}
  37. \usepackage{graphicx}
  38. \usepackage[english]{babel}
  39. \usepackage{listings}
  40. \usepackage{amsmath}
  41. \usepackage{amsthm}
  42. \usepackage{amssymb}
  43. \usepackage{natbib}
  44. \usepackage{stmaryrd}
  45. \usepackage{xypic}
  46. \usepackage{semantic}
  47. \usepackage{wrapfig}
  48. \usepackage{tcolorbox}
  49. \usepackage{multirow}
  50. \usepackage{color}
  51. \usepackage{upquote}
  52. \usepackage{makeidx}
  53. \makeindex
  54. \definecolor{lightgray}{gray}{1}
  55. \newcommand{\black}[1]{{\color{black} #1}}
  56. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  57. \newcommand{\gray}[1]{{\color{gray} #1}}
  58. %% For pictures
  59. \usepackage{tikz}
  60. \usetikzlibrary{arrows.meta}
  61. \tikzset{baseline=(current bounding box.center), >/.tip={Triangle[scale=1.4]}}
  62. % Computer Modern is already the default. -Jeremy
  63. %\renewcommand{\ttdefault}{cmtt}
  64. \definecolor{comment-red}{rgb}{0.8,0,0}
  65. \if01
  66. \newcommand{\rn}[1]{{\color{comment-red}{(RRN: #1)}}}
  67. \newcommand{\margincomment}[1]{\marginpar{\color{comment-red}\tiny #1}}
  68. \else
  69. \newcommand{\rn}[1]{}
  70. \newcommand{\margincomment}[1]{}
  71. \fi
  72. \lstset{%
  73. language=Lisp,
  74. basicstyle=\ttfamily\small,
  75. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void},
  76. deletekeywords={read},
  77. escapechar=|,
  78. columns=flexible,
  79. moredelim=[is][\color{red}]{~}{~},
  80. showstringspaces=false
  81. }
  82. \newtheorem{theorem}{Theorem}
  83. \newtheorem{lemma}[theorem]{Lemma}
  84. \newtheorem{corollary}[theorem]{Corollary}
  85. \newtheorem{proposition}[theorem]{Proposition}
  86. \newtheorem{constraint}[theorem]{Constraint}
  87. \newtheorem{definition}[theorem]{Definition}
  88. \newtheorem{exercise}[theorem]{Exercise}
  89. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  90. % 'dedication' environment: To add a dedication paragraph at the start of book %
  91. % Source: http://www.tug.org/pipermail/texhax/2010-June/015184.html %
  92. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  93. \newenvironment{dedication}
  94. {
  95. \cleardoublepage
  96. \thispagestyle{empty}
  97. \vspace*{\stretch{1}}
  98. \hfill\begin{minipage}[t]{0.66\textwidth}
  99. \raggedright
  100. }
  101. {
  102. \end{minipage}
  103. \vspace*{\stretch{3}}
  104. \clearpage
  105. }
  106. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  107. % Chapter quote at the start of chapter %
  108. % Source: http://tex.stackexchange.com/a/53380 %
  109. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  110. \makeatletter
  111. \renewcommand{\@chapapp}{}% Not necessary...
  112. \newenvironment{chapquote}[2][2em]
  113. {\setlength{\@tempdima}{#1}%
  114. \def\chapquote@author{#2}%
  115. \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
  116. \itshape}
  117. {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
  118. \makeatother
  119. \input{defs}
  120. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  121. \title{\Huge \textbf{Essentials of Compilation} \\
  122. \huge An Incremental Approach}
  123. \author{\textsc{Jeremy G. Siek} \\
  124. %\thanks{\url{http://homes.soic.indiana.edu/jsiek/}} \\
  125. Indiana University \\
  126. \\
  127. with contributions from: \\
  128. Carl Factora \\
  129. Andre Kuhlenschmidt \\
  130. Ryan R. Newton \\
  131. Ryan Scott \\
  132. Cameron Swords \\
  133. Michael M. Vitousek \\
  134. Michael Vollmer
  135. }
  136. \begin{document}
  137. \frontmatter
  138. \maketitle
  139. \begin{dedication}
  140. This book is dedicated to the programming language wonks at Indiana
  141. University.
  142. \end{dedication}
  143. \tableofcontents
  144. \listoffigures
  145. %\listoftables
  146. \mainmatter
  147. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  148. \chapter*{Preface}
  149. The tradition of compiler writing at Indiana University goes back to
  150. research and courses about programming languages by Daniel Friedman in
  151. the 1970's and 1980's. Dan conducted research on lazy
  152. evaluation~\citep{Friedman:1976aa} in the context of
  153. Lisp~\citep{McCarthy:1960dz} and then studied
  154. continuations~\citep{Felleisen:kx} and
  155. macros~\citep{Kohlbecker:1986dk} in the context of the
  156. Scheme~\citep{Sussman:1975ab}, a dialect of Lisp. One of the students
  157. of those courses, Kent Dybvig, went on to build Chez
  158. Scheme~\citep{Dybvig:2006aa}, a production-quality and efficient
  159. compiler for Scheme. After completing his Ph.D. at the University of
  160. North Carolina, Kent returned to teach at Indiana University.
  161. Throughout the 1990's and 2000's, Kent continued development of Chez
  162. Scheme and taught the compiler course.
  163. The compiler course evolved to incorporate novel pedagogical ideas
  164. while also including elements of effective real-world compilers. One
  165. of Dan's ideas was to split the compiler into many small ``passes'' so
  166. that the code for each pass would be easy to understood in isolation.
  167. (In contrast, most compilers of the time were organized into only a
  168. few monolithic passes for reasons of compile-time efficiency.) Kent,
  169. with later help from his students Dipanwita Sarkar and Andrew Keep,
  170. developed infrastructure to support this approach and evolved the
  171. course, first to use micro-sized passes and then into even smaller
  172. nano passes~\citep{Sarkar:2004fk,Keep:2012aa}. Jeremy Siek was a
  173. student in this compiler course in the early 2000's, as part of his
  174. Ph.D. studies at Indiana University. Needless to say, Jeremy enjoyed
  175. the course immensely!
  176. During that time, another student named Abdulaziz Ghuloum observed
  177. that the front-to-back organization of the course made it difficult
  178. for students to understand the rationale for the compiler
  179. design. Abdulaziz proposed an incremental approach in which the
  180. students build the compiler in stages; they start by implementing a
  181. complete compiler for a very small subset of the input language and in
  182. each subsequent stage they add a language feature and add or modify
  183. passes to handle the new feature~\citep{Ghuloum:2006bh}. In this way,
  184. the students see how the language features motivate aspects of the
  185. compiler design.
  186. After graduating from Indiana University in 2005, Jeremy went on to
  187. teach at the University of Colorado. He adapted the nano pass and
  188. incremental approaches to compiling a subset of the Python
  189. language~\citep{Siek:2012ab}. Python and Scheme are quite different
  190. on the surface but there is a large overlap in the compiler techniques
  191. required for the two languages. Thus, Jeremy was able to teach much of
  192. the same content from the Indiana compiler course. He very much
  193. enjoyed teaching the course organized in this way, and even better,
  194. many of the students learned a lot and got excited about compilers.
  195. Jeremy returned to teach at Indiana University in 2013. In his
  196. absence the compiler course had switched from the front-to-back
  197. organization to a back-to-front organization. Seeing how well the
  198. incremental approach worked at Colorado, he started porting and
  199. adapting the structure of the Colorado course back into the land of
  200. Scheme. In the meantime Indiana had moved on from Scheme to Racket, so
  201. the course is now about compiling a subset of Racket (and Typed
  202. Racket) to the x86 assembly language. The compiler is implemented in
  203. Racket 7.1~\citep{plt-tr}.
  204. This is the textbook for the incremental version of the compiler
  205. course at Indiana University (Spring 2016 - present) and it is the
  206. first open textbook for an Indiana compiler course. With this book we
  207. hope to make the Indiana compiler course available to people that have
  208. not had the chance to study in Bloomington in person. Many of the
  209. compiler design decisions in this book are drawn from the assignment
  210. descriptions of \cite{Dybvig:2010aa}. We have captured what we think
  211. are the most important topics from \cite{Dybvig:2010aa} but we have
  212. omitted topics that we think are less interesting conceptually and we
  213. have made simplifications to reduce complexity. In this way, this
  214. book leans more towards pedagogy than towards the efficiency of the
  215. generated code. Also, the book differs in places where we saw the
  216. opportunity to make the topics more fun, such as in relating register
  217. allocation to Sudoku (Chapter~\ref{ch:register-allocation-r1}).
  218. \section*{Prerequisites}
  219. The material in this book is challenging but rewarding. It is meant to
  220. prepare students for a lifelong career in programming languages.
  221. The book uses the Racket language both for the implementation of the
  222. compiler and for the language that is compiled, so a student should be
  223. proficient with Racket (or Scheme) prior to reading this book. There
  224. are many excellent resources for learning Scheme and
  225. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}. It
  226. is helpful but not necessary for the student to have prior exposure to
  227. the x86 (or x86-64) assembly language~\citep{Intel:2015aa}, as one might
  228. obtain from a computer systems
  229. course~\citep{Bryant:2005aa,Bryant:2010aa}. This book introduces the
  230. parts of x86-64 assembly language that are needed.
  231. %\section*{Structure of book}
  232. % You might want to add short description about each chapter in this book.
  233. %\section*{About the companion website}
  234. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  235. %\begin{itemize}
  236. % \item A link to (freely downlodable) latest version of this document.
  237. % \item Link to download LaTeX source for this document.
  238. % \item Miscellaneous material (e.g. suggested readings etc).
  239. %\end{itemize}
  240. \section*{Acknowledgments}
  241. Many people have contributed to the ideas, techniques, organization,
  242. and teaching of the materials in this book. We especially thank the
  243. following people.
  244. \begin{itemize}
  245. \item Bor-Yuh Evan Chang
  246. \item Kent Dybvig
  247. \item Daniel P. Friedman
  248. \item Ronald Garcia
  249. \item Abdulaziz Ghuloum
  250. \item Jay McCarthy
  251. \item Dipanwita Sarkar
  252. \item Andrew Keep
  253. \item Oscar Waddell
  254. \item Michael Wollowski
  255. \end{itemize}
  256. \mbox{}\\
  257. \noindent Jeremy G. Siek \\
  258. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  259. %\noindent Spring 2016
  260. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  261. \chapter{Preliminaries}
  262. \label{ch:trees-recur}
  263. In this chapter we review the basic tools that are needed to implement
  264. a compiler. Programs are typically input by a programmer as text,
  265. i.e., a sequence of characters. The program-as-text representation is
  266. called \emph{concrete syntax}. We use concrete syntax to concisely
  267. write down and talk about programs. Inside the compiler, we use
  268. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  269. that efficiently supports the operations that the compiler needs to
  270. perform.
  271. \index{concrete syntax}
  272. \index{abstract syntax}
  273. \index{abstract syntax tree}
  274. \index{AST}
  275. \index{program}
  276. \index{parse}
  277. %
  278. The translation from concrete syntax to abstract syntax is a process
  279. called \emph{parsing}~\cite{Aho:1986qf}. We do not cover the theory
  280. and implementation of parsing in this book. A parser is provided in
  281. the supporting materials for translating from concrete syntax to
  282. abstract syntax for the languages used in this book.
  283. ASTs can be represented in many different ways inside the compiler,
  284. depending on the programming language used to write the compiler.
  285. %
  286. We use Racket's \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  287. feature to represent ASTs (Section~\ref{sec:ast}). We use grammars to
  288. define the abstract syntax of programming languages (Section~\ref{sec:grammar})
  289. and pattern matching to inspect individual nodes in an AST
  290. (Section~\ref{sec:pattern-matching}). We use recursion to construct
  291. and deconstruct entire ASTs (Section~\ref{sec:recursion}). This
  292. chapter provides an brief introduction to these ideas.
  293. \index{struct}
  294. \section{Abstract Syntax Trees and Racket Structures}
  295. \label{sec:ast}
  296. Compilers use abstract syntax trees to represent programs because
  297. compilers often need to ask questions like: for a given part of a
  298. program, what kind of language feature is it? What are the sub-parts
  299. of this part of the program? Consider the program on the left and its
  300. AST on the right. This program is an addition and it has two
  301. sub-parts, a read operation and a negation. The negation has another
  302. sub-part, the integer constant \code{8}. By using a tree to represent
  303. the program, we can easily follow the links to go from one part of a
  304. program to its sub-parts.
  305. \begin{center}
  306. \begin{minipage}{0.4\textwidth}
  307. \begin{lstlisting}
  308. (+ (read) (- 8))
  309. \end{lstlisting}
  310. \end{minipage}
  311. \begin{minipage}{0.4\textwidth}
  312. \begin{equation}
  313. \begin{tikzpicture}
  314. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  315. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  316. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  317. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  318. \draw[->] (plus) to (read);
  319. \draw[->] (plus) to (minus);
  320. \draw[->] (minus) to (8);
  321. \end{tikzpicture}
  322. \label{eq:arith-prog}
  323. \end{equation}
  324. \end{minipage}
  325. \end{center}
  326. We use the standard terminology for trees to describe ASTs: each
  327. circle above is called a \emph{node}. The arrows connect a node to its
  328. \emph{children} (which are also nodes). The top-most node is the
  329. \emph{root}. Every node except for the root has a \emph{parent} (the
  330. node it is the child of). If a node has no children, it is a
  331. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  332. \index{node}
  333. \index{children}
  334. \index{root}
  335. \index{parent}
  336. \index{leaf}
  337. \index{internal node}
  338. %% Recall that an \emph{symbolic expression} (S-expression) is either
  339. %% \begin{enumerate}
  340. %% \item an atom, or
  341. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  342. %% where $e_1$ and $e_2$ are each an S-expression.
  343. %% \end{enumerate}
  344. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  345. %% null value \code{'()}, etc. We can create an S-expression in Racket
  346. %% simply by writing a backquote (called a quasi-quote in Racket)
  347. %% followed by the textual representation of the S-expression. It is
  348. %% quite common to use S-expressions to represent a list, such as $a, b
  349. %% ,c$ in the following way:
  350. %% \begin{lstlisting}
  351. %% `(a . (b . (c . ())))
  352. %% \end{lstlisting}
  353. %% Each element of the list is in the first slot of a pair, and the
  354. %% second slot is either the rest of the list or the null value, to mark
  355. %% the end of the list. Such lists are so common that Racket provides
  356. %% special notation for them that removes the need for the periods
  357. %% and so many parenthesis:
  358. %% \begin{lstlisting}
  359. %% `(a b c)
  360. %% \end{lstlisting}
  361. %% The following expression creates an S-expression that represents AST
  362. %% \eqref{eq:arith-prog}.
  363. %% \begin{lstlisting}
  364. %% `(+ (read) (- 8))
  365. %% \end{lstlisting}
  366. %% When using S-expressions to represent ASTs, the convention is to
  367. %% represent each AST node as a list and to put the operation symbol at
  368. %% the front of the list. The rest of the list contains the children. So
  369. %% in the above case, the root AST node has operation \code{`+} and its
  370. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  371. %% diagram \eqref{eq:arith-prog}.
  372. %% To build larger S-expressions one often needs to splice together
  373. %% several smaller S-expressions. Racket provides the comma operator to
  374. %% splice an S-expression into a larger one. For example, instead of
  375. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  376. %% we could have first created an S-expression for AST
  377. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  378. %% S-expression.
  379. %% \begin{lstlisting}
  380. %% (define ast1.4 `(- 8))
  381. %% (define ast1.1 `(+ (read) ,ast1.4))
  382. %% \end{lstlisting}
  383. %% In general, the Racket expression that follows the comma (splice)
  384. %% can be any expression that produces an S-expression.
  385. We define a Racket \code{struct} for each kind of node. For this
  386. chapter we require just two kinds of nodes: one for integer constants
  387. and one for primitive operations. The following is the \code{struct}
  388. definition for integer constants.
  389. \begin{lstlisting}
  390. (struct Int (value))
  391. \end{lstlisting}
  392. An integer node includes just one thing: the integer value.
  393. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  394. \begin{lstlisting}
  395. (define eight (Int 8))
  396. \end{lstlisting}
  397. We say that the value created by \code{(Int 8)} is an
  398. \emph{instance} of the \code{Int} structure.
  399. The following is the \code{struct} definition for primitives operations.
  400. \begin{lstlisting}
  401. (struct Prim (op arg*))
  402. \end{lstlisting}
  403. A primitive operation node includes an operator symbol \code{op}
  404. and a list of children \code{arg*}. For example, to create
  405. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  406. \begin{lstlisting}
  407. (define neg-eight (Prim '- (list eight)))
  408. \end{lstlisting}
  409. Primitive operations may have zero or more children. The \code{read}
  410. operator has zero children:
  411. \begin{lstlisting}
  412. (define rd (Prim 'read '()))
  413. \end{lstlisting}
  414. whereas the addition operator has two children:
  415. \begin{lstlisting}
  416. (define ast1.1 (Prim '+ (list rd neg-eight)))
  417. \end{lstlisting}
  418. We have made a design choice regarding the \code{Prim} structure.
  419. Instead of using one structure for many different operations
  420. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  421. structure for each operation, as follows.
  422. \begin{lstlisting}
  423. (struct Read ())
  424. (struct Add (left right))
  425. (struct Neg (value))
  426. \end{lstlisting}
  427. The reason we choose to use just one structure is that in many parts
  428. of the compiler the code for the different primitive operators is the
  429. same, so we might as well just write that code once, which is enabled
  430. by using a single structure.
  431. When compiling a program such as \eqref{eq:arith-prog}, we need to
  432. know that the operation associated with the root node is addition and
  433. we need to be able to access its two children. Racket provides pattern
  434. matching over structures to support these kinds of queries, as we
  435. see in Section~\ref{sec:pattern-matching}.
  436. In this book, we often write down the concrete syntax of a program
  437. even when we really have in mind the AST because the concrete syntax
  438. is more concise. We recommend that, in your mind, you always think of
  439. programs as abstract syntax trees.
  440. \section{Grammars}
  441. \label{sec:grammar}
  442. \index{integer}
  443. \index{literal}
  444. \index{constant}
  445. A programming language can be thought of as a \emph{set} of programs.
  446. The set is typically infinite (one can always create larger and larger
  447. programs), so one cannot simply describe a language by listing all of
  448. the programs in the language. Instead we write down a set of rules, a
  449. \emph{grammar}, for building programs. Grammars are often used to
  450. define the concrete syntax of a language, but they can also be used to
  451. describe the abstract syntax. We write our rules in a variant of
  452. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  453. \index{Backus-Naur Form}\index{BNF}
  454. As an example, we describe a small language, named $R_0$, that consists of
  455. integers and arithmetic operations.
  456. \index{grammar}
  457. The first grammar rule for the abstract syntax of $R_0$ says that an
  458. instance of the \code{Int} structure is an expression:
  459. \begin{equation}
  460. \Exp ::= \INT{\Int} \label{eq:arith-int}
  461. \end{equation}
  462. %
  463. Each rule has a left-hand-side and a right-hand-side. The way to read
  464. a rule is that if you have all the program parts on the
  465. right-hand-side, then you can create an AST node and categorize it
  466. according to the left-hand-side.
  467. %
  468. A name such as $\Exp$ that is
  469. defined by the grammar rules is a \emph{non-terminal}.
  470. \index{non-terminal}
  471. %
  472. The name $\Int$ is a also a non-terminal, but instead of defining it
  473. with a grammar rule, we define it with the following explanation. We
  474. make the simplifying design decision that all of the languages in this
  475. book only handle machine-representable integers. On most modern
  476. machines this corresponds to integers represented with 64-bits, i.e.,
  477. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  478. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  479. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  480. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  481. that the sequence of decimals represent an integer in range $-2^{62}$
  482. to $2^{62}-1$.
  483. The second grammar rule is the \texttt{read} operation that receives
  484. an input integer from the user of the program.
  485. \begin{equation}
  486. \Exp ::= \READ{} \label{eq:arith-read}
  487. \end{equation}
  488. The third rule says that, given an $\Exp$ node, you can build another
  489. $\Exp$ node by negating it.
  490. \begin{equation}
  491. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  492. \end{equation}
  493. Symbols in typewriter font such as \key{-} and \key{read} are
  494. \emph{terminal} symbols and must literally appear in the program for
  495. the rule to be applicable.
  496. \index{terminal}
  497. We can apply the rules to build ASTs in the $R_0$
  498. language. For example, by rule \eqref{eq:arith-int}, \texttt{(Int 8)} is an
  499. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  500. an $\Exp$.
  501. \begin{center}
  502. \begin{minipage}{0.4\textwidth}
  503. \begin{lstlisting}
  504. (Prim '- (list (Int 8)))
  505. \end{lstlisting}
  506. \end{minipage}
  507. \begin{minipage}{0.25\textwidth}
  508. \begin{equation}
  509. \begin{tikzpicture}
  510. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  511. \node[draw, circle] (8) at (0, -1.2) {$8$};
  512. \draw[->] (minus) to (8);
  513. \end{tikzpicture}
  514. \label{eq:arith-neg8}
  515. \end{equation}
  516. \end{minipage}
  517. \end{center}
  518. The next grammar rule defines addition expressions:
  519. \begin{equation}
  520. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  521. \end{equation}
  522. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  523. $R_0$. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  524. \eqref{eq:arith-read} and we have already shown that \code{(Prim '-
  525. (list (Int 8)))} is an $\Exp$, so we apply rule \eqref{eq:arith-add}
  526. to show that
  527. \begin{lstlisting}
  528. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  529. \end{lstlisting}
  530. is an $\Exp$ in the $R_0$ language.
  531. If you have an AST for which the above rules do not apply, then the
  532. AST is not in $R_0$. For example, the program \code{(- (read) (+ 8))}
  533. is not in $R_0$ because there are no rules for \code{+} with only one
  534. argument, nor for \key{-} with two arguments. Whenever we define a
  535. language with a grammar, the language only includes those programs
  536. that are justified by the rules.
  537. The last grammar rule for $R_0$ states that there is a \code{Program}
  538. node to mark the top of the whole program:
  539. \[
  540. R_0 ::= \PROGRAM{\code{'()}}{\Exp}
  541. \]
  542. The \code{Program} structure is defined as follows
  543. \begin{lstlisting}
  544. (struct Program (info body))
  545. \end{lstlisting}
  546. where \code{body} is an expression. In later chapters, the \code{info}
  547. part will be used to store auxiliary information but for now it is
  548. just the empty list.
  549. It is common to have many grammar rules with the same left-hand side
  550. but different right-hand sides, such as the rules for $\Exp$ in the
  551. grammar of $R_0$. As a short-hand, a vertical bar can be used to
  552. combine several right-hand-sides into a single rule.
  553. We collect all of the grammar rules for the abstract syntax of $R_0$
  554. in Figure~\ref{fig:r0-syntax}. The concrete syntax for $R_0$ is
  555. defined in Figure~\ref{fig:r0-concrete-syntax}.
  556. The \code{read-program} function provided in \code{utilities.rkt} of
  557. the support materials reads a program in from a file (the sequence of
  558. characters in the concrete syntax of Racket) and parses it into an
  559. abstract syntax tree. See the description of \code{read-program} in
  560. Appendix~\ref{appendix:utilities} for more details.
  561. \begin{figure}[tp]
  562. \fbox{
  563. \begin{minipage}{0.96\textwidth}
  564. \[
  565. \begin{array}{rcl}
  566. \begin{array}{rcl}
  567. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)\\
  568. R_0 &::=& \Exp
  569. \end{array}
  570. \end{array}
  571. \]
  572. \end{minipage}
  573. }
  574. \caption{The concrete syntax of $R_0$.}
  575. \label{fig:r0-concrete-syntax}
  576. \end{figure}
  577. \begin{figure}[tp]
  578. \fbox{
  579. \begin{minipage}{0.96\textwidth}
  580. \[
  581. \begin{array}{rcl}
  582. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  583. &\mid& \ADD{\Exp}{\Exp} \\
  584. R_0 &::=& \PROGRAM{\code{'()}}{\Exp}
  585. \end{array}
  586. \]
  587. \end{minipage}
  588. }
  589. \caption{The abstract syntax of $R_0$.}
  590. \label{fig:r0-syntax}
  591. \end{figure}
  592. \section{Pattern Matching}
  593. \label{sec:pattern-matching}
  594. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  595. the parts of an AST node. Racket provides the \texttt{match} form to
  596. access the parts of a structure. Consider the following example and
  597. the output on the right. \index{match} \index{pattern matching}
  598. \begin{center}
  599. \begin{minipage}{0.5\textwidth}
  600. \begin{lstlisting}
  601. (match ast1.1
  602. [(Prim op (list child1 child2))
  603. (print op)])
  604. \end{lstlisting}
  605. \end{minipage}
  606. \vrule
  607. \begin{minipage}{0.25\textwidth}
  608. \begin{lstlisting}
  609. '+
  610. \end{lstlisting}
  611. \end{minipage}
  612. \end{center}
  613. In the above example, the \texttt{match} form takes the AST
  614. \eqref{eq:arith-prog} and binds its parts to the three pattern
  615. variables \texttt{op}, \texttt{child1}, and \texttt{child2}. In
  616. general, a match clause consists of a \emph{pattern} and a
  617. \emph{body}.
  618. \index{pattern}
  619. Patterns are recursively defined to be either a pattern
  620. variable, a structure name followed by a pattern for each of the
  621. structure's arguments, or an S-expression (symbols, lists, etc.).
  622. (See Chapter 12 of The Racket
  623. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  624. and Chapter 9 of The Racket
  625. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  626. for a complete description of \code{match}.)
  627. %
  628. The body of a match clause may contain arbitrary Racket code. The
  629. pattern variables can be used in the scope of the body.
  630. A \code{match} form may contain several clauses, as in the following
  631. function \code{leaf?} that recognizes when an $R_0$ node is
  632. a leaf. The \code{match} proceeds through the clauses in order,
  633. checking whether the pattern can match the input AST. The
  634. body of the first clause that matches is executed. The output of
  635. \code{leaf?} for several ASTs is shown on the right.
  636. \begin{center}
  637. \begin{minipage}{0.6\textwidth}
  638. \begin{lstlisting}
  639. (define (leaf? arith)
  640. (match arith
  641. [(Int n) #t]
  642. [(Prim 'read '()) #t]
  643. [(Prim '- (list c1)) #f]
  644. [(Prim '+ (list c1 c2)) #f]))
  645. (leaf? (Prim 'read '()))
  646. (leaf? (Prim '- (list (Int 8))))
  647. (leaf? (Int 8))
  648. \end{lstlisting}
  649. \end{minipage}
  650. \vrule
  651. \begin{minipage}{0.25\textwidth}
  652. \begin{lstlisting}
  653. #t
  654. #f
  655. #t
  656. \end{lstlisting}
  657. \end{minipage}
  658. \end{center}
  659. When writing a \code{match}, we refer to the grammar definition to
  660. identify which non-terminal we are expecting to match against, then we
  661. make sure that 1) we have one clause for each alternative of that
  662. non-terminal and 2) that the pattern in each clause corresponds to the
  663. corresponding right-hand side of a grammar rule. For the \code{match}
  664. in the \code{leaf?} function, we refer to the grammar for $R_0$ in
  665. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  666. alternatives, so the \code{match} has 4 clauses. The pattern in each
  667. clause corresponds to the right-hand side of a grammar rule. For
  668. example, the pattern \code{(Prim '+ (list c1 c2))} corresponds to the
  669. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  670. patterns, replace non-terminals such as $\Exp$ with pattern variables
  671. of your choice (e.g. \code{c1} and \code{c2}).
  672. \section{Recursion}
  673. \label{sec:recursion}
  674. \index{recursive function}
  675. Programs are inherently recursive. For example, an $R_0$ expression is
  676. often made of smaller expressions. Thus, the natural way to process an
  677. entire program is with a recursive function. As a first example of
  678. such a recursive function, we define \texttt{exp?} below, which takes
  679. an arbitrary value and determines whether or not it is an $R_0$
  680. expression.
  681. %
  682. When a recursive function is defined using a sequence of match clauses
  683. that correspond to a grammar, and the body of each clause makes a
  684. recursive call on each child node, then we say the function is defined
  685. by \emph{structural recursion}\footnote{This principle of structuring
  686. code according to the data definition is advocated in the book
  687. \emph{How to Design Programs}
  688. \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}. Below we also
  689. define a second function, named \code{R0?}, that determines whether a
  690. value is an $R_0$ program. In general we can expect to write one
  691. recursive function to handle each non-terminal in a grammar.
  692. \index{structural recursion}
  693. %
  694. \begin{center}
  695. \begin{minipage}{0.7\textwidth}
  696. \begin{lstlisting}
  697. (define (exp? ast)
  698. (match ast
  699. [(Int n) #t]
  700. [(Prim 'read '()) #t]
  701. [(Prim '- (list e)) (exp? e)]
  702. [(Prim '+ (list e1 e2))
  703. (and (exp? e1) (exp? e2))]
  704. [else #f]))
  705. (define (R0? ast)
  706. (match ast
  707. [(Program '() e) (exp? e)]
  708. [else #f]))
  709. (R0? (Program '() ast1.1)
  710. (R0? (Program '()
  711. (Prim '- (list (Prim 'read '())
  712. (Prim '+ (list (Num 8)))))))
  713. \end{lstlisting}
  714. \end{minipage}
  715. \vrule
  716. \begin{minipage}{0.25\textwidth}
  717. \begin{lstlisting}
  718. #t
  719. #f
  720. \end{lstlisting}
  721. \end{minipage}
  722. \end{center}
  723. You may be tempted to merge the two functions into one, like this:
  724. \begin{center}
  725. \begin{minipage}{0.5\textwidth}
  726. \begin{lstlisting}
  727. (define (R0? ast)
  728. (match ast
  729. [(Int n) #t]
  730. [(Prim 'read '()) #t]
  731. [(Prim '- (list e)) (R0? e)]
  732. [(Prim '+ (list e1 e2)) (and (R0? e1) (R0? e2))]
  733. [(Program '() e) (R0? e)]
  734. [else #f]))
  735. \end{lstlisting}
  736. \end{minipage}
  737. \end{center}
  738. %
  739. Sometimes such a trick will save a few lines of code, especially when
  740. it comes to the \code{Program} wrapper. Yet this style is generally
  741. \emph{not} recommended because it can get you into trouble.
  742. %
  743. For example, the above function is subtly wrong:
  744. \lstinline{(R0? (Program '() (Program '() (Int 3))))}
  745. will return true, when it should return false.
  746. %% NOTE FIXME - must check for consistency on this issue throughout.
  747. \section{Interpreters}
  748. \label{sec:interp-R0}
  749. \index{interpreter}
  750. The meaning, or semantics, of a program is typically defined in the
  751. specification of the language. For example, the Scheme language is
  752. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  753. defined in its reference manual~\citep{plt-tr}. In this book we use an
  754. interpreter to define the meaning of each language that we consider,
  755. following Reynolds' advice~\citep{reynolds72:_def_interp}. An
  756. interpreter that is designated (by some people) as the definition of a
  757. language is called a \emph{definitional interpreter}.
  758. \index{definitional interpreter}
  759. We warm up by creating a definitional interpreter for the $R_0$ language, which
  760. serves as a second example of structural recursion. The
  761. \texttt{interp-R0} function is defined in
  762. Figure~\ref{fig:interp-R0}. The body of the function is a match on the
  763. input program followed by a call to the \lstinline{interp-exp} helper
  764. function, which in turn has one match clause per grammar rule for
  765. $R_0$ expressions.
  766. \begin{figure}[tp]
  767. \begin{lstlisting}
  768. (define (interp-exp e)
  769. (match e
  770. [(Int n) n]
  771. [(Prim 'read '())
  772. (define r (read))
  773. (cond [(fixnum? r) r]
  774. [else (error 'interp-R0 "expected an integer" r)])]
  775. [(Prim '- (list e))
  776. (define v (interp-exp e))
  777. (fx- 0 v)]
  778. [(Prim '+ (list e1 e2))
  779. (define v1 (interp-exp e1))
  780. (define v2 (interp-exp e2))
  781. (fx+ v1 v2)]
  782. ))
  783. (define (interp-R0 p)
  784. (match p
  785. [(Program '() e) (interp-exp e)]
  786. ))
  787. \end{lstlisting}
  788. \caption{Interpreter for the $R_0$ language.}
  789. \label{fig:interp-R0}
  790. \end{figure}
  791. Let us consider the result of interpreting a few $R_0$ programs. The
  792. following program adds two integers.
  793. \begin{lstlisting}
  794. (+ 10 32)
  795. \end{lstlisting}
  796. The result is \key{42}. We wrote the above program in concrete syntax,
  797. whereas the parsed abstract syntax is:
  798. \begin{lstlisting}
  799. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  800. \end{lstlisting}
  801. The next example demonstrates that expressions may be nested within
  802. each other, in this case nesting several additions and negations.
  803. \begin{lstlisting}
  804. (+ 10 (- (+ 12 20)))
  805. \end{lstlisting}
  806. What is the result of the above program?
  807. As mentioned previously, the $R_0$ language does not support
  808. arbitrarily-large integers, but only $63$-bit integers, so we
  809. interpret the arithmetic operations of $R_0$ using fixnum arithmetic
  810. in Racket.
  811. Suppose
  812. \[
  813. n = 999999999999999999
  814. \]
  815. which indeed fits in $63$-bits. What happens when we run the
  816. following program in our interpreter?
  817. \begin{lstlisting}
  818. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  819. \end{lstlisting}
  820. It produces an error:
  821. \begin{lstlisting}
  822. fx+: result is not a fixnum
  823. \end{lstlisting}
  824. We establish the convention that if running the definitional
  825. interpreter on a program produces an error, then the meaning of that
  826. program is \emph{unspecified}. That means a compiler for the language
  827. is under no obligations regarding that program; it may or may not
  828. produce an executable, and if it does, that executable can do
  829. anything. This convention applies to the languages defined in this
  830. book, as a way to simplify the student's task of implementing them,
  831. but this convention is not applicable to all programming languages.
  832. \index{unspecified behavior}
  833. Moving on to the last feature of the $R_0$ language, the \key{read}
  834. operation prompts the user of the program for an integer. Recall that
  835. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  836. \code{8}. So if we run
  837. \begin{lstlisting}
  838. (interp-R0 (Program '() ast1.1))
  839. \end{lstlisting}
  840. and if the input is \code{50}, then we get the answer to life, the
  841. universe, and everything: \code{42}!\footnote{\emph{The Hitchhiker's
  842. Guide to the Galaxy} by Douglas Adams.}
  843. We include the \key{read} operation in $R_0$ so a clever student
  844. cannot implement a compiler for $R_0$ that simply runs the interpreter
  845. during compilation to obtain the output and then generates the trivial
  846. code to produce the output. (Yes, a clever student did this in the
  847. first instance of this course.)
  848. The job of a compiler is to translate a program in one language into a
  849. program in another language so that the output program behaves the
  850. same way as the input program does according to its definitional
  851. interpreter. This idea is depicted in the following diagram. Suppose
  852. we have two languages, $\mathcal{L}_1$ and $\mathcal{L}_2$, and an
  853. interpreter for each language. Suppose that the compiler translates
  854. program $P_1$ in language $\mathcal{L}_1$ into program $P_2$ in
  855. language $\mathcal{L}_2$. Then interpreting $P_1$ and $P_2$ on their
  856. respective interpreters with input $i$ should yield the same output
  857. $o$.
  858. \begin{equation} \label{eq:compile-correct}
  859. \begin{tikzpicture}[baseline=(current bounding box.center)]
  860. \node (p1) at (0, 0) {$P_1$};
  861. \node (p2) at (3, 0) {$P_2$};
  862. \node (o) at (3, -2.5) {$o$};
  863. \path[->] (p1) edge [above] node {compile} (p2);
  864. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  865. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  866. \end{tikzpicture}
  867. \end{equation}
  868. In the next section we see our first example of a compiler.
  869. \section{Example Compiler: a Partial Evaluator}
  870. \label{sec:partial-evaluation}
  871. In this section we consider a compiler that translates $R_0$ programs
  872. into $R_0$ programs that may be more efficient, that is, this compiler
  873. is an optimizer. This optimizer eagerly computes the parts of the
  874. program that do not depend on any inputs, a process known as
  875. \emph{partial evaluation}~\cite{Jones:1993uq}.
  876. \index{partial evaluation}
  877. For example, given the following program
  878. \begin{lstlisting}
  879. (+ (read) (- (+ 5 3)))
  880. \end{lstlisting}
  881. our compiler will translate it into the program
  882. \begin{lstlisting}
  883. (+ (read) -8)
  884. \end{lstlisting}
  885. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  886. evaluator for the $R_0$ language. The output of the partial evaluator
  887. is an $R_0$ program. In Figure~\ref{fig:pe-arith}, the structural
  888. recursion over $\Exp$ is captured in the \code{pe-exp} function
  889. whereas the code for partially evaluating the negation and addition
  890. operations is factored into two separate helper functions:
  891. \code{pe-neg} and \code{pe-add}. The input to these helper
  892. functions is the output of partially evaluating the children.
  893. \begin{figure}[tp]
  894. \begin{lstlisting}
  895. (define (pe-neg r)
  896. (match r
  897. [(Int n) (Int (fx- 0 n))]
  898. [else (Prim '- (list r))]))
  899. (define (pe-add r1 r2)
  900. (match* (r1 r2)
  901. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  902. [(_ _) (Prim '+ (list r1 r2))]))
  903. (define (pe-exp e)
  904. (match e
  905. [(Int n) (Int n)]
  906. [(Prim 'read '()) (Prim 'read '())]
  907. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  908. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]
  909. ))
  910. (define (pe-R0 p)
  911. (match p
  912. [(Program '() e) (Program '() (pe-exp e))]
  913. ))
  914. \end{lstlisting}
  915. \caption{A partial evaluator for $R_0$ expressions.}
  916. \label{fig:pe-arith}
  917. \end{figure}
  918. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  919. arguments are integers and if they are, perform the appropriate
  920. arithmetic. Otherwise, they create an AST node for the operation
  921. (either negation or addition).
  922. To gain some confidence that the partial evaluator is correct, we can
  923. test whether it produces programs that get the same result as the
  924. input programs. That is, we can test whether it satisfies Diagram
  925. \eqref{eq:compile-correct}. The following code runs the partial
  926. evaluator on several examples and tests the output program. The
  927. \texttt{parse-program} and \texttt{assert} functions are defined in
  928. Appendix~\ref{appendix:utilities}.\\
  929. \begin{minipage}{1.0\textwidth}
  930. \begin{lstlisting}
  931. (define (test-pe p)
  932. (assert "testing pe-R0"
  933. (equal? (interp-R0 p) (interp-R0 (pe-R0 p)))))
  934. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  935. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  936. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  937. \end{lstlisting}
  938. \end{minipage}
  939. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  940. \chapter{Integers and Variables}
  941. \label{ch:int-exp}
  942. This chapter is about compiling the subset of Racket that includes
  943. integer arithmetic and local variable binding, which we name $R_1$, to
  944. x86-64 assembly code~\citep{Intel:2015aa}. Henceforth we refer
  945. to x86-64 simply as x86. The chapter begins with a description of the
  946. $R_1$ language (Section~\ref{sec:s0}) followed by a description of x86
  947. (Section~\ref{sec:x86}). The x86 assembly language is large, so we
  948. discuss only what is needed for compiling $R_1$. We introduce more of
  949. x86 in later chapters. Once we have introduced $R_1$ and x86, we
  950. reflect on their differences and come up with a plan to break down the
  951. translation from $R_1$ to x86 into a handful of steps
  952. (Section~\ref{sec:plan-s0-x86}). The rest of the sections in this
  953. chapter give detailed hints regarding each step
  954. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  955. to give enough hints that the well-prepared reader, together with a
  956. few friends, can implement a compiler from $R_1$ to x86 in a couple
  957. weeks while at the same time leaving room for some fun and creativity.
  958. To give the reader a feeling for the scale of this first compiler, the
  959. instructor solution for the $R_1$ compiler is less than 500 lines of
  960. code.
  961. \section{The $R_1$ Language}
  962. \label{sec:s0}
  963. \index{variable}
  964. The $R_1$ language extends the $R_0$ language with variable
  965. definitions. The concrete syntax of the $R_1$ language is defined by
  966. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  967. syntax is defined in Figure~\ref{fig:r1-syntax}. The non-terminal
  968. \Var{} may be any Racket identifier. As in $R_0$, \key{read} is a
  969. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  970. operator. Similar to $R_0$, the abstract syntax of $R_1$ includes the
  971. \key{Program} struct to mark the top of the program.
  972. %% The $\itm{info}$
  973. %% field of the \key{Program} structure contains an \emph{association
  974. %% list} (a list of key-value pairs) that is used to communicate
  975. %% auxiliary data from one compiler pass the next.
  976. Despite the simplicity of the $R_1$ language, it is rich enough to
  977. exhibit several compilation techniques.
  978. \begin{figure}[tp]
  979. \centering
  980. \fbox{
  981. \begin{minipage}{0.96\textwidth}
  982. \[
  983. \begin{array}{rcl}
  984. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp}\\
  985. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  986. R_1 &::=& \Exp
  987. \end{array}
  988. \]
  989. \end{minipage}
  990. }
  991. \caption{The concrete syntax of $R_1$.}
  992. \label{fig:r1-concrete-syntax}
  993. \end{figure}
  994. \begin{figure}[tp]
  995. \centering
  996. \fbox{
  997. \begin{minipage}{0.96\textwidth}
  998. \[
  999. \begin{array}{rcl}
  1000. \Exp &::=& \INT{\Int} \mid \READ{} \\
  1001. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  1002. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  1003. R_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1004. \end{array}
  1005. \]
  1006. \end{minipage}
  1007. }
  1008. \caption{The abstract syntax of $R_1$.}
  1009. \label{fig:r1-syntax}
  1010. \end{figure}
  1011. Let us dive further into the syntax and semantics of the $R_1$
  1012. language. The \key{Let} feature defines a variable for use within its
  1013. body and initializes the variable with the value of an expression.
  1014. The abstract syntax for \key{Let} is defined in Figure~\ref{fig:r1-syntax}.
  1015. The concrete syntax for \key{Let} is
  1016. \begin{lstlisting}
  1017. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1018. \end{lstlisting}
  1019. For example, the following program initializes \code{x} to $32$ and then
  1020. evaluates the body \code{(+ 10 x)}, producing $42$.
  1021. \begin{lstlisting}
  1022. (let ([x (+ 12 20)]) (+ 10 x))
  1023. \end{lstlisting}
  1024. When there are multiple \key{let}'s for the same variable, the closest
  1025. enclosing \key{let} is used. That is, variable definitions overshadow
  1026. prior definitions. Consider the following program with two \key{let}'s
  1027. that define variables named \code{x}. Can you figure out the result?
  1028. \begin{lstlisting}
  1029. (let ([x 32]) (+ (let ([x 10]) x) x))
  1030. \end{lstlisting}
  1031. For the purposes of depicting which variable uses correspond to which
  1032. definitions, the following shows the \code{x}'s annotated with
  1033. subscripts to distinguish them. Double check that your answer for the
  1034. above is the same as your answer for this annotated version of the
  1035. program.
  1036. \begin{lstlisting}
  1037. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1038. \end{lstlisting}
  1039. The initializing expression is always evaluated before the body of the
  1040. \key{let}, so in the following, the \key{read} for \code{x} is
  1041. performed before the \key{read} for \code{y}. Given the input
  1042. $52$ then $10$, the following produces $42$ (not $-42$).
  1043. \begin{lstlisting}
  1044. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1045. \end{lstlisting}
  1046. \begin{wrapfigure}[24]{r}[1.0in]{0.6\textwidth}
  1047. \small
  1048. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1049. An \emph{association list} (alist) is a list of key-value pairs.
  1050. For example, we can map people to their ages with an alist.
  1051. \index{alist}\index{association list}
  1052. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1053. (define ages
  1054. '((jane . 25) (sam . 24) (kate . 45)))
  1055. \end{lstlisting}
  1056. The \emph{dictionary} interface is for mapping keys to values.
  1057. Every alist implements this interface. \index{dictionary} The package
  1058. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1059. provides many functions for working with dictionaries. Here
  1060. are a few of them:
  1061. \begin{description}
  1062. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1063. returns the value associated with the given $\itm{key}$.
  1064. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1065. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1066. but otherwise is the same as $\itm{dict}$.
  1067. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1068. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1069. of keys and values in $\itm{dict}$. For example, the following
  1070. creates a new alist in which the ages are incremented.
  1071. \end{description}
  1072. \vspace{-10pt}
  1073. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1074. (for/list ([(k v) (in-dict ages)])
  1075. (cons k (add1 v)))
  1076. \end{lstlisting}
  1077. \end{tcolorbox}
  1078. \end{wrapfigure}
  1079. Figure~\ref{fig:interp-R1} shows the definitional interpreter for the
  1080. $R_1$ language. It extends the interpreter for $R_0$ with two new
  1081. \key{match} clauses for variables and for \key{let}. For \key{let},
  1082. we need a way to communicate the value of a variable to all the uses
  1083. of a variable. To accomplish this, we maintain a mapping from
  1084. variables to values. Throughout the compiler we often need to map
  1085. variables to information about them. We refer to these mappings as
  1086. \emph{environments}\index{environment}
  1087. \footnote{Another common term for environment in the compiler
  1088. literature is \emph{symbol table}\index{symbol table}.}.
  1089. For simplicity, we use an
  1090. association list (alist) to represent the environment. The sidebar to
  1091. the right gives a brief introduction to alists and the
  1092. \code{racket/dict} package. The \code{interp-R1} function takes the
  1093. current environment, \code{env}, as an extra parameter. When the
  1094. interpreter encounters a variable, it finds the corresponding value
  1095. using the \code{dict-ref} function. When the interpreter encounters a
  1096. \key{Let}, it evaluates the initializing expression, extends the
  1097. environment with the result value bound to the variable, using
  1098. \code{dict-set}, then evaluates the body of the \key{Let}.
  1099. \begin{figure}[tp]
  1100. \begin{lstlisting}
  1101. (define (interp-exp env)
  1102. (lambda (e)
  1103. (match e
  1104. [(Int n) n]
  1105. [(Prim 'read '())
  1106. (define r (read))
  1107. (cond [(fixnum? r) r]
  1108. [else (error 'interp-R1 "expected an integer" r)])]
  1109. [(Prim '- (list e))
  1110. (define v ((interp-exp env) e))
  1111. (fx- 0 v)]
  1112. [(Prim '+ (list e1 e2))
  1113. (define v1 ((interp-exp env) e1))
  1114. (define v2 ((interp-exp env) e2))
  1115. (fx+ v1 v2)]
  1116. [(Var x) (dict-ref env x)]
  1117. [(Let x e body)
  1118. (define new-env (dict-set env x ((interp-exp env) e)))
  1119. ((interp-exp new-env) body)]
  1120. )))
  1121. (define (interp-R1 p)
  1122. (match p
  1123. [(Program '() e) ((interp-exp '()) e)]
  1124. ))
  1125. \end{lstlisting}
  1126. \caption{Interpreter for the $R_1$ language.}
  1127. \label{fig:interp-R1}
  1128. \end{figure}
  1129. The goal for this chapter is to implement a compiler that translates
  1130. any program $P_1$ written in the $R_1$ language into an x86 assembly
  1131. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1132. computer as the $P_1$ program interpreted by \code{interp-R1}. That
  1133. is, they both output the same integer $n$. We depict this correctness
  1134. criteria in the following diagram.
  1135. \[
  1136. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1137. \node (p1) at (0, 0) {$P_1$};
  1138. \node (p2) at (4, 0) {$P_2$};
  1139. \node (o) at (4, -2) {$n$};
  1140. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1141. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  1142. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  1143. \end{tikzpicture}
  1144. \]
  1145. In the next section we introduce enough of the x86 assembly
  1146. language to compile $R_1$.
  1147. \section{The x86$_0$ Assembly Language}
  1148. \label{sec:x86}
  1149. \index{x86}
  1150. Figure~\ref{fig:x86-0-concrete} defines the concrete syntax for the subset of
  1151. the x86 assembly language needed for this chapter, which we call x86$_0$.
  1152. %
  1153. An x86 program begins with a \code{main} label followed by a sequence
  1154. of instructions. In the grammar, elipses such as $\ldots$ are used to
  1155. indicate a sequence of items, e.g., $\Instr \ldots$ is a sequence of
  1156. instructions.\index{instruction}
  1157. %
  1158. An x86 program is stored in the computer's memory and the computer has
  1159. a \emph{program counter} (PC)\index{program counter}\index{PC}
  1160. that points to the address of the next
  1161. instruction to be executed. For most instructions, once the
  1162. instruction is executed, the program counter is incremented to point
  1163. to the immediately following instruction in memory. Most x86
  1164. instructions take two operands, where each operand is either an
  1165. integer constant (called \emph{immediate value}\index{immediate value}),
  1166. a \emph{register}\index{register}, or a memory location.
  1167. A register is a special kind of variable. Each
  1168. one holds a 64-bit value; there are 16 registers in the computer and
  1169. their names are given in Figure~\ref{fig:x86-0-concrete}. The computer's memory
  1170. as a mapping of 64-bit addresses to 64-bit values%
  1171. \footnote{This simple story suffices for describing how sequential
  1172. programs access memory but is not sufficient for multi-threaded
  1173. programs. However, multi-threaded execution is beyond the scope of
  1174. this book.}.
  1175. %
  1176. We use the AT\&T syntax expected by the GNU assembler, which comes
  1177. with the \key{gcc} compiler that we use for compiling assembly code to
  1178. machine code.
  1179. %
  1180. Appendix~\ref{sec:x86-quick-reference} is a quick-reference for all of
  1181. the x86 instructions used in this book.
  1182. % to do: finish treatment of imulq
  1183. % it's needed for vector's in R6/R7
  1184. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1185. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1186. && \key{r8} \mid \key{r9} \mid \key{r10}
  1187. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1188. \mid \key{r14} \mid \key{r15}}
  1189. \begin{figure}[tp]
  1190. \fbox{
  1191. \begin{minipage}{0.96\textwidth}
  1192. \[
  1193. \begin{array}{lcl}
  1194. \Reg &::=& \allregisters{} \\
  1195. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1196. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1197. \key{subq} \; \Arg\key{,} \Arg \mid
  1198. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1199. && \key{callq} \; \mathit{label} \mid
  1200. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} \\
  1201. && \itm{label}\key{:}\; \Instr \\
  1202. x86_0 &::= & \key{.globl main}\\
  1203. & & \key{main:} \; \Instr\ldots
  1204. \end{array}
  1205. \]
  1206. \end{minipage}
  1207. }
  1208. \caption{The concrete syntax of the x86$_0$ assembly language (AT\&T syntax).}
  1209. \label{fig:x86-0-concrete}
  1210. \end{figure}
  1211. An immediate value is written using the notation \key{\$}$n$ where $n$
  1212. is an integer.
  1213. %
  1214. A register is written with a \key{\%} followed by the register name,
  1215. such as \key{\%rax}.
  1216. %
  1217. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1218. which obtains the address stored in register $r$ and then adds $n$
  1219. bytes to the address. The resulting address is used to either load or
  1220. store to memory depending on whether it occurs as a source or
  1221. destination argument of an instruction.
  1222. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1223. source $s$ and destination $d$, applies the arithmetic operation, then
  1224. writes the result back to the destination $d$.
  1225. %
  1226. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1227. stores the result in $d$.
  1228. %
  1229. The $\key{callq}\,\itm{label}$ instruction executes the procedure
  1230. specified by the label and $\key{retq}$ returns from a procedure to
  1231. its caller. The abstract syntax for \code{callq} includes an extra
  1232. integer field that represents the arity (number of parameters) of the
  1233. function being called.
  1234. %
  1235. We discuss procedure calls in more detail later in this
  1236. chapter and in Chapter~\ref{ch:functions}. The
  1237. $\key{jmp}\,\itm{label}$ instruction updates the program counter to
  1238. the address of the instruction after the specified label.
  1239. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  1240. to \code{(+ 10 32)}. The \key{globl} directive says that the
  1241. \key{main} procedure is externally visible, which is necessary so
  1242. that the operating system can call it. The label \key{main:}
  1243. indicates the beginning of the \key{main} procedure which is where
  1244. the operating system starts executing this program. The instruction
  1245. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  1246. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  1247. $10$ in \key{rax} and puts the result, $42$, back into
  1248. \key{rax}.
  1249. %
  1250. The last instruction, \key{retq}, finishes the \key{main} function by
  1251. returning the integer in \key{rax} to the operating system. The
  1252. operating system interprets this integer as the program's exit
  1253. code. By convention, an exit code of 0 indicates that a program
  1254. completed successfully, and all other exit codes indicate various
  1255. errors. Nevertheless, we return the result of the program as the exit
  1256. code.
  1257. %\begin{wrapfigure}{r}{2.25in}
  1258. \begin{figure}[tbp]
  1259. \begin{lstlisting}
  1260. .globl main
  1261. main:
  1262. movq $10, %rax
  1263. addq $32, %rax
  1264. retq
  1265. \end{lstlisting}
  1266. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1267. \label{fig:p0-x86}
  1268. %\end{wrapfigure}
  1269. \end{figure}
  1270. Unfortunately, x86 varies in a couple ways depending on what operating
  1271. system it is assembled in. The code examples shown here are correct on
  1272. Linux and most Unix-like platforms, but when assembled on Mac OS X,
  1273. labels like \key{main} must be prefixed with an underscore, as in
  1274. \key{\_main}.
  1275. We exhibit the use of memory for storing intermediate results in the
  1276. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1277. equivalent to \code{(+ 52 (- 10))}. This program uses a region of
  1278. memory called the \emph{procedure call stack} (or \emph{stack} for
  1279. short). \index{stack}\index{procedure call stack} The stack consists
  1280. of a separate \emph{frame}\index{frame} for each procedure call. The
  1281. memory layout for an individual frame is shown in
  1282. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1283. \emph{stack pointer}\index{stack pointer} and points to the item at
  1284. the top of the stack. The stack grows downward in memory, so we
  1285. increase the size of the stack by subtracting from the stack pointer.
  1286. In the context of a procedure call, the \emph{return
  1287. address}\index{return address} is the instruction after the call
  1288. instruction on the caller side. The function call inststruction,
  1289. \code{callq}, pushes the return address onto the stack. The register
  1290. \key{rbp} is the \emph{base pointer}\index{base pointer} and is used
  1291. to access variables associated with the current procedure call. The
  1292. base pointer of the caller is pushed onto the stack after the return
  1293. address. We number the variables from $1$ to $n$. Variable $1$ is
  1294. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  1295. $-16\key{(\%rbp)}$, etc.
  1296. \begin{figure}[tbp]
  1297. \begin{lstlisting}
  1298. start:
  1299. movq $10, -8(%rbp)
  1300. negq -8(%rbp)
  1301. movq -8(%rbp), %rax
  1302. addq $52, %rax
  1303. jmp conclusion
  1304. .globl main
  1305. main:
  1306. pushq %rbp
  1307. movq %rsp, %rbp
  1308. subq $16, %rsp
  1309. jmp start
  1310. conclusion:
  1311. addq $16, %rsp
  1312. popq %rbp
  1313. retq
  1314. \end{lstlisting}
  1315. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1316. \label{fig:p1-x86}
  1317. \end{figure}
  1318. \begin{figure}[tbp]
  1319. \centering
  1320. \begin{tabular}{|r|l|} \hline
  1321. Position & Contents \\ \hline
  1322. 8(\key{\%rbp}) & return address \\
  1323. 0(\key{\%rbp}) & old \key{rbp} \\
  1324. -8(\key{\%rbp}) & variable $1$ \\
  1325. -16(\key{\%rbp}) & variable $2$ \\
  1326. \ldots & \ldots \\
  1327. 0(\key{\%rsp}) & variable $n$\\ \hline
  1328. \end{tabular}
  1329. \caption{Memory layout of a frame.}
  1330. \label{fig:frame}
  1331. \end{figure}
  1332. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  1333. control is transfered from the operating system to the \code{main}
  1334. function. The operating system issues a \code{callq main} instruction
  1335. which pushes its return address on the stack and then jumps to
  1336. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  1337. by 16 bytes prior to the execution of any \code{callq} instruction, so
  1338. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  1339. alignment (because the \code{callq} pushed the return address). The
  1340. first three instructions are the typical \emph{prelude}\index{prelude}
  1341. for a procedure. The instruction \code{pushq \%rbp} saves the base
  1342. pointer for the caller onto the stack and subtracts $8$ from the stack
  1343. pointer. At this point the stack pointer is back to being 16-byte
  1344. aligned. The second instruction \code{movq \%rsp, \%rbp} changes the
  1345. base pointer so that it points the location of the old base
  1346. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  1347. pointer down to make enough room for storing variables. This program
  1348. needs one variable ($8$ bytes) but we round up to 16 bytes to maintain
  1349. the 16-byte alignment of the \code{rsp}. With the \code{rsp} aligned,
  1350. we are ready to make calls to other functions. The last instruction of
  1351. the prelude is \code{jmp start}, which transfers control to the
  1352. instructions that were generated from the Racket expression \code{(+
  1353. 10 32)}.
  1354. The four instructions under the label \code{start} carry out the work
  1355. of computing \code{(+ 52 (- 10)))}.
  1356. %
  1357. The first instruction \code{movq \$10, -8(\%rbp)} stores $10$ in
  1358. variable $1$.
  1359. %
  1360. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  1361. %
  1362. The following instruction moves the $-10$ from variable $1$ into the
  1363. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  1364. the value in \code{rax}, updating its contents to $42$.
  1365. The three instructions under the label \code{conclusion} are the
  1366. typical \emph{conclusion}\index{conclusion} of a procedure. The first
  1367. two instructions are necessary to get the state of the machine back to
  1368. where it was at the beginning of the procedure. The instruction
  1369. \key{addq \$16, \%rsp} moves the stack pointer back to point at the
  1370. old base pointer. The amount added here needs to match the amount that
  1371. was subtracted in the prelude of the procedure. Then \key{popq \%rbp}
  1372. returns the old base pointer to \key{rbp} and adds $8$ to the stack
  1373. pointer. The last instruction, \key{retq}, jumps back to the
  1374. procedure that called this one and adds 8 to the stack pointer, which
  1375. returns the stack pointer to where it was prior to the procedure call.
  1376. The compiler needs a convenient representation for manipulating x86
  1377. programs, so we define an abstract syntax for x86 in
  1378. Figure~\ref{fig:x86-0-ast}. We refer to this language as x86$_0$ with
  1379. a subscript $0$ because later we introduce extended versions of this
  1380. assembly language. The main difference compared to the concrete syntax
  1381. of x86 (Figure~\ref{fig:x86-0-concrete}) is that it does not allow
  1382. labeled instructions to appear anywhere, but instead organizes
  1383. instructions into a group called a \emph{block}\index{block}\index{basic block}
  1384. and associates a label with every block, which is why the \key{CFG} struct
  1385. (for control-flow graph) includes an alist mapping labels to
  1386. blocks. The reason for this organization becomes apparent in
  1387. Chapter~\ref{ch:bool-types} when we introduce conditional
  1388. branching. The \code{Block} structure includes an $\itm{info}$ field
  1389. that is not needed for this chapter, but will become useful in
  1390. Chapter~\ref{ch:register-allocation-r1}. For now, the $\itm{info}$
  1391. field should just contain an empty list.
  1392. \begin{figure}[tp]
  1393. \fbox{
  1394. \begin{minipage}{0.96\textwidth}
  1395. \small
  1396. \[
  1397. \begin{array}{lcl}
  1398. \Reg &::=& \allregisters{} \\
  1399. \Arg &::=& \IMM{\Int} \mid \REG{\Reg}
  1400. \mid \DEREF{\Reg}{\Int} \\
  1401. \Instr &::=& \BININSTR{\code{'addq}}{\Arg}{\Arg}
  1402. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} \\
  1403. &\mid& \BININSTR{\code{'movq}}{\Arg}{\Arg}
  1404. \mid \UNIINSTR{\code{'negq}}{\Arg}\\
  1405. &\mid& \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  1406. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  1407. \Block &::= & \BLOCK{\itm{info}}{\Instr\ldots} \\
  1408. x86_0 &::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}}
  1409. \end{array}
  1410. \]
  1411. \end{minipage}
  1412. }
  1413. \caption{The abstract syntax of x86$_0$ assembly.}
  1414. \label{fig:x86-0-ast}
  1415. \end{figure}
  1416. \section{Planning the trip to x86 via the $C_0$ language}
  1417. \label{sec:plan-s0-x86}
  1418. To compile one language to another it helps to focus on the
  1419. differences between the two languages because the compiler will need
  1420. to bridge those differences. What are the differences between $R_1$
  1421. and x86 assembly? Here are some of the most important ones:
  1422. \begin{enumerate}
  1423. \item[(a)] x86 arithmetic instructions typically have two arguments
  1424. and update the second argument in place. In contrast, $R_1$
  1425. arithmetic operations take two arguments and produce a new value.
  1426. An x86 instruction may have at most one memory-accessing argument.
  1427. Furthermore, some instructions place special restrictions on their
  1428. arguments.
  1429. \item[(b)] An argument of an $R_1$ operator can be any expression,
  1430. whereas x86 instructions restrict their arguments to be integers
  1431. constants, registers, and memory locations.
  1432. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1433. sequence of instructions and jumps to labeled positions, whereas in
  1434. $R_1$ the order of evaluation is a left-to-right depth-first
  1435. traversal of the abstract syntax tree.
  1436. \item[(d)] An $R_1$ program can have any number of variables whereas
  1437. x86 has 16 registers and the procedure calls stack.
  1438. \item[(e)] Variables in $R_1$ can overshadow other variables with the
  1439. same name. The registers and memory locations of x86 all have unique
  1440. names or addresses.
  1441. \end{enumerate}
  1442. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1443. the problem into several steps, dealing with the above differences one
  1444. at a time. Each of these steps is called a \emph{pass} of the
  1445. compiler.\index{pass}\index{compiler pass}
  1446. %
  1447. This terminology comes from each step traverses (i.e. passes over) the
  1448. AST of the program.
  1449. %
  1450. We begin by sketching how we might implement each pass, and give them
  1451. names. We then figure out an ordering of the passes and the
  1452. input/output language for each pass. The very first pass has $R_1$ as
  1453. its input language and the last pass has x86 as its output
  1454. language. In between we can choose whichever language is most
  1455. convenient for expressing the output of each pass, whether that be
  1456. $R_1$, x86, or new \emph{intermediate languages} of our own design.
  1457. Finally, to implement each pass we write one recursive function per
  1458. non-terminal in the grammar of the input language of the pass.
  1459. \index{intermediate language}
  1460. \begin{description}
  1461. \item[Pass \key{select-instructions}] To handle the difference between
  1462. $R_1$ operations and x86 instructions we convert each $R_1$
  1463. operation to a short sequence of instructions that accomplishes the
  1464. same task.
  1465. \item[Pass \key{remove-complex-opera*}] To ensure that each
  1466. subexpression (i.e. operator and operand, and hence the name
  1467. \key{opera*}) is an \emph{atomic} expression (a variable or
  1468. integer), we introduce temporary variables to hold the results
  1469. of subexpressions.\index{atomic expression}
  1470. \item[Pass \key{explicate-control}] To make the execution order of the
  1471. program explicit, we convert from the abstract syntax tree
  1472. representation into a control-flow graph in which each node
  1473. contains a sequence of statements and the edges between nodes say
  1474. where to go at the end of the sequence.
  1475. \item[Pass \key{assign-homes}] To handle the difference between the
  1476. variables in $R_1$ versus the registers and stack locations in x86,
  1477. we map each variable to a register or stack location.
  1478. \item[Pass \key{uniquify}] This pass deals with the shadowing of variables
  1479. by renaming every variable to a unique name, so that shadowing no
  1480. longer occurs.
  1481. \end{description}
  1482. The next question is: in what order should we apply these passes? This
  1483. question can be challenging because it is difficult to know ahead of
  1484. time which orders will be better (easier to implement, produce more
  1485. efficient code, etc.) so oftentimes trial-and-error is
  1486. involved. Nevertheless, we can try to plan ahead and make educated
  1487. choices regarding the ordering.
  1488. Let us consider the ordering of \key{uniquify} and
  1489. \key{remove-complex-opera*}. The assignment of subexpressions to
  1490. temporary variables involves introducing new variables and moving
  1491. subexpressions, which might change the shadowing of variables and
  1492. inadvertently change the behavior of the program. But if we apply
  1493. \key{uniquify} first, this will not be an issue. Of course, this means
  1494. that in \key{remove-complex-opera*}, we need to ensure that the
  1495. temporary variables that it creates are unique.
  1496. What should be the ordering of \key{explicate-control} with respect to
  1497. \key{uniquify}? The \key{uniquify} pass should come first because
  1498. \key{explicate-control} changes all the \key{let}-bound variables to
  1499. become local variables whose scope is the entire program, which would
  1500. confuse variables with the same name.
  1501. %
  1502. Likewise, we place \key{explicate-control} after
  1503. \key{remove-complex-opera*} because \key{explicate-control} removes
  1504. the \key{let} form, but it is convenient to use \key{let} in the
  1505. output of \key{remove-complex-opera*}.
  1506. %
  1507. Regarding \key{assign-homes}, it is helpful to place
  1508. \key{explicate-control} first because \key{explicate-control} changes
  1509. \key{let}-bound variables into program-scope variables. This means
  1510. that the \key{assign-homes} pass can read off the variables from the
  1511. $\itm{info}$ of the \key{Program} AST node instead of traversing the
  1512. entire program in search of \key{let}-bound variables.
  1513. Last, we need to decide on the ordering of \key{select-instructions}
  1514. and \key{assign-homes}. These two passes are intertwined, creating a
  1515. Gordian Knot. To do a good job of assigning homes, it is helpful to
  1516. have already determined which instructions will be used, because x86
  1517. instructions have restrictions about which of their arguments can be
  1518. registers versus stack locations. One might want to give preferential
  1519. treatment to variables that occur in register-argument positions. On
  1520. the other hand, it may turn out to be impossible to make sure that all
  1521. such variables are assigned to registers, and then one must redo the
  1522. selection of instructions. Some compilers handle this problem by
  1523. iteratively repeating these two passes until a good solution is found.
  1524. We use a simpler approach in which \key{select-instructions}
  1525. comes first, followed by the \key{assign-homes}, then a third
  1526. pass named \key{patch-instructions} that uses a reserved register to
  1527. patch-up outstanding problems regarding instructions with too many
  1528. memory accesses. The disadvantage of this approach is some programs
  1529. may not execute as efficiently as they would if we used the iterative
  1530. approach and used all of the registers for variables.
  1531. \begin{figure}[tbp]
  1532. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1533. \node (R1) at (0,2) {\large $R_1$};
  1534. \node (R1-2) at (3,2) {\large $R_1$};
  1535. \node (R1-3) at (6,2) {\large $R_1^{\dagger}$};
  1536. %\node (C0-1) at (6,0) {\large $C_0$};
  1537. \node (C0-2) at (3,0) {\large $C_0$};
  1538. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_0$};
  1539. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_0$};
  1540. \node (x86-4) at (9,-2) {\large $\text{x86}_0$};
  1541. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}_0$};
  1542. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1543. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  1544. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-2);
  1545. %\path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  1546. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1547. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1548. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1549. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1550. \end{tikzpicture}
  1551. \caption{Overview of the passes for compiling $R_1$. }
  1552. \label{fig:R1-passes}
  1553. \end{figure}
  1554. Figure~\ref{fig:R1-passes} presents the ordering of the compiler
  1555. passes in the form of a graph. Each pass is an edge and the
  1556. input/output language of each pass is a node in the graph. The output
  1557. of \key{uniquify} and \key{remove-complex-opera*} are programs that
  1558. are still in the $R_1$ language, but the output of the pass
  1559. \key{explicate-control} is in a different language $C_0$ that is
  1560. designed to make the order of evaluation explicit in its syntax, which
  1561. we introduce in the next section. The \key{select-instruction} pass
  1562. translates from $C_0$ to a variant of x86. The \key{assign-homes} and
  1563. \key{patch-instructions} passes input and output variants of x86
  1564. assembly. The last pass in Figure~\ref{fig:R1-passes} is
  1565. \key{print-x86}, which converts from the abstract syntax of
  1566. $\text{x86}_0$ to the concrete syntax of x86.
  1567. In the next sections we discuss the $C_0$ language and the
  1568. $\text{x86}^{*}_0$ and $\text{x86}^{\dagger}_0$ dialects of x86. The
  1569. remainder of this chapter gives hints regarding the implementation of
  1570. each of the compiler passes in Figure~\ref{fig:R1-passes}.
  1571. \subsection{The $C_0$ Intermediate Language}
  1572. The output of \key{explicate-control} is similar to the $C$
  1573. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1574. categories for expressions and statements, so we name it $C_0$. The
  1575. concrete syntax for $C_0$ is defined in
  1576. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for $C_0$
  1577. is defined in Figure~\ref{fig:c0-syntax}.
  1578. %
  1579. The $C_0$ language supports the same operators as $R_1$ but the
  1580. arguments of operators are restricted to atomic expressions (variables
  1581. and integers), thanks to the \key{remove-complex-opera*} pass. Instead
  1582. of \key{Let} expressions, $C_0$ has assignment statements which can be
  1583. executed in sequence using the \key{Seq} form. A sequence of
  1584. statements always ends with \key{Return}, a guarantee that is baked
  1585. into the grammar rules for the \itm{tail} non-terminal. The naming of
  1586. this non-terminal comes from the term \emph{tail position}\index{tail position},
  1587. which refers to an expression that is the last one to execute within a
  1588. function. (An expression in tail position may contain subexpressions,
  1589. and those may or may not be in tail position depending on the kind of
  1590. expression.)
  1591. A $C_0$ program consists of a control-flow graph (represented as an
  1592. alist mapping labels to tails). This is more general than
  1593. necessary for the present chapter, as we do not yet need to introduce
  1594. \key{goto} for jumping to labels, but it saves us from having to
  1595. change the syntax of the program construct in
  1596. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1597. \key{start}, and the whole program is its tail.
  1598. %
  1599. The $\itm{info}$ field of the \key{Program} form, after the
  1600. \key{explicate-control} pass, contains a mapping from the symbol
  1601. \key{locals} to a list of variables, that is, a list of all the
  1602. variables used in the program. At the start of the program, these
  1603. variables are uninitialized; they become initialized on their first
  1604. assignment.
  1605. \begin{figure}[tbp]
  1606. \fbox{
  1607. \begin{minipage}{0.96\textwidth}
  1608. \[
  1609. \begin{array}{lcl}
  1610. \Atm &::=& \Int \mid \Var \\
  1611. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  1612. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  1613. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  1614. C_0 & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  1615. \end{array}
  1616. \]
  1617. \end{minipage}
  1618. }
  1619. \caption{The concrete syntax of the $C_0$ intermediate language.}
  1620. \label{fig:c0-concrete-syntax}
  1621. \end{figure}
  1622. \begin{figure}[tbp]
  1623. \fbox{
  1624. \begin{minipage}{0.96\textwidth}
  1625. \[
  1626. \begin{array}{lcl}
  1627. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1628. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1629. &\mid& \ADD{\Atm}{\Atm}\\
  1630. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  1631. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1632. C_0 & ::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}\ldots}}
  1633. \end{array}
  1634. \]
  1635. \end{minipage}
  1636. }
  1637. \caption{The abstract syntax of the $C_0$ intermediate language.}
  1638. \label{fig:c0-syntax}
  1639. \end{figure}
  1640. \subsection{The dialects of x86}
  1641. The x86$^{*}_0$ language, pronounced ``pseudo x86'', is the output of
  1642. the pass \key{select-instructions}. It extends x86$_0$ with an
  1643. unbounded number of program-scope variables and has looser rules
  1644. regarding instruction arguments. The x86$^{\dagger}$ language, the
  1645. output of \key{print-x86}, is the concrete syntax for x86.
  1646. \section{Uniquify Variables}
  1647. \label{sec:uniquify-s0}
  1648. The \code{uniquify} pass compiles arbitrary $R_1$ programs into $R_1$
  1649. programs in which every \key{let} uses a unique variable name. For
  1650. example, the \code{uniquify} pass should translate the program on the
  1651. left into the program on the right. \\
  1652. \begin{tabular}{lll}
  1653. \begin{minipage}{0.4\textwidth}
  1654. \begin{lstlisting}
  1655. (let ([x 32])
  1656. (+ (let ([x 10]) x) x))
  1657. \end{lstlisting}
  1658. \end{minipage}
  1659. &
  1660. $\Rightarrow$
  1661. &
  1662. \begin{minipage}{0.4\textwidth}
  1663. \begin{lstlisting}
  1664. (let ([x.1 32])
  1665. (+ (let ([x.2 10]) x.2) x.1))
  1666. \end{lstlisting}
  1667. \end{minipage}
  1668. \end{tabular} \\
  1669. %
  1670. The following is another example translation, this time of a program
  1671. with a \key{let} nested inside the initializing expression of another
  1672. \key{let}.\\
  1673. \begin{tabular}{lll}
  1674. \begin{minipage}{0.4\textwidth}
  1675. \begin{lstlisting}
  1676. (let ([x (let ([x 4])
  1677. (+ x 1))])
  1678. (+ x 2))
  1679. \end{lstlisting}
  1680. \end{minipage}
  1681. &
  1682. $\Rightarrow$
  1683. &
  1684. \begin{minipage}{0.4\textwidth}
  1685. \begin{lstlisting}
  1686. (let ([x.2 (let ([x.1 4])
  1687. (+ x.1 1))])
  1688. (+ x.2 2))
  1689. \end{lstlisting}
  1690. \end{minipage}
  1691. \end{tabular}
  1692. We recommend implementing \code{uniquify} by creating a function named
  1693. \code{uniquify-exp} that is structurally recursive function and mostly
  1694. just copies the input program. However, when encountering a \key{let},
  1695. it should generate a unique name for the variable (the Racket function
  1696. \code{gensym} is handy for this) and associate the old name with the
  1697. new unique name in an alist. The \code{uniquify-exp}
  1698. function will need to access this alist when it gets to a
  1699. variable reference, so we add another parameter to \code{uniquify-exp}
  1700. for the alist.
  1701. The skeleton of the \code{uniquify-exp} function is shown in
  1702. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1703. convenient to partially apply it to a symbol table and then apply it
  1704. to different expressions, as in the last clause for primitive
  1705. operations in Figure~\ref{fig:uniquify-s0}. The \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  1706. form is useful for applying a function to each element of a list to produce
  1707. a new list.
  1708. \index{for/list}
  1709. \begin{exercise}
  1710. \normalfont % I don't like the italics for exercises. -Jeremy
  1711. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1712. implement the clauses for variables and for the \key{let} form.
  1713. \end{exercise}
  1714. \begin{figure}[tbp]
  1715. \begin{lstlisting}
  1716. (define (uniquify-exp symtab)
  1717. (lambda (e)
  1718. (match e
  1719. [(Var x) ___]
  1720. [(Int n) (Int n)]
  1721. [(Let x e body) ___]
  1722. [(Prim op es)
  1723. (Prim op (for/list ([e es]) ((uniquify-exp symtab) e)))]
  1724. )))
  1725. (define (uniquify p)
  1726. (match p
  1727. [(Program '() e)
  1728. (Program '() ((uniquify-exp '()) e))]
  1729. )))
  1730. \end{lstlisting}
  1731. \caption{Skeleton for the \key{uniquify} pass.}
  1732. \label{fig:uniquify-s0}
  1733. \end{figure}
  1734. \begin{exercise}
  1735. \normalfont % I don't like the italics for exercises. -Jeremy
  1736. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1737. and checking whether the output programs produce the same result as
  1738. the input programs. The $R_1$ programs should be designed to test the
  1739. most interesting parts of the \key{uniquify} pass, that is, the
  1740. programs should include \key{let} forms, variables, and variables
  1741. that overshadow each other. The five programs should be in a
  1742. subdirectory named \key{tests} and they should have the same file name
  1743. except for a different integer at the end of the name, followed by the
  1744. ending \key{.rkt}. Use the \key{interp-tests} function
  1745. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1746. your \key{uniquify} pass on the example programs. See the
  1747. \key{run-tests.rkt} script in the student support code for an example
  1748. of how to use \key{interp-tests}.
  1749. \end{exercise}
  1750. \section{Remove Complex Operands}
  1751. \label{sec:remove-complex-opera-R1}
  1752. The \code{remove-complex-opera*} pass compiles $R_1$ programs into
  1753. $R_1$ programs in which the arguments of operations are atomic
  1754. expressions. Put another way, this pass removes complex
  1755. operands\index{complex operand}, such as the expression \code{(- 10)}
  1756. in the program below. This is accomplished by introducing a new
  1757. \key{let}-bound variable, binding the complex operand to the new
  1758. variable, and then using the new variable in place of the complex
  1759. operand, as shown in the output of \code{remove-complex-opera*} on the
  1760. right.\\
  1761. \begin{tabular}{lll}
  1762. \begin{minipage}{0.4\textwidth}
  1763. % s0_19.rkt
  1764. \begin{lstlisting}
  1765. (+ 52 (- 10))
  1766. \end{lstlisting}
  1767. \end{minipage}
  1768. &
  1769. $\Rightarrow$
  1770. &
  1771. \begin{minipage}{0.4\textwidth}
  1772. \begin{lstlisting}
  1773. (let ([tmp.1 (- 10)])
  1774. (+ 52 tmp.1))
  1775. \end{lstlisting}
  1776. \end{minipage}
  1777. \end{tabular}
  1778. \begin{figure}[tp]
  1779. \centering
  1780. \fbox{
  1781. \begin{minipage}{0.96\textwidth}
  1782. \[
  1783. \begin{array}{rcl}
  1784. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1785. \Exp &::=& \Atm \mid \READ{} \\
  1786. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  1787. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  1788. R^{\dagger}_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1789. \end{array}
  1790. \]
  1791. \end{minipage}
  1792. }
  1793. \caption{$R_1^{\dagger}$ is $R_1$ in administrative normal form (ANF).}
  1794. \label{fig:r1-anf-syntax}
  1795. \end{figure}
  1796. Figure~\ref{fig:r1-anf-syntax} presents the grammar for the output of
  1797. this pass, language $R_1^{\dagger}$. The main difference is that
  1798. operator arguments are required to be atomic expressions. In the
  1799. literature, this is called \emph{administrative normal form}, or ANF
  1800. for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  1801. \index{administrative normal form}
  1802. \index{ANF}
  1803. We recommend implementing this pass with two mutually recursive
  1804. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1805. \code{rco-atom} to subexpressions that are required to be atomic and
  1806. to apply \code{rco-exp} to subexpressions that can be atomic or
  1807. complex (see Figure~\ref{fig:r1-anf-syntax}). Both functions take an
  1808. $R_1$ expression as input. The \code{rco-exp} function returns an
  1809. expression. The \code{rco-atom} function returns two things: an
  1810. atomic expression and alist mapping temporary variables to complex
  1811. subexpressions. You can return multiple things from a function using
  1812. Racket's \key{values} form and you can receive multiple things from a
  1813. function call using the \key{define-values} form. If you are not
  1814. familiar with these features, review the Racket documentation. Also,
  1815. the \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flists%29%29}{\code{for/lists}}
  1816. form is useful for applying a function to each
  1817. element of a list, in the case where the function returns multiple
  1818. values.
  1819. \index{for/lists}
  1820. The following shows the output of \code{rco-atom} on the expression
  1821. \code{(- 10)} (using concrete syntax to be concise).
  1822. \begin{tabular}{lll}
  1823. \begin{minipage}{0.4\textwidth}
  1824. \begin{lstlisting}
  1825. (- 10)
  1826. \end{lstlisting}
  1827. \end{minipage}
  1828. &
  1829. $\Rightarrow$
  1830. &
  1831. \begin{minipage}{0.4\textwidth}
  1832. \begin{lstlisting}
  1833. tmp.1
  1834. ((tmp.1 . (- 10)))
  1835. \end{lstlisting}
  1836. \end{minipage}
  1837. \end{tabular}
  1838. Take special care of programs such as the next one that \key{let}-bind
  1839. variables with integers or other variables. You should leave them
  1840. unchanged, as shown in to the program on the right \\
  1841. \begin{tabular}{lll}
  1842. \begin{minipage}{0.4\textwidth}
  1843. % s0_20.rkt
  1844. \begin{lstlisting}
  1845. (let ([a 42])
  1846. (let ([b a])
  1847. b))
  1848. \end{lstlisting}
  1849. \end{minipage}
  1850. &
  1851. $\Rightarrow$
  1852. &
  1853. \begin{minipage}{0.4\textwidth}
  1854. \begin{lstlisting}
  1855. (let ([a 42])
  1856. (let ([b a])
  1857. b))
  1858. \end{lstlisting}
  1859. \end{minipage}
  1860. \end{tabular} \\
  1861. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  1862. produce the following output.\\
  1863. \begin{minipage}{0.4\textwidth}
  1864. \begin{lstlisting}
  1865. (let ([tmp.1 42])
  1866. (let ([a tmp.1])
  1867. (let ([tmp.2 a])
  1868. (let ([b tmp.2])
  1869. b))))
  1870. \end{lstlisting}
  1871. \end{minipage}
  1872. \begin{exercise}
  1873. \normalfont Implement the \code{remove-complex-opera*} pass.
  1874. Test the new pass on all of the example programs that you created to test the
  1875. \key{uniquify} pass and create three new example programs that are
  1876. designed to exercise the interesting code in the
  1877. \code{remove-complex-opera*} pass. Use the \key{interp-tests} function
  1878. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1879. your passes on the example programs.
  1880. \end{exercise}
  1881. \section{Explicate Control}
  1882. \label{sec:explicate-control-r1}
  1883. The \code{explicate-control} pass compiles $R_1$ programs into $C_0$
  1884. programs that make the order of execution explicit in their
  1885. syntax. For now this amounts to flattening \key{let} constructs into a
  1886. sequence of assignment statements. For example, consider the following
  1887. $R_1$ program.\\
  1888. % s0_11.rkt
  1889. \begin{minipage}{0.96\textwidth}
  1890. \begin{lstlisting}
  1891. (let ([y (let ([x 20])
  1892. (+ x (let ([x 22]) x)))])
  1893. y)
  1894. \end{lstlisting}
  1895. \end{minipage}\\
  1896. %
  1897. The output of the previous pass and of \code{explicate-control} is
  1898. shown below. Recall that the right-hand-side of a \key{let} executes
  1899. before its body, so the order of evaluation for this program is to
  1900. assign \code{20} to \code{x.1}, assign \code{22} to \code{x.2}, assign
  1901. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  1902. output of \code{explicate-control} makes this ordering explicit.\\
  1903. \begin{tabular}{lll}
  1904. \begin{minipage}{0.4\textwidth}
  1905. \begin{lstlisting}
  1906. (let ([y (let ([x.1 20])
  1907. (let ([x.2 22])
  1908. (+ x.1 x.2)))])
  1909. y)
  1910. \end{lstlisting}
  1911. \end{minipage}
  1912. &
  1913. $\Rightarrow$
  1914. &
  1915. \begin{minipage}{0.4\textwidth}
  1916. \begin{lstlisting}
  1917. locals: y x.1 x.2
  1918. start:
  1919. x.1 = 20;
  1920. x.2 = 22;
  1921. y = (+ x.1 x.2);
  1922. return y;
  1923. \end{lstlisting}
  1924. \end{minipage}
  1925. \end{tabular}
  1926. We recommend implementing \code{explicate-control} using two mutually
  1927. recursive functions: \code{explicate-tail} and
  1928. \code{explicate-assign}. The first function should be applied to
  1929. expressions in tail position whereas the second should be applied to
  1930. expressions that occur on the right-hand-side of a \key{let}.
  1931. %
  1932. The \code{explicate-tail} function takes an $R_1$ expression as input
  1933. and produces a $C_0$ $\Tail$ (see Figure~\ref{fig:c0-syntax}) and a
  1934. list of formerly \key{let}-bound variables.
  1935. %
  1936. The \code{explicate-assign} function takes an $R_1$ expression, the
  1937. variable that it is to be assigned to, and $C_0$ code (a $\Tail$) that
  1938. should come after the assignment (e.g., the code generated for the
  1939. body of the \key{let}). It returns a $\Tail$ and a list of
  1940. variables. The \code{explicate-assign} function is in
  1941. accumulator-passing style in that its third parameter is some $C_0$
  1942. code which it then adds to and returns. The reader might be tempted to
  1943. instead organize \code{explicate-assign} in a more direct fashion,
  1944. without the third parameter and perhaps using \code{append} to combine
  1945. statements. We warn against that alternative because the
  1946. accumulator-passing style is key to how we generate high-quality code
  1947. for conditional expressions in Chapter~\ref{ch:bool-types}.
  1948. The top-level \code{explicate-control} function should invoke
  1949. \code{explicate-tail} on the body of the \key{program} and then
  1950. associate the \code{locals} symbol with the resulting list of
  1951. variables in the $\itm{info}$ field, as in the above example.
  1952. \section{Select Instructions}
  1953. \label{sec:select-r1}
  1954. \index{instruction selection}
  1955. In the \code{select-instructions} pass we begin the work of
  1956. translating from $C_0$ to $\text{x86}^{*}_0$. The target language of
  1957. this pass is a variant of x86 that still uses variables, so we add an
  1958. AST node of the form $\VAR{\itm{var}}$ to the $\text{x86}_0$ abstract
  1959. syntax of Figure~\ref{fig:x86-0-ast}. We recommend implementing the
  1960. \code{select-instructions} in terms of three auxiliary functions, one
  1961. for each of the non-terminals of $C_0$: $\Atm$, $\Stmt$, and $\Tail$.
  1962. The cases for $\Atm$ are straightforward, variables stay
  1963. the same and integer constants are changed to immediates:
  1964. $\INT{n}$ changes to $\IMM{n}$.
  1965. Next we consider the cases for $\Stmt$, starting with arithmetic
  1966. operations. For example, in $C_0$ an addition operation can take the
  1967. form below, to the left of the $\Rightarrow$. To translate to x86, we
  1968. need to use the \key{addq} instruction which does an in-place
  1969. update. So we must first move \code{10} to \code{x}. \\
  1970. \begin{tabular}{lll}
  1971. \begin{minipage}{0.4\textwidth}
  1972. \begin{lstlisting}
  1973. x = (+ 10 32);
  1974. \end{lstlisting}
  1975. \end{minipage}
  1976. &
  1977. $\Rightarrow$
  1978. &
  1979. \begin{minipage}{0.4\textwidth}
  1980. \begin{lstlisting}
  1981. movq $10, x
  1982. addq $32, x
  1983. \end{lstlisting}
  1984. \end{minipage}
  1985. \end{tabular} \\
  1986. %
  1987. There are cases that require special care to avoid generating
  1988. needlessly complicated code. If one of the arguments of the addition
  1989. is the same as the left-hand side of the assignment, then there is no
  1990. need for the extra move instruction. For example, the following
  1991. assignment statement can be translated into a single \key{addq}
  1992. instruction.\\
  1993. \begin{tabular}{lll}
  1994. \begin{minipage}{0.4\textwidth}
  1995. \begin{lstlisting}
  1996. x = (+ 10 x);
  1997. \end{lstlisting}
  1998. \end{minipage}
  1999. &
  2000. $\Rightarrow$
  2001. &
  2002. \begin{minipage}{0.4\textwidth}
  2003. \begin{lstlisting}
  2004. addq $10, x
  2005. \end{lstlisting}
  2006. \end{minipage}
  2007. \end{tabular} \\
  2008. The \key{read} operation does not have a direct counterpart in x86
  2009. assembly, so we have instead implemented this functionality in the C
  2010. language~\citep{Kernighan:1988nx}, with the function \code{read\_int}
  2011. in the file \code{runtime.c}. In general, we refer to all of the
  2012. functionality in this file as the \emph{runtime system}\index{runtime system},
  2013. or simply the \emph{runtime} for short. When compiling your generated x86
  2014. assembly code, you need to compile \code{runtime.c} to \code{runtime.o} (an
  2015. ``object file'', using \code{gcc} option \code{-c}) and link it into
  2016. the executable. For our purposes of code generation, all you need to
  2017. do is translate an assignment of \key{read} into some variable
  2018. $\itm{lhs}$ (for left-hand side) into a call to the \code{read\_int}
  2019. function followed by a move from \code{rax} to the left-hand side.
  2020. The move from \code{rax} is needed because the return value from
  2021. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  2022. \begin{tabular}{lll}
  2023. \begin{minipage}{0.3\textwidth}
  2024. \begin{lstlisting}
  2025. |$\itm{var}$| = (read);
  2026. \end{lstlisting}
  2027. \end{minipage}
  2028. &
  2029. $\Rightarrow$
  2030. &
  2031. \begin{minipage}{0.3\textwidth}
  2032. \begin{lstlisting}
  2033. callq read_int
  2034. movq %rax, |$\itm{var}$|
  2035. \end{lstlisting}
  2036. \end{minipage}
  2037. \end{tabular} \\
  2038. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  2039. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  2040. assignment to the \key{rax} register followed by a jump to the
  2041. conclusion of the program (so the conclusion needs to be labeled).
  2042. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  2043. recursively and append the resulting instructions.
  2044. \begin{exercise}
  2045. \normalfont
  2046. Implement the \key{select-instructions} pass and test it on all of the
  2047. example programs that you created for the previous passes and create
  2048. three new example programs that are designed to exercise all of the
  2049. interesting code in this pass. Use the \key{interp-tests} function
  2050. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2051. your passes on the example programs.
  2052. \end{exercise}
  2053. \section{Assign Homes}
  2054. \label{sec:assign-r1}
  2055. The \key{assign-homes} pass compiles $\text{x86}^{*}_0$ programs to
  2056. $\text{x86}^{*}_0$ programs that no longer use program variables.
  2057. Thus, the \key{assign-homes} pass is responsible for placing all of
  2058. the program variables in registers or on the stack. For runtime
  2059. efficiency, it is better to place variables in registers, but as there
  2060. are only 16 registers, some programs must necessarily resort to
  2061. placing some variables on the stack. In this chapter we focus on the
  2062. mechanics of placing variables on the stack. We study an algorithm for
  2063. placing variables in registers in
  2064. Chapter~\ref{ch:register-allocation-r1}.
  2065. Consider again the following $R_1$ program.
  2066. % s0_20.rkt
  2067. \begin{lstlisting}
  2068. (let ([a 42])
  2069. (let ([b a])
  2070. b))
  2071. \end{lstlisting}
  2072. For reference, we repeat the output of \code{select-instructions} on
  2073. the left and show the output of \code{assign-homes} on the right.
  2074. Recall that \key{explicate-control} associated the list of
  2075. variables with the \code{locals} symbol in the program's $\itm{info}$
  2076. field, so \code{assign-homes} has convenient access to the them. In
  2077. this example, we assign variable \code{a} to stack location
  2078. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.\\
  2079. \begin{tabular}{l}
  2080. \begin{minipage}{0.4\textwidth}
  2081. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2082. locals: a b
  2083. start:
  2084. movq $42, a
  2085. movq a, b
  2086. movq b, %rax
  2087. jmp conclusion
  2088. \end{lstlisting}
  2089. \end{minipage}
  2090. {$\Rightarrow$}
  2091. \begin{minipage}{0.4\textwidth}
  2092. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2093. stack-space: 16
  2094. start:
  2095. movq $42, -8(%rbp)
  2096. movq -8(%rbp), -16(%rbp)
  2097. movq -16(%rbp), %rax
  2098. jmp conclusion
  2099. \end{lstlisting}
  2100. \end{minipage}
  2101. \end{tabular} \\
  2102. In the process of assigning variables to stack locations, it is
  2103. convenient to compute and store the size of the frame (in bytes) in
  2104. the $\itm{info}$ field of the \key{Program} node, with the key
  2105. \code{stack-space}, which will be needed later to generate the
  2106. procedure conclusion. The x86-64 standard requires the frame size to
  2107. be a multiple of 16 bytes.
  2108. \index{frame}
  2109. \begin{exercise}
  2110. \normalfont Implement the \key{assign-homes} pass and test it on all
  2111. of the example programs that you created for the previous passes pass.
  2112. We recommend that \key{assign-homes} take an extra parameter that is a
  2113. mapping of variable names to homes (stack locations for now). Use the
  2114. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  2115. \key{utilities.rkt} to test your passes on the example programs.
  2116. \end{exercise}
  2117. \section{Patch Instructions}
  2118. \label{sec:patch-s0}
  2119. The \code{patch-instructions} pass compiles $\text{x86}^{*}_0$
  2120. programs to $\text{x86}_0$ programs by making sure that each
  2121. instruction adheres to the restrictions of the x86 assembly language.
  2122. In particular, at most one argument of an instruction may be a memory
  2123. reference.
  2124. We return to the following running example.
  2125. % s0_20.rkt
  2126. \begin{lstlisting}
  2127. (let ([a 42])
  2128. (let ([b a])
  2129. b))
  2130. \end{lstlisting}
  2131. After the \key{assign-homes} pass, the above program has been translated to
  2132. the following. \\
  2133. \begin{minipage}{0.5\textwidth}
  2134. \begin{lstlisting}
  2135. stack-space: 16
  2136. start:
  2137. movq $42, -8(%rbp)
  2138. movq -8(%rbp), -16(%rbp)
  2139. movq -16(%rbp), %rax
  2140. jmp conclusion
  2141. \end{lstlisting}
  2142. \end{minipage}\\
  2143. The second \key{movq} instruction is problematic because both
  2144. arguments are stack locations. We suggest fixing this problem by
  2145. moving from the source location to the register \key{rax} and then
  2146. from \key{rax} to the destination location, as follows.
  2147. \begin{lstlisting}
  2148. movq -8(%rbp), %rax
  2149. movq %rax, -16(%rbp)
  2150. \end{lstlisting}
  2151. \begin{exercise}
  2152. \normalfont
  2153. Implement the \key{patch-instructions} pass and test it on all of the
  2154. example programs that you created for the previous passes and create
  2155. three new example programs that are designed to exercise all of the
  2156. interesting code in this pass. Use the \key{interp-tests} function
  2157. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2158. your passes on the example programs.
  2159. \end{exercise}
  2160. \section{Print x86}
  2161. \label{sec:print-x86}
  2162. The last step of the compiler from $R_1$ to x86 is to convert the
  2163. $\text{x86}_0$ AST (defined in Figure~\ref{fig:x86-0-ast}) to the
  2164. string representation (defined in Figure~\ref{fig:x86-0-concrete}). The Racket
  2165. \key{format} and \key{string-append} functions are useful in this
  2166. regard. The main work that this step needs to perform is to create the
  2167. \key{main} function and the standard instructions for its prelude and
  2168. conclusion, as shown in Figure~\ref{fig:p1-x86} of
  2169. Section~\ref{sec:x86}. You need to know the number of stack-allocated
  2170. variables, so we suggest computing it in the \key{assign-homes} pass
  2171. (Section~\ref{sec:assign-r1}) and storing it in the $\itm{info}$ field
  2172. of the \key{program} node.
  2173. %% Your compiled code should print the result of the program's execution
  2174. %% by using the \code{print\_int} function provided in
  2175. %% \code{runtime.c}. If your compiler has been implemented correctly so
  2176. %% far, this final result should be stored in the \key{rax} register.
  2177. %% We'll talk more about how to perform function calls with arguments in
  2178. %% general later on, but for now, place the following after the compiled
  2179. %% code for the $R_1$ program but before the conclusion:
  2180. %% \begin{lstlisting}
  2181. %% movq %rax, %rdi
  2182. %% callq print_int
  2183. %% \end{lstlisting}
  2184. %% These lines move the value in \key{rax} into the \key{rdi} register, which
  2185. %% stores the first argument to be passed into \key{print\_int}.
  2186. If you want your program to run on Mac OS X, your code needs to
  2187. determine whether or not it is running on a Mac, and prefix
  2188. underscores to labels like \key{main}. You can determine the platform
  2189. with the Racket call \code{(system-type 'os)}, which returns
  2190. \code{'macosx}, \code{'unix}, or \code{'windows}.
  2191. %% In addition to
  2192. %% placing underscores on \key{main}, you need to put them in front of
  2193. %% \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  2194. %% \_print\_int}).
  2195. \begin{exercise}
  2196. \normalfont Implement the \key{print-x86} pass and test it on all of
  2197. the example programs that you created for the previous passes. Use the
  2198. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  2199. \key{utilities.rkt} to test your complete compiler on the example
  2200. programs. See the \key{run-tests.rkt} script in the student support
  2201. code for an example of how to use \key{compiler-tests}. Also, remember
  2202. to compile the provided \key{runtime.c} file to \key{runtime.o} using
  2203. \key{gcc}.
  2204. \end{exercise}
  2205. \section{Challenge: Partial Evaluator for $R_1$}
  2206. \label{sec:pe-R1}
  2207. \index{partial evaluation}
  2208. This section describes optional challenge exercises that involve
  2209. adapting and improving the partial evaluator for $R_0$ that was
  2210. introduced in Section~\ref{sec:partial-evaluation}.
  2211. \begin{exercise}\label{ex:pe-R1}
  2212. \normalfont
  2213. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2214. (Figure~\ref{fig:pe-arith}) so that it applies to $R_1$ programs
  2215. instead of $R_0$ programs. Recall that $R_1$ adds \key{let} binding
  2216. and variables to the $R_0$ language, so you will need to add cases for
  2217. them in the \code{pe-exp} function. Also, note that the \key{program}
  2218. form changes slightly to include an $\itm{info}$ field. Once
  2219. complete, add the partial evaluation pass to the front of your
  2220. compiler and make sure that your compiler still passes all of the
  2221. tests.
  2222. \end{exercise}
  2223. The next exercise builds on Exercise~\ref{ex:pe-R1}.
  2224. \begin{exercise}
  2225. \normalfont
  2226. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2227. \code{pe-add} auxiliary functions with functions that know more about
  2228. arithmetic. For example, your partial evaluator should translate
  2229. \begin{lstlisting}
  2230. (+ 1 (+ (read) 1))
  2231. \end{lstlisting}
  2232. into
  2233. \begin{lstlisting}
  2234. (+ 2 (read))
  2235. \end{lstlisting}
  2236. To accomplish this, the \code{pe-exp} function should produce output
  2237. in the form of the $\itm{residual}$ non-terminal of the following
  2238. grammar.
  2239. \[
  2240. \begin{array}{lcl}
  2241. \itm{inert} &::=& \Var \mid (\key{read}) \mid (\key{-} \;(\key{read}))
  2242. \mid (\key{+} \; \itm{inert} \; \itm{inert})\\
  2243. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \itm{inert}) \mid \itm{inert}
  2244. \end{array}
  2245. \]
  2246. The \code{pe-add} and \code{pe-neg} functions may therefore assume
  2247. that their inputs are $\itm{residual}$ expressions and they should
  2248. return $\itm{residual}$ expressions. Once the improvements are
  2249. complete, make sure that your compiler still passes all of the tests.
  2250. After all, fast code is useless if it produces incorrect results!
  2251. \end{exercise}
  2252. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2253. \chapter{Register Allocation}
  2254. \label{ch:register-allocation-r1}
  2255. \index{register allocation}
  2256. In Chapter~\ref{ch:int-exp} we placed all variables on the stack to
  2257. make our life easier. However, we can improve the performance of the
  2258. generated code if we instead place some variables into registers. The
  2259. CPU can access a register in a single cycle, whereas accessing the
  2260. stack takes many cycles if the relevant data is in cache or many more
  2261. to access main memory if the data is not in cache.
  2262. Figure~\ref{fig:reg-eg} shows a program with four variables that
  2263. serves as a running example. We show the source program and also the
  2264. output of instruction selection. At that point the program is almost
  2265. x86 assembly but not quite; it still contains variables instead of
  2266. stack locations or registers.
  2267. \begin{figure}
  2268. \begin{minipage}{0.45\textwidth}
  2269. Example $R_1$ program:
  2270. % s0_28.rkt
  2271. \begin{lstlisting}
  2272. (let ([v 1])
  2273. (let ([w 42])
  2274. (let ([x (+ v 7)])
  2275. (let ([y x])
  2276. (let ([z (+ x w)])
  2277. (+ z (- y)))))))
  2278. \end{lstlisting}
  2279. \end{minipage}
  2280. \begin{minipage}{0.45\textwidth}
  2281. After instruction selection:
  2282. \begin{lstlisting}
  2283. locals: (v w x y z t)
  2284. start:
  2285. movq $1, v
  2286. movq $42, w
  2287. movq v, x
  2288. addq $7, x
  2289. movq x, y
  2290. movq x, z
  2291. addq w, z
  2292. movq y, t
  2293. negq t
  2294. movq z, %rax
  2295. addq t, %rax
  2296. jmp conclusion
  2297. \end{lstlisting}
  2298. \end{minipage}
  2299. \caption{A running example program for register allocation.}
  2300. \label{fig:reg-eg}
  2301. \end{figure}
  2302. The goal of register allocation is to fit as many variables into
  2303. registers as possible. A program sometimes has more variables than
  2304. registers, so we cannot map each variable to a different
  2305. register. Fortunately, it is common for different variables to be
  2306. needed during different periods of time during program execution, and
  2307. in such cases several variables can be mapped to the same register.
  2308. Consider variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}.
  2309. After the variable \code{x} is moved to \code{z} it is no longer
  2310. needed. Variable \code{y}, on the other hand, is used only after this
  2311. point, so \code{x} and \code{y} could share the same register. The
  2312. topic of Section~\ref{sec:liveness-analysis-r1} is how to compute
  2313. where a variable is needed. Once we have that information, we compute
  2314. which variables are needed at the same time, i.e., which ones
  2315. \emph{interfere} with each other, and represent this relation as an
  2316. undirected graph whose vertices are variables and edges indicate when
  2317. two variables interfere (Section~\ref{sec:build-interference}). We
  2318. then model register allocation as a graph coloring problem, which we
  2319. discuss in Section~\ref{sec:graph-coloring}.
  2320. In the event that we run out of registers despite these efforts, we
  2321. place the remaining variables on the stack, similar to what we did in
  2322. Chapter~\ref{ch:int-exp}. It is common to use the verb \emph{spill}
  2323. for assigning a variable to a stack location. The process of spilling
  2324. variables is handled as part of the graph coloring process described
  2325. in \ref{sec:graph-coloring}.
  2326. We make the simplifying assumption that each variable is assigned to
  2327. one location (a register or stack address). A more sophisticated
  2328. approach is to assign a variable to one or more locations in different
  2329. regions of the program. For example, if a variable is used many times
  2330. in short sequence and then only used again after many other
  2331. instructions, it could be more efficient to assign the variable to a
  2332. register during the intial sequence and then move it to the stack for
  2333. the rest of its lifetime. We refer the interested reader to
  2334. \citet{Cooper:1998ly} and \citet{Cooper:2011aa} for more information
  2335. about this approach.
  2336. % discuss prioritizing variables based on how much they are used.
  2337. \section{Registers and Calling Conventions}
  2338. \label{sec:calling-conventions}
  2339. \index{calling conventions}
  2340. As we perform register allocation, we need to be aware of the
  2341. conventions that govern the way in which registers interact with
  2342. function calls, such as calls to the \code{read\_int} function in our
  2343. generated code and even the call that the operating system makes to
  2344. execute our \code{main} function. The convention for x86 regarding
  2345. how functions share the use of registers is that the caller is
  2346. responsible for freeing up some registers, the \emph{caller-saved
  2347. registers}, prior to the function call, and the callee is
  2348. responsible for preserving the values of some other registers, the
  2349. \emph{callee-saved registers}. \index{caller-saved registers}
  2350. \index{callee-saved registers} The caller-saved registers are
  2351. \begin{lstlisting}
  2352. rax rcx rdx rsi rdi r8 r9 r10 r11
  2353. \end{lstlisting}
  2354. while the callee-saved registers are
  2355. \begin{lstlisting}
  2356. rsp rbp rbx r12 r13 r14 r15
  2357. \end{lstlisting}
  2358. We can think about this caller/callee convention from two points of
  2359. view, the caller view and the callee view:
  2360. \begin{itemize}
  2361. \item The caller should assume that all the caller-saved registers get
  2362. overwritten with arbitrary values by the callee. On the other hand,
  2363. the caller can safely assume that all the callee-saved registers
  2364. contain the same values after the call that they did before the
  2365. call.
  2366. \item The callee can freely use any of the caller-saved registers.
  2367. However, if the callee wants to use a callee-saved register, the
  2368. callee must arrange to put the original value back in the register
  2369. prior to returning to the caller, which is usually accomplished by
  2370. saving the value to the stack in the prelude of the function and
  2371. restoring the value in the conclusion of the function.
  2372. \end{itemize}
  2373. In x86, registers are also used for passing arguments to a function
  2374. and for the return value. In particular, the first six arguments of a
  2375. function are passed in the following six registers, in the order
  2376. given.
  2377. \begin{lstlisting}
  2378. rdi rsi rdx rcx r8 r9
  2379. \end{lstlisting}
  2380. If there are more than six arguments, then the convention is to use
  2381. space on the frame of the caller for the rest of the
  2382. arguments. However, in Chapter~\ref{ch:functions} we arrange to never
  2383. need more than six arguments. For now, the only function we care about
  2384. is \code{read\_int} and it takes zero argument.
  2385. %
  2386. The register \code{rax} is for the return value of a function.
  2387. The next question is how these calling conventions impact register
  2388. allocation. Consider the $R_1$ program in
  2389. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  2390. example from the caller point of view and then from the callee point
  2391. of view.
  2392. The program makes two calls to the \code{read} function. Also, the
  2393. variable \code{x} is in-use during the second call to \code{read}, so
  2394. we need to make sure that the value in \code{x} does not get
  2395. accidentally wiped out by the call to \code{read}. One obvious
  2396. approach is to save all the values in caller-saved registers to the
  2397. stack prior to each function call, and restore them after each
  2398. call. That way, if the register allocator chooses to assign \code{x}
  2399. to a caller-saved register, its value will be preserved accross the
  2400. call to \code{read}. However, the disadvantage of this approach is
  2401. that saving and restoring to the stack is relatively slow. If \code{x}
  2402. is not used many times, it may be better to assign \code{x} to a stack
  2403. location in the first place. Or better yet, if we can arrange for
  2404. \code{x} to be placed in a callee-saved register, then it won't need
  2405. to be saved and restored during function calls.
  2406. The approach that we recommend for variables that are in-use during a
  2407. function call is to either assign them to callee-saved registers or to
  2408. spill them to the stack. On the other hand, for variables that are not
  2409. in-use during a function call, we try the following alternatives in
  2410. order 1) look for an available caller-saved register (to leave room
  2411. for other variables in the callee-saved register), 2) look for a
  2412. callee-saved register, and 3) spill the variable to the stack.
  2413. It is straightforward to implement this approach in a graph coloring
  2414. register allocator. First, we know which variables are in-use during
  2415. every function call because we compute that information for every
  2416. instruction (Section~\ref{sec:liveness-analysis-r1}). Second, when we
  2417. build the interference graph (Section~\ref{sec:build-interference}),
  2418. we can place an edge between each of these variables and the
  2419. caller-saved registers in the interference graph. This will prevent
  2420. the graph coloring algorithm from assigning those variables to
  2421. caller-saved registers.
  2422. Returning to the example in
  2423. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  2424. generated x86 code on the right-hand side, focusing on the
  2425. \code{start} block. Notice that variable \code{x} is assigned to
  2426. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  2427. place during the second call to \code{read\_int}. Next, notice that
  2428. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  2429. because there are no function calls in the remainder of the block.
  2430. Next we analyze the example from the callee point of view, focusing on
  2431. the prelude and conclusion of the \code{main} function. As usual the
  2432. prelude begins with saving the \code{rbp} register to the stack and
  2433. setting the \code{rbp} to the current stack pointer. We now know why
  2434. it is necessary to save the \code{rbp}: it is a callee-saved register.
  2435. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  2436. is also a callee-saved register and 2) \code{rbx} is assigned to a
  2437. variable (\code{x}). There are several more callee-saved register that
  2438. are not saved in the prelude because they were not assigned to
  2439. variables. The prelude subtracts 8 bytes from the \code{rsp} to make
  2440. it 16-byte aligned and then jumps to the \code{start} block. Shifting
  2441. attention to the \code{conclusion}, we see that \code{rbx} is restored
  2442. from the stack with a \code{popq} instruction.
  2443. \index{prelude}\index{conclusion}
  2444. \begin{figure}[tp]
  2445. \begin{minipage}{0.45\textwidth}
  2446. Example $R_1$ program:
  2447. %s0_14.rkt
  2448. \begin{lstlisting}
  2449. (let ([x (read)])
  2450. (let ([y (read)])
  2451. (+ (+ x y) 42)))
  2452. \end{lstlisting}
  2453. \end{minipage}
  2454. \begin{minipage}{0.45\textwidth}
  2455. Generated x86 assembly:
  2456. \begin{lstlisting}
  2457. start:
  2458. callq read_int
  2459. movq %rax, %rbx
  2460. callq read_int
  2461. movq %rax, %rcx
  2462. addq %rcx, %rbx
  2463. movq %rbx, %rax
  2464. addq $42, %rax
  2465. jmp _conclusion
  2466. .globl main
  2467. main:
  2468. pushq %rbp
  2469. movq %rsp, %rbp
  2470. pushq %rbx
  2471. subq $8, %rsp
  2472. jmp start
  2473. conclusion:
  2474. addq $8, %rsp
  2475. popq %rbx
  2476. popq %rbp
  2477. retq
  2478. \end{lstlisting}
  2479. \end{minipage}
  2480. \caption{An example with function calls.}
  2481. \label{fig:example-calling-conventions}
  2482. \end{figure}
  2483. \clearpage
  2484. \section{Liveness Analysis}
  2485. \label{sec:liveness-analysis-r1}
  2486. \index{liveness analysis}
  2487. A variable or register is \emph{live} at a program point if its
  2488. current value is used at some later point in the program. We
  2489. refer to variables and registers collectively as \emph{locations}.
  2490. %
  2491. Consider the following code fragment in which there are two writes to
  2492. \code{b}. Are \code{a} and \code{b} both live at the same time?
  2493. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2494. movq $5, a
  2495. movq $30, b
  2496. movq a, c
  2497. movq $10, b
  2498. addq b, c
  2499. \end{lstlisting}
  2500. The answer is no because the integer \code{30} written to \code{b} on
  2501. line 2 is never used. The variable \code{b} is read on line 5 and
  2502. there is an intervening write to \code{b} on line 4, so the read on
  2503. line 5 receives the value written on line 4, not line 2.
  2504. \begin{wrapfigure}[18]{l}[1.0in]{0.6\textwidth}
  2505. \small
  2506. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  2507. A \emph{set} is an unordered collection of elements without duplicates.
  2508. \index{set}
  2509. \begin{description}
  2510. \item[$\LP\code{set}\,v\,\ldots\RP$] constructs a set containing the specified elements.
  2511. \item[$\LP\code{set-union}\,set_1\,set_2\RP$] returns the union of the two sets.
  2512. \item[$\LP\code{set-subtract}\,set_1\,set_2\RP$] returns the difference of the two sets.
  2513. \item[$\LP\code{set-member?}\,set\,v\RP$] is element $v$ in $set$?
  2514. \item[$\LP\code{set-count}\,set\RP$] how many unique elements are in $set$?
  2515. \item[$\LP\code{set->list}\,set\RP$] converts the set to a list.
  2516. \end{description}
  2517. \end{tcolorbox}
  2518. \end{wrapfigure}
  2519. The live locations can be computed by traversing the instruction
  2520. sequence back to front (i.e., backwards in execution order). Let
  2521. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2522. $L_{\mathsf{after}}(k)$ for the set of live locations after
  2523. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2524. locations before instruction $I_k$. The live locations after an
  2525. instruction are always the same as the live locations before the next
  2526. instruction. \index{live-after} \index{live-before}
  2527. \begin{equation} \label{eq:live-after-before-next}
  2528. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2529. \end{equation}
  2530. To start things off, there are no live locations after the last
  2531. instruction\footnote{Technically, the \code{rax} register is live
  2532. but we do not use it for register allocation.}, so
  2533. \begin{equation}\label{eq:live-last-empty}
  2534. L_{\mathsf{after}}(n) = \emptyset
  2535. \end{equation}
  2536. We then apply the following rule repeatedly, traversing the
  2537. instruction sequence back to front.
  2538. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2539. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2540. \end{equation}
  2541. where $W(k)$ are the locations written to by instruction $I_k$ and
  2542. $R(k)$ are the locations read by instruction $I_k$.
  2543. Let us walk through the above example, applying these formulas
  2544. starting with the instruction on line 5. We collect the answers in the
  2545. below listing. The $L_{\mathsf{after}}$ for the \code{addq b, c}
  2546. instruction is $\emptyset$ because it is the last instruction
  2547. (formula~\ref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  2548. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  2549. variables \code{b} and \code{c}
  2550. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  2551. \[
  2552. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  2553. \]
  2554. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2555. the live-before set from line 5 to be the live-after set for this
  2556. instruction (formula~\ref{eq:live-after-before-next}).
  2557. \[
  2558. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  2559. \]
  2560. This move instruction writes to \code{b} and does not read from any
  2561. variables, so we have the following live-before set
  2562. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2563. \[
  2564. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  2565. \]
  2566. The live-before for instruction \code{movq a, c}
  2567. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  2568. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2569. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  2570. variable that is not live and does not read from a variable.
  2571. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2572. because it writes to variable \code{a}.
  2573. \begin{center}
  2574. \begin{minipage}{0.45\textwidth}
  2575. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2576. movq $5, a
  2577. movq $30, b
  2578. movq a, c
  2579. movq $10, b
  2580. addq b, c
  2581. \end{lstlisting}
  2582. \end{minipage}
  2583. \vrule\hspace{10pt}
  2584. \begin{minipage}{0.45\textwidth}
  2585. \begin{align*}
  2586. L_{\mathsf{before}}(1)= \emptyset,
  2587. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  2588. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  2589. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  2590. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  2591. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  2592. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  2593. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  2594. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  2595. L_{\mathsf{after}}(5)= \emptyset
  2596. \end{align*}
  2597. \end{minipage}
  2598. \end{center}
  2599. Figure~\ref{fig:live-eg} shows the results of liveness analysis for
  2600. the running example program, with the live-before and live-after sets
  2601. shown between each instruction to make the figure easy to read.
  2602. \begin{figure}[tp]
  2603. \hspace{20pt}
  2604. \begin{minipage}{0.45\textwidth}
  2605. \begin{lstlisting}
  2606. |$\{\}$|
  2607. movq $1, v
  2608. |$\{\ttm{v}\}$|
  2609. movq $42, w
  2610. |$\{\ttm{v},\ttm{w}\}$|
  2611. movq v, x
  2612. |$\{\ttm{w},\ttm{x}\}$|
  2613. addq $7, x
  2614. |$\{\ttm{w},\ttm{x}\}$|
  2615. movq x, y
  2616. |$\{\ttm{w},\ttm{x},\ttm{y}\}$|
  2617. movq x, z
  2618. |$\{\ttm{w},\ttm{y},\ttm{z}\}$|
  2619. addq w, z
  2620. |$\{\ttm{y},\ttm{z}\}$|
  2621. movq y, t
  2622. |$\{\ttm{t},\ttm{z}\}$|
  2623. negq t
  2624. |$\{\ttm{t},\ttm{z}\}$|
  2625. movq z, %rax
  2626. |$\{\ttm{rax},\ttm{t}\}$|
  2627. addq t, %rax
  2628. |$\{\}$|
  2629. jmp conclusion
  2630. |$\{\}$|
  2631. \end{lstlisting}
  2632. \end{minipage}
  2633. \caption{The running example annotated with live-after sets.}
  2634. \label{fig:live-eg}
  2635. \end{figure}
  2636. \begin{exercise}\normalfont
  2637. Implement the compiler pass named \code{uncover-live} that computes
  2638. the live-after sets. We recommend storing the live-after sets (a list
  2639. of a set of variables) in the $\itm{info}$ field of the \code{Block}
  2640. structure.
  2641. %
  2642. We recommend organizing your code to use a helper function that takes
  2643. a list of instructions and an initial live-after set (typically empty)
  2644. and returns the list of live-after sets.
  2645. %
  2646. We recommend creating helper functions to 1) compute the set of
  2647. locations that appear in an argument (of an instruction), 2) compute
  2648. the locations read by an instruction which corresponds to the $R$
  2649. function discussed above, and 3) the locations written by an
  2650. instruction which corresponds to $W$. The \code{callq} instruction
  2651. should include all of the caller-saved registers in its write-set $W$
  2652. because the calling convention says that those registers may be
  2653. written to during the function call. Likewise, the \code{callq}
  2654. instruction should include the appropriate number of argument passing
  2655. registers in its read-set $R$, depending on the arity of the function
  2656. being called. (This is why the abstract syntax for \code{callq}
  2657. includes the arity.)
  2658. \end{exercise}
  2659. \section{Building the Interference Graph}
  2660. \label{sec:build-interference}
  2661. \begin{wrapfigure}[27]{r}[1.0in]{0.6\textwidth}
  2662. \small
  2663. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  2664. A \emph{graph} is a collection of vertices and edges where each
  2665. edge connects two vertices. A graph is \emph{directed} if each
  2666. edge points from a source to a target. Otherwise the graph is
  2667. \emph{undirected}.
  2668. \index{graph}\index{directed graph}\index{undirected graph}
  2669. \begin{description}
  2670. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  2671. directed graph from a list of edges. Each edge is a list
  2672. containing the source and target vertex.
  2673. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  2674. undirected graph from a list of edges. Each edge is represented by
  2675. a list containing two vertices.
  2676. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  2677. inserts a vertex into the graph.
  2678. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  2679. inserts an edge between the two vertices into the graph.
  2680. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  2681. returns a sequence of all the neighbors of the given vertex.
  2682. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  2683. returns a sequence of all the vertices in the graph.
  2684. \end{description}
  2685. \end{tcolorbox}
  2686. \end{wrapfigure}
  2687. Based on the liveness analysis, we know where each variable is needed.
  2688. However, during register allocation, we need to answer questions of
  2689. the specific form: are variables $u$ and $v$ live at the same time?
  2690. (And therefore cannot be assigned to the same register.) To make this
  2691. question easier to answer, we create an explicit data structure, an
  2692. \emph{interference graph}\index{interference graph}. An interference
  2693. graph is an undirected graph that has an edge between two variables if
  2694. they are live at the same time, that is, if they interfere with each
  2695. other.
  2696. The most obvious way to compute the interference graph is to look at
  2697. the set of live location between each statement in the program and add
  2698. an edge to the graph for every pair of variables in the same set.
  2699. This approach is less than ideal for two reasons. First, it can be
  2700. expensive because it takes $O(n^2)$ time to look at every pair in a
  2701. set of $n$ live locations. Second, there is a special case in which
  2702. two locations that are live at the same time do not actually interfere
  2703. with each other: when they both contain the same value because we have
  2704. assigned one to the other.
  2705. A better way to compute the interference graph is to focus on the
  2706. writes~\cite{Appel:2003fk}. We do not want the writes performed by an
  2707. instruction to overwrite something in a live location. So for each
  2708. instruction, we create an edge between the locations being written to
  2709. and all the other live locations. (Except that one should not create
  2710. self edges.) Recall that for a \key{callq} instruction, we consider
  2711. all of the caller-saved registers as being written to, so an edge will
  2712. be added between every live variable and every caller-saved
  2713. register. For \key{movq}, we deal with the above-mentioned special
  2714. case by not adding an edge between a live variable $v$ and destination
  2715. $d$ if $v$ matches the source of the move. So we have the following
  2716. two rules.
  2717. \begin{enumerate}
  2718. \item If instruction $I_k$ is a move such as \key{movq} $s$\key{,}
  2719. $d$, then add the edge $(d,v)$ for every $v \in
  2720. L_{\mathsf{after}}(k)$ unless $v = d$ or $v = s$.
  2721. \item For any other instruction $I_k$, for every $d \in W(k)$
  2722. add an edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  2723. %% \item If instruction $I_k$ is an arithmetic instruction such as
  2724. %% \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2725. %% L_{\mathsf{after}}(k)$ unless $v = d$.
  2726. %% \item If instruction $I_k$ is of the form \key{callq}
  2727. %% $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2728. %% register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2729. \end{enumerate}
  2730. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  2731. the above rules to each instruction. We highlight a few of the
  2732. instructions and then refer the reader to
  2733. Figure~\ref{fig:interference-results} for all the interference
  2734. results. The first instruction is \lstinline{movq $1, v}, so rule 3
  2735. applies, and the live-after set is $\{\ttm{v}\}$. We do not add any
  2736. interference edges because the one live variable \code{v} is also the
  2737. destination of this instruction.
  2738. %
  2739. For the second instruction, \lstinline{movq $42, w}, so rule 3 applies
  2740. again, and the live-after set is $\{\ttm{v},\ttm{w}\}$. So the target
  2741. $\ttm{w}$ of \key{movq} interferes with $\ttm{v}$.
  2742. %
  2743. Next we skip forward to the instruction \lstinline{movq x, y}.
  2744. \begin{figure}[tbp]
  2745. \begin{quote}
  2746. \begin{tabular}{ll}
  2747. \lstinline!movq $1, v!& no interference by rule 3,\\
  2748. \lstinline!movq $42, w!& $w$ interferes with $v$ by rule 3,\\
  2749. \lstinline!movq v, x!& $x$ interferes with $w$ by rule 3,\\
  2750. \lstinline!addq $7, x!& $x$ interferes with $w$ by rule 1,\\
  2751. \lstinline!movq x, y!& $y$ interferes with $w$ but not $x$ by rule 3,\\
  2752. \lstinline!movq x, z!& $z$ interferes with $w$ and $y$ by rule 3,\\
  2753. \lstinline!addq w, z!& $z$ interferes with $y$ by rule 1, \\
  2754. \lstinline!movq y, t!& $t$ interferes with $z$ by rule 3, \\
  2755. \lstinline!negq t!& $t$ interferes with $z$ by rule 1, \\
  2756. \lstinline!movq z, %rax! & no interference (ignore rax), \\
  2757. \lstinline!addq t, %rax! & no interference (ignore rax). \\
  2758. \lstinline!jmp conclusion!& no interference.
  2759. \end{tabular}
  2760. \end{quote}
  2761. \caption{Interference results for the running example.}
  2762. \label{fig:interference-results}
  2763. \end{figure}
  2764. The resulting interference graph is shown in
  2765. Figure~\ref{fig:interfere}.
  2766. \begin{figure}[tbp]
  2767. \large
  2768. \[
  2769. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2770. \node (rax) at (0,0) {$\ttm{rax}$};
  2771. \node (t1) at (0,2) {$\ttm{t}$};
  2772. \node (z) at (3,2) {$\ttm{z}$};
  2773. \node (x) at (6,2) {$\ttm{x}$};
  2774. \node (y) at (3,0) {$\ttm{y}$};
  2775. \node (w) at (6,0) {$\ttm{w}$};
  2776. \node (v) at (9,0) {$\ttm{v}$};
  2777. \draw (t1) to (rax);
  2778. \draw (t1) to (z);
  2779. \draw (z) to (y);
  2780. \draw (z) to (w);
  2781. \draw (x) to (w);
  2782. \draw (y) to (w);
  2783. \draw (v) to (w);
  2784. \end{tikzpicture}
  2785. \]
  2786. \caption{The interference graph of the example program.}
  2787. \label{fig:interfere}
  2788. \end{figure}
  2789. %% Our next concern is to choose a data structure for representing the
  2790. %% interference graph. There are many choices for how to represent a
  2791. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2792. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2793. %% data structure is to study the algorithm that uses the data structure,
  2794. %% determine what operations need to be performed, and then choose the
  2795. %% data structure that provide the most efficient implementations of
  2796. %% those operations. Often times the choice of data structure can have an
  2797. %% effect on the time complexity of the algorithm, as it does here. If
  2798. %% you skim the next section, you will see that the register allocation
  2799. %% algorithm needs to ask the graph for all of its vertices and, given a
  2800. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2801. %% correct choice of graph representation is that of an adjacency
  2802. %% list. There are helper functions in \code{utilities.rkt} for
  2803. %% representing graphs using the adjacency list representation:
  2804. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2805. %% (Appendix~\ref{appendix:utilities}).
  2806. %% %
  2807. %% \margincomment{\footnotesize To do: change to use the
  2808. %% Racket graph library. \\ --Jeremy}
  2809. %% %
  2810. %% In particular, those functions use a hash table to map each vertex to
  2811. %% the set of adjacent vertices, and the sets are represented using
  2812. %% Racket's \key{set}, which is also a hash table.
  2813. \begin{exercise}\normalfont
  2814. Implement the compiler pass named \code{build-interference} according
  2815. to the algorithm suggested above. We recommend using the \code{graph}
  2816. package to create and inspect the interference graph. The output
  2817. graph of this pass should be stored in the $\itm{info}$ field of the
  2818. program, under the key \code{conflicts}.
  2819. \end{exercise}
  2820. \section{Graph Coloring via Sudoku}
  2821. \label{sec:graph-coloring}
  2822. \index{graph coloring}
  2823. \index{Sudoku}
  2824. \index{color}
  2825. We come to the main event, mapping variables to registers (or to stack
  2826. locations in the event that we run out of registers). We need to make
  2827. sure that two variables do not get mapped to the same register if the
  2828. two variables interfere with each other. Thinking about the
  2829. interference graph, this means that adjacent vertices must be mapped
  2830. to different registers. If we think of registers as colors, the
  2831. register allocation problem becomes the widely-studied graph coloring
  2832. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2833. The reader may be more familiar with the graph coloring problem than he
  2834. or she realizes; the popular game of Sudoku is an instance of the
  2835. graph coloring problem. The following describes how to build a graph
  2836. out of an initial Sudoku board.
  2837. \begin{itemize}
  2838. \item There is one vertex in the graph for each Sudoku square.
  2839. \item There is an edge between two vertices if the corresponding squares
  2840. are in the same row, in the same column, or if the squares are in
  2841. the same $3\times 3$ region.
  2842. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2843. \item Based on the initial assignment of numbers to squares in the
  2844. Sudoku board, assign the corresponding colors to the corresponding
  2845. vertices in the graph.
  2846. \end{itemize}
  2847. If you can color the remaining vertices in the graph with the nine
  2848. colors, then you have also solved the corresponding game of Sudoku.
  2849. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2850. the corresponding graph with colored vertices. We map the Sudoku
  2851. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2852. sampling of the vertices (the colored ones) because showing edges for
  2853. all of the vertices would make the graph unreadable.
  2854. \begin{figure}[tbp]
  2855. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2856. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2857. \caption{A Sudoku game board and the corresponding colored graph.}
  2858. \label{fig:sudoku-graph}
  2859. \end{figure}
  2860. Given that Sudoku is an instance of graph coloring, one can use Sudoku
  2861. strategies to come up with an algorithm for allocating registers. For
  2862. example, one of the basic techniques for Sudoku is called Pencil
  2863. Marks. The idea is to use a process of elimination to determine what
  2864. numbers no longer make sense for a square and write down those
  2865. numbers in the square (writing very small). For example, if the number
  2866. $1$ is assigned to a square, then by process of elimination, you can
  2867. write the pencil mark $1$ in all the squares in the same row, column,
  2868. and region. Many Sudoku computer games provide automatic support for
  2869. Pencil Marks.
  2870. %
  2871. The Pencil Marks technique corresponds to the notion of
  2872. \emph{saturation}\index{saturation} due to \cite{Brelaz:1979eu}.
  2873. The saturation of a
  2874. vertex, in Sudoku terms, is the set of numbers that are no longer
  2875. available. In graph terminology, we have the following definition:
  2876. \begin{equation*}
  2877. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  2878. \text{ and } \mathrm{color}(v) = c \}
  2879. \end{equation*}
  2880. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  2881. edge with $u$.
  2882. Using the Pencil Marks technique leads to a simple strategy for
  2883. filling in numbers: if there is a square with only one possible number
  2884. left, then choose that number! But what if there are no squares with
  2885. only one possibility left? One brute-force approach is to try them
  2886. all: choose the first and if it ultimately leads to a solution,
  2887. great. If not, backtrack and choose the next possibility. One good
  2888. thing about Pencil Marks is that it reduces the degree of branching in
  2889. the search tree. Nevertheless, backtracking can be horribly time
  2890. consuming. One way to reduce the amount of backtracking is to use the
  2891. most-constrained-first heuristic. That is, when choosing a square,
  2892. always choose one with the fewest possibilities left (the vertex with
  2893. the highest saturation). The idea is that choosing highly constrained
  2894. squares earlier rather than later is better because later on there may
  2895. not be any possibilities left for those squares.
  2896. However, register allocation is easier than Sudoku because the
  2897. register allocator can map variables to stack locations when the
  2898. registers run out. Thus, it makes sense to drop backtracking in favor
  2899. of greedy search, that is, make the best choice at the time and keep
  2900. going. We still wish to minimize the number of colors needed, so
  2901. keeping the most-constrained-first heuristic is a good idea.
  2902. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  2903. algorithm for register allocation based on saturation and the
  2904. most-constrained-first heuristic. It is roughly equivalent to the
  2905. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2906. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just as in
  2907. Sudoku, the algorithm represents colors with integers. The integers
  2908. $0$ through $k-1$ correspond to the $k$ registers that we use for
  2909. register allocation. The integers $k$ and larger correspond to stack
  2910. locations. The registers that are not used for register allocation,
  2911. such as \code{rax}, are assigned to negative integers. In particular,
  2912. we assign $-1$ to \code{rax}.
  2913. \begin{figure}[btp]
  2914. \centering
  2915. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2916. Algorithm: DSATUR
  2917. Input: a graph |$G$|
  2918. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  2919. |$W \gets \mathrm{vertices}(G)$|
  2920. while |$W \neq \emptyset$| do
  2921. pick a vertex |$u$| from |$W$| with the highest saturation,
  2922. breaking ties randomly
  2923. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  2924. |$\mathrm{color}[u] \gets c$|
  2925. |$W \gets W - \{u\}$|
  2926. \end{lstlisting}
  2927. \caption{The saturation-based greedy graph coloring algorithm.}
  2928. \label{fig:satur-algo}
  2929. \end{figure}
  2930. With this algorithm in hand, let us return to the running example and
  2931. consider how to color the interference graph in
  2932. Figure~\ref{fig:interfere}.
  2933. %
  2934. We color the vertices for registers with their own color. For example,
  2935. \code{rax} is assigned the color $-1$. We then update the saturation
  2936. for their neighboring vertices. In this case, the saturation for
  2937. \code{t} includes $-1$. The remaining vertices are not yet colored,
  2938. so they annotated with a dash, and their saturation sets are empty.
  2939. \[
  2940. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2941. \node (rax) at (0,0) {$\ttm{rax}:-1,\{\}$};
  2942. \node (t1) at (0,2) {$\ttm{t}:-,\{-1\}$};
  2943. \node (z) at (3,2) {$\ttm{z}:-,\{\}$};
  2944. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  2945. \node (y) at (3,0) {$\ttm{y}:-,\{\}$};
  2946. \node (w) at (6,0) {$\ttm{w}:-,\{\}$};
  2947. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  2948. \draw (t1) to (rax);
  2949. \draw (t1) to (z);
  2950. \draw (z) to (y);
  2951. \draw (z) to (w);
  2952. \draw (x) to (w);
  2953. \draw (y) to (w);
  2954. \draw (v) to (w);
  2955. \end{tikzpicture}
  2956. \]
  2957. The algorithm says to select a maximally saturated vertex. So we pick
  2958. $\ttm{t}$ and color it with the first available integer, which is
  2959. $0$. We mark $0$ as no longer available for $\ttm{z}$ and $\ttm{rax}$
  2960. because they interfere with $\ttm{t}$.
  2961. \[
  2962. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2963. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  2964. \node (t1) at (0,2) {$\ttm{t}:0,\{-1\}$};
  2965. \node (z) at (3,2) {$\ttm{z}:-,\{0\}$};
  2966. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  2967. \node (y) at (3,0) {$\ttm{y}:-,\{\}$};
  2968. \node (w) at (6,0) {$\ttm{w}:-,\{\}$};
  2969. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  2970. \draw (t1) to (rax);
  2971. \draw (t1) to (z);
  2972. \draw (z) to (y);
  2973. \draw (z) to (w);
  2974. \draw (x) to (w);
  2975. \draw (y) to (w);
  2976. \draw (v) to (w);
  2977. \end{tikzpicture}
  2978. \]
  2979. We repeat the process, selecting another maximally saturated
  2980. vertex, which is \code{z}, and color it with the first available
  2981. number, which is $1$. We add $1$ to the saturations for the
  2982. neighboring vertices \code{t}, \code{y}, and \code{w}.
  2983. \[
  2984. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2985. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  2986. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1\}$};
  2987. \node (z) at (3,2) {$\ttm{z}:1,\{0\}$};
  2988. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  2989. \node (y) at (3,0) {$\ttm{y}:-,\{1\}$};
  2990. \node (w) at (6,0) {$\ttm{w}:-,\{1\}$};
  2991. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  2992. \draw (t1) to (rax);
  2993. \draw (t1) to (z);
  2994. \draw (z) to (y);
  2995. \draw (z) to (w);
  2996. \draw (x) to (w);
  2997. \draw (y) to (w);
  2998. \draw (v) to (w);
  2999. \end{tikzpicture}
  3000. \]
  3001. The most saturated vertices are now \code{w} and \code{y}. We color
  3002. \code{w} with the first available color, which is $0$.
  3003. \[
  3004. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3005. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3006. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1\}$};
  3007. \node (z) at (3,2) {$\ttm{z}:1,\{0\}$};
  3008. \node (x) at (6,2) {$\ttm{x}:-,\{0\}$};
  3009. \node (y) at (3,0) {$\ttm{y}:-,\{0,1\}$};
  3010. \node (w) at (6,0) {$\ttm{w}:0,\{1\}$};
  3011. \node (v) at (9,0) {$\ttm{v}:-,\{0\}$};
  3012. \draw (t1) to (rax);
  3013. \draw (t1) to (z);
  3014. \draw (z) to (y);
  3015. \draw (z) to (w);
  3016. \draw (x) to (w);
  3017. \draw (y) to (w);
  3018. \draw (v) to (w);
  3019. \end{tikzpicture}
  3020. \]
  3021. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  3022. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  3023. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  3024. and \code{z}, whose colors are $0$ and $1$ respectively.
  3025. \[
  3026. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3027. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3028. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1\}$};
  3029. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3030. \node (x) at (6,2) {$\ttm{x}:-,\{0\}$};
  3031. \node (y) at (3,0) {$\ttm{y}:2,\{0,1\}$};
  3032. \node (w) at (6,0) {$\ttm{w}:0,\{1,2\}$};
  3033. \node (v) at (9,0) {$\ttm{v}:-,\{0\}$};
  3034. \draw (t1) to (rax);
  3035. \draw (t1) to (z);
  3036. \draw (z) to (y);
  3037. \draw (z) to (w);
  3038. \draw (x) to (w);
  3039. \draw (y) to (w);
  3040. \draw (v) to (w);
  3041. \end{tikzpicture}
  3042. \]
  3043. Now \code{x} and \code{v} are the most saturated, so we color \code{v} it $1$.
  3044. \[
  3045. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3046. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3047. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1\}$};
  3048. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3049. \node (x) at (6,2) {$\ttm{x}:-,\{0\}$};
  3050. \node (y) at (3,0) {$\ttm{y}:2,\{0,1\}$};
  3051. \node (w) at (6,0) {$\ttm{w}:0,\{1,2\}$};
  3052. \node (v) at (9,0) {$\ttm{v}:1,\{0\}$};
  3053. \draw (t1) to (rax);
  3054. \draw (t1) to (z);
  3055. \draw (z) to (y);
  3056. \draw (z) to (w);
  3057. \draw (x) to (w);
  3058. \draw (y) to (w);
  3059. \draw (v) to (w);
  3060. \end{tikzpicture}
  3061. \]
  3062. In the last step of the algorithm, we color \code{x} with $1$.
  3063. \[
  3064. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3065. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3066. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,\}$};
  3067. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3068. \node (x) at (6,2) {$\ttm{x}:1,\{0\}$};
  3069. \node (y) at (3,0) {$\ttm{y}:2,\{0,1\}$};
  3070. \node (w) at (6,0) {$\ttm{w}:0,\{1,2\}$};
  3071. \node (v) at (9,0) {$\ttm{v}:1,\{0\}$};
  3072. \draw (t1) to (rax);
  3073. \draw (t1) to (z);
  3074. \draw (z) to (y);
  3075. \draw (z) to (w);
  3076. \draw (x) to (w);
  3077. \draw (y) to (w);
  3078. \draw (v) to (w);
  3079. \end{tikzpicture}
  3080. \]
  3081. With the coloring complete, we finalize the assignment of variables to
  3082. registers and stack locations. Recall that if we have $k$ registers to
  3083. use for allocation, we map the first $k$ colors to registers and the
  3084. rest to stack locations. Suppose for the moment that we have just one
  3085. register to use for register allocation, \key{rcx}. Then the following
  3086. is the mapping of colors to registers and stack allocations.
  3087. \[
  3088. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  3089. \]
  3090. Putting this mapping together with the above coloring of the
  3091. variables, we arrive at the following assignment of variables to
  3092. registers and stack locations.
  3093. \begin{gather*}
  3094. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  3095. \ttm{w} \mapsto \key{\%rcx}, \,
  3096. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  3097. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  3098. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  3099. \ttm{t} \mapsto \key{\%rcx} \}
  3100. \end{gather*}
  3101. Applying this assignment to our running example, on the left, yields
  3102. the program on the right.
  3103. % why frame size of 32? -JGS
  3104. \begin{center}
  3105. \begin{minipage}{0.3\textwidth}
  3106. \begin{lstlisting}
  3107. movq $1, v
  3108. movq $42, w
  3109. movq v, x
  3110. addq $7, x
  3111. movq x, y
  3112. movq x, z
  3113. addq w, z
  3114. movq y, t
  3115. negq t
  3116. movq z, %rax
  3117. addq t, %rax
  3118. jmp conclusion
  3119. \end{lstlisting}
  3120. \end{minipage}
  3121. $\Rightarrow\qquad$
  3122. \begin{minipage}{0.45\textwidth}
  3123. \begin{lstlisting}
  3124. movq $1, %rcx
  3125. movq $42, %rcx
  3126. movq %rcx, -8(%rbp)
  3127. addq $7, -8(%rbp)
  3128. movq -8(%rbp), -16(%rbp)
  3129. movq -8(%rbp), -8(%rbp)
  3130. addq %rcx, -8(%rbp)
  3131. movq -16(%rbp), %rcx
  3132. negq %rcx
  3133. movq -8(%rbp), %rax
  3134. addq %rcx, %rax
  3135. jmp conclusion
  3136. \end{lstlisting}
  3137. \end{minipage}
  3138. \end{center}
  3139. The resulting program is almost an x86 program. The remaining step is
  3140. the patch instructions pass. In this example, the trivial move of
  3141. \code{-8(\%rbp)} to itself is deleted and the addition of
  3142. \code{-8(\%rbp)} to \key{-16(\%rbp)} is fixed by going through
  3143. \code{rax} as follows.
  3144. \begin{lstlisting}
  3145. movq -8(%rbp), %rax
  3146. addq %rax, -16(%rbp)
  3147. \end{lstlisting}
  3148. An overview of all of the passes involved in register allocation is
  3149. shown in Figure~\ref{fig:reg-alloc-passes}.
  3150. \begin{figure}[tbp]
  3151. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3152. \node (R1) at (0,2) {\large $R_1$};
  3153. \node (R1-2) at (3,2) {\large $R_1$};
  3154. \node (R1-3) at (6,2) {\large $R_1$};
  3155. \node (C0-1) at (3,0) {\large $C_0$};
  3156. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  3157. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  3158. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  3159. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}$};
  3160. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  3161. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  3162. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  3163. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  3164. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  3165. \path[->,bend right=15] (C0-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  3166. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  3167. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  3168. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  3169. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  3170. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  3171. \end{tikzpicture}
  3172. \caption{Diagram of the passes for $R_1$ with register allocation.}
  3173. \label{fig:reg-alloc-passes}
  3174. \end{figure}
  3175. \begin{wrapfigure}[24]{r}[1.0in]{0.6\textwidth}
  3176. \small
  3177. \begin{tcolorbox}[title=Priority Queue]
  3178. A \emph{priority queue} is a collection of items in which the
  3179. removal of items is governed by priority. In a ``min'' queue,
  3180. lower priority items are removed first. An implementation is in
  3181. \code{priority\_queue.rkt} of the support code. \index{priority
  3182. queue} \index{minimum priority queue}
  3183. \begin{description}
  3184. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  3185. priority queue that uses the $\itm{cmp}$ predicate to determine
  3186. whether its first argument has lower or equal priority to its
  3187. second argument.
  3188. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  3189. items in the queue.
  3190. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  3191. the item into the queue and returns a handle for the item in the
  3192. queue.
  3193. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  3194. the lowest priority.
  3195. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  3196. notifices the queue the the priority has decreased for the item
  3197. associated with the given handle.
  3198. \end{description}
  3199. \end{tcolorbox}
  3200. \end{wrapfigure}
  3201. We recommend creating a helper function named \code{color-graph} that
  3202. takes an interference graph and a list of all the variables in the
  3203. program. This function should return a mapping of variables to their
  3204. colors (represented as natural numbers). By creating this helper
  3205. function, you will be able to reuse it in Chapter~\ref{ch:functions}
  3206. when you add support for functions. To prioritize the process of
  3207. highly saturated nodes inside your \code{color-graph} function, we
  3208. recommend using the priority queue data structure (see the side bar on
  3209. the right). Note that you will also need to maintain a mapping from
  3210. variables to their ``handles'' in the priority queue so that you can
  3211. notify the priority queue when their saturation changes.
  3212. Once you have obtained the coloring from \code{color-graph}, you can
  3213. assign the variables to registers or stack locations and then reuse
  3214. code from the \code{assign-homes} pass from
  3215. Section~\ref{sec:assign-r1} to replace the variables with their
  3216. assigned location.
  3217. \begin{exercise}\normalfont
  3218. Implement the compiler pass \code{allocate-registers}, which should come
  3219. after the \code{build-interference} pass. The three new passes,
  3220. \code{uncover-live}, \code{build-interference}, and
  3221. \code{allocate-registers} replace the \code{assign-homes} pass of
  3222. Section~\ref{sec:assign-r1}.
  3223. Test your updated compiler by creating new example programs that
  3224. exercise all of the register allocation algorithm, such as forcing
  3225. variables to be spilled to the stack.
  3226. \end{exercise}
  3227. \section{Print x86 and Conventions for Registers}
  3228. \label{sec:print-x86-reg-alloc}
  3229. \index{calling conventions}
  3230. \index{prelude}\index{conclusion}
  3231. Recall that the \code{print-x86} pass generates the prelude and
  3232. conclusion instructions for the \code{main} function.
  3233. %
  3234. The prelude saved the values in \code{rbp} and \code{rsp} and the
  3235. conclusion returned those values to \code{rbp} and \code{rsp}. The
  3236. reason for this is that our \code{main} function must adhere to the
  3237. x86 calling conventions that we described in
  3238. Section~\ref{sec:calling-conventions}. Furthermore, if your register
  3239. allocator assigned variables to other callee-saved registers
  3240. (e.g. \code{rbx}, \code{r12}, etc.), then those variables must also be
  3241. saved to the stack in the prelude and restored in the conclusion. The
  3242. simplest approach is to save and restore all of the callee-saved
  3243. registers. The more efficient approach is to keep track of which
  3244. callee-saved registers were used and only save and restore
  3245. them. Either way, make sure to take this use of stack space into
  3246. account when you are calculating the size of the frame and adjusting
  3247. the \code{rsp} in the prelude. Also, don't forget that the size of the
  3248. frame needs to be a multiple of 16 bytes!
  3249. \section{Challenge: Move Biasing}
  3250. \label{sec:move-biasing}
  3251. \index{move biasing}
  3252. This section describes an optional enhancement to register allocation
  3253. for those students who are looking for an extra challenge or who have
  3254. a deeper interest in register allocation.
  3255. We return to the running example, but we remove the supposition that
  3256. we only have one register to use. So we have the following mapping of
  3257. color numbers to registers.
  3258. \[
  3259. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx} \}
  3260. \]
  3261. Using the same assignment of variables to color numbers that was
  3262. produced by the register allocator described in the last section, we
  3263. get the following program.
  3264. \begin{minipage}{0.3\textwidth}
  3265. \begin{lstlisting}
  3266. movq $1, v
  3267. movq $42, w
  3268. movq v, x
  3269. addq $7, x
  3270. movq x, y
  3271. movq x, z
  3272. addq w, z
  3273. movq y, t
  3274. negq t
  3275. movq z, %rax
  3276. addq t, %rax
  3277. jmp conclusion
  3278. \end{lstlisting}
  3279. \end{minipage}
  3280. $\Rightarrow\qquad$
  3281. \begin{minipage}{0.45\textwidth}
  3282. \begin{lstlisting}
  3283. movq $1, %rcx
  3284. movq $42, $rbx
  3285. movq %rcx, %rcx
  3286. addq $7, %rcx
  3287. movq %rcx, %rdx
  3288. movq %rcx, %rcx
  3289. addq %rbx, %rcx
  3290. movq %rdx, %rbx
  3291. negq %rbx
  3292. movq %rcx, %rax
  3293. addq %rbx, %rax
  3294. jmp conclusion
  3295. \end{lstlisting}
  3296. \end{minipage}
  3297. In the above output code there are two \key{movq} instructions that
  3298. can be removed because their source and target are the same. However,
  3299. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  3300. register, we could instead remove three \key{movq} instructions. We
  3301. can accomplish this by taking into account which variables appear in
  3302. \key{movq} instructions with which other variables.
  3303. We say that two variables $p$ and $q$ are \emph{move
  3304. related}\index{move related} if they participate together in a
  3305. \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  3306. \key{movq} $q$\key{,} $p$. When the register allocator chooses a color
  3307. for a variable, it should prefer a color that has already been used
  3308. for a move-related variable (assuming that they do not interfere). Of
  3309. course, this preference should not override the preference for
  3310. registers over stack locations. This preference should be used as a
  3311. tie breaker when choosing between registers or when choosing between
  3312. stack locations.
  3313. We recommend representing the move relationships in a graph, similar
  3314. to how we represented interference. The following is the \emph{move
  3315. graph} for our running example.
  3316. \[
  3317. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3318. \node (rax) at (0,0) {$\ttm{rax}$};
  3319. \node (t) at (0,2) {$\ttm{t}$};
  3320. \node (z) at (3,2) {$\ttm{z}$};
  3321. \node (x) at (6,2) {$\ttm{x}$};
  3322. \node (y) at (3,0) {$\ttm{y}$};
  3323. \node (w) at (6,0) {$\ttm{w}$};
  3324. \node (v) at (9,0) {$\ttm{v}$};
  3325. \draw (v) to (x);
  3326. \draw (x) to (y);
  3327. \draw (x) to (z);
  3328. \draw (y) to (t);
  3329. \end{tikzpicture}
  3330. \]
  3331. Now we replay the graph coloring, pausing to see the coloring of
  3332. \code{y}. Recall the following configuration. The most saturated vertices
  3333. were \code{w} and \code{y}.
  3334. \[
  3335. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3336. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3337. \node (t1) at (0,2) {$\ttm{t}:0,\{1\}$};
  3338. \node (z) at (3,2) {$\ttm{z}:1,\{0\}$};
  3339. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  3340. \node (y) at (3,0) {$\ttm{y}:-,\{1\}$};
  3341. \node (w) at (6,0) {$\ttm{w}:-,\{1\}$};
  3342. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  3343. \draw (t1) to (rax);
  3344. \draw (t1) to (z);
  3345. \draw (z) to (y);
  3346. \draw (z) to (w);
  3347. \draw (x) to (w);
  3348. \draw (y) to (w);
  3349. \draw (v) to (w);
  3350. \end{tikzpicture}
  3351. \]
  3352. %
  3353. Last time we chose to color \code{w} with $0$. But this time we see
  3354. that \code{w} is not move related to any vertex, but \code{y} is move
  3355. related to \code{t}. So we choose to color \code{y} the same color,
  3356. $0$.
  3357. \[
  3358. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3359. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3360. \node (t1) at (0,2) {$\ttm{t}:0,\{1\}$};
  3361. \node (z) at (3,2) {$\ttm{z}:1,\{0\}$};
  3362. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  3363. \node (y) at (3,0) {$\ttm{y}:0,\{1\}$};
  3364. \node (w) at (6,0) {$\ttm{w}:-,\{0,1\}$};
  3365. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  3366. \draw (t1) to (rax);
  3367. \draw (t1) to (z);
  3368. \draw (z) to (y);
  3369. \draw (z) to (w);
  3370. \draw (x) to (w);
  3371. \draw (y) to (w);
  3372. \draw (v) to (w);
  3373. \end{tikzpicture}
  3374. \]
  3375. Now \code{w} is the most saturated, so we color it $2$.
  3376. \[
  3377. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3378. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3379. \node (t1) at (0,2) {$\ttm{t}:0,\{1\}$};
  3380. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3381. \node (x) at (6,2) {$\ttm{x}:-,\{2\}$};
  3382. \node (y) at (3,0) {$\ttm{y}:0,\{1,2\}$};
  3383. \node (w) at (6,0) {$\ttm{w}:2,\{0,1\}$};
  3384. \node (v) at (9,0) {$\ttm{v}:-,\{2\}$};
  3385. \draw (t1) to (rax);
  3386. \draw (t1) to (z);
  3387. \draw (z) to (y);
  3388. \draw (z) to (w);
  3389. \draw (x) to (w);
  3390. \draw (y) to (w);
  3391. \draw (v) to (w);
  3392. \end{tikzpicture}
  3393. \]
  3394. At this point, vertices \code{x} and \code{v} are most saturated, but
  3395. \code{x} is move related to \code{y} and \code{z}, so we color
  3396. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  3397. \[
  3398. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3399. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3400. \node (t) at (0,2) {$\ttm{t}:0,\{1\}$};
  3401. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3402. \node (x) at (6,2) {$\ttm{x}:0,\{2\}$};
  3403. \node (y) at (3,0) {$\ttm{y}:0,\{1,2\}$};
  3404. \node (w) at (6,0) {$\ttm{w}:2,\{0,1\}$};
  3405. \node (v) at (9,0) {$\ttm{v}:0,\{2\}$};
  3406. \draw (t1) to (rax);
  3407. \draw (t) to (z);
  3408. \draw (z) to (y);
  3409. \draw (z) to (w);
  3410. \draw (x) to (w);
  3411. \draw (y) to (w);
  3412. \draw (v) to (w);
  3413. \end{tikzpicture}
  3414. \]
  3415. So we have the following assignment of variables to registers.
  3416. \begin{gather*}
  3417. \{ \ttm{v} \mapsto \key{\%rbx}, \,
  3418. \ttm{w} \mapsto \key{\%rdx}, \,
  3419. \ttm{x} \mapsto \key{\%rbx}, \,
  3420. \ttm{y} \mapsto \key{\%rbx}, \,
  3421. \ttm{z} \mapsto \key{\%rcx}, \,
  3422. \ttm{t} \mapsto \key{\%rbx} \}
  3423. \end{gather*}
  3424. We apply this register assignment to the running example, on the left,
  3425. to obtain the code on right.
  3426. \begin{minipage}{0.3\textwidth}
  3427. \begin{lstlisting}
  3428. movq $1, v
  3429. movq $42, w
  3430. movq v, x
  3431. addq $7, x
  3432. movq x, y
  3433. movq x, z
  3434. addq w, z
  3435. movq y, t
  3436. negq t
  3437. movq z, %rax
  3438. addq t, %rax
  3439. jmp conclusion
  3440. \end{lstlisting}
  3441. \end{minipage}
  3442. $\Rightarrow\qquad$
  3443. \begin{minipage}{0.45\textwidth}
  3444. \begin{lstlisting}
  3445. movq $1, %rbx
  3446. movq $42, %rdx
  3447. movq %rbx, %rbx
  3448. addq $7, %rbx
  3449. movq %rbx, %rbx
  3450. movq %rbx, %rcx
  3451. addq %rdx, %rcx
  3452. movq %rbx, %rbx
  3453. negq %rbx
  3454. movq %rcx, %rax
  3455. addq %rbx, %rax
  3456. jmp conclusion
  3457. \end{lstlisting}
  3458. \end{minipage}
  3459. The \code{patch-instructions} then removes the three trivial moves
  3460. from \key{rbx} to \key{rbx} to obtain the following result.
  3461. \begin{minipage}{0.45\textwidth}
  3462. \begin{lstlisting}
  3463. movq $1, %rbx
  3464. movq $42, %rdx
  3465. addq $7, %rbx
  3466. movq %rbx, %rcx
  3467. addq %rdx, %rcx
  3468. negq %rbx
  3469. movq %rcx, %rax
  3470. addq %rbx, %rax
  3471. jmp conclusion
  3472. \end{lstlisting}
  3473. \end{minipage}
  3474. \begin{exercise}\normalfont
  3475. Change your implementation of \code{allocate-registers} to take move
  3476. biasing into account. Make sure that your compiler still passes all of
  3477. the previous tests. Create two new tests that include at least one
  3478. opportunity for move biasing and visually inspect the output x86
  3479. programs to make sure that your move biasing is working properly.
  3480. \end{exercise}
  3481. \margincomment{\footnotesize To do: another neat challenge would be to do
  3482. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3483. \section{Output of the Running Example}
  3484. \label{sec:reg-alloc-output}
  3485. \index{prelude}\index{conclusion}
  3486. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  3487. the running example (Figure~\ref{fig:reg-eg}) with register allocation
  3488. and move biasing. To demonstrate both the use of registers and the
  3489. stack, we have limited the register allocator to use just two
  3490. registers: \code{rbx} and \code{rcx}. In the prelude of the
  3491. \code{main} function, we push \code{rbx} onto the stack because it is
  3492. a callee-saved register and it was assigned to variable by the
  3493. register allocator. We substract \code{8} from the \code{rsp} at the
  3494. end of the prelude to reserve space for the one spilled variable.
  3495. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  3496. Moving on the the \code{start} block, we see how the registers were
  3497. allocated. Variables \code{v}, \code{x}, and \code{y} were assigned to
  3498. \code{rbx} and variable \code{z} was assigned to \code{rcx}. Variable
  3499. \code{w} was spilled to the stack location \code{-16(\%rbp)}. Recall
  3500. that the prelude saved the callee-save register \code{rbx} onto the
  3501. stack. The spilled variables must be placed lower on the stack than
  3502. the saved callee-save registers, so in this case \code{w} is placed at
  3503. \code{-16(\%rbp)}.
  3504. In the \code{conclusion}, we undo the work that was done in the
  3505. prelude. We move the stack pointer up by \code{8} bytes (the room for
  3506. spilled variables), then we pop the old values of \code{rbx} and
  3507. \code{rbp} (callee-saved registers), and finish with \code{retq} to
  3508. return control to the operating system.
  3509. \begin{figure}[tbp]
  3510. % s0_28.rkt
  3511. % (use-minimal-set-of-registers! #t)
  3512. % and only rbx rcx
  3513. % tmp 0 rbx
  3514. % z 1 rcx
  3515. % y 0 rbx
  3516. % w 2 16(%rbp)
  3517. % v 0 rbx
  3518. % x 0 rbx
  3519. \begin{lstlisting}
  3520. start:
  3521. movq $1, %rbx
  3522. movq $42, -16(%rbp)
  3523. addq $7, %rbx
  3524. movq %rbx, %rcx
  3525. addq -16(%rbp), %rcx
  3526. negq %rbx
  3527. movq %rcx, %rax
  3528. addq %rbx, %rax
  3529. jmp conclusion
  3530. .globl main
  3531. main:
  3532. pushq %rbp
  3533. movq %rsp, %rbp
  3534. pushq %rbx
  3535. subq $8, %rsp
  3536. jmp start
  3537. conclusion:
  3538. addq $8, %rsp
  3539. popq %rbx
  3540. popq %rbp
  3541. retq
  3542. \end{lstlisting}
  3543. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  3544. \label{fig:running-example-x86}
  3545. \end{figure}
  3546. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3547. \chapter{Booleans and Control Flow}
  3548. \label{ch:bool-types}
  3549. \index{Boolean}
  3550. \index{control flow}
  3551. \index{conditional expression}
  3552. The $R_0$ and $R_1$ languages only have a single kind of value, the
  3553. integers. In this chapter we add a second kind of value, the Booleans,
  3554. to create the $R_2$ language. The Boolean values \emph{true} and
  3555. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  3556. Racket. The $R_2$ language includes several operations that involve
  3557. Booleans (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the
  3558. conditional \key{if} expression. With the addition of \key{if}
  3559. expressions, programs can have non-trivial control flow which which
  3560. significantly impacts the \code{explicate-control} and the liveness
  3561. analysis for register allocation. Also, because we now have two kinds
  3562. of values, we need to handle programs that apply an operation to the
  3563. wrong kind of value, such as \code{(not 1)}.
  3564. There are two language design options for such situations. One option
  3565. is to signal an error and the other is to provide a wider
  3566. interpretation of the operation. The Racket language uses a mixture of
  3567. these two options, depending on the operation and the kind of
  3568. value. For example, the result of \code{(not 1)} in Racket is
  3569. \code{\#f} because Racket treats non-zero integers as if they were
  3570. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  3571. error in Racket stating that \code{car} expects a pair.
  3572. The Typed Racket language makes similar design choices as Racket,
  3573. except much of the error detection happens at compile time instead of
  3574. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  3575. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  3576. reports a compile-time error because Typed Racket expects the type of
  3577. the argument to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  3578. For the $R_2$ language we choose to be more like Typed Racket in that
  3579. we perform type checking during compilation. In
  3580. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  3581. is, how to compile a dynamically typed language like Racket. The
  3582. $R_2$ language is a subset of Typed Racket but by no means includes
  3583. all of Typed Racket. For many operations we take a narrower
  3584. interpretation than Typed Racket, for example, rejecting \code{(not 1)}.
  3585. This chapter is organized as follows. We begin by defining the syntax
  3586. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  3587. then introduce the idea of type checking and build a type checker for
  3588. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  3589. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  3590. Section~\ref{sec:c1}. The remaining sections of this chapter discuss
  3591. how our compiler passes need to change to accommodate Booleans and
  3592. conditional control flow.
  3593. \section{The $R_2$ Language}
  3594. \label{sec:r2-lang}
  3595. The concrete syntax of the $R_2$ language is defined in
  3596. Figure~\ref{fig:r2-concrete-syntax} and the abstract syntax is defined
  3597. in Figure~\ref{fig:r2-syntax}. The $R_2$ language includes all of
  3598. $R_1$ (shown in gray), the Boolean literals \code{\#t} and \code{\#f},
  3599. and the conditional \code{if} expression. Also, we expand the
  3600. operators to include
  3601. \begin{enumerate}
  3602. \item subtraction on integers,
  3603. \item the logical operators \key{and}, \key{or} and \key{not},
  3604. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  3605. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  3606. comparing integers.
  3607. \end{enumerate}
  3608. We reorganize the abstract syntax for the primitive operations in
  3609. Figure~\ref{fig:r2-syntax}, using only one grammar rule for all of
  3610. them. This means that the grammar no longer checks whether the arity
  3611. of an operators matches the number of arguments. That responsibility
  3612. is moved to the type checker for $R_2$, which we introduce in
  3613. Section~\ref{sec:type-check-r2}.
  3614. \begin{figure}[tp]
  3615. \centering
  3616. \fbox{
  3617. \begin{minipage}{0.96\textwidth}
  3618. \[
  3619. \begin{array}{lcl}
  3620. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3621. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3622. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} } \mid \CSUB{\Exp}{\Exp} \\
  3623. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} } \\
  3624. &\mid& \itm{bool}
  3625. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  3626. \mid (\key{not}\;\Exp) \\
  3627. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} \\
  3628. R_2 &::=& \Exp
  3629. \end{array}
  3630. \]
  3631. \end{minipage}
  3632. }
  3633. \caption{The concrete syntax of $R_2$, extending $R_1$
  3634. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  3635. \label{fig:r2-concrete-syntax}
  3636. \end{figure}
  3637. \begin{figure}[tp]
  3638. \centering
  3639. \fbox{
  3640. \begin{minipage}{0.96\textwidth}
  3641. \[
  3642. \begin{array}{lcl}
  3643. \itm{bool} &::=& \code{\#t} \mid \code{\#f} \\
  3644. \itm{cmp} &::= & \code{eq?} \mid \code{<} \mid \code{<=} \mid \code{>} \mid \code{>=} \\
  3645. \itm{op} &::= & \itm{cmp} \mid \code{read} \mid \code{+} \mid \code{-}
  3646. \mid \code{and} \mid \code{or} \mid \code{not} \\
  3647. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  3648. &\mid& \PRIM{\itm{op}}{\Exp\ldots}\\
  3649. &\mid& \BOOL{\itm{bool}} \mid \IF{\Exp}{\Exp}{\Exp} \\
  3650. R_2 &::=& \PROGRAM{\code{'()}}{\Exp}
  3651. \end{array}
  3652. \]
  3653. \end{minipage}
  3654. }
  3655. \caption{The abstract syntax of $R_2$.}
  3656. \label{fig:r2-syntax}
  3657. \end{figure}
  3658. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  3659. the parts that are the same as the interpreter for $R_1$
  3660. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  3661. evaluate to the corresponding Boolean values. The conditional
  3662. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  3663. the Boolean expression \itm{cnd} and then either evaluates \itm{thn}
  3664. or \itm{els} depending on whether \itm{cnd} produced \code{\#t} or
  3665. \code{\#f}. The logical operations \code{not} and \code{and} behave as
  3666. you might expect, but note that the \code{and} operation is
  3667. short-circuiting. That is, given the expression
  3668. $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not evaluated if
  3669. $e_1$ evaluates to \code{\#f}.
  3670. With the increase in the number of primitive operations, the
  3671. interpreter code for them could become repetitive without some
  3672. care. In Figure~\ref{fig:interp-R2} we factor out the different parts
  3673. of the code for primitive operations into the \code{interp-op}
  3674. function and the similar parts of the code into the match clause for
  3675. \code{Prim} shown in Figure~\ref{fig:interp-R2}. We do not use
  3676. \code{interp-op} for the \code{and} operation because of the
  3677. short-circuiting behavior in the order of evaluation of its arguments.
  3678. \begin{figure}[tbp]
  3679. \begin{lstlisting}
  3680. (define (interp-op op)
  3681. (match op
  3682. ...
  3683. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  3684. ['eq? (lambda (v1 v2)
  3685. (cond [(or (and (fixnum? v1) (fixnum? v2))
  3686. (and (boolean? v1) (boolean? v2)))
  3687. (eq? v1 v2)]))]
  3688. ['< (lambda (v1 v2)
  3689. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  3690. ['<= (lambda (v1 v2)
  3691. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  3692. ['> (lambda (v1 v2)
  3693. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  3694. ['>= (lambda (v1 v2)
  3695. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  3696. [else (error 'interp-op "unknown operator")]))
  3697. (define (interp-exp env)
  3698. (lambda (e)
  3699. (define recur (interp-exp env))
  3700. (match e
  3701. ...
  3702. [(Bool b) b]
  3703. [(If cnd thn els)
  3704. (define b (recur cnd))
  3705. (match b
  3706. [#t (recur thn)]
  3707. [#f (recur els)])]
  3708. [(Prim 'and (list e1 e2))
  3709. (define v1 (recur e1))
  3710. (match v1
  3711. [#t (match (recur e2) [#t #t] [#f #f])]
  3712. [#f #f])]
  3713. [(Prim op args)
  3714. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  3715. )))
  3716. (define (interp-R2 p)
  3717. (match p
  3718. [(Program info e)
  3719. ((interp-exp '()) e)]
  3720. ))
  3721. \end{lstlisting}
  3722. \caption{Interpreter for the $R_2$ language.}
  3723. \label{fig:interp-R2}
  3724. \end{figure}
  3725. \section{Type Checking $R_2$ Programs}
  3726. \label{sec:type-check-r2}
  3727. \index{type checking}
  3728. \index{semantic analysis}
  3729. It is helpful to think about type checking in two complementary
  3730. ways. A type checker predicts the type of value that will be produced
  3731. by each expression in the program. For $R_2$, we have just two types,
  3732. \key{Integer} and \key{Boolean}. So a type checker should predict that
  3733. \begin{lstlisting}
  3734. (+ 10 (- (+ 12 20)))
  3735. \end{lstlisting}
  3736. produces an \key{Integer} while
  3737. \begin{lstlisting}
  3738. (and (not #f) #t)
  3739. \end{lstlisting}
  3740. produces a \key{Boolean}.
  3741. Another way to think about type checking is that it enforces a set of
  3742. rules about which operators can be applied to which kinds of
  3743. values. For example, our type checker for $R_2$ will signal an error
  3744. for the below expression because, as we have seen above, the
  3745. expression \code{(+ 10 ...)} has type \key{Integer} but the type
  3746. checker enforces the rule that the argument of \code{not} must be a
  3747. \key{Boolean}.
  3748. \begin{lstlisting}
  3749. (not (+ 10 (- (+ 12 20))))
  3750. \end{lstlisting}
  3751. The type checker for $R_2$ is a structurally recursive function over
  3752. the AST. Figure~\ref{fig:type-check-R2} defines the
  3753. \code{type-check-exp} function. The code for the type checker is
  3754. included in the student support code.
  3755. %
  3756. Given an input expression \code{e}, the type checker either returns a
  3757. type (\key{Integer} or \key{Boolean}) or it signals an error. The
  3758. type of an integer literal is \code{Integer} and the type of a Boolean
  3759. literal is \code{Boolean}. To handle variables, the type checker uses
  3760. the environment \code{env} to map variables to types. Consider the
  3761. clause for \key{let}. We type check the initializing expression to
  3762. obtain its type \key{T} and then associate type \code{T} with the
  3763. variable \code{x} in the environment used to type check the body of
  3764. the \key{let}. Thus, when the type checker encounters a use of
  3765. variable \code{x}, it can find its type in the environment.
  3766. \begin{figure}[tbp]
  3767. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3768. (define (type-check-exp env)
  3769. (lambda (e)
  3770. (match e
  3771. [(Var x)
  3772. (let ([t (dict-ref env x)])
  3773. (values (Var x) t))]
  3774. [(Int n) (values (Int n) 'Integer)]
  3775. [(Bool b) (values (Bool b) 'Boolean)]
  3776. [(Let x e body)
  3777. (define-values (e^ Te) ((type-check-exp env) e))
  3778. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  3779. (values (Let x e^ b) Tb)]
  3780. [(If cnd thn els)
  3781. (define-values (c Tc) ((type-check-exp env) cnd))
  3782. (define-values (t Tt) ((type-check-exp env) thn))
  3783. (define-values (e Te) ((type-check-exp env) els))
  3784. (unless (type-equal? Tc 'Boolean)
  3785. (error 'type-check-exp "condition should be Boolean, not ~a" Tc))
  3786. (unless (type-equal? Tt Te)
  3787. (error 'type-check-exp "types of branches not equal, ~a != ~a" Tt Te))
  3788. (values (If c t e) Te)]
  3789. [(Prim 'eq? (list e1 e2))
  3790. (define-values (e1^ T1) ((type-check-exp env) e1))
  3791. (define-values (e2^ T2) ((type-check-exp env) e2))
  3792. (unless (type-equal? T1 T2)
  3793. (error 'type-check-exp "argument types of eq?: ~a != ~a" T1 T2))
  3794. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  3795. [(Prim op es)
  3796. (define-values (new-es ts)
  3797. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  3798. (define t-ret (type-check-op op ts))
  3799. (values (Prim op new-es) t-ret)]
  3800. [else
  3801. (error 'type-check-exp "couldn't match" e)])))
  3802. (define (type-check-R2 e)
  3803. (match e
  3804. [(Program info body)
  3805. (define-values (body^ Tb) ((type-check-exp '()) body))
  3806. (unless (type-equal? Tb 'Integer)
  3807. (error 'type-check-R2 "result type must be Integer, not ~a" Tb))
  3808. (Program info body^)]
  3809. [else (error 'type-check-R2 "couldn't match ~a" e)]))
  3810. \end{lstlisting}
  3811. \caption{Type checker for the $R_2$ language.}
  3812. \label{fig:type-check-R2}
  3813. \end{figure}
  3814. Figure~\ref{fig:type-check-aux-R2} defines three auxilliary functions
  3815. that are used in the type checker. The \code{operator-types} function
  3816. defines a dictionary that maps the operator names to their parameter
  3817. and return types. The \code{type-equal?} function determines whether
  3818. two types are equal, which for now simply dispatches to \code{equal?}
  3819. (deep equality). The \code{type-check-op} function looks up the
  3820. operator in the \code{operator-types} dictionary and then checks
  3821. whether the argument types are equal to the parameter types. The
  3822. result is the return type of the operator.
  3823. \begin{figure}[tbp]
  3824. \begin{lstlisting}
  3825. (define (operator-types)
  3826. '((+ . ((Integer Integer) . Integer))
  3827. (- . ((Integer Integer) . Integer))
  3828. (and . ((Boolean Boolean) . Boolean))
  3829. (or . ((Boolean Boolean) . Boolean))
  3830. (< . ((Integer Integer) . Boolean))
  3831. (<= . ((Integer Integer) . Boolean))
  3832. (> . ((Integer Integer) . Boolean))
  3833. (>= . ((Integer Integer) . Boolean))
  3834. (- . ((Integer) . Integer))
  3835. (not . ((Boolean) . Boolean))
  3836. (read . (() . Integer))
  3837. ))
  3838. (define (type-equal? t1 t2)
  3839. (equal? t1 t2))
  3840. (define (type-check-op op arg-types)
  3841. (match (dict-ref (operator-types) op)
  3842. [`(,param-types . ,return-type)
  3843. (for ([at arg-types] [pt param-types])
  3844. (unless (type-equal? at pt)
  3845. (error 'type-check-op
  3846. "argument and parameter mismatch, ~a != ~a" at pt)))
  3847. return-type]
  3848. [else
  3849. (error 'type-check-op "unrecognized operator ~a" op)]))
  3850. \end{lstlisting}
  3851. \caption{Auxilliary functions for type checking.}
  3852. \label{fig:type-check-aux-R2}
  3853. \end{figure}
  3854. \begin{exercise}\normalfont
  3855. Create 10 new example programs in $R_2$. Half of the example programs
  3856. should have a type error. For those programs, to signal that a type
  3857. error is expected, create an empty file with the same base name but
  3858. with file extension \code{.tyerr}. For example, if the test
  3859. \code{r2\_14.rkt} is expected to error, then create an empty file
  3860. named \code{r2\_14.tyerr}. The other half of the example programs
  3861. should not have type errors. Note that if the type checker does not
  3862. signal an error for a program, then interpreting that program should
  3863. not encounter an error.
  3864. \end{exercise}
  3865. \section{Shrink the $R_2$ Language}
  3866. \label{sec:shrink-r2}
  3867. The $R_2$ language includes several operators that are easily
  3868. expressible in terms of other operators. For example, subtraction is
  3869. expressible in terms of addition and negation.
  3870. \[
  3871. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  3872. \]
  3873. Several of the comparison operations are expressible in terms of
  3874. less-than and logical negation.
  3875. \[
  3876. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  3877. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  3878. \]
  3879. The \key{let} is needed in the above translation to ensure that
  3880. expression $e_1$ is evaluated before $e_2$.
  3881. By performing these translations near the front-end of the compiler,
  3882. the later passes of the compiler do not need to deal with these
  3883. constructs, making those passes shorter. On the other hand, sometimes
  3884. these translations make it more difficult to generate the most
  3885. efficient code with respect to the number of instructions. However,
  3886. these differences typically do not affect the number of accesses to
  3887. memory, which is the primary factor that determines execution time on
  3888. modern computer architectures.
  3889. \begin{exercise}\normalfont
  3890. Implement the pass \code{shrink} that removes subtraction,
  3891. \key{and}, \key{or}, \key{<=}, \key{>}, and \key{>=} from the language
  3892. by translating them to other constructs in $R_2$. Create tests to
  3893. make sure that the behavior of all of these constructs stays the
  3894. same after translation.
  3895. \end{exercise}
  3896. \section{The x86$_1$ Language}
  3897. \label{sec:x86-1}
  3898. \index{x86}
  3899. To implement the new logical operations, the comparison operations,
  3900. and the \key{if} expression, we need to delve further into the x86
  3901. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} define
  3902. the concrete and abstract syntax for a larger subset of x86 that
  3903. includes instructions for logical operations, comparisons, and
  3904. conditional jumps.
  3905. One small challenge is that x86 does not provide an instruction that
  3906. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  3907. However, the \code{xorq} instruction can be used to encode \code{not}.
  3908. The \key{xorq} instruction takes two arguments, performs a pairwise
  3909. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  3910. and writes the results into its second argument. Recall the truth
  3911. table for exclusive-or:
  3912. \begin{center}
  3913. \begin{tabular}{l|cc}
  3914. & 0 & 1 \\ \hline
  3915. 0 & 0 & 1 \\
  3916. 1 & 1 & 0
  3917. \end{tabular}
  3918. \end{center}
  3919. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  3920. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  3921. for the bit $1$, the result is the opposite of the second bit. Thus,
  3922. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  3923. the first argument:
  3924. \[
  3925. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  3926. \qquad\Rightarrow\qquad
  3927. \begin{array}{l}
  3928. \key{movq}~ \Arg\key{,} \Var\\
  3929. \key{xorq}~ \key{\$1,} \Var
  3930. \end{array}
  3931. \]
  3932. \begin{figure}[tp]
  3933. \fbox{
  3934. \begin{minipage}{0.96\textwidth}
  3935. \[
  3936. \begin{array}{lcl}
  3937. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  3938. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  3939. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} } \mid \key{\%}\itm{bytereg}\\
  3940. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3941. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \mid
  3942. \key{subq} \; \Arg\key{,} \Arg \mid
  3943. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid } \\
  3944. && \gray{ \key{callq} \; \itm{label} \mid
  3945. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} } \\
  3946. && \gray{ \itm{label}\key{:}\; \Instr }
  3947. \mid \key{xorq}~\Arg\key{,}~\Arg
  3948. \mid \key{cmpq}~\Arg\key{,}~\Arg \mid \\
  3949. && \key{set}cc~\Arg
  3950. \mid \key{movzbq}~\Arg\key{,}~\Arg
  3951. \mid \key{j}cc~\itm{label}
  3952. \\
  3953. x86_1 &::= & \gray{ \key{.globl main} }\\
  3954. & & \gray{ \key{main:} \; \Instr\ldots }
  3955. \end{array}
  3956. \]
  3957. \end{minipage}
  3958. }
  3959. \caption{The concrete syntax of x86$_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-concrete}).}
  3960. \label{fig:x86-1-concrete}
  3961. \end{figure}
  3962. \begin{figure}[tp]
  3963. \fbox{
  3964. \begin{minipage}{0.96\textwidth}
  3965. \small
  3966. \[
  3967. \begin{array}{lcl}
  3968. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  3969. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  3970. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}}
  3971. \mid \BYTEREG{\itm{bytereg}} \\
  3972. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3973. \Instr &::=& \gray{ \BININSTR{\code{'addq}}{\Arg}{\Arg}
  3974. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} } \\
  3975. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  3976. \mid \UNIINSTR{\code{'negq}}{\Arg} } \\
  3977. &\mid& \gray{ \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  3978. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  3979. &\mid& \BININSTR{\code{'xorq}}{\Arg}{\Arg}
  3980. \mid \BININSTR{\code{'cmpq}}{\Arg}{\Arg}\\
  3981. &\mid& \BININSTR{\code{'set}}{\itm{cc}}{\Arg}
  3982. \mid \BININSTR{\code{'movzbq}}{\Arg}{\Arg}\\
  3983. &\mid& \JMPIF{\itm{cc}}{\itm{label}} \\
  3984. \Block &::= & \gray{\BLOCK{\itm{info}}{\Instr\ldots}} \\
  3985. x86_1 &::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}}}
  3986. \end{array}
  3987. \]
  3988. \end{minipage}
  3989. }
  3990. \caption{The abstract syntax of x86$_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-ast}).}
  3991. \label{fig:x86-1}
  3992. \end{figure}
  3993. Next we consider the x86 instructions that are relevant for compiling
  3994. the comparison operations. The \key{cmpq} instruction compares its two
  3995. arguments to determine whether one argument is less than, equal, or
  3996. greater than the other argument. The \key{cmpq} instruction is unusual
  3997. regarding the order of its arguments and where the result is
  3998. placed. The argument order is backwards: if you want to test whether
  3999. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  4000. \key{cmpq} is placed in the special EFLAGS register. This register
  4001. cannot be accessed directly but it can be queried by a number of
  4002. instructions, including the \key{set} instruction. The \key{set}
  4003. instruction puts a \key{1} or \key{0} into its destination depending
  4004. on whether the comparison came out according to the condition code
  4005. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  4006. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  4007. The \key{set} instruction has an annoying quirk in that its
  4008. destination argument must be single byte register, such as \code{al}
  4009. (L for lower bits) or \code{ah} (H for higher bits), which are part of
  4010. the \code{rax} register. Thankfully, the \key{movzbq} instruction can
  4011. then be used to move from a single byte register to a normal 64-bit
  4012. register.
  4013. The x86 instruction for conditional jump are relevant to the
  4014. compilation of \key{if} expressions. The \key{JmpIf} instruction
  4015. updates the program counter to point to the instruction after the
  4016. indicated label depending on whether the result in the EFLAGS register
  4017. matches the condition code \itm{cc}, otherwise the \key{JmpIf}
  4018. instruction falls through to the next instruction. The abstract
  4019. syntax for \key{JmpIf} differs from the concrete syntax for x86 in
  4020. that it separates the instruction name from the condition code. For
  4021. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  4022. the \key{JmpIf} instruction relies on the EFLAGS register, it is
  4023. common for the \key{JmpIf} to be immediately preceded by a \key{cmpq}
  4024. instruction to set the EFLAGS register.
  4025. \section{The $C_1$ Intermediate Language}
  4026. \label{sec:c1}
  4027. As with $R_1$, we compile $R_2$ to a C-like intermediate language, but
  4028. we need to grow that intermediate language to handle the new features
  4029. in $R_2$: Booleans and conditional expressions.
  4030. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of
  4031. $C_1$ and Figure~\ref{fig:c1-syntax} defines the abstract syntax. In
  4032. particular, we add logical and comparison operators to the $\Exp$
  4033. non-terminal and the literals \key{\#t} and \key{\#f} to the $\Arg$
  4034. non-terminal. Regarding control flow, $C_1$ differs considerably from
  4035. $R_2$. Instead of \key{if} expressions, $C_1$ has \key{goto} and
  4036. conditional \key{goto} in the grammar for $\Tail$. This means that a
  4037. sequence of statements may now end with a \code{goto} or a conditional
  4038. \code{goto}. The conditional \code{goto} jumps to one of two labels
  4039. depending on the outcome of the comparison. In
  4040. Section~\ref{sec:explicate-control-r2} we discuss how to translate
  4041. from $R_2$ to $C_1$, bridging this gap between \key{if} expressions
  4042. and \key{goto}'s.
  4043. \begin{figure}[tbp]
  4044. \fbox{
  4045. \begin{minipage}{0.96\textwidth}
  4046. \small
  4047. \[
  4048. \begin{array}{lcl}
  4049. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  4050. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  4051. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  4052. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  4053. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  4054. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  4055. \mid \key{goto}~\itm{label}\key{;}\\
  4056. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  4057. C_1 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  4058. \end{array}
  4059. \]
  4060. \end{minipage}
  4061. }
  4062. \caption{The concrete syntax of the $C_1$ intermediate language.}
  4063. \label{fig:c1-concrete-syntax}
  4064. \end{figure}
  4065. \begin{figure}[tp]
  4066. \fbox{
  4067. \begin{minipage}{0.96\textwidth}
  4068. \small
  4069. \[
  4070. \begin{array}{lcl}
  4071. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  4072. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  4073. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  4074. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4075. &\mid& \UNIOP{\key{'not}}{\Atm}
  4076. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  4077. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  4078. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  4079. \mid \GOTO{\itm{label}} \\
  4080. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  4081. C_1 & ::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}\ldots}}}
  4082. \end{array}
  4083. \]
  4084. \end{minipage}
  4085. }
  4086. \caption{The abstract syntax of $C_1$, an extention of $C_0$
  4087. (Figure~\ref{fig:c0-syntax}).}
  4088. \label{fig:c1-syntax}
  4089. \end{figure}
  4090. \clearpage
  4091. \section{Remove Complex Operands}
  4092. \label{sec:remove-complex-opera-R2}
  4093. Add cases for \code{Bool} and \code{If} to the \code{rco-exp} and
  4094. \code{rco-atom} functions according to the definition of the output
  4095. language for this pass, $R_2^{\dagger}$, the administrative normal
  4096. form of $R_2$, which is defined in Figure~\ref{fig:r2-anf-syntax}. The
  4097. \code{Bool} form is an atomic expressions but \code{If} is not. All
  4098. three sub-expressions of an \code{If} are allowed to be complex
  4099. expressions in the output of \code{remove-complex-opera*}, but the
  4100. operands of \code{not} and the comparisons must be atoms. Regarding
  4101. the \code{If} form, it is particularly important to \textbf{not}
  4102. replace its condition with a temporary variable because that would
  4103. interfere with the generation of high-quality output in the
  4104. \code{explicate-control} pass.
  4105. \begin{figure}[tp]
  4106. \centering
  4107. \fbox{
  4108. \begin{minipage}{0.96\textwidth}
  4109. \[
  4110. \begin{array}{rcl}
  4111. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} } \mid \BOOL{\itm{bool}}\\
  4112. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  4113. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4114. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  4115. &\mid& \UNIOP{\key{'not}}{\Atm} \\
  4116. &\mid& \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4117. R^{\dagger}_2 &::=& \PROGRAM{\code{'()}}{\Exp}
  4118. \end{array}
  4119. \]
  4120. \end{minipage}
  4121. }
  4122. \caption{$R_2^{\dagger}$ is $R_2$ in administrative normal form (ANF).}
  4123. \label{fig:r2-anf-syntax}
  4124. \end{figure}
  4125. \section{Explicate Control}
  4126. \label{sec:explicate-control-r2}
  4127. Recall that the purpose of \code{explicate-control} is to make the
  4128. order of evaluation explicit in the syntax of the program. With the
  4129. addition of \key{if} in $R_2$ this get more interesting.
  4130. As a motivating example, consider the following program that has an
  4131. \key{if} expression nested in the predicate of another \key{if}.
  4132. % s1_41.rkt
  4133. \begin{center}
  4134. \begin{minipage}{0.96\textwidth}
  4135. \begin{lstlisting}
  4136. (let ([x (read)])
  4137. (let ([y (read)])
  4138. (if (if (< x 1) (eq? x 0) (eq? x 2))
  4139. (+ y 2)
  4140. (+ y 10))))
  4141. \end{lstlisting}
  4142. \end{minipage}
  4143. \end{center}
  4144. %
  4145. The naive way to compile \key{if} and the comparison would be to
  4146. handle each of them in isolation, regardless of their context. Each
  4147. comparison would be translated into a \key{cmpq} instruction followed
  4148. by a couple instructions to move the result from the EFLAGS register
  4149. into a general purpose register or stack location. Each \key{if} would
  4150. be translated into the combination of a \key{cmpq} and a conditional
  4151. jump. The generated code for the inner \key{if} in the above example
  4152. would be as follows.
  4153. \begin{center}
  4154. \begin{minipage}{0.96\textwidth}
  4155. \begin{lstlisting}
  4156. ...
  4157. cmpq $1, x ;; (< x 1)
  4158. setl %al
  4159. movzbq %al, tmp
  4160. cmpq $1, tmp ;; (if (< x 1) ...)
  4161. je then_branch_1
  4162. jmp else_branch_1
  4163. ...
  4164. \end{lstlisting}
  4165. \end{minipage}
  4166. \end{center}
  4167. However, if we take context into account we can do better and reduce
  4168. the use of \key{cmpq} and EFLAG-accessing instructions.
  4169. One idea is to try and reorganize the code at the level of $R_2$,
  4170. pushing the outer \key{if} inside the inner one. This would yield the
  4171. following code.
  4172. \begin{center}
  4173. \begin{minipage}{0.96\textwidth}
  4174. \begin{lstlisting}
  4175. (let ([x (read)])
  4176. (let ([y (read)])
  4177. (if (< x 1)
  4178. (if (eq? x 0)
  4179. (+ y 2)
  4180. (+ y 10))
  4181. (if (eq? x 2)
  4182. (+ y 2)
  4183. (+ y 10)))))
  4184. \end{lstlisting}
  4185. \end{minipage}
  4186. \end{center}
  4187. Unfortunately, this approach duplicates the two branches, and a
  4188. compiler must never duplicate code!
  4189. We need a way to perform the above transformation, but without
  4190. duplicating code. The solution is straightforward if we think at the
  4191. level of x86 assembly: we can label the code for each of the branches
  4192. and insert jumps in all the places that need to execute the
  4193. branches. Put another way, we need to move away from abstract syntax
  4194. \emph{trees} and instead use \emph{graphs}. In particular, we
  4195. use a standard program representation called a \emph{control flow
  4196. graph} (CFG), due to Frances Elizabeth \citet{Allen:1970uq}.
  4197. \index{control-flow graph}
  4198. Each vertex is a labeled sequence of code, called a \emph{basic block}, and
  4199. each edge represents a jump to another block. The \key{Program}
  4200. construct of $C_0$ and $C_1$ contains a control flow graph represented
  4201. as an alist mapping labels to basic blocks. Each basic block is
  4202. represented by the $\Tail$ non-terminal.
  4203. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  4204. \code{remove-complex-opera*} pass and then the
  4205. \code{explicate-control} pass on the example program. We walk through
  4206. the output program and then discuss the algorithm.
  4207. %
  4208. Following the order of evaluation in the output of
  4209. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  4210. and then the less-than-comparison to \code{1} in the predicate of the
  4211. inner \key{if}. In the output of \code{explicate-control}, in the
  4212. block labeled \code{start}, this becomes two assignment statements
  4213. followed by a conditional \key{goto} to label \code{block96} or
  4214. \code{block97}. The blocks associated with those labels contain the
  4215. translations of the code \code{(eq? x 0)} and \code{(eq? x 2)},
  4216. respectively. Regarding the block labeled with \code{block96}, we
  4217. start with the comparison to \code{0} and then have a conditional
  4218. goto, either to label \code{block92} or label \code{block93}, which
  4219. indirectly take us to labels \code{block90} and \code{block91}, the
  4220. two branches of the outer \key{if}, i.e., \code{(+ y 2)} and \code{(+
  4221. y 10)}. The story for the block labeled \code{block97} is similar.
  4222. \begin{figure}[tbp]
  4223. \begin{tabular}{lll}
  4224. \begin{minipage}{0.4\textwidth}
  4225. % s1_41.rkt
  4226. \begin{lstlisting}
  4227. (let ([x (read)])
  4228. (let ([y (read)])
  4229. (if (if (< x 1)
  4230. (eq? x 0)
  4231. (eq? x 2))
  4232. (+ y 2)
  4233. (+ y 10))))
  4234. \end{lstlisting}
  4235. \hspace{40pt}$\Downarrow$
  4236. \begin{lstlisting}
  4237. (let ([x (read)])
  4238. (let ([y (read)])
  4239. (if (if (< x 1)
  4240. (eq? x 0)
  4241. (eq? x 2))
  4242. (+ y 2)
  4243. (+ y 10))))
  4244. \end{lstlisting}
  4245. \end{minipage}
  4246. &
  4247. $\Rightarrow$
  4248. &
  4249. \begin{minipage}{0.55\textwidth}
  4250. \begin{lstlisting}
  4251. start:
  4252. x = (read);
  4253. y = (read);
  4254. if (< x 1)
  4255. goto block96;
  4256. else
  4257. goto block97;
  4258. block96:
  4259. if (eq? x 0)
  4260. goto block92;
  4261. else
  4262. goto block93;
  4263. block97:
  4264. if (eq? x 2)
  4265. goto block94;
  4266. else
  4267. goto block95;
  4268. block92:
  4269. goto block90;
  4270. block93:
  4271. goto block91;
  4272. block94:
  4273. goto block90;
  4274. block95:
  4275. goto block91;
  4276. block90:
  4277. return (+ y 2);
  4278. block91:
  4279. return (+ y 10);
  4280. \end{lstlisting}
  4281. \end{minipage}
  4282. \end{tabular}
  4283. \caption{Example translation from $R_2$ to $C_1$
  4284. via the \code{explicate-control}.}
  4285. \label{fig:explicate-control-s1-38}
  4286. \end{figure}
  4287. The nice thing about the output of \code{explicate-control} is that
  4288. there are no unnecessary comparisons and every comparison is part of a
  4289. conditional jump. The down-side of this output is that it includes
  4290. trivial blocks, such as the blocks labeled \code{block92} through
  4291. \code{block95}, that only jump to another block. We discuss a solution
  4292. to this problem in Section~\ref{sec:opt-jumps}.
  4293. Recall that in Section~\ref{sec:explicate-control-r1} we implement
  4294. \code{explicate-control} for $R_1$ using two mutually recursive
  4295. functions, \code{explicate-tail} and \code{explicate-assign}. The
  4296. former function translates expressions in tail position whereas the
  4297. later function translates expressions on the right-hand-side of a
  4298. \key{let}. With the addition of \key{if} expression in $R_2$ we have a
  4299. new kind of context to deal with: the predicate position of the
  4300. \key{if}. We need another function, \code{explicate-pred}, that takes
  4301. an $R_2$ expression and two blocks (two $C_1$ $\Tail$ AST nodes) for
  4302. the then-branch and else-branch. The output of \code{explicate-pred}
  4303. is a block and a list of formerly \key{let}-bound variables.
  4304. Note that the three explicate functions need to construct a
  4305. control-flow graph, which we recommend they do via updates to a global
  4306. variable.
  4307. In the following paragraphs we consider the specific additions to the
  4308. \code{explicate-tail} and \code{explicate-assign} functions, and some
  4309. of cases for the \code{explicate-pred} function.
  4310. The \code{explicate-tail} function needs an additional case for
  4311. \key{if}. The branches of the \key{if} inherit the current context, so
  4312. they are in tail position. Let $B_1$ be the result of
  4313. \code{explicate-tail} on the ``then'' branch of the \key{if}, so $B_1$
  4314. is a $\Tail$ AST node. Let $B_2$ be the result of applying
  4315. \code{explicate-tail} to the ``else'' branch. Finally, let $B_3$ be
  4316. the $\Tail$ that results from applying \code{explicate-pred} to the
  4317. predicate $\itm{cnd}$ and the blocks $B_1$ and $B_2$. Then the
  4318. \key{if} as a whole translates to block $B_3$.
  4319. \[
  4320. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  4321. \]
  4322. In the above discussion, we use the metavariables $B_1$, $B_2$, and
  4323. $B_3$ to refer to blocks for the purposes of our discussion, but they
  4324. should not be confused with the labels for the blocks that appear in
  4325. the generated code. We initially construct unlabeled blocks; we only
  4326. attach labels to blocks when we add them to the control-flow graph, as
  4327. we see in the next case.
  4328. Next consider the case for \key{if} in the \code{explicate-assign}
  4329. function. The context of the \key{if} is an assignment to some
  4330. variable $x$ and then the control continues to some block $B_1$. The
  4331. code that we generate for both the ``then'' and ``else'' branches
  4332. needs to continue to $B_1$, so to avoid duplicating $B_1$ we instead
  4333. add it to the control flow graph with a fresh label $\ell_1$. The
  4334. branches of the \key{if} inherit the current context, so they are in
  4335. assignment positions. Let $B_2$ be the result of applying
  4336. \code{explicate-assign} to the ``then'' branch, variable $x$, and the
  4337. block \GOTO{$\ell_1$}. Let $B_3$ be the result of applying
  4338. \code{explicate-assign} to the ``else'' branch, variable $x$, and the
  4339. block \GOTO{$\ell_1$}. Finally, let $B_4$ be the result of applying
  4340. \code{explicate-pred} to the predicate $\itm{cnd}$ and the blocks
  4341. $B_2$ and $B_3$. The \key{if} as a whole translates to the block
  4342. $B_4$.
  4343. \[
  4344. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  4345. \]
  4346. The function \code{explicate-pred} will need a case for every
  4347. expression that can have type \code{Boolean}. We detail a few cases
  4348. here and leave the rest for the reader. The input to this function is
  4349. an expression and two blocks, $B_1$ and $B_2$, for the two branches of
  4350. the enclosing \key{if}. Suppose the expression is the Boolean
  4351. \code{\#t}. Then we can perform a kind of partial evaluation
  4352. \index{partial evaluation} and translate it to the ``then'' branch
  4353. $B_1$. Likewise, we translate \code{\#f} to the ``else`` branch $B_2$.
  4354. \[
  4355. \key{\#t} \quad\Rightarrow\quad B_1,
  4356. \qquad\qquad\qquad
  4357. \key{\#f} \quad\Rightarrow\quad B_2
  4358. \]
  4359. Next, suppose the expression is a less-than comparison. We translate
  4360. it to a conditional \code{goto}. We need labels for the two branches
  4361. $B_1$ and $B_2$, so we add those blocks to the control flow graph and
  4362. obtain their labels $\ell_1$ and $\ell_2$. The translation of the
  4363. less-than comparison is as follows.
  4364. \[
  4365. (\key{<}~e_1~e_2) \quad\Rightarrow\quad
  4366. \begin{array}{l}
  4367. \key{if}~(\key{<}~e_1~e_2) \\
  4368. \qquad\key{goto}~\ell_1\key{;}\\
  4369. \key{else}\\
  4370. \qquad\key{goto}~\ell_2\key{;}
  4371. \end{array}
  4372. \]
  4373. The case for \key{if} in \code{explicate-pred} is particularly
  4374. illuminating as it deals with the challenges that we discussed above
  4375. regarding the example of the nested \key{if} expressions. Again, we
  4376. add the two branches $B_1$ and $B_2$ to the control flow graph and
  4377. obtain their labels $\ell_1$ and $\ell_2$. The ``then'' and ``else''
  4378. branches of the current \key{if} inherit their context from the
  4379. current one, that is, predicate context. So we apply
  4380. \code{explicate-pred} to the ``then'' branch with the two blocks
  4381. \GOTO{$\ell_1$} and \GOTO{$\ell_2$} to obtain $B_3$. Proceed in a
  4382. similar way with the ``else'' branch to obtain $B_4$. Finally, we
  4383. apply \code{explicate-pred} to the predicate of the \code{if} and the
  4384. blocks $B_3$ and $B_4$ to obtain the result $B_5$.
  4385. \[
  4386. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  4387. \quad\Rightarrow\quad
  4388. B_5
  4389. \]
  4390. Finally, note that the way in which the \code{shrink} pass transforms
  4391. logical operations such as \code{and} and \code{or} can impact the
  4392. quality of code generated by \code{explicate-control}. For example,
  4393. consider the following program.
  4394. \begin{lstlisting}
  4395. (if (and (eq? (read) 0) (eq? (read) 1))
  4396. 0
  4397. 42)
  4398. \end{lstlisting}
  4399. The \code{and} operation should transform into something that the
  4400. \code{explicat-pred} function can still analyze and descend through to
  4401. reach the underlying \code{eq?} conditions. Ideally, your
  4402. \code{explicate-control} pass should generate code similar to the
  4403. following for the above program.\footnote{If the trivial blocks 17,
  4404. 18, and 20 bother you, take a look at the challenge problem in
  4405. Section~\ref{sec:opt-jumps}.}
  4406. \begin{center}
  4407. \begin{minipage}{0.45\textwidth}
  4408. \begin{lstlisting}
  4409. start:
  4410. tmp13 = (read);
  4411. if (eq? tmp13 0)
  4412. goto block19;
  4413. else
  4414. goto block20;
  4415. block19:
  4416. tmp14 = (read);
  4417. if (eq? tmp14 1)
  4418. goto block17;
  4419. else
  4420. goto block18;
  4421. \end{lstlisting}
  4422. \end{minipage}
  4423. \begin{minipage}{0.45\textwidth}
  4424. \begin{lstlisting}
  4425. block20:
  4426. goto block16;
  4427. block17:
  4428. goto block15;
  4429. block18:
  4430. goto block16;
  4431. block15:
  4432. return 0;
  4433. block16:
  4434. return 42;
  4435. \end{lstlisting}
  4436. \end{minipage}
  4437. \end{center}
  4438. \begin{exercise}\normalfont
  4439. Implement the pass \code{explicate-control} by adding the cases for
  4440. \key{if} to the functions for tail and assignment contexts, and
  4441. implement \code{explicate-pred} for predicate contexts. Create test
  4442. cases that exercise all of the new cases in the code for this pass.
  4443. \end{exercise}
  4444. \section{Select Instructions}
  4445. \label{sec:select-r2}
  4446. \index{instruction selection}
  4447. Recall that the \code{select-instructions} pass lowers from our
  4448. $C$-like intermediate representation to the pseudo-x86 language, which
  4449. is suitable for conducting register allocation. The pass is
  4450. implemented using three auxiliary functions, one for each of the
  4451. non-terminals $\Atm$, $\Stmt$, and $\Tail$.
  4452. For $\Atm$, we have new cases for the Booleans. We take the usual
  4453. approach of encoding them as integers, with true as 1 and false as 0.
  4454. \[
  4455. \key{\#t} \Rightarrow \key{1}
  4456. \qquad
  4457. \key{\#f} \Rightarrow \key{0}
  4458. \]
  4459. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  4460. be implemented in terms of \code{xorq} as we discussed at the
  4461. beginning of this section. Given an assignment
  4462. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  4463. if the left-hand side $\itm{var}$ is
  4464. the same as $\Atm$, then just the \code{xorq} suffices.
  4465. \[
  4466. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  4467. \quad\Rightarrow\quad
  4468. \key{xorq}~\key{\$}1\key{,}~\Var
  4469. \]
  4470. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  4471. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  4472. x86. Then we have
  4473. \[
  4474. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  4475. \quad\Rightarrow\quad
  4476. \begin{array}{l}
  4477. \key{movq}~\Arg\key{,}~\Var\\
  4478. \key{xorq}~\key{\$}1\key{,}~\Var
  4479. \end{array}
  4480. \]
  4481. Next consider the cases for \code{eq?} and less-than comparison.
  4482. Translating these operations to x86 is slightly involved due to the
  4483. unusual nature of the \key{cmpq} instruction discussed above. We
  4484. recommend translating an assignment from \code{eq?} into the following
  4485. sequence of three instructions. \\
  4486. \begin{tabular}{lll}
  4487. \begin{minipage}{0.4\textwidth}
  4488. \begin{lstlisting}
  4489. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  4490. \end{lstlisting}
  4491. \end{minipage}
  4492. &
  4493. $\Rightarrow$
  4494. &
  4495. \begin{minipage}{0.4\textwidth}
  4496. \begin{lstlisting}
  4497. cmpq |$\Arg_2$|, |$\Arg_1$|
  4498. sete %al
  4499. movzbq %al, |$\Var$|
  4500. \end{lstlisting}
  4501. \end{minipage}
  4502. \end{tabular} \\
  4503. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  4504. and conditional \key{goto}. Both are straightforward to handle. A
  4505. \key{goto} becomes a jump instruction.
  4506. \[
  4507. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  4508. \]
  4509. A conditional \key{goto} becomes a compare instruction followed
  4510. by a conditional jump (for ``then'') and the fall-through is
  4511. to a regular jump (for ``else'').\\
  4512. \begin{tabular}{lll}
  4513. \begin{minipage}{0.4\textwidth}
  4514. \begin{lstlisting}
  4515. if (eq? |$\Atm_1$| |$\Atm_2$|)
  4516. goto |$\ell_1$|;
  4517. else
  4518. goto |$\ell_2$|;
  4519. \end{lstlisting}
  4520. \end{minipage}
  4521. &
  4522. $\Rightarrow$
  4523. &
  4524. \begin{minipage}{0.4\textwidth}
  4525. \begin{lstlisting}
  4526. cmpq |$\Arg_2$|, |$\Arg_1$|
  4527. je |$\ell_1$|
  4528. jmp |$\ell_2$|
  4529. \end{lstlisting}
  4530. \end{minipage}
  4531. \end{tabular} \\
  4532. \begin{exercise}\normalfont
  4533. Expand your \code{select-instructions} pass to handle the new features
  4534. of the $R_2$ language. Test the pass on all the examples you have
  4535. created and make sure that you have some test programs that use the
  4536. \code{eq?} and \code{<} operators, creating some if necessary. Test
  4537. the output using the \code{interp-x86} interpreter
  4538. (Appendix~\ref{appendix:interp}).
  4539. \end{exercise}
  4540. \section{Register Allocation}
  4541. \label{sec:register-allocation-r2}
  4542. \index{register allocation}
  4543. The changes required for $R_2$ affect liveness analysis, building the
  4544. interference graph, and assigning homes, but the graph coloring
  4545. algorithm itself does not change.
  4546. \subsection{Liveness Analysis}
  4547. \label{sec:liveness-analysis-r2}
  4548. \index{liveness analysis}
  4549. Recall that for $R_1$ we implemented liveness analysis for a single
  4550. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  4551. addition of \key{if} expressions to $R_2$, \code{explicate-control}
  4552. produces many basic blocks arranged in a control-flow graph. The first
  4553. question we need to consider is: what order should we process the
  4554. basic blocks? Recall that to perform liveness analysis, we need to
  4555. know the live-after set. If a basic block has no successor blocks
  4556. (i.e. no out-edges in the control flow graph), then it has an empty
  4557. live-after set and we can immediately apply liveness analysis to
  4558. it. If a basic block has some successors, then we need to complete
  4559. liveness analysis on those blocks first. Furthermore, we know that
  4560. the control flow graph does not contain any cycles because $R_2$ does
  4561. not include loops
  4562. %
  4563. \footnote{If we were to add loops to the language, then the CFG could
  4564. contain cycles and we would instead need to use the classic worklist
  4565. algorithm for computing the fixed point of the liveness
  4566. analysis~\citep{Aho:1986qf}.}.
  4567. %
  4568. Returning to the question of what order should we process the basic
  4569. blocks, the answer is reverse topological order. We recommend using
  4570. the \code{tsort} (topological sort) and \code{transpose} functions of
  4571. the Racket \code{graph} package to obtain this ordering.
  4572. \index{topological order}
  4573. \index{topological sort}
  4574. The next question is how to compute the live-after set of a block
  4575. given the live-before sets of all its successor blocks. (There can be
  4576. more than one because of conditional jumps.) During compilation we do
  4577. not know which way a conditional jump will go, so we do not know which
  4578. of the successor's live-before set to use. The solution to this
  4579. challenge is based on the observation that there is no harm to the
  4580. correctness of the compiler if we classify more variables as live than
  4581. the ones that are truly live during a particular execution of the
  4582. block. Thus, we can take the union of the live-before sets from all
  4583. the successors to be the live-after set for the block. Once we have
  4584. computed the live-after set, we can proceed to perform liveness
  4585. analysis on the block just as we did in
  4586. Section~\ref{sec:liveness-analysis-r1}.
  4587. The helper functions for computing the variables in an instruction's
  4588. argument and for computing the variables read-from ($R$) or written-to
  4589. ($W$) by an instruction need to be updated to handle the new kinds of
  4590. arguments and instructions in x86$_1$.
  4591. \subsection{Build Interference}
  4592. \label{sec:build-interference-r2}
  4593. Many of the new instructions in x86$_1$ can be handled in the same way
  4594. as the instructions in x86$_0$. Thus, if your code was already quite
  4595. general, it will not need to be changed to handle the new
  4596. instructions. If you code is not general enough, I recommend that you
  4597. change your code to be more general. For example, you can factor out
  4598. the computing of the the read and write sets for each kind of
  4599. instruction into two auxiliary functions.
  4600. Note that the \key{movzbq} instruction requires some special care,
  4601. just like the \key{movq} instruction. See rule number 3 in
  4602. Section~\ref{sec:build-interference}.
  4603. %% \subsection{Assign Homes}
  4604. %% \label{sec:assign-homes-r2}
  4605. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  4606. %% to be updated to handle the \key{if} statement, simply by recursively
  4607. %% processing the child nodes. Hopefully your code already handles the
  4608. %% other new instructions, but if not, you can generalize your code.
  4609. \begin{exercise}\normalfont
  4610. Update the \code{register-allocation} pass so that it works for $R_2$
  4611. and test your compiler using your previously created programs on the
  4612. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4613. \end{exercise}
  4614. \section{Patch Instructions}
  4615. The second argument of the \key{cmpq} instruction must not be an
  4616. immediate value (such as an integer). So if you are comparing two
  4617. immediates, we recommend inserting a \key{movq} instruction to put the
  4618. second argument in \key{rax}.
  4619. %
  4620. The second argument of the \key{movzbq} must be a register.
  4621. %
  4622. There are no special restrictions on the x86 instructions \key{JmpIf}
  4623. and \key{Jmp}.
  4624. \begin{exercise}\normalfont
  4625. Update \code{patch-instructions} to handle the new x86 instructions.
  4626. Test your compiler using your previously created programs on the
  4627. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4628. \end{exercise}
  4629. \section{An Example Translation}
  4630. Figure~\ref{fig:if-example-x86} shows a simple example program in
  4631. $R_2$ translated to x86, showing the results of
  4632. \code{explicate-control}, \code{select-instructions}, and the final
  4633. x86 assembly code.
  4634. \begin{figure}[tbp]
  4635. \begin{tabular}{lll}
  4636. \begin{minipage}{0.5\textwidth}
  4637. % s1_20.rkt
  4638. \begin{lstlisting}
  4639. (if (eq? (read) 1) 42 0)
  4640. \end{lstlisting}
  4641. $\Downarrow$
  4642. \begin{lstlisting}
  4643. start:
  4644. tmp7951 = (read);
  4645. if (eq? tmp7951 1) then
  4646. goto block7952;
  4647. else
  4648. goto block7953;
  4649. block7952:
  4650. return 42;
  4651. block7953:
  4652. return 0;
  4653. \end{lstlisting}
  4654. $\Downarrow$
  4655. \begin{lstlisting}
  4656. start:
  4657. callq read_int
  4658. movq %rax, tmp7951
  4659. cmpq $1, tmp7951
  4660. je block7952
  4661. jmp block7953
  4662. block7953:
  4663. movq $0, %rax
  4664. jmp conclusion
  4665. block7952:
  4666. movq $42, %rax
  4667. jmp conclusion
  4668. \end{lstlisting}
  4669. \end{minipage}
  4670. &
  4671. $\Rightarrow\qquad$
  4672. \begin{minipage}{0.4\textwidth}
  4673. \begin{lstlisting}
  4674. start:
  4675. callq read_int
  4676. movq %rax, %rcx
  4677. cmpq $1, %rcx
  4678. je block7952
  4679. jmp block7953
  4680. block7953:
  4681. movq $0, %rax
  4682. jmp conclusion
  4683. block7952:
  4684. movq $42, %rax
  4685. jmp conclusion
  4686. .globl main
  4687. main:
  4688. pushq %rbp
  4689. movq %rsp, %rbp
  4690. pushq %r13
  4691. pushq %r12
  4692. pushq %rbx
  4693. pushq %r14
  4694. subq $0, %rsp
  4695. jmp start
  4696. conclusion:
  4697. addq $0, %rsp
  4698. popq %r14
  4699. popq %rbx
  4700. popq %r12
  4701. popq %r13
  4702. popq %rbp
  4703. retq
  4704. \end{lstlisting}
  4705. \end{minipage}
  4706. \end{tabular}
  4707. \caption{Example compilation of an \key{if} expression to x86.}
  4708. \label{fig:if-example-x86}
  4709. \end{figure}
  4710. \begin{figure}[p]
  4711. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4712. \node (R2) at (0,2) {\large $R_2$};
  4713. \node (R2-2) at (3,2) {\large $R_2$};
  4714. \node (R2-3) at (6,2) {\large $R_2$};
  4715. \node (R2-4) at (9,2) {\large $R_2$};
  4716. \node (R2-5) at (9,0) {\large $R_2$};
  4717. \node (C1-1) at (3,-2) {\large $C_1$};
  4718. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_1$};
  4719. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_1$};
  4720. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_1$};
  4721. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_1$};
  4722. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_1$};
  4723. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_1$};
  4724. \path[->,bend left=15] (R2) edge [above] node {\ttfamily\footnotesize\color{red} type-check} (R2-2);
  4725. \path[->,bend left=15] (R2-2) edge [above] node {\ttfamily\footnotesize\color{red} shrink} (R2-3);
  4726. \path[->,bend left=15] (R2-3) edge [above] node {\ttfamily\footnotesize uniquify} (R2-4);
  4727. \path[->,bend left=15] (R2-4) edge [right] node {\ttfamily\footnotesize remove-complex.} (R2-5);
  4728. \path[->,bend right=15] (R2-5) edge [left] node {\ttfamily\footnotesize\color{red} explicate-control} (C1-1);
  4729. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize\color{red} select-instructions} (x86-2);
  4730. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  4731. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  4732. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4733. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  4734. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86 } (x86-5);
  4735. \end{tikzpicture}
  4736. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  4737. \label{fig:R2-passes}
  4738. \end{figure}
  4739. Figure~\ref{fig:R2-passes} lists all the passes needed for the
  4740. compilation of $R_2$.
  4741. \section{Challenge: Optimize and Remove Jumps}
  4742. \label{sec:opt-jumps}
  4743. Recall that in the example output of \code{explicate-control} in
  4744. Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  4745. \code{block60} are trivial blocks, they do nothing but jump to another
  4746. block. The first goal of this challenge assignment is to remove those
  4747. blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  4748. \code{explicate-control} on the left and shows the result of bypassing
  4749. the trivial blocks on the right. Let us focus on \code{block61}. The
  4750. \code{then} branch jumps to \code{block57}, which in turn jumps to
  4751. \code{block55}. The optimized code on the right of
  4752. Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  4753. \code{then} branch jumping directly to \code{block55}. The story is
  4754. similar for the \code{else} branch, as well as for the two branches in
  4755. \code{block62}. After the jumps in \code{block61} and \code{block62}
  4756. have been optimized in this way, there are no longer any jumps to
  4757. blocks \code{block57} through \code{block60}, so they can be removed.
  4758. \begin{figure}[tbp]
  4759. \begin{tabular}{lll}
  4760. \begin{minipage}{0.4\textwidth}
  4761. \begin{lstlisting}
  4762. block62:
  4763. tmp54 = (read);
  4764. if (eq? tmp54 2) then
  4765. goto block59;
  4766. else
  4767. goto block60;
  4768. block61:
  4769. tmp53 = (read);
  4770. if (eq? tmp53 0) then
  4771. goto block57;
  4772. else
  4773. goto block58;
  4774. block60:
  4775. goto block56;
  4776. block59:
  4777. goto block55;
  4778. block58:
  4779. goto block56;
  4780. block57:
  4781. goto block55;
  4782. block56:
  4783. return (+ 700 77);
  4784. block55:
  4785. return (+ 10 32);
  4786. start:
  4787. tmp52 = (read);
  4788. if (eq? tmp52 1) then
  4789. goto block61;
  4790. else
  4791. goto block62;
  4792. \end{lstlisting}
  4793. \end{minipage}
  4794. &
  4795. $\Rightarrow$
  4796. &
  4797. \begin{minipage}{0.55\textwidth}
  4798. \begin{lstlisting}
  4799. block62:
  4800. tmp54 = (read);
  4801. if (eq? tmp54 2) then
  4802. goto block55;
  4803. else
  4804. goto block56;
  4805. block61:
  4806. tmp53 = (read);
  4807. if (eq? tmp53 0) then
  4808. goto block55;
  4809. else
  4810. goto block56;
  4811. block56:
  4812. return (+ 700 77);
  4813. block55:
  4814. return (+ 10 32);
  4815. start:
  4816. tmp52 = (read);
  4817. if (eq? tmp52 1) then
  4818. goto block61;
  4819. else
  4820. goto block62;
  4821. \end{lstlisting}
  4822. \end{minipage}
  4823. \end{tabular}
  4824. \caption{Optimize jumps by removing trivial blocks.}
  4825. \label{fig:optimize-jumps}
  4826. \end{figure}
  4827. The name of this pass is \code{optimize-jumps}. We recommend
  4828. implementing this pass in two phases. The first phrase builds a hash
  4829. table that maps labels to possibly improved labels. The second phase
  4830. changes the target of each \code{goto} to use the improved label. If
  4831. the label is for a trivial block, then the hash table should map the
  4832. label to the first non-trivial block that can be reached from this
  4833. label by jumping through trivial blocks. If the label is for a
  4834. non-trivial block, then the hash table should map the label to itself;
  4835. we do not want to change jumps to non-trivial blocks.
  4836. The first phase can be accomplished by constructing an empty hash
  4837. table, call it \code{short-cut}, and then iterating over the control
  4838. flow graph. Each time you encouter a block that is just a \code{goto},
  4839. then update the hash table, mapping the block's source to the target
  4840. of the \code{goto}. Also, the hash table may already have mapped some
  4841. labels to the block's source, to you must iterate through the hash
  4842. table and update all of those so that they instead map to the target
  4843. of the \code{goto}.
  4844. For the second phase, we recommend iterating through the $\Tail$ of
  4845. each block in the program, updating the target of every \code{goto}
  4846. according to the mapping in \code{short-cut}.
  4847. \begin{exercise}\normalfont
  4848. Implement the \code{optimize-jumps} pass as a transformation from
  4849. $C_1$ to $C_1$, coming after the \code{explicate-control} pass.
  4850. Check that \code{optimize-jumps} removes trivial blocks in a few
  4851. example programs. Then check that your compiler still passes all of
  4852. your tests.
  4853. \end{exercise}
  4854. There is another opportunity for optimizing jumps that is apparent in
  4855. the example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  4856. end with a jump to \code{block7953} and there are no other jumps to
  4857. \code{block7953} in the rest of the program. In this situation we can
  4858. avoid the runtime overhead of this jump by merging \code{block7953}
  4859. into the preceeding block, in this case the \code{start} block.
  4860. Figure~\ref{fig:remove-jumps} shows the output of
  4861. \code{select-instructions} on the left and the result of this
  4862. optimization on the right.
  4863. \begin{figure}[tbp]
  4864. \begin{tabular}{lll}
  4865. \begin{minipage}{0.5\textwidth}
  4866. % s1_20.rkt
  4867. \begin{lstlisting}
  4868. start:
  4869. callq read_int
  4870. movq %rax, tmp7951
  4871. cmpq $1, tmp7951
  4872. je block7952
  4873. jmp block7953
  4874. block7953:
  4875. movq $0, %rax
  4876. jmp conclusion
  4877. block7952:
  4878. movq $42, %rax
  4879. jmp conclusion
  4880. \end{lstlisting}
  4881. \end{minipage}
  4882. &
  4883. $\Rightarrow\qquad$
  4884. \begin{minipage}{0.4\textwidth}
  4885. \begin{lstlisting}
  4886. start:
  4887. callq read_int
  4888. movq %rax, tmp7951
  4889. cmpq $1, tmp7951
  4890. je block7952
  4891. movq $0, %rax
  4892. jmp conclusion
  4893. block7952:
  4894. movq $42, %rax
  4895. jmp conclusion
  4896. \end{lstlisting}
  4897. \end{minipage}
  4898. \end{tabular}
  4899. \caption{Merging basic blocks by removing unnecessary jumps.}
  4900. \label{fig:remove-jumps}
  4901. \end{figure}
  4902. \begin{exercise}\normalfont
  4903. Implement a pass named \code{remove-jumps} that merges basic blocks
  4904. into their preceeding basic block, when there is only one preceeding
  4905. block. The pass should translate from psuedo $x86_1$ to pseudo
  4906. $x86_1$ and it should come immediately after
  4907. \code{select-instructions}. Check that \code{remove-jumps}
  4908. accomplishes the goal of merging basic blocks on several test
  4909. programs and check that your compiler passes all of your tests.
  4910. \end{exercise}
  4911. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4912. \chapter{Tuples and Garbage Collection}
  4913. \label{ch:tuples}
  4914. \index{tuple}
  4915. \index{vector}
  4916. \margincomment{\scriptsize To do: challenge assignments: mark-and-sweep,
  4917. add simple structures. \\ --Jeremy}
  4918. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  4919. things to discuss in this chapter. \\ --Jeremy}
  4920. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  4921. all the IR grammars are spelled out! \\ --Jeremy}
  4922. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  4923. but keep type annotations on vector creation and local variables, function
  4924. parameters, etc. \\ --Jeremy}
  4925. \margincomment{\scriptsize Be more explicit about how to deal with
  4926. the root stack. \\ --Jeremy}
  4927. In this chapter we study the implementation of mutable tuples (called
  4928. ``vectors'' in Racket). This language feature is the first to use the
  4929. computer's \emph{heap}\index{heap} because the lifetime of a Racket tuple is
  4930. indefinite, that is, a tuple lives forever from the programmer's
  4931. viewpoint. Of course, from an implementer's viewpoint, it is important
  4932. to reclaim the space associated with a tuple when it is no longer
  4933. needed, which is why we also study \emph{garbage collection}
  4934. \emph{garbage collection}
  4935. techniques in this chapter.
  4936. Section~\ref{sec:r3} introduces the $R_3$ language including its
  4937. interpreter and type checker. The $R_3$ language extends the $R_2$
  4938. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  4939. \code{void} value. The reason for including the later is that the
  4940. \code{vector-set!} operation returns a value of type
  4941. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  4942. called the \code{Unit} type in the programming languages
  4943. literature. Racket's \code{Void} type is inhabited by a single value
  4944. \code{void} which corresponds to \code{unit} or \code{()} in the
  4945. literature~\citep{Pierce:2002hj}.}.
  4946. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  4947. copying live objects back and forth between two halves of the
  4948. heap. The garbage collector requires coordination with the compiler so
  4949. that it can see all of the \emph{root} pointers, that is, pointers in
  4950. registers or on the procedure call stack.
  4951. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  4952. discuss all the necessary changes and additions to the compiler
  4953. passes, including a new compiler pass named \code{expose-allocation}.
  4954. \section{The $R_3$ Language}
  4955. \label{sec:r3}
  4956. Figure~\ref{fig:r3-concrete-syntax} defines the concrete syntax for
  4957. $R_3$ and Figure~\ref{fig:r3-syntax} defines the abstract syntax. The
  4958. $R_3$ language includes three new forms: \code{vector} for creating a
  4959. tuple, \code{vector-ref} for reading an element of a tuple, and
  4960. \code{vector-set!} for writing to an element of a tuple. The program
  4961. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  4962. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  4963. the 3-tuple, demonstrating that tuples are first-class values. The
  4964. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  4965. of the \key{if} is taken. The element at index $0$ of \code{t} is
  4966. \code{40}, to which we add \code{2}, the element at index $0$ of the
  4967. 1-tuple. So the result of the program is \code{42}.
  4968. \begin{figure}[tbp]
  4969. \centering
  4970. \fbox{
  4971. \begin{minipage}{0.96\textwidth}
  4972. \[
  4973. \begin{array}{lcl}
  4974. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  4975. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}\\
  4976. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  4977. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  4978. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  4979. \mid (\key{and}\;\Exp\;\Exp)
  4980. \mid (\key{or}\;\Exp\;\Exp)
  4981. \mid (\key{not}\;\Exp) } \\
  4982. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  4983. \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  4984. &\mid& (\key{vector}\;\Exp\ldots)
  4985. \mid (\key{vector-ref}\;\Exp\;\Int) \\
  4986. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)
  4987. \mid (\key{vector-length}\;\Exp) \\
  4988. &\mid& (\key{void}) \mid (\key{has-type}~\Exp~\Type)\\
  4989. R_3 &::=& \Exp
  4990. \end{array}
  4991. \]
  4992. \end{minipage}
  4993. }
  4994. \caption{The concrete syntax of $R_3$, extending $R_2$
  4995. (Figure~\ref{fig:r2-concrete-syntax}).}
  4996. \label{fig:r3-concrete-syntax}
  4997. \end{figure}
  4998. \begin{figure}[tbp]
  4999. \begin{lstlisting}
  5000. (let ([t (vector 40 #t (vector 2))])
  5001. (if (vector-ref t 1)
  5002. (+ (vector-ref t 0)
  5003. (vector-ref (vector-ref t 2) 0))
  5004. 44))
  5005. \end{lstlisting}
  5006. \caption{Example program that creates tuples and reads from them.}
  5007. \label{fig:vector-eg}
  5008. \end{figure}
  5009. \begin{figure}[tp]
  5010. \centering
  5011. \fbox{
  5012. \begin{minipage}{0.96\textwidth}
  5013. \[
  5014. \begin{array}{lcl}
  5015. \itm{op} &::=& \ldots
  5016. \mid \code{vector} \mid \code{vector-ref} \mid \code{vector-set!}
  5017. \mid \code{vector-length} \\
  5018. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  5019. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots}
  5020. \mid \BOOL{\itm{bool}}
  5021. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  5022. &\mid& \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP \\
  5023. R_3 &::=& \PROGRAM{\key{'()}}{\Exp}
  5024. \end{array}
  5025. \]
  5026. \end{minipage}
  5027. }
  5028. \caption{The abstract syntax of $R_3$.}
  5029. \label{fig:r3-syntax}
  5030. \end{figure}
  5031. \index{allocate}
  5032. \index{heap allocate}
  5033. Tuples are our first encounter with heap-allocated data, which raises
  5034. several interesting issues. First, variable binding performs a
  5035. shallow-copy when dealing with tuples, which means that different
  5036. variables can refer to the same tuple, that is, different variables
  5037. can be \emph{aliases} for the same entity. Consider the following
  5038. example in which both \code{t1} and \code{t2} refer to the same tuple.
  5039. Thus, the mutation through \code{t2} is visible when referencing the
  5040. tuple from \code{t1}, so the result of this program is \code{42}.
  5041. \index{alias}\index{mutation}
  5042. \begin{center}
  5043. \begin{minipage}{0.96\textwidth}
  5044. \begin{lstlisting}
  5045. (let ([t1 (vector 3 7)])
  5046. (let ([t2 t1])
  5047. (let ([_ (vector-set! t2 0 42)])
  5048. (vector-ref t1 0))))
  5049. \end{lstlisting}
  5050. \end{minipage}
  5051. \end{center}
  5052. The next issue concerns the lifetime of tuples. Of course, they are
  5053. created by the \code{vector} form, but when does their lifetime end?
  5054. Notice that $R_3$ does not include an operation for deleting
  5055. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  5056. of static scoping. For example, the following program returns
  5057. \code{42} even though the variable \code{w} goes out of scope prior to
  5058. the \code{vector-ref} that reads from the vector it was bound to.
  5059. \begin{center}
  5060. \begin{minipage}{0.96\textwidth}
  5061. \begin{lstlisting}
  5062. (let ([v (vector (vector 44))])
  5063. (let ([x (let ([w (vector 42)])
  5064. (let ([_ (vector-set! v 0 w)])
  5065. 0))])
  5066. (+ x (vector-ref (vector-ref v 0) 0))))
  5067. \end{lstlisting}
  5068. \end{minipage}
  5069. \end{center}
  5070. From the perspective of programmer-observable behavior, tuples live
  5071. forever. Of course, if they really lived forever, then many programs
  5072. would run out of memory.\footnote{The $R_3$ language does not have
  5073. looping or recursive functions, so it is nigh impossible to write a
  5074. program in $R_3$ that will run out of memory. However, we add
  5075. recursive functions in the next Chapter!} A Racket implementation
  5076. must therefore perform automatic garbage collection.
  5077. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  5078. $R_3$ language. We define the \code{vector}, \code{vector-ref}, and
  5079. \code{vector-set!} operations for $R_3$ in terms of the corresponding
  5080. operations in Racket. One subtle point is that the \code{vector-set!}
  5081. operation returns the \code{\#<void>} value. The \code{\#<void>} value
  5082. can be passed around just like other values inside an $R_3$ program
  5083. and a \code{\#<void>} value can be compared for equality with another
  5084. \code{\#<void>} value. However, there are no other operations specific
  5085. to the the \code{\#<void>} value in $R_3$. In contrast, Racket defines
  5086. the \code{void?} predicate that returns \code{\#t} when applied to
  5087. \code{\#<void>} and \code{\#f} otherwise.
  5088. \begin{figure}[tbp]
  5089. \begin{lstlisting}
  5090. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  5091. (define (interp-op op)
  5092. (match op
  5093. ...
  5094. ['vector vector]
  5095. ['vector-ref vector-ref]
  5096. ['vector-set! vector-set!]
  5097. [else (error 'interp-op "unknown operator")]))
  5098. (define (interp-exp env)
  5099. (lambda (e)
  5100. (define recur (interp-exp env))
  5101. (match e
  5102. ...
  5103. )))
  5104. (define (interp-R3 p)
  5105. (match p
  5106. [(Program '() e)
  5107. ((interp-exp '()) e)]
  5108. ))
  5109. \end{lstlisting}
  5110. \caption{Interpreter for the $R_3$ language.}
  5111. \label{fig:interp-R3}
  5112. \end{figure}
  5113. Figure~\ref{fig:type-check-R3} shows the type checker for $R_3$, which
  5114. deserves some explanation. As we see in Section~\ref{sec:GC}, we
  5115. need to know which variables contain pointers into the heap, that is,
  5116. which variables contain vectors. Also, when allocating a vector, we
  5117. need to know which elements of the vector are pointers. We can obtain
  5118. this information during type checking. The type checker in
  5119. Figure~\ref{fig:type-check-R3} not only computes the type of an
  5120. expression, it also wraps every sub-expression $e$ with the form
  5121. $(\key{HasType}~e~T)$, where $T$ is $e$'s type.
  5122. Subsequently, in the \code{uncover-locals} pass
  5123. (Section~\ref{sec:uncover-locals-r3}) this type information is
  5124. propagated to all variables (including the temporaries generated by
  5125. \code{remove-complex-opera*}).
  5126. To create the s-expression for the \code{Vector} type in
  5127. Figure~\ref{fig:type-check-R3}, we use the
  5128. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  5129. operator} \code{,@} to insert the list \code{t*} without its usual
  5130. start and end parentheses. \index{unquote-slicing}
  5131. \begin{figure}[tp]
  5132. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5133. (define (type-check-exp env)
  5134. (lambda (e)
  5135. (define recur (type-check-exp env))
  5136. (match e
  5137. ...
  5138. [(Void) (values (HasType (Void) 'Void) 'Void)]
  5139. [(Prim 'vector es)
  5140. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  5141. (let ([t `(Vector ,@t*)])
  5142. (values (HasType (Prim 'vector e*) t) t))]
  5143. [(Prim 'vector-ref (list e (Int i)))
  5144. (define-values (e^ t) (recur e))
  5145. (match t
  5146. [`(Vector ,ts ...)
  5147. (unless (and (exact-nonnegative-integer? i) (< i (length ts)))
  5148. (error 'type-check-exp "invalid index ~a" i))
  5149. (let ([t (list-ref ts i)])
  5150. (values
  5151. (HasType (Prim 'vector-ref
  5152. (list e^ (HasType (Int i) 'Integer)))
  5153. t)
  5154. t))]
  5155. [else (error "expected a vector in vector-ref, not" t)])]
  5156. [(Prim 'vector-set! (list e (Int i) arg) )
  5157. (define-values (e-vec t-vec) (recur e))
  5158. (define-values (e-arg^ t-arg) (recur arg))
  5159. (match t-vec
  5160. [`(Vector ,ts ...)
  5161. (unless (and (exact-nonnegative-integer? i)
  5162. (i . < . (length ts)))
  5163. (error 'type-check-exp "invalid index ~a" i))
  5164. (unless (type-equal? (list-ref ts i) t-arg)
  5165. (error 'type-check-exp "type mismatch in vector-set! ~a ~a"
  5166. (list-ref ts i) t-arg))
  5167. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  5168. [else (error 'type-check-exp
  5169. "expected a vector in vector-set!, not ~a"
  5170. t-vec)])]
  5171. [(Prim 'vector-length (list e))
  5172. (define-values (e^ t) (recur e))
  5173. (match t
  5174. [`(Vector ,ts ...)
  5175. (values (Prim 'vector-length (list e^)) 'Integer)]
  5176. [else (error 'type-check-exp
  5177. "expected a vector in vector-lenfth, not ~a" t)])]
  5178. [(Prim 'eq? (list e1 e2))
  5179. (define-values (e1^ T1) (recur e1))
  5180. (define-values (e2^ T2) (recur e2))
  5181. (unless (equal? T1 T2)
  5182. (error "arguments of eq? must have the same type, but are not"
  5183. (list T1 T2)))
  5184. (values (HasType (Prim 'eq? (list e1^ e2^)) 'Boolean) 'Boolean)]
  5185. ...
  5186. )))
  5187. \end{lstlisting}
  5188. \caption{Type checker for the $R_3$ language.}
  5189. \label{fig:type-check-R3}
  5190. \end{figure}
  5191. \section{Garbage Collection}
  5192. \label{sec:GC}
  5193. Here we study a relatively simple algorithm for garbage collection
  5194. that is the basis of state-of-the-art garbage
  5195. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  5196. particular, we describe a two-space copying
  5197. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  5198. perform the
  5199. copy~\citep{Cheney:1970aa}.
  5200. \index{copying collector}
  5201. \index{two-space copying collector}
  5202. Figure~\ref{fig:copying-collector} gives a
  5203. coarse-grained depiction of what happens in a two-space collector,
  5204. showing two time steps, prior to garbage collection (on the top) and
  5205. after garbage collection (on the bottom). In a two-space collector,
  5206. the heap is divided into two parts named the FromSpace and the
  5207. ToSpace. Initially, all allocations go to the FromSpace until there is
  5208. not enough room for the next allocation request. At that point, the
  5209. garbage collector goes to work to make more room.
  5210. \index{ToSpace}
  5211. \index{FromSpace}
  5212. The garbage collector must be careful not to reclaim tuples that will
  5213. be used by the program in the future. Of course, it is impossible in
  5214. general to predict what a program will do, but we can over approximate
  5215. the will-be-used tuples by preserving all tuples that could be
  5216. accessed by \emph{any} program given the current computer state. A
  5217. program could access any tuple whose address is in a register or on
  5218. the procedure call stack. These addresses are called the \emph{root
  5219. set}\index{root set}. In addition, a program could access any tuple that is
  5220. transitively reachable from the root set. Thus, it is safe for the
  5221. garbage collector to reclaim the tuples that are not reachable in this
  5222. way.
  5223. So the goal of the garbage collector is twofold:
  5224. \begin{enumerate}
  5225. \item preserve all tuple that are reachable from the root set via a
  5226. path of pointers, that is, the \emph{live} tuples, and
  5227. \item reclaim the memory of everything else, that is, the
  5228. \emph{garbage}.
  5229. \end{enumerate}
  5230. A copying collector accomplishes this by copying all of the live
  5231. objects from the FromSpace into the ToSpace and then performs a slight
  5232. of hand, treating the ToSpace as the new FromSpace and the old
  5233. FromSpace as the new ToSpace. In the example of
  5234. Figure~\ref{fig:copying-collector}, there are three pointers in the
  5235. root set, one in a register and two on the stack. All of the live
  5236. objects have been copied to the ToSpace (the right-hand side of
  5237. Figure~\ref{fig:copying-collector}) in a way that preserves the
  5238. pointer relationships. For example, the pointer in the register still
  5239. points to a 2-tuple whose first element is a 3-tuple and whose second
  5240. element is a 2-tuple. There are four tuples that are not reachable
  5241. from the root set and therefore do not get copied into the ToSpace.
  5242. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  5243. created by a well-typed program in $R_3$ because it contains a
  5244. cycle. However, creating cycles will be possible once we get to $R_6$.
  5245. We design the garbage collector to deal with cycles to begin with so
  5246. we will not need to revisit this issue.
  5247. \begin{figure}[tbp]
  5248. \centering
  5249. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  5250. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  5251. \caption{A copying collector in action.}
  5252. \label{fig:copying-collector}
  5253. \end{figure}
  5254. There are many alternatives to copying collectors (and their bigger
  5255. siblings, the generational collectors) when its comes to garbage
  5256. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  5257. reference counting~\citep{Collins:1960aa}. The strengths of copying
  5258. collectors are that allocation is fast (just a comparison and pointer
  5259. increment), there is no fragmentation, cyclic garbage is collected,
  5260. and the time complexity of collection only depends on the amount of
  5261. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  5262. main disadvantages of a two-space copying collector is that it uses a
  5263. lot of space and takes a long time to perform the copy, though these
  5264. problems are ameliorated in generational collectors. Racket and
  5265. Scheme programs tend to allocate many small objects and generate a lot
  5266. of garbage, so copying and generational collectors are a good fit.
  5267. Garbage collection is an active research topic, especially concurrent
  5268. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  5269. developing new techniques and revisiting old
  5270. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  5271. meet every year at the International Symposium on Memory Management to
  5272. present these findings.
  5273. \subsection{Graph Copying via Cheney's Algorithm}
  5274. \label{sec:cheney}
  5275. \index{Cheney's algorithm}
  5276. Let us take a closer look at the copying of the live objects. The
  5277. allocated objects and pointers can be viewed as a graph and we need to
  5278. copy the part of the graph that is reachable from the root set. To
  5279. make sure we copy all of the reachable vertices in the graph, we need
  5280. an exhaustive graph traversal algorithm, such as depth-first search or
  5281. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  5282. such algorithms take into account the possibility of cycles by marking
  5283. which vertices have already been visited, so as to ensure termination
  5284. of the algorithm. These search algorithms also use a data structure
  5285. such as a stack or queue as a to-do list to keep track of the vertices
  5286. that need to be visited. We use breadth-first search and a trick
  5287. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  5288. and copying tuples into the ToSpace.
  5289. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  5290. copy progresses. The queue is represented by a chunk of contiguous
  5291. memory at the beginning of the ToSpace, using two pointers to track
  5292. the front and the back of the queue. The algorithm starts by copying
  5293. all tuples that are immediately reachable from the root set into the
  5294. ToSpace to form the initial queue. When we copy a tuple, we mark the
  5295. old tuple to indicate that it has been visited. We discuss how this
  5296. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  5297. pointers inside the copied tuples in the queue still point back to the
  5298. FromSpace. Once the initial queue has been created, the algorithm
  5299. enters a loop in which it repeatedly processes the tuple at the front
  5300. of the queue and pops it off the queue. To process a tuple, the
  5301. algorithm copies all the tuple that are directly reachable from it to
  5302. the ToSpace, placing them at the back of the queue. The algorithm then
  5303. updates the pointers in the popped tuple so they point to the newly
  5304. copied tuples.
  5305. \begin{figure}[tbp]
  5306. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  5307. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  5308. \label{fig:cheney}
  5309. \end{figure}
  5310. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  5311. tuple whose second element is $42$ to the back of the queue. The other
  5312. pointer goes to a tuple that has already been copied, so we do not
  5313. need to copy it again, but we do need to update the pointer to the new
  5314. location. This can be accomplished by storing a \emph{forwarding
  5315. pointer} to the new location in the old tuple, back when we initially
  5316. copied the tuple into the ToSpace. This completes one step of the
  5317. algorithm. The algorithm continues in this way until the front of the
  5318. queue is empty, that is, until the front catches up with the back.
  5319. \subsection{Data Representation}
  5320. \label{sec:data-rep-gc}
  5321. The garbage collector places some requirements on the data
  5322. representations used by our compiler. First, the garbage collector
  5323. needs to distinguish between pointers and other kinds of data. There
  5324. are several ways to accomplish this.
  5325. \begin{enumerate}
  5326. \item Attached a tag to each object that identifies what type of
  5327. object it is~\citep{McCarthy:1960dz}.
  5328. \item Store different types of objects in different
  5329. regions~\citep{Steele:1977ab}.
  5330. \item Use type information from the program to either generate
  5331. type-specific code for collecting or to generate tables that can
  5332. guide the
  5333. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  5334. \end{enumerate}
  5335. Dynamically typed languages, such as Lisp, need to tag objects
  5336. anyways, so option 1 is a natural choice for those languages.
  5337. However, $R_3$ is a statically typed language, so it would be
  5338. unfortunate to require tags on every object, especially small and
  5339. pervasive objects like integers and Booleans. Option 3 is the
  5340. best-performing choice for statically typed languages, but comes with
  5341. a relatively high implementation complexity. To keep this chapter
  5342. within a 2-week time budget, we recommend a combination of options 1
  5343. and 2, using separate strategies for the stack and the heap.
  5344. Regarding the stack, we recommend using a separate stack for pointers,
  5345. which we call a \emph{root stack}\index{root stack} (a.k.a. ``shadow
  5346. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  5347. is, when a local variable needs to be spilled and is of type
  5348. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  5349. stack instead of the normal procedure call stack. Furthermore, we
  5350. always spill vector-typed variables if they are live during a call to
  5351. the collector, thereby ensuring that no pointers are in registers
  5352. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  5353. example from Figure~\ref{fig:copying-collector} and contrasts it with
  5354. the data layout using a root stack. The root stack contains the two
  5355. pointers from the regular stack and also the pointer in the second
  5356. register.
  5357. \begin{figure}[tbp]
  5358. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  5359. \caption{Maintaining a root stack to facilitate garbage collection.}
  5360. \label{fig:shadow-stack}
  5361. \end{figure}
  5362. The problem of distinguishing between pointers and other kinds of data
  5363. also arises inside of each tuple on the heap. We solve this problem by
  5364. attaching a tag, an extra 64-bits, to each
  5365. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  5366. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  5367. that we have drawn the bits in a big-endian way, from right-to-left,
  5368. with bit location 0 (the least significant bit) on the far right,
  5369. which corresponds to the direction of the x86 shifting instructions
  5370. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  5371. is dedicated to specifying which elements of the tuple are pointers,
  5372. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  5373. indicates there is a pointer and a 0 bit indicates some other kind of
  5374. data. The pointer mask starts at bit location 7. We have limited
  5375. tuples to a maximum size of 50 elements, so we just need 50 bits for
  5376. the pointer mask. The tag also contains two other pieces of
  5377. information. The length of the tuple (number of elements) is stored in
  5378. bits location 1 through 6. Finally, the bit at location 0 indicates
  5379. whether the tuple has yet to be copied to the ToSpace. If the bit has
  5380. value 1, then this tuple has not yet been copied. If the bit has
  5381. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  5382. of a pointer are always zero anyways because our tuples are 8-byte
  5383. aligned.)
  5384. \begin{figure}[tbp]
  5385. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  5386. \caption{Representation of tuples in the heap.}
  5387. \label{fig:tuple-rep}
  5388. \end{figure}
  5389. \subsection{Implementation of the Garbage Collector}
  5390. \label{sec:organize-gz}
  5391. \index{prelude}
  5392. An implementation of the copying collector is provided in the
  5393. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  5394. interface to the garbage collector that is used by the compiler. The
  5395. \code{initialize} function creates the FromSpace, ToSpace, and root
  5396. stack and should be called in the prelude of the \code{main}
  5397. function. The \code{initialize} function puts the address of the
  5398. beginning of the FromSpace into the global variable
  5399. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  5400. the address that is 1-past the last element of the FromSpace. (We use
  5401. half-open intervals to represent chunks of
  5402. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  5403. points to the first element of the root stack.
  5404. As long as there is room left in the FromSpace, your generated code
  5405. can allocate tuples simply by moving the \code{free\_ptr} forward.
  5406. %
  5407. The amount of room left in FromSpace is the difference between the
  5408. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  5409. function should be called when there is not enough room left in the
  5410. FromSpace for the next allocation. The \code{collect} function takes
  5411. a pointer to the current top of the root stack (one past the last item
  5412. that was pushed) and the number of bytes that need to be
  5413. allocated. The \code{collect} function performs the copying collection
  5414. and leaves the heap in a state such that the next allocation will
  5415. succeed.
  5416. \begin{figure}[tbp]
  5417. \begin{lstlisting}
  5418. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  5419. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  5420. int64_t* free_ptr;
  5421. int64_t* fromspace_begin;
  5422. int64_t* fromspace_end;
  5423. int64_t** rootstack_begin;
  5424. \end{lstlisting}
  5425. \caption{The compiler's interface to the garbage collector.}
  5426. \label{fig:gc-header}
  5427. \end{figure}
  5428. %% \begin{exercise}
  5429. %% In the file \code{runtime.c} you will find the implementation of
  5430. %% \code{initialize} and a partial implementation of \code{collect}.
  5431. %% The \code{collect} function calls another function, \code{cheney},
  5432. %% to perform the actual copy, and that function is left to the reader
  5433. %% to implement. The following is the prototype for \code{cheney}.
  5434. %% \begin{lstlisting}
  5435. %% static void cheney(int64_t** rootstack_ptr);
  5436. %% \end{lstlisting}
  5437. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  5438. %% rootstack (which is an array of pointers). The \code{cheney} function
  5439. %% also communicates with \code{collect} through the global
  5440. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  5441. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  5442. %% the ToSpace:
  5443. %% \begin{lstlisting}
  5444. %% static int64_t* tospace_begin;
  5445. %% static int64_t* tospace_end;
  5446. %% \end{lstlisting}
  5447. %% The job of the \code{cheney} function is to copy all the live
  5448. %% objects (reachable from the root stack) into the ToSpace, update
  5449. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  5450. %% update the root stack so that it points to the objects in the
  5451. %% ToSpace, and finally to swap the global pointers for the FromSpace
  5452. %% and ToSpace.
  5453. %% \end{exercise}
  5454. %% \section{Compiler Passes}
  5455. %% \label{sec:code-generation-gc}
  5456. The introduction of garbage collection has a non-trivial impact on our
  5457. compiler passes. We introduce two new compiler passes named
  5458. \code{expose-allocation} and \code{uncover-locals}. We make
  5459. significant changes to \code{select-instructions},
  5460. \code{build-interference}, \code{allocate-registers}, and
  5461. \code{print-x86} and make minor changes in severl more passes. The
  5462. following program will serve as our running example. It creates two
  5463. tuples, one nested inside the other. Both tuples have length one. The
  5464. program accesses the element in the inner tuple tuple via two vector
  5465. references.
  5466. % tests/s2_17.rkt
  5467. \begin{lstlisting}
  5468. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  5469. \end{lstlisting}
  5470. \section{Shrink}
  5471. \label{sec:shrink-R3}
  5472. Recall that the \code{shrink} pass translates the primitives operators
  5473. into a smaller set of primitives. Because this pass comes after type
  5474. checking, but before the passes that require the type information in
  5475. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  5476. to wrap \code{HasType} around each AST node that it generates.
  5477. \section{Expose Allocation}
  5478. \label{sec:expose-allocation}
  5479. The pass \code{expose-allocation} lowers the \code{vector} creation
  5480. form into a conditional call to the collector followed by the
  5481. allocation. We choose to place the \code{expose-allocation} pass
  5482. before \code{remove-complex-opera*} because the code generated by
  5483. \code{expose-allocation} contains complex operands. We also place
  5484. \code{expose-allocation} before \code{explicate-control} because
  5485. \code{expose-allocation} introduces new variables using \code{let},
  5486. but \code{let} is gone after \code{explicate-control}.
  5487. The output of \code{expose-allocation} is a language $R'_3$ that
  5488. extends $R_3$ with the three new forms that we use in the translation
  5489. of the \code{vector} form.
  5490. \[
  5491. \begin{array}{lcl}
  5492. \Exp &::=& \cdots
  5493. \mid (\key{collect} \,\itm{int})
  5494. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  5495. \mid (\key{global-value} \,\itm{name})
  5496. \end{array}
  5497. \]
  5498. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  5499. $n$ bytes. It will become a call to the \code{collect} function in
  5500. \code{runtime.c} in \code{select-instructions}. The
  5501. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  5502. \index{allocate}
  5503. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  5504. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  5505. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  5506. a global variable, such as \code{free\_ptr}.
  5507. In the following, we show the transformation for the \code{vector}
  5508. form into 1) a sequence of let-bindings for the initializing
  5509. expressions, 2) a conditional call to \code{collect}, 3) a call to
  5510. \code{allocate}, and 4) the initialization of the vector. In the
  5511. following, \itm{len} refers to the length of the vector and
  5512. \itm{bytes} is how many total bytes need to be allocated for the
  5513. vector, which is 8 for the tag plus \itm{len} times 8.
  5514. \begin{lstlisting}
  5515. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  5516. |$\Longrightarrow$|
  5517. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  5518. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  5519. (global-value fromspace_end))
  5520. (void)
  5521. (collect |\itm{bytes}|))])
  5522. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  5523. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  5524. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  5525. |$v$|) ... )))) ...)
  5526. \end{lstlisting}
  5527. In the above, we suppressed all of the \code{has-type} forms in the
  5528. output for the sake of readability. The placement of the initializing
  5529. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  5530. sequence of \code{vector-set!} is important, as those expressions may
  5531. trigger garbage collection and we cannot have an allocated but
  5532. uninitialized tuple on the heap during a collection.
  5533. Figure~\ref{fig:expose-alloc-output} shows the output of the
  5534. \code{expose-allocation} pass on our running example.
  5535. \begin{figure}[tbp]
  5536. % tests/s2_17.rkt
  5537. \begin{lstlisting}
  5538. (vector-ref
  5539. (vector-ref
  5540. (let ([vecinit7976
  5541. (let ([vecinit7972 42])
  5542. (let ([collectret7974
  5543. (if (< (+ (global-value free_ptr) 16)
  5544. (global-value fromspace_end))
  5545. (void)
  5546. (collect 16)
  5547. )])
  5548. (let ([alloc7971 (allocate 1 (Vector Integer))])
  5549. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  5550. alloc7971)
  5551. )
  5552. )
  5553. )
  5554. ])
  5555. (let ([collectret7978
  5556. (if (< (+ (global-value free_ptr) 16)
  5557. (global-value fromspace_end))
  5558. (void)
  5559. (collect 16)
  5560. )])
  5561. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  5562. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  5563. alloc7975)
  5564. )
  5565. )
  5566. )
  5567. 0)
  5568. 0)
  5569. \end{lstlisting}
  5570. \caption{Output of the \code{expose-allocation} pass, minus
  5571. all of the \code{has-type} forms.}
  5572. \label{fig:expose-alloc-output}
  5573. \end{figure}
  5574. \section{Remove Complex Operands}
  5575. \label{sec:remove-complex-opera-R3}
  5576. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  5577. should all be treated as complex operands. A new case for
  5578. \code{HasType} is needed and the case for \code{Prim} needs to be
  5579. handled carefully to prevent the \code{Prim} node from being separated
  5580. from its enclosing \code{HasType}.
  5581. \section{Explicate Control and the $C_2$ language}
  5582. \label{sec:explicate-control-r3}
  5583. \begin{figure}[tbp]
  5584. \fbox{
  5585. \begin{minipage}{0.96\textwidth}
  5586. \small
  5587. \[
  5588. \begin{array}{lcl}
  5589. \Atm &::=& \gray{ \Int \mid \Var \mid \itm{bool} } \\
  5590. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5591. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  5592. &\mid& \gray{ \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP } \\
  5593. &\mid& \LP \key{allocate}~\Int~\Type \RP \\
  5594. &\mid& (\key{vector-ref}\;\Atm\;\Int) \mid (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  5595. &\mid& \LP \key{global-value}~\Var \RP \mid \LP \key{void} \RP \\
  5596. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \mid \LP\key{collect}~\Int \RP\\
  5597. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  5598. \mid \gray{ \key{goto}~\itm{label}\key{;} }\\
  5599. &\mid& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  5600. C_2 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  5601. \end{array}
  5602. \]
  5603. \end{minipage}
  5604. }
  5605. \caption{The concrete syntax of the $C_2$ intermediate language.}
  5606. \label{fig:c2-concrete-syntax}
  5607. \end{figure}
  5608. \begin{figure}[tp]
  5609. \fbox{
  5610. \begin{minipage}{0.96\textwidth}
  5611. \small
  5612. \[
  5613. \begin{array}{lcl}
  5614. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  5615. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5616. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  5617. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  5618. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  5619. &\mid& (\key{Allocate} \,\itm{int}\,\itm{type}) \\
  5620. &\mid& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  5621. &\mid& (\key{Prim}~\key{'vector-set!}\,(\key{list}\,\Atm\,\INT{\Int}\,\Atm))\\
  5622. &\mid& (\key{GlobalValue} \,\Var) \mid (\key{Void})\\
  5623. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  5624. \mid (\key{Collect} \,\itm{int}) \\
  5625. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  5626. \mid \GOTO{\itm{label}} } \\
  5627. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  5628. C_2 & ::= & \gray{ \PROGRAM{\itm{info}}{\CFG{(\itm{label}\,\key{.}\,\Tail)\ldots}} }
  5629. \end{array}
  5630. \]
  5631. \end{minipage}
  5632. }
  5633. \caption{The abstract syntax of $C_2$, extending $C_1$
  5634. (Figure~\ref{fig:c1-syntax}).}
  5635. \label{fig:c2-syntax}
  5636. \end{figure}
  5637. The output of \code{explicate-control} is a program in the
  5638. intermediate language $C_2$, whose concrete syntax is defined in
  5639. Figure~\ref{fig:c2-concrete-syntax} and whose abstract syntax is
  5640. defined in Figure~\ref{fig:c2-syntax}. The new forms of $C_2$ include
  5641. the \key{allocate}, \key{vector-ref}, and \key{vector-set!}, and
  5642. \key{global-value} expressions and the \code{collect} statement. The
  5643. \code{explicate-control} pass can treat these new forms much like the
  5644. other forms.
  5645. \section{Uncover Locals}
  5646. \label{sec:uncover-locals-r3}
  5647. Recall that the \code{explicate-control} function collects all of the
  5648. local variables so that it can store them in the $\itm{info}$ field of
  5649. the \code{Program} structure. Also recall that we need to know the
  5650. types of all the local variables for purposes of identifying the root
  5651. set for the garbage collector. Thus, we create a pass named
  5652. \code{uncover-locals} to collect not just the variables but the
  5653. variables and their types in the form of an alist. Thanks to the
  5654. \code{HasType} nodes, the types are readily available at every
  5655. assignment to a variable. We recommend storing the resulting alist in
  5656. the $\itm{info}$ field of the program, associated with the
  5657. \code{locals} key. Figure~\ref{fig:uncover-locals-r3} lists the output
  5658. of the \code{uncover-locals} pass on the running example.
  5659. \begin{figure}[tbp]
  5660. % tests/s2_17.rkt
  5661. \begin{lstlisting}
  5662. locals:
  5663. vecinit7976 : '(Vector Integer), tmp7980 : 'Integer,
  5664. alloc7975 : '(Vector (Vector Integer)), tmp7983 : 'Integer,
  5665. collectret7974 : 'Void, initret7977 : 'Void,
  5666. collectret7978 : 'Void, tmp7985 : '(Vector Integer),
  5667. tmp7984 : 'Integer, tmp7979 : 'Integer, tmp7982 : 'Integer,
  5668. alloc7971 : '(Vector Integer), tmp7981 : 'Integer,
  5669. vecinit7972 : 'Integer, initret7973 : 'Void,
  5670. block91:
  5671. (collect 16)
  5672. goto block89;
  5673. block90:
  5674. collectret7974 = (void);
  5675. goto block89;
  5676. block89:
  5677. alloc7971 = (allocate 1 (Vector Integer));
  5678. initret7973 = (vector-set! alloc7971 0 vecinit7972);
  5679. vecinit7976 = alloc7971;
  5680. tmp7982 = (global-value free_ptr);
  5681. tmp7983 = (+ tmp7982 16);
  5682. tmp7984 = (global-value fromspace_end);
  5683. if (< tmp7983 tmp7984) then
  5684. goto block87;
  5685. else
  5686. goto block88;
  5687. block88:
  5688. (collect 16)
  5689. goto block86;
  5690. block87:
  5691. collectret7978 = (void);
  5692. goto block86;
  5693. block86:
  5694. alloc7975 = (allocate 1 (Vector (Vector Integer)));
  5695. initret7977 = (vector-set! alloc7975 0 vecinit7976);
  5696. tmp7985 = (vector-ref alloc7975 0);
  5697. return (vector-ref tmp7985 0);
  5698. start:
  5699. vecinit7972 = 42;
  5700. tmp7979 = (global-value free_ptr);
  5701. tmp7980 = (+ tmp7979 16);
  5702. tmp7981 = (global-value fromspace_end);
  5703. if (< tmp7980 tmp7981) then
  5704. goto block90;
  5705. else
  5706. goto block91;
  5707. \end{lstlisting}
  5708. \caption{Output of \code{uncover-locals} for the running example.}
  5709. \label{fig:uncover-locals-r3}
  5710. \end{figure}
  5711. \clearpage
  5712. \section{Select Instructions and the x86$_2$ Language}
  5713. \label{sec:select-instructions-gc}
  5714. \index{instruction selection}
  5715. %% void (rep as zero)
  5716. %% allocate
  5717. %% collect (callq collect)
  5718. %% vector-ref
  5719. %% vector-set!
  5720. %% global (postpone)
  5721. In this pass we generate x86 code for most of the new operations that
  5722. were needed to compile tuples, including \code{Allocate},
  5723. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  5724. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  5725. the later has a different concrete syntax (see
  5726. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  5727. \index{x86}
  5728. The \code{vector-ref} and \code{vector-set!} forms translate into
  5729. \code{movq} instructions. (The plus one in the offset is to get past
  5730. the tag at the beginning of the tuple representation.)
  5731. \begin{lstlisting}
  5732. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  5733. |$\Longrightarrow$|
  5734. movq |$\itm{vec}'$|, %r11
  5735. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  5736. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  5737. |$\Longrightarrow$|
  5738. movq |$\itm{vec}'$|, %r11
  5739. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  5740. movq $0, |$\itm{lhs'}$|
  5741. \end{lstlisting}
  5742. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  5743. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  5744. register \code{r11} ensures that offset expression
  5745. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  5746. removing \code{r11} from consideration by the register allocating.
  5747. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  5748. \code{rax}. Then the generated code for \code{vector-set!} would be
  5749. \begin{lstlisting}
  5750. movq |$\itm{vec}'$|, %rax
  5751. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  5752. movq $0, |$\itm{lhs}'$|
  5753. \end{lstlisting}
  5754. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  5755. \code{patch-instructions} would insert a move through \code{rax}
  5756. as follows.
  5757. \begin{lstlisting}
  5758. movq |$\itm{vec}'$|, %rax
  5759. movq |$\itm{arg}'$|, %rax
  5760. movq %rax, |$8(n+1)$|(%rax)
  5761. movq $0, |$\itm{lhs}'$|
  5762. \end{lstlisting}
  5763. But the above sequence of instructions does not work because we're
  5764. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  5765. $\itm{arg}'$) at the same time!
  5766. We compile the \code{allocate} form to operations on the
  5767. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  5768. is the next free address in the FromSpace, so we copy it into
  5769. \code{r11} and then move it forward by enough space for the tuple
  5770. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  5771. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  5772. initialize the \itm{tag} and finally copy the address in \code{r11} to
  5773. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  5774. tag is organized. We recommend using the Racket operations
  5775. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  5776. during compilation. The type annotation in the \code{vector} form is
  5777. used to determine the pointer mask region of the tag.
  5778. \begin{lstlisting}
  5779. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  5780. |$\Longrightarrow$|
  5781. movq free_ptr(%rip), %r11
  5782. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  5783. movq $|$\itm{tag}$|, 0(%r11)
  5784. movq %r11, |$\itm{lhs}'$|
  5785. \end{lstlisting}
  5786. The \code{collect} form is compiled to a call to the \code{collect}
  5787. function in the runtime. The arguments to \code{collect} are 1) the
  5788. top of the root stack and 2) the number of bytes that need to be
  5789. allocated. We use another dedicated register, \code{r15}, to
  5790. store the pointer to the top of the root stack. So \code{r15} is not
  5791. available for use by the register allocator.
  5792. \begin{lstlisting}
  5793. (collect |$\itm{bytes}$|)
  5794. |$\Longrightarrow$|
  5795. movq %r15, %rdi
  5796. movq $|\itm{bytes}|, %rsi
  5797. callq collect
  5798. \end{lstlisting}
  5799. \begin{figure}[tp]
  5800. \fbox{
  5801. \begin{minipage}{0.96\textwidth}
  5802. \[
  5803. \begin{array}{lcl}
  5804. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)} \\
  5805. x86_1 &::= & \gray{ \key{.globl main} }\\
  5806. & & \gray{ \key{main:} \; \Instr\ldots }
  5807. \end{array}
  5808. \]
  5809. \end{minipage}
  5810. }
  5811. \caption{The concrete syntax of x86$_2$ (extends x86$_1$ of Figure~\ref{fig:x86-1-concrete}).}
  5812. \label{fig:x86-2-concrete}
  5813. \end{figure}
  5814. \begin{figure}[tp]
  5815. \fbox{
  5816. \begin{minipage}{0.96\textwidth}
  5817. \small
  5818. \[
  5819. \begin{array}{lcl}
  5820. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  5821. \mid \BYTEREG{\Reg}} \\
  5822. &\mid& (\key{Global}~\Var) \\
  5823. x86_2 &::= & \gray{ \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}} }
  5824. \end{array}
  5825. \]
  5826. \end{minipage}
  5827. }
  5828. \caption{The abstract syntax of x86$_2$ (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  5829. \label{fig:x86-2}
  5830. \end{figure}
  5831. The concrete and abstract syntax of the $x86_2$ language is defined in
  5832. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It differs from
  5833. x86$_1$ just in the addition of the form for global variables.
  5834. %
  5835. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  5836. \code{select-instructions} pass on the running example.
  5837. \begin{figure}[tbp]
  5838. \centering
  5839. % tests/s2_17.rkt
  5840. \begin{minipage}[t]{0.5\textwidth}
  5841. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5842. block35:
  5843. movq free_ptr(%rip), alloc9024
  5844. addq $16, free_ptr(%rip)
  5845. movq alloc9024, %r11
  5846. movq $131, 0(%r11)
  5847. movq alloc9024, %r11
  5848. movq vecinit9025, 8(%r11)
  5849. movq $0, initret9026
  5850. movq alloc9024, %r11
  5851. movq 8(%r11), tmp9034
  5852. movq tmp9034, %r11
  5853. movq 8(%r11), %rax
  5854. jmp conclusion
  5855. block36:
  5856. movq $0, collectret9027
  5857. jmp block35
  5858. block38:
  5859. movq free_ptr(%rip), alloc9020
  5860. addq $16, free_ptr(%rip)
  5861. movq alloc9020, %r11
  5862. movq $3, 0(%r11)
  5863. movq alloc9020, %r11
  5864. movq vecinit9021, 8(%r11)
  5865. movq $0, initret9022
  5866. movq alloc9020, vecinit9025
  5867. movq free_ptr(%rip), tmp9031
  5868. movq tmp9031, tmp9032
  5869. addq $16, tmp9032
  5870. movq fromspace_end(%rip), tmp9033
  5871. cmpq tmp9033, tmp9032
  5872. jl block36
  5873. jmp block37
  5874. block37:
  5875. movq %r15, %rdi
  5876. movq $16, %rsi
  5877. callq 'collect
  5878. jmp block35
  5879. block39:
  5880. movq $0, collectret9023
  5881. jmp block38
  5882. \end{lstlisting}
  5883. \end{minipage}
  5884. \begin{minipage}[t]{0.45\textwidth}
  5885. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5886. start:
  5887. movq $42, vecinit9021
  5888. movq free_ptr(%rip), tmp9028
  5889. movq tmp9028, tmp9029
  5890. addq $16, tmp9029
  5891. movq fromspace_end(%rip), tmp9030
  5892. cmpq tmp9030, tmp9029
  5893. jl block39
  5894. jmp block40
  5895. block40:
  5896. movq %r15, %rdi
  5897. movq $16, %rsi
  5898. callq 'collect
  5899. jmp block38
  5900. \end{lstlisting}
  5901. \end{minipage}
  5902. \caption{Output of the \code{select-instructions} pass.}
  5903. \label{fig:select-instr-output-gc}
  5904. \end{figure}
  5905. \clearpage
  5906. \section{Register Allocation}
  5907. \label{sec:reg-alloc-gc}
  5908. \index{register allocation}
  5909. As discussed earlier in this chapter, the garbage collector needs to
  5910. access all the pointers in the root set, that is, all variables that
  5911. are vectors. It will be the responsibility of the register allocator
  5912. to make sure that:
  5913. \begin{enumerate}
  5914. \item the root stack is used for spilling vector-typed variables, and
  5915. \item if a vector-typed variable is live during a call to the
  5916. collector, it must be spilled to ensure it is visible to the
  5917. collector.
  5918. \end{enumerate}
  5919. The later responsibility can be handled during construction of the
  5920. interference graph, by adding interference edges between the call-live
  5921. vector-typed variables and all the callee-saved registers. (They
  5922. already interfere with the caller-saved registers.) The type
  5923. information for variables is in the \code{Program} form, so we
  5924. recommend adding another parameter to the \code{build-interference}
  5925. function to communicate this alist.
  5926. The spilling of vector-typed variables to the root stack can be
  5927. handled after graph coloring, when choosing how to assign the colors
  5928. (integers) to registers and stack locations. The \code{Program} output
  5929. of this pass changes to also record the number of spills to the root
  5930. stack.
  5931. % build-interference
  5932. %
  5933. % callq
  5934. % extra parameter for var->type assoc. list
  5935. % update 'program' and 'if'
  5936. % allocate-registers
  5937. % allocate spilled vectors to the rootstack
  5938. % don't change color-graph
  5939. \section{Print x86}
  5940. \label{sec:print-x86-gc}
  5941. \index{prelude}\index{conclusion}
  5942. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  5943. \code{print-x86} pass on the running example. In the prelude and
  5944. conclusion of the \code{main} function, we treat the root stack very
  5945. much like the regular stack in that we move the root stack pointer
  5946. (\code{r15}) to make room for the spills to the root stack, except
  5947. that the root stack grows up instead of down. For the running
  5948. example, there was just one spill so we increment \code{r15} by 8
  5949. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  5950. One issue that deserves special care is that there may be a call to
  5951. \code{collect} prior to the initializing assignments for all the
  5952. variables in the root stack. We do not want the garbage collector to
  5953. accidentally think that some uninitialized variable is a pointer that
  5954. needs to be followed. Thus, we zero-out all locations on the root
  5955. stack in the prelude of \code{main}. In
  5956. Figure~\ref{fig:print-x86-output-gc}, the instruction
  5957. %
  5958. \lstinline{movq $0, (%r15)}
  5959. %
  5960. accomplishes this task. The garbage collector tests each root to see
  5961. if it is null prior to dereferencing it.
  5962. \begin{figure}[htbp]
  5963. \begin{minipage}[t]{0.5\textwidth}
  5964. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5965. block35:
  5966. movq free_ptr(%rip), %rcx
  5967. addq $16, free_ptr(%rip)
  5968. movq %rcx, %r11
  5969. movq $131, 0(%r11)
  5970. movq %rcx, %r11
  5971. movq -8(%r15), %rax
  5972. movq %rax, 8(%r11)
  5973. movq $0, %rdx
  5974. movq %rcx, %r11
  5975. movq 8(%r11), %rcx
  5976. movq %rcx, %r11
  5977. movq 8(%r11), %rax
  5978. jmp conclusion
  5979. block36:
  5980. movq $0, %rcx
  5981. jmp block35
  5982. block38:
  5983. movq free_ptr(%rip), %rcx
  5984. addq $16, free_ptr(%rip)
  5985. movq %rcx, %r11
  5986. movq $3, 0(%r11)
  5987. movq %rcx, %r11
  5988. movq %rbx, 8(%r11)
  5989. movq $0, %rdx
  5990. movq %rcx, -8(%r15)
  5991. movq free_ptr(%rip), %rcx
  5992. addq $16, %rcx
  5993. movq fromspace_end(%rip), %rdx
  5994. cmpq %rdx, %rcx
  5995. jl block36
  5996. movq %r15, %rdi
  5997. movq $16, %rsi
  5998. callq collect
  5999. jmp block35
  6000. block39:
  6001. movq $0, %rcx
  6002. jmp block38
  6003. \end{lstlisting}
  6004. \end{minipage}
  6005. \begin{minipage}[t]{0.45\textwidth}
  6006. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6007. start:
  6008. movq $42, %rbx
  6009. movq free_ptr(%rip), %rdx
  6010. addq $16, %rdx
  6011. movq fromspace_end(%rip), %rcx
  6012. cmpq %rcx, %rdx
  6013. jl block39
  6014. movq %r15, %rdi
  6015. movq $16, %rsi
  6016. callq collect
  6017. jmp block38
  6018. .globl main
  6019. main:
  6020. pushq %rbp
  6021. movq %rsp, %rbp
  6022. pushq %r13
  6023. pushq %r12
  6024. pushq %rbx
  6025. pushq %r14
  6026. subq $0, %rsp
  6027. movq $16384, %rdi
  6028. movq $16, %rsi
  6029. callq initialize
  6030. movq rootstack_begin(%rip), %r15
  6031. movq $0, (%r15)
  6032. addq $8, %r15
  6033. jmp start
  6034. conclusion:
  6035. subq $8, %r15
  6036. addq $0, %rsp
  6037. popq %r14
  6038. popq %rbx
  6039. popq %r12
  6040. popq %r13
  6041. popq %rbp
  6042. retq
  6043. \end{lstlisting}
  6044. \end{minipage}
  6045. \caption{Output of the \code{print-x86} pass.}
  6046. \label{fig:print-x86-output-gc}
  6047. \end{figure}
  6048. \begin{figure}[p]
  6049. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6050. \node (R3) at (0,2) {\large $R_3$};
  6051. \node (R3-2) at (3,2) {\large $R_3$};
  6052. \node (R3-3) at (6,2) {\large $R_3$};
  6053. \node (R3-4) at (9,2) {\large $R_3$};
  6054. \node (R3-5) at (9,0) {\large $R'_3$};
  6055. \node (R3-6) at (6,0) {\large $R'_3$};
  6056. \node (C2-4) at (3,-2) {\large $C_2$};
  6057. \node (C2-3) at (0,-2) {\large $C_2$};
  6058. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_2$};
  6059. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_2$};
  6060. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_2$};
  6061. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_2$};
  6062. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_2$};
  6063. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_2$};
  6064. \path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize\color{red} type-check} (R3-2);
  6065. \path[->,bend left=15] (R3-2) edge [above] node {\ttfamily\footnotesize shrink} (R3-3);
  6066. \path[->,bend left=15] (R3-3) edge [above] node {\ttfamily\footnotesize uniquify} (R3-4);
  6067. \path[->,bend left=15] (R3-4) edge [right] node {\ttfamily\footnotesize\color{red} expose-alloc.} (R3-5);
  6068. \path[->,bend left=15] (R3-5) edge [below] node {\ttfamily\footnotesize remove-complex.} (R3-6);
  6069. \path[->,bend right=20] (R3-6) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-3);
  6070. \path[->,bend right=15] (C2-3) edge [below] node {\ttfamily\footnotesize\color{red} uncover-locals} (C2-4);
  6071. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  6072. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6073. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  6074. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  6075. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  6076. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  6077. \end{tikzpicture}
  6078. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  6079. \label{fig:R3-passes}
  6080. \end{figure}
  6081. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  6082. for the compilation of $R_3$.
  6083. \section{Challenge: Simple Structures}
  6084. \label{sec:simple-structures}
  6085. \index{struct}
  6086. \index{structure}
  6087. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  6088. $R^s_3$, which extends $R^3$ with support for simple structures.
  6089. Recall that a \code{struct} in Typed Racket is a user-defined data
  6090. type that contains named fields and that is heap allocated, similar to
  6091. a vector. The following is an example of a structure definition, in
  6092. this case the definition of a \code{point} type.
  6093. \begin{lstlisting}
  6094. (struct point ([x : Integer] [y : Integer]) #:mutable)
  6095. \end{lstlisting}
  6096. \begin{figure}[tbp]
  6097. \centering
  6098. \fbox{
  6099. \begin{minipage}{0.96\textwidth}
  6100. \[
  6101. \begin{array}{lcl}
  6102. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6103. \mid (\key{Vector}\;\Type \ldots) \mid \key{Void} } \mid \Var \\
  6104. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6105. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  6106. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  6107. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6108. \mid (\key{and}\;\Exp\;\Exp)
  6109. \mid (\key{or}\;\Exp\;\Exp)
  6110. \mid (\key{not}\;\Exp) } \\
  6111. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  6112. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  6113. &\mid& \gray{ (\key{vector}\;\Exp \ldots)
  6114. \mid (\key{vector-ref}\;\Exp\;\Int) } \\
  6115. &\mid& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  6116. &\mid& \gray{ (\key{void}) } \mid (\Var\;\Exp \ldots)\\
  6117. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  6118. R_3 &::=& \Def \ldots \; \Exp
  6119. \end{array}
  6120. \]
  6121. \end{minipage}
  6122. }
  6123. \caption{The concrete syntax of $R^s_3$, extending $R_3$
  6124. (Figure~\ref{fig:r3-concrete-syntax}).}
  6125. \label{fig:r3s-concrete-syntax}
  6126. \end{figure}
  6127. An instance of a structure is created using function call syntax, with
  6128. the name of the structure in the function position:
  6129. \begin{lstlisting}
  6130. (point 7 12)
  6131. \end{lstlisting}
  6132. Function-call syntax is also used to read the value in a field of a
  6133. structure. The function name is formed by the structure name, a dash,
  6134. and the field name. The following example uses \code{point-x} and
  6135. \code{point-y} to access the \code{x} and \code{y} fields of two point
  6136. instances.
  6137. \begin{center}
  6138. \begin{lstlisting}
  6139. (let ([pt1 (point 7 12)])
  6140. (let ([pt2 (point 4 3)])
  6141. (+ (- (point-x pt1) (point-x pt2))
  6142. (- (point-y pt1) (point-y pt2)))))
  6143. \end{lstlisting}
  6144. \end{center}
  6145. Similarly, to write to a field of a structure, use its set function,
  6146. whose name starts with \code{set-}, followed by the structure name,
  6147. then a dash, then the field name, and conclused with an exclamation
  6148. mark. The folowing example uses \code{set-point-x!} to change the
  6149. \code{x} field from \code{7} to \code{42}.
  6150. \begin{center}
  6151. \begin{lstlisting}
  6152. (let ([pt (point 7 12)])
  6153. (let ([_ (set-point-x! pt 42)])
  6154. (point-x pt)))
  6155. \end{lstlisting}
  6156. \end{center}
  6157. \begin{exercise}\normalfont
  6158. Extend your compiler with support for simple structures, compiling
  6159. $R^s_3$ to x86 assembly code. Create five new test cases that use
  6160. structures and test your compiler.
  6161. \end{exercise}
  6162. \section{Challenge: Generational Collection}
  6163. The copying collector described in Section~\ref{sec:GC} can incur
  6164. significant runtime overhead because the call to \code{collect} takes
  6165. time proportional to all of the live data. One way to reduce this
  6166. overhead is to reduce how much data is inspected in each call to
  6167. \code{collect}. In particular, researchers have observed that recently
  6168. allocated data is more likely to become garbage then data that has
  6169. survived one or more previous calls to \code{collect}. This insight
  6170. motivated the creation of \emph{generational garbage collectors}
  6171. \index{generational garbage collector} that
  6172. 1) segragates data according to its age into two or more generations,
  6173. 2) allocates less space for younger generations, so collecting them is
  6174. faster, and more space for the older generations, and 3) performs
  6175. collection on the younger generations more frequently then for older
  6176. generations~\citep{Wilson:1992fk}.
  6177. For this challenge assignment, the goal is to adapt the copying
  6178. collector implemented in \code{runtime.c} to use two generations, one
  6179. for young data and one for old data. Each generation consists of a
  6180. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  6181. \code{collect} function to use the two generations.
  6182. \begin{enumerate}
  6183. \item Copy the young generation's FromSpace to its ToSpace then switch
  6184. the role of the ToSpace and FromSpace
  6185. \item If there is enough space for the requested number of bytes in
  6186. the young FromSpace, then return from \code{collect}.
  6187. \item If there is not enough space in the young FromSpace for the
  6188. requested bytes, then move the data from the young generation to the
  6189. old one with the following steps:
  6190. \begin{enumerate}
  6191. \item If there is enough room in the old FromSpace, copy the young
  6192. FromSpace to the old FromSpace and then return.
  6193. \item If there is not enough room in the old FromSpace, then collect
  6194. the old generation by copying the old FromSpace to the old ToSpace
  6195. and swap the roles of the old FromSpace and ToSpace.
  6196. \item If there is enough room now, copy the young FromSpace to the
  6197. old FromSpace and return. Otherwise, allocate a larger FromSpace
  6198. and ToSpace for the old generation. Copy the young FromSpace and
  6199. the old FromSpace into the larger FromSpace for the old
  6200. generation and then return.
  6201. \end{enumerate}
  6202. \end{enumerate}
  6203. We recommend that you generalize the \code{cheney} function so that it
  6204. can be used for all the copies mentioned above: between the young
  6205. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  6206. between the young FromSpace and old FromSpace. This can be
  6207. accomplished by adding parameters to \code{cheney} that replace its
  6208. use of the global variables \code{fromspace\_begin},
  6209. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  6210. Note that the collection of the young generation does not traverse the
  6211. old generation. This introduces a potential problem: there may be
  6212. young data that is only reachable through pointers in the old
  6213. generation. If these pointers are not taken into account, the
  6214. collector could throw away young data that is live! One solution,
  6215. called \emph{pointer recording}, is to maintain a set of all the
  6216. pointers from the old generation into the new generation and consider
  6217. this set as part of the root set. To maintain this set, the compiler
  6218. must insert extra instructions around every \code{vector-set!}. If the
  6219. vector being modified is in the old generation, and if the value being
  6220. written is a pointer into the new generation, than that pointer must
  6221. be added to the set. Also, if the value being overwritten was a
  6222. pointer into the new generation, then that pointer should be removed
  6223. from the set.
  6224. \begin{exercise}\normalfont
  6225. Adapt the \code{collect} function in \code{runtime.c} to implement
  6226. generational garbage collection, as outlined in this section.
  6227. Update the code generation for \code{vector-set!} to implement
  6228. pointer recording. Make sure that your new compiler and runtime
  6229. passes your test suite.
  6230. \end{exercise}
  6231. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6232. \chapter{Functions}
  6233. \label{ch:functions}
  6234. \index{function}
  6235. This chapter studies the compilation of functions similar to those
  6236. found in the C language. This corresponds to a subset of Typed Racket
  6237. in which only top-level function definitions are allowed. This kind of
  6238. function is an important stepping stone to implementing
  6239. lexically-scoped functions, that is, \key{lambda} abstractions, which
  6240. is the topic of Chapter~\ref{ch:lambdas}.
  6241. \section{The $R_4$ Language}
  6242. The concrete and abstract syntax for function definitions and function
  6243. application is shown in Figures~\ref{fig:r4-concrete-syntax} and
  6244. \ref{fig:r4-syntax}, where we define the $R_4$ language. Programs in
  6245. $R_4$ begin with zero or more function definitions. The function
  6246. names from these definitions are in-scope for the entire program,
  6247. including all other function definitions (so the ordering of function
  6248. definitions does not matter). The concrete syntax for function
  6249. application\index{function application} is $(\Exp \; \Exp \ldots)$
  6250. where the first expression must
  6251. evaluate to a function and the rest are the arguments.
  6252. The abstract syntax for function application is
  6253. $\APPLY{\Exp}{\Exp\ldots}$.
  6254. %% The syntax for function application does not include an explicit
  6255. %% keyword, which is error prone when using \code{match}. To alleviate
  6256. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  6257. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  6258. Functions are first-class in the sense that a function pointer
  6259. \index{function pointer} is data and can be stored in memory or passed
  6260. as a parameter to another function. Thus, we introduce a function
  6261. type, written
  6262. \begin{lstlisting}
  6263. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  6264. \end{lstlisting}
  6265. for a function whose $n$ parameters have the types $\Type_1$ through
  6266. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  6267. these functions (with respect to Racket functions) is that they are
  6268. not lexically scoped. That is, the only external entities that can be
  6269. referenced from inside a function body are other globally-defined
  6270. functions. The syntax of $R_4$ prevents functions from being nested
  6271. inside each other.
  6272. \begin{figure}[tp]
  6273. \centering
  6274. \fbox{
  6275. \begin{minipage}{0.96\textwidth}
  6276. \small
  6277. \[
  6278. \begin{array}{lcl}
  6279. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  6280. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void} } \mid (\Type \ldots \; \key{->}\; \Type) \\
  6281. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6282. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  6283. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  6284. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6285. \mid (\key{and}\;\Exp\;\Exp)
  6286. \mid (\key{or}\;\Exp\;\Exp)
  6287. \mid (\key{not}\;\Exp)} \\
  6288. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  6289. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  6290. (\key{vector-ref}\;\Exp\;\Int)} \\
  6291. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  6292. \mid \LP\key{has-type}~\Exp~\Type\RP } \\
  6293. &\mid& \LP\Exp \; \Exp \ldots\RP \\
  6294. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  6295. R_4 &::=& \Def \ldots \; \Exp
  6296. \end{array}
  6297. \]
  6298. \end{minipage}
  6299. }
  6300. \caption{The concrete syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-concrete-syntax}).}
  6301. \label{fig:r4-concrete-syntax}
  6302. \end{figure}
  6303. \begin{figure}[tp]
  6304. \centering
  6305. \fbox{
  6306. \begin{minipage}{0.96\textwidth}
  6307. \small
  6308. \[
  6309. \begin{array}{lcl}
  6310. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6311. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  6312. &\mid& \gray{ \BOOL{\itm{bool}}
  6313. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6314. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP }
  6315. \mid \APPLY{\Exp}{\Exp\ldots}\\
  6316. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}\\
  6317. R_4 &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  6318. \end{array}
  6319. \]
  6320. \end{minipage}
  6321. }
  6322. \caption{The abstract syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-syntax}).}
  6323. \label{fig:r4-syntax}
  6324. \end{figure}
  6325. The program in Figure~\ref{fig:r4-function-example} is a
  6326. representative example of defining and using functions in $R_4$. We
  6327. define a function \code{map-vec} that applies some other function
  6328. \code{f} to both elements of a vector and returns a new
  6329. vector containing the results. We also define a function \code{add1}.
  6330. The program applies
  6331. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  6332. \code{(vector 1 42)}, from which we return the \code{42}.
  6333. \begin{figure}[tbp]
  6334. \begin{lstlisting}
  6335. (define (map-vec [f : (Integer -> Integer)]
  6336. [v : (Vector Integer Integer)])
  6337. : (Vector Integer Integer)
  6338. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  6339. (define (add1 [x : Integer]) : Integer
  6340. (+ x 1))
  6341. (vector-ref (map-vec add1 (vector 0 41)) 1)
  6342. \end{lstlisting}
  6343. \caption{Example of using functions in $R_4$.}
  6344. \label{fig:r4-function-example}
  6345. \end{figure}
  6346. The definitional interpreter for $R_4$ is in
  6347. Figure~\ref{fig:interp-R4}. The case for the \code{ProgramDefsExp} form is
  6348. responsible for setting up the mutual recursion between the top-level
  6349. function definitions. We use the classic back-patching \index{back-patching}
  6350. approach that uses mutable variables and makes two passes over the function
  6351. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  6352. top-level environment using a mutable cons cell for each function
  6353. definition. Note that the \code{lambda} value for each function is
  6354. incomplete; it does not yet include the environment. Once the
  6355. top-level environment is constructed, we then iterate over it and
  6356. update the \code{lambda} values to use the top-level environment.
  6357. \begin{figure}[tp]
  6358. \begin{lstlisting}
  6359. (define (interp-exp env)
  6360. (lambda (e)
  6361. (define recur (interp-exp env))
  6362. (match e
  6363. ...
  6364. [(Apply fun args)
  6365. (define fun-val (recur fun))
  6366. (define arg-vals (for/list ([e args]) (recur e)))
  6367. (match fun-val
  6368. [`(lambda (,xs ...) ,body ,fun-env)
  6369. (define new-env (append (map cons xs arg-vals) fun-env))
  6370. ((interp-exp new-env) body)])]
  6371. ...
  6372. )))
  6373. (define (interp-def d)
  6374. (match d
  6375. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  6376. (mcons f `(lambda ,xs ,body ()))]
  6377. ))
  6378. (define (interp-R4 p)
  6379. (match p
  6380. [(ProgramDefsExp info ds body)
  6381. (let ([top-level (for/list ([d ds]) (interp-def d))])
  6382. (for/list ([b top-level])
  6383. (set-mcdr! b (match (mcdr b)
  6384. [`(lambda ,xs ,body ())
  6385. `(lambda ,xs ,body ,top-level)])))
  6386. ((interp-exp top-level) body))]
  6387. ))
  6388. \end{lstlisting}
  6389. \caption{Interpreter for the $R_4$ language.}
  6390. \label{fig:interp-R4}
  6391. \end{figure}
  6392. \margincomment{TODO: explain type checker}
  6393. The type checker for $R_4$ is is in Figure~\ref{fig:type-check-R4}.
  6394. \begin{figure}[tp]
  6395. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6396. (define (fun-def-name d)
  6397. (match d [(Def f (list `[,xs : ,ps] ...) rt info body) f]))
  6398. (define (fun-def-type d)
  6399. (match d
  6400. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  6401. (define (type-check-exp env)
  6402. (lambda (e)
  6403. (match e
  6404. ...
  6405. [(Apply e es)
  6406. (define-values (e^ ty) ((type-check-exp env) e))
  6407. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  6408. ((type-check-exp env) e)))
  6409. (match ty
  6410. [`(,ty^* ... -> ,rt)
  6411. (for ([arg-ty ty*] [prm-ty ty^*])
  6412. (unless (equal? arg-ty prm-ty)
  6413. (error "argument ~a not equal to parameter ~a" arg-ty prm-ty)))
  6414. (values (HasType (Apply e^ e*) rt) rt)]
  6415. [else (error "expected a function, not" ty)])])))
  6416. (define (type-check-def env)
  6417. (lambda (e)
  6418. (match e
  6419. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  6420. (define new-env (append (map cons xs ps) env))
  6421. (define-values (body^ ty^) ((type-check-exp new-env) body))
  6422. (unless (equal? ty^ rt)
  6423. (error "body type ~a not equal to return type ~a" ty^ rt))
  6424. (Def f p:t* rt info body^)])))
  6425. (define (type-check env)
  6426. (lambda (e)
  6427. (match e
  6428. [(ProgramDefsExp info ds body)
  6429. (define new-env (for/list ([d ds])
  6430. (cons (fun-def-name d) (fun-def-type d))))
  6431. (define ds^ (for/list ([d ds])
  6432. ((type-check-def new-env) d)))
  6433. (define-values (body^ ty) ((type-check-exp new-env) body))
  6434. (unless (equal? ty 'Integer)
  6435. (error "result of the program must be an integer, not " ty))
  6436. (ProgramDefsExp info ds^ body^)]
  6437. [else (error 'type-check "R4/type-check unmatched ~a" e)])))
  6438. \end{lstlisting}
  6439. \caption{Type checker for the $R_4$ language.}
  6440. \label{fig:type-check-R4}
  6441. \end{figure}
  6442. \section{Functions in x86}
  6443. \label{sec:fun-x86}
  6444. \margincomment{\tiny Make sure callee-saved registers are discussed
  6445. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  6446. \margincomment{\tiny Talk about the return address on the
  6447. stack and what callq and retq does.\\ --Jeremy }
  6448. The x86 architecture provides a few features to support the
  6449. implementation of functions. We have already seen that x86 provides
  6450. labels so that one can refer to the location of an instruction, as is
  6451. needed for jump instructions. Labels can also be used to mark the
  6452. beginning of the instructions for a function. Going further, we can
  6453. obtain the address of a label by using the \key{leaq} instruction and
  6454. PC-relative addressing. For example, the following puts the
  6455. address of the \code{add1} label into the \code{rbx} register.
  6456. \begin{lstlisting}
  6457. leaq add1(%rip), %rbx
  6458. \end{lstlisting}
  6459. The instruction pointer register \key{rip} (aka. the program counter
  6460. \index{program counter}) always points to the next instruction to be
  6461. executed. When combined with an label, as in \code{add1(\%rip)}, the
  6462. linker computes the distance $d$ between the address of \code{add1}
  6463. and where the \code{rip} would be at that moment and then changes
  6464. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  6465. the address of \code{add1}.
  6466. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  6467. jump to a function whose location is given by a label. To support
  6468. function calls in this chapter we instead will be jumping to a
  6469. function whose location is given by an address in a register, that is,
  6470. we need to make an \emph{indirect function call}. The x86 syntax for
  6471. this is a \code{callq} instruction but with an asterisk before the
  6472. register name.\index{indirect function call}
  6473. \begin{lstlisting}
  6474. callq *%rbx
  6475. \end{lstlisting}
  6476. \subsection{Calling Conventions}
  6477. \index{calling conventions}
  6478. The \code{callq} instruction provides partial support for implementing
  6479. functions: it pushes the return address on the stack and it jumps to
  6480. the target. However, \code{callq} does not handle
  6481. \begin{enumerate}
  6482. \item parameter passing,
  6483. \item pushing frames on the procedure call stack and popping them off,
  6484. or
  6485. \item determining how registers are shared by different functions.
  6486. \end{enumerate}
  6487. These issues require coordination between the caller and the callee,
  6488. which is often assembly code written by different programmers or
  6489. generated by different compilers. As a result, people have developed
  6490. \emph{conventions} that govern how functions calls are performed.
  6491. Here we use conventions that are compatible with those of the
  6492. \code{gcc} compiler~\citep{Matz:2013aa}.
  6493. Regarding (1) parameter passing, recall that the following six
  6494. registers:
  6495. \begin{lstlisting}
  6496. rdi rsi rdx rcx r8 r9
  6497. \end{lstlisting}
  6498. in that order, are used to pass arguments to a function. If there are
  6499. more than six arguments, then the convention is to use space on the
  6500. frame of the caller for the rest of the arguments. However, to ease
  6501. the implementation of efficient tail calls
  6502. (Section~\ref{sec:tail-call}), we arrange to never need more than six
  6503. arguments.
  6504. %
  6505. Also recall that the register \code{rax} is for the return value of
  6506. the function.
  6507. \index{prelude}\index{conclusion}
  6508. Regarding (2) frames \index{frame} and the procedure call stack
  6509. \index{procedure call stack}, recall from Section~\ref{sec:x86} that
  6510. the stack grows down, with each function call using a chunk of space
  6511. called a frame. The caller sets the stack pointer, register
  6512. \code{rsp}, to the last data item in its frame. The callee must not
  6513. change anything in the caller's frame, that is, anything that is at or
  6514. above the stack pointer. The callee is free to use locations that are
  6515. below the stack pointer.
  6516. Recall that we are storing variables of vector type on the root stack.
  6517. So the prelude needs to move the root stack pointer \code{r15} up and
  6518. the conclusion needs to move the root stack pointer back down. Also,
  6519. the prelude must initialize to \code{0} this frame's slots in the root
  6520. stack to signal to the garbage collector that those slots do not yet
  6521. contain a pointer to a vector. Otherwise the garbage collector will
  6522. interpret the garbage bits in those slots as memory addresses and try
  6523. to traverse them, causing serious mayhem!
  6524. Regarding (3) the sharing of registers between different functions,
  6525. recall from Section~\ref{sec:calling-conventions} that the registers
  6526. are divided into two groups, the caller-saved registers and the
  6527. callee-saved registers. The caller should assume that all the
  6528. caller-saved registers get overwritten with arbitrary values by the
  6529. callee. That is why we recommend in
  6530. Section~\ref{sec:calling-conventions} that variables that are live
  6531. during a function call should not be assigned to caller-saved
  6532. registers.
  6533. On the flip side, if the callee wants to use a callee-saved register,
  6534. the callee must save the contents of those registers on their stack
  6535. frame and then put them back prior to returning to the caller. That
  6536. is why we recommended in Section~\ref{sec:calling-conventions} that if
  6537. the register allocator assigns a variable to a callee-saved register,
  6538. then the prelude of the \code{main} function must save that register
  6539. to the stack and the conclusion of \code{main} must restore it. This
  6540. recommendation now generalizes to all functions.
  6541. Also recall that the base pointer, register \code{rbp}, is used as a
  6542. point-of-reference within a frame, so that each local variable can be
  6543. accessed at a fixed offset from the base pointer
  6544. (Section~\ref{sec:x86}).
  6545. %
  6546. Figure~\ref{fig:call-frames} shows the general layout of the caller
  6547. and callee frames.
  6548. \begin{figure}[tbp]
  6549. \centering
  6550. \begin{tabular}{r|r|l|l} \hline
  6551. Caller View & Callee View & Contents & Frame \\ \hline
  6552. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  6553. 0(\key{\%rbp}) & & old \key{rbp} \\
  6554. -8(\key{\%rbp}) & & callee-saved $1$ \\
  6555. \ldots & & \ldots \\
  6556. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  6557. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  6558. \ldots & & \ldots \\
  6559. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  6560. %% & & \\
  6561. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  6562. %% & \ldots & \ldots \\
  6563. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  6564. \hline
  6565. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  6566. & 0(\key{\%rbp}) & old \key{rbp} \\
  6567. & -8(\key{\%rbp}) & callee-saved $1$ \\
  6568. & \ldots & \ldots \\
  6569. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  6570. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  6571. & \ldots & \ldots \\
  6572. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  6573. \end{tabular}
  6574. \caption{Memory layout of caller and callee frames.}
  6575. \label{fig:call-frames}
  6576. \end{figure}
  6577. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  6578. %% local variables and for storing the values of callee-saved registers
  6579. %% (we shall refer to all of these collectively as ``locals''), and that
  6580. %% at the beginning of a function we move the stack pointer \code{rsp}
  6581. %% down to make room for them.
  6582. %% We recommend storing the local variables
  6583. %% first and then the callee-saved registers, so that the local variables
  6584. %% can be accessed using \code{rbp} the same as before the addition of
  6585. %% functions.
  6586. %% To make additional room for passing arguments, we shall
  6587. %% move the stack pointer even further down. We count how many stack
  6588. %% arguments are needed for each function call that occurs inside the
  6589. %% body of the function and find their maximum. Adding this number to the
  6590. %% number of locals gives us how much the \code{rsp} should be moved at
  6591. %% the beginning of the function. In preparation for a function call, we
  6592. %% offset from \code{rsp} to set up the stack arguments. We put the first
  6593. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  6594. %% so on.
  6595. %% Upon calling the function, the stack arguments are retrieved by the
  6596. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  6597. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  6598. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  6599. %% the layout of the caller and callee frames. Notice how important it is
  6600. %% that we correctly compute the maximum number of arguments needed for
  6601. %% function calls; if that number is too small then the arguments and
  6602. %% local variables will smash into each other!
  6603. \subsection{Efficient Tail Calls}
  6604. \label{sec:tail-call}
  6605. In general, the amount of stack space used by a program is determined
  6606. by the longest chain of nested function calls. That is, if function
  6607. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  6608. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  6609. $n$ can grow quite large in the case of recursive or mutually
  6610. recursive functions. However, in some cases we can arrange to use only
  6611. constant space, i.e. $O(1)$, instead of $O(n)$.
  6612. If a function call is the last action in a function body, then that
  6613. call is said to be a \emph{tail call}\index{tail call}.
  6614. For example, in the following
  6615. program, the recursive call to \code{tail-sum} is a tail call.
  6616. \begin{center}
  6617. \begin{lstlisting}
  6618. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  6619. (if (eq? n 0)
  6620. r
  6621. (tail-sum (- n 1) (+ n r))))
  6622. (+ (tail-sum 5 0) 27)
  6623. \end{lstlisting}
  6624. \end{center}
  6625. At a tail call, the frame of the caller is no longer needed, so we
  6626. can pop the caller's frame before making the tail call. With this
  6627. approach, a recursive function that only makes tail calls will only
  6628. use $O(1)$ stack space. Functional languages like Racket typically
  6629. rely heavily on recursive functions, so they typically guarantee that
  6630. all tail calls will be optimized in this way.
  6631. \index{frame}
  6632. However, some care is needed with regards to argument passing in tail
  6633. calls. As mentioned above, for arguments beyond the sixth, the
  6634. convention is to use space in the caller's frame for passing
  6635. arguments. But for a tail call we pop the caller's frame and can no
  6636. longer use it. Another alternative is to use space in the callee's
  6637. frame for passing arguments. However, this option is also problematic
  6638. because the caller and callee's frame overlap in memory. As we begin
  6639. to copy the arguments from their sources in the caller's frame, the
  6640. target locations in the callee's frame might overlap with the sources
  6641. for later arguments! We solve this problem by not using the stack for
  6642. passing more than six arguments but instead using the heap, as we
  6643. describe in the Section~\ref{sec:limit-functions-r4}.
  6644. As mentioned above, for a tail call we pop the caller's frame prior to
  6645. making the tail call. The instructions for popping a frame are the
  6646. instructions that we usually place in the conclusion of a
  6647. function. Thus, we also need to place such code immediately before
  6648. each tail call. These instructions include restoring the callee-saved
  6649. registers, so it is good that the argument passing registers are all
  6650. caller-saved registers.
  6651. One last note regarding which instruction to use to make the tail
  6652. call. When the callee is finished, it should not return to the current
  6653. function, but it should return to the function that called the current
  6654. one. Thus, the return address that is already on the stack is the
  6655. right one, and we should not use \key{callq} to make the tail call, as
  6656. that would unnecessarily overwrite the return address. Instead we can
  6657. simply use the \key{jmp} instruction. Like the indirect function call,
  6658. we write an \emph{indirect jump}\index{indirect jump} with a register
  6659. prefixed with an asterisk. We recommend using \code{rax} to hold the
  6660. jump target because the preceding conclusion overwrites just about
  6661. everything else.
  6662. \begin{lstlisting}
  6663. jmp *%rax
  6664. \end{lstlisting}
  6665. \section{Shrink $R_4$}
  6666. \label{sec:shrink-r4}
  6667. The \code{shrink} pass performs a minor modification to ease the
  6668. later passes. This pass introduces an explicit \code{main} function
  6669. and changes the top \code{ProgramDefsExp} form to
  6670. \code{ProgramDefs} as follows.
  6671. \begin{lstlisting}
  6672. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  6673. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  6674. \end{lstlisting}
  6675. where $\itm{mainDef}$ is
  6676. \begin{lstlisting}
  6677. (Def 'main '() 'Integer '() |$\Exp'$|)
  6678. \end{lstlisting}
  6679. \section{Reveal Functions and the $F_1$ language}
  6680. \label{sec:reveal-functions-r4}
  6681. The syntax of $R_4$ is inconvenient for purposes of compilation in one
  6682. respect: it conflates the use of function names and local
  6683. variables. This is a problem because we need to compile the use of a
  6684. function name differently than the use of a local variable; we need to
  6685. use \code{leaq} to convert the function name (a label in x86) to an
  6686. address in a register. Thus, it is a good idea to create a new pass
  6687. that changes function references from just a symbol $f$ to
  6688. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  6689. output language, $F_1$, is defined in Figure~\ref{fig:f1-syntax}.
  6690. \begin{figure}[tp]
  6691. \centering
  6692. \fbox{
  6693. \begin{minipage}{0.96\textwidth}
  6694. \[
  6695. \begin{array}{lcl}
  6696. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  6697. &\mid& \gray{ \ADD{\Exp}{\Exp}
  6698. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  6699. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6700. &\mid& \gray{ \BOOL{\itm{bool}}
  6701. \mid \AND{\Exp}{\Exp} }\\
  6702. &\mid& \gray{ \OR{\Exp}{\Exp}
  6703. \mid \NOT{\Exp} } \\
  6704. &\mid& \gray{ \BINOP{\itm{cmp}}{\Exp}{\Exp}
  6705. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6706. &\mid& \gray{ \VECTOR{\Exp} } \\
  6707. &\mid& \gray{ \VECREF{\Exp}{\INT{\Int}} }\\
  6708. &\mid& \gray{ \VECSET{\Exp}{\INT{\Int}}{\Exp}} \\
  6709. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  6710. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  6711. &\mid& \FUNREF{\Var}\\
  6712. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  6713. F_1 &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  6714. \end{array}
  6715. \]
  6716. \end{minipage}
  6717. }
  6718. \caption{The abstract syntax $F_1$, an extension of $R_4$
  6719. (Figure~\ref{fig:r4-syntax}).}
  6720. \label{fig:f1-syntax}
  6721. \end{figure}
  6722. %% Distinguishing between calls in tail position and non-tail position
  6723. %% requires the pass to have some notion of context. We recommend using
  6724. %% two mutually recursive functions, one for processing expressions in
  6725. %% tail position and another for the rest.
  6726. Placing this pass after \code{uniquify} will make sure that there are
  6727. no local variables and functions that share the same name. On the
  6728. other hand, \code{reveal-functions} needs to come before the
  6729. \code{explicate-control} pass because that pass helps us compile
  6730. \code{FunRef} forms into assignment statements.
  6731. \section{Limit Functions}
  6732. \label{sec:limit-functions-r4}
  6733. Recall that we wish to limit the number of function parameters to six
  6734. so that we do not need to use the stack for argument passing, which
  6735. makes it easier to implement efficient tail calls. However, because
  6736. the input language $R_4$ supports arbitrary numbers of function
  6737. arguments, we have some work to do!
  6738. This pass transforms functions and function calls that involve more
  6739. than six arguments to pass the first five arguments as usual, but it
  6740. packs the rest of the arguments into a vector and passes it as the
  6741. sixth argument.
  6742. Each function definition with too many parameters is transformed as
  6743. follows.
  6744. \begin{lstlisting}
  6745. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  6746. |$\Rightarrow$|
  6747. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  6748. \end{lstlisting}
  6749. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  6750. the occurences of the later parameters with vector references.
  6751. \begin{lstlisting}
  6752. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  6753. \end{lstlisting}
  6754. For function calls with too many arguments, the \code{limit-functions}
  6755. pass transforms them in the following way.
  6756. \begin{tabular}{lll}
  6757. \begin{minipage}{0.2\textwidth}
  6758. \begin{lstlisting}
  6759. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  6760. \end{lstlisting}
  6761. \end{minipage}
  6762. &
  6763. $\Rightarrow$
  6764. &
  6765. \begin{minipage}{0.4\textwidth}
  6766. \begin{lstlisting}
  6767. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  6768. \end{lstlisting}
  6769. \end{minipage}
  6770. \end{tabular}
  6771. \section{Remove Complex Operators and Operands}
  6772. \label{sec:rco-r4}
  6773. The primary decisions to make for this pass is whether to classify
  6774. \code{FunRef} and \code{Apply} as either simple or complex
  6775. expressions. Recall that a simple expression will eventually end up as
  6776. just an ``immediate'' argument of an x86 instruction. Function
  6777. application will be translated to a sequence of instructions, so
  6778. \code{Apply} must be classified as complex expression. Regarding
  6779. \code{FunRef}, as discussed above, the function label needs to
  6780. be converted to an address using the \code{leaq} instruction. Thus,
  6781. even though \code{FunRef} seems rather simple, it needs to be
  6782. classified as a complex expression so that we generate an assignment
  6783. statement with a left-hand side that can serve as the target of the
  6784. \code{leaq}.
  6785. \section{Explicate Control and the $C_3$ language}
  6786. \label{sec:explicate-control-r4}
  6787. Figures~\ref{fig:c3-concrete-syntax} and \ref{fig:c3-syntax} define
  6788. the concrete and abstract syntax for $C_3$, the output of
  6789. \key{explicate-control}. The three mutually recursive functions for
  6790. this pass, for assignment, tail, and predicate contexts, must all be
  6791. updated with cases for \code{FunRef} and \code{Apply}. In assignment
  6792. and predicate contexts, \code{Apply} becomes \code{Call} in $C_3$,
  6793. whereas in tail position \code{Apply} becomes \code{TailCall} in
  6794. $C_3$. We recommend defining a new function for processing function
  6795. definitions. This code is similar to the case for \code{Program} in
  6796. $R_3$. The top-level \code{explicate-control} function that handles
  6797. the \code{ProgramDefs} form of $R_4$ can then apply this new function
  6798. to all the function definitions.
  6799. \begin{figure}[tp]
  6800. \fbox{
  6801. \begin{minipage}{0.96\textwidth}
  6802. \[
  6803. \begin{array}{lcl}
  6804. \Atm &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  6805. \\
  6806. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  6807. \Exp &::= & \gray{ \Atm \mid (\key{read}) \mid (\key{-}\;\Atm) \mid (\key{+} \; \Atm\;\Atm)
  6808. \mid (\key{not}\;\Atm) \mid (\itm{cmp}\;\Atm\;\Atm) } \\
  6809. &\mid& \gray{ (\key{allocate}\,\Int\,\Type)
  6810. \mid (\key{vector-ref}\, \Atm\, \Int) } \\
  6811. &\mid& \gray{ (\key{vector-set!}\,\Atm\,\Int\,\Atm) \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) } \\
  6812. &\mid& (\key{fun-ref}~\itm{label}) \mid (\key{call} \,\Atm\,\Atm\ldots) \\
  6813. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  6814. \mid (\key{collect} \,\itm{int}) }\\
  6815. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  6816. &\mid& \gray{(\key{goto}\,\itm{label})
  6817. \mid \IF{(\itm{cmp}\, \Atm\,\Atm)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  6818. &\mid& (\key{tail-call}\,\Atm\,\Atm\ldots) \\
  6819. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]\ldots) \key{:} \Type \; ((\itm{label}\,\key{.}\,\Tail)\ldots)) \\
  6820. C_3 & ::= & \Def\ldots
  6821. \end{array}
  6822. \]
  6823. \end{minipage}
  6824. }
  6825. \caption{The $C_3$ language, extending $C_2$ (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  6826. \label{fig:c3-concrete-syntax}
  6827. \end{figure}
  6828. \begin{figure}[tp]
  6829. \fbox{
  6830. \begin{minipage}{0.96\textwidth}
  6831. \small
  6832. \[
  6833. \begin{array}{lcl}
  6834. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  6835. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  6836. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  6837. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  6838. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  6839. &\mid& \gray{ (\key{Allocate} \,\itm{int}\,\itm{type}) } \\
  6840. &\mid& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  6841. &\mid& \gray{ (\key{Prim}~\key{'vector-set!}\,(\key{list}\,\Atm\,\INT{\Int}\,\Atm)) }\\
  6842. &\mid& \gray{ (\key{GlobalValue} \,\Var) \mid (\key{Void}) }\\
  6843. &\mid& \FUNREF{\itm{label}} \mid \CALL{\Atm}{\Atm\ldots} \\
  6844. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  6845. \mid (\key{Collect} \,\itm{int}) } \\
  6846. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  6847. \mid \GOTO{\itm{label}} } \\
  6848. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  6849. &\mid& \TAILCALL{\Atm}{\Atm\ldots} \\
  6850. \Def &::=& \DEF{\itm{label}}{([\Var\key{:}\Type]\ldots)}{\Type}{((\itm{label}\,\key{.}\,\Tail)\ldots)}\\
  6851. C_3 & ::= & \PROGRAMDEFS{\itm{info}}{(\Def\ldots)}
  6852. \end{array}
  6853. \]
  6854. \end{minipage}
  6855. }
  6856. \caption{The abstract syntax of $C_3$, extending $C_2$ (Figure~\ref{fig:c2-syntax}).}
  6857. \label{fig:c3-syntax}
  6858. \end{figure}
  6859. \section{Uncover Locals}
  6860. \label{sec:uncover-locals-r4}
  6861. The function for processing $\Tail$ should be updated with a case for
  6862. \code{TailCall}. We also recommend creating a new function for
  6863. processing function definitions. Each function definition in $C_3$ has
  6864. its own set of local variables, so the code for function definitions
  6865. should be similar to the case for the \code{Program} form in $C_2$.
  6866. \section{Select Instructions and the x86$_3$ Language}
  6867. \label{sec:select-r4}
  6868. \index{instruction selection}
  6869. The output of select instructions is a program in the x86$_3$
  6870. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  6871. \index{x86}
  6872. \begin{figure}[tp]
  6873. \fbox{
  6874. \begin{minipage}{0.96\textwidth}
  6875. \[
  6876. \begin{array}{lcl}
  6877. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg}
  6878. \mid (\key{deref}\,\Reg\,\Int) } \\
  6879. &\mid& \gray{ (\key{byte-reg}\; \Reg)
  6880. \mid (\key{global}\; \itm{name}) }
  6881. \mid (\key{fun-ref}\; \itm{label})\\
  6882. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  6883. \Instr &::=& \gray{ (\key{addq} \; \Arg\; \Arg) \mid
  6884. (\key{subq} \; \Arg\; \Arg) \mid
  6885. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) } \\
  6886. &\mid& \gray{ (\key{callq} \; \mathit{label}) \mid
  6887. (\key{pushq}\;\Arg) \mid
  6888. (\key{popq}\;\Arg) \mid
  6889. (\key{retq}) } \\
  6890. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  6891. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  6892. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  6893. \mid (\key{jmp} \; \itm{label})
  6894. \mid (\key{j}\itm{cc} \; \itm{label})
  6895. \mid (\key{label} \; \itm{label}) } \\
  6896. &\mid& (\key{indirect-callq}\;\Arg ) \mid (\key{tail-jmp}\;\Arg) \\
  6897. &\mid& (\key{leaq}\;\Arg\;\Reg)\\
  6898. \Block &::= & \gray{(\key{block} \;\itm{info}\; \Instr\ldots)} \\
  6899. \Def &::= & (\key{define} \; (\itm{label}) \;\itm{info}\; ((\itm{label} \,\key{.}\, \Block)\ldots))\\
  6900. x86_3 &::= & (\key{program} \;\itm{info} \;\Def\ldots)
  6901. \end{array}
  6902. \]
  6903. \end{minipage}
  6904. }
  6905. \caption{The concrete syntax of x86$_3$ (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  6906. \label{fig:x86-3-concrete}
  6907. \end{figure}
  6908. \begin{figure}[tp]
  6909. \fbox{
  6910. \begin{minipage}{0.96\textwidth}
  6911. \small
  6912. \[
  6913. \begin{array}{lcl}
  6914. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  6915. \mid \BYTEREG{\Reg} } \\
  6916. &\mid& \gray{ (\key{Global}~\Var) } \mid \FUNREF{\itm{label}} \\
  6917. \Instr &::=& \ldots \mid \INDCALLQ{\itm{label}}{\itm{int}}
  6918. \mid \TAILJMP{\Arg}{\itm{int}}\\
  6919. &\mid& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  6920. \Def &::= & \DEF{\itm{label}}{([\Var\key{:}\Type]\ldots)}{\Type}{((\itm{label}\,\key{.}\,\Block)\ldots)} \\
  6921. x86_3 &::= & \PROGRAMDEFS{\itm{info}}{(\Def\ldots)}
  6922. \end{array}
  6923. \]
  6924. \end{minipage}
  6925. }
  6926. \caption{The abstract syntax of x86$_3$ (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  6927. \label{fig:x86-3}
  6928. \end{figure}
  6929. An assignment of a function reference to a variable becomes a
  6930. load-effective-address instruction as follows: \\
  6931. \begin{tabular}{lcl}
  6932. \begin{minipage}{0.35\textwidth}
  6933. \begin{lstlisting}
  6934. |$\itm{lhs}$| = (fun-ref |$f$|);
  6935. \end{lstlisting}
  6936. \end{minipage}
  6937. &
  6938. $\Rightarrow$\qquad\qquad
  6939. &
  6940. \begin{minipage}{0.3\textwidth}
  6941. \begin{lstlisting}
  6942. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  6943. \end{lstlisting}
  6944. \end{minipage}
  6945. \end{tabular} \\
  6946. Regarding function definitions, we need to remove the parameters and
  6947. instead perform parameter passing using the conventions discussed in
  6948. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  6949. registers. We recommend turning the parameters into local variables
  6950. and generating instructions at the beginning of the function to move
  6951. from the argument passing registers to these local variables.
  6952. \begin{lstlisting}
  6953. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  6954. |$\Rightarrow$|
  6955. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  6956. \end{lstlisting}
  6957. The $G'$ control-flow graph is the same as $G$ except that the
  6958. \code{start} block is modified to add the instructions for moving from
  6959. the argument registers to the parameter variables. So the \code{start}
  6960. block of $G$ shown on the left is changed to the code on the right.
  6961. \begin{center}
  6962. \begin{minipage}{0.3\textwidth}
  6963. \begin{lstlisting}
  6964. start:
  6965. |$\itm{instr}_1$|
  6966. |$\vdots$|
  6967. |$\itm{instr}_n$|
  6968. \end{lstlisting}
  6969. \end{minipage}
  6970. $\Rightarrow$
  6971. \begin{minipage}{0.3\textwidth}
  6972. \begin{lstlisting}
  6973. start:
  6974. movq %rdi, |$x_1$|
  6975. movq %rsi, |$x_2$|
  6976. |$\vdots$|
  6977. |$\itm{instr}_1$|
  6978. |$\vdots$|
  6979. |$\itm{instr}_n$|
  6980. \end{lstlisting}
  6981. \end{minipage}
  6982. \end{center}
  6983. By changing the parameters to local variables, we are giving the
  6984. register allocator control over which registers or stack locations to
  6985. use for them. If you implemented the move-biasing challenge
  6986. (Section~\ref{sec:move-biasing}), the register allocator will try to
  6987. assign the parameter variables to the corresponding argument register,
  6988. in which case the \code{patch-instructions} pass will remove the
  6989. \code{movq} instruction. This happens in the example translation in
  6990. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  6991. the \code{add} function.
  6992. %
  6993. Also, note that the register allocator will perform liveness analysis
  6994. on this sequence of move instructions and build the interference
  6995. graph. So, for example, $x_1$ will be marked as interfering with
  6996. \code{rsi} and that will prevent the assignment of $x_1$ to
  6997. \code{rsi}, which is good, because that would overwrite the argument
  6998. that needs to move into $x_2$.
  6999. Next, consider the compilation of function calls. In the mirror image
  7000. of handling the parameters of function definitions, the arguments need
  7001. to be moved to the argument passing registers. The function call
  7002. itself is performed with an indirect function call. The return value
  7003. from the function is stored in \code{rax}, so it needs to be moved
  7004. into the \itm{lhs}.
  7005. \begin{lstlisting}
  7006. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  7007. |$\Rightarrow$|
  7008. movq |$\itm{arg}_1$|, %rdi
  7009. movq |$\itm{arg}_2$|, %rsi
  7010. |$\vdots$|
  7011. callq *|\itm{fun}|
  7012. movq %rax, |\itm{lhs}|
  7013. \end{lstlisting}
  7014. Regarding tail calls, the parameter passing is the same as non-tail
  7015. calls: generate instructions to move the arguments into to the
  7016. argument passing registers. After that we need to pop the frame from
  7017. the procedure call stack. However, we do not yet know how big the
  7018. frame is; that gets determined during register allocation. So instead
  7019. of generating those instructions here, we invent a new instruction
  7020. that means ``pop the frame and then do an indirect jump'', which we
  7021. name \code{TailJmp}. The abstract syntax for this instruction includes
  7022. an argument that specifies where to jump and an integer that
  7023. represents the arity of the function being called.
  7024. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  7025. using the label \code{start} for the initial block of a program, and
  7026. in Section~\ref{sec:select-r1} we recommended labeling the conclusion
  7027. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  7028. can be compiled to an assignment to \code{rax} followed by a jump to
  7029. \code{conclusion}. With the addition of function definitions, we will
  7030. have a starting block and conclusion for each function, but their
  7031. labels need to be unique. We recommend prepending the function's name
  7032. to \code{start} and \code{conclusion}, respectively, to obtain unique
  7033. labels. (Alternatively, one could \code{gensym} labels for the start
  7034. and conclusion and store them in the $\itm{info}$ field of the
  7035. function definition.)
  7036. \section{Uncover Live}
  7037. %% The rest of the passes need only minor modifications to handle the new
  7038. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  7039. %% \code{leaq}.
  7040. The \code{IndirectCallq} instruction should be treated like
  7041. \code{Callq} regarding its written locations $W$, in that they should
  7042. include all the caller-saved registers. Recall that the reason for
  7043. that is to force call-live variables to be assigned to callee-saved
  7044. registers or to be spilled to the stack.
  7045. \section{Build Interference Graph}
  7046. With the addition of function definitions, we compute an interference
  7047. graph for each function (not just one for the whole program).
  7048. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  7049. spill vector-typed variables that are live during a call to the
  7050. \code{collect}. With the addition of functions to our language, we
  7051. need to revisit this issue. Many functions perform allocation and
  7052. therefore have calls to the collector inside of them. Thus, we should
  7053. not only spill a vector-typed variable when it is live during a call
  7054. to \code{collect}, but we should spill the variable if it is live
  7055. during any function call. Thus, in the \code{build-interference} pass,
  7056. we recommend adding interference edges between call-live vector-typed
  7057. variables and the callee-saved registers (in addition to the usual
  7058. addition of edges between call-live variables and the caller-saved
  7059. registers).
  7060. \section{Patch Instructions}
  7061. In \code{patch-instructions}, you should deal with the x86
  7062. idiosyncrasy that the destination argument of \code{leaq} must be a
  7063. register. Additionally, you should ensure that the argument of
  7064. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  7065. code generation more convenient, because we trample many registers
  7066. before the tail call (as explained in the next section).
  7067. \section{Print x86}
  7068. For the \code{print-x86} pass, the cases for \code{FunRef} and
  7069. \code{IndirectCallq} are straightforward: output their concrete
  7070. syntax.
  7071. \begin{lstlisting}
  7072. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  7073. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  7074. \end{lstlisting}
  7075. The \code{TailJmp} node requires a bit work. A straightforward
  7076. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  7077. before the jump we need to pop the current frame. This sequence of
  7078. instructions is the same as the code for the conclusion of a function,
  7079. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  7080. Note that your \code{print-x86} pass needs to add the code for saving
  7081. and restoring callee-saved registers, if you have not already
  7082. implemented that. This is necessary when generating code for function
  7083. definitions.
  7084. \begin{exercise}\normalfont
  7085. Expand your compiler to handle $R_4$ as outlined in this chapter.
  7086. Create 5 new programs that use functions, including examples that pass
  7087. functions and return functions from other functions and including
  7088. recursive functions. Test your compiler on these new programs and all
  7089. of your previously created test programs.
  7090. \end{exercise}
  7091. \begin{figure}[tbp]
  7092. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7093. \node (R4) at (0,2) {\large $R_4$};
  7094. \node (R4-2) at (3,2) {\large $R_4$};
  7095. \node (R4-3) at (6,2) {\large $R_4$};
  7096. \node (F1-1) at (12,0) {\large $F_1$};
  7097. \node (F1-2) at (9,0) {\large $F_1$};
  7098. \node (F1-3) at (6,0) {\large $F_1$};
  7099. \node (F1-4) at (3,0) {\large $F_1$};
  7100. \node (C3-1) at (6,-2) {\large $C_3$};
  7101. \node (C3-2) at (3,-2) {\large $C_3$};
  7102. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  7103. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  7104. \node (x86-4) at (9,-4) {\large $\text{x86}_3$};
  7105. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  7106. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  7107. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  7108. \path[->,bend left=15] (R4) edge [above] node
  7109. {\ttfamily\footnotesize\color{red} type-check} (R4-2);
  7110. \path[->,bend left=15] (R4-2) edge [above] node
  7111. {\ttfamily\footnotesize uniquify} (R4-3);
  7112. \path[->,bend left=15] (R4-3) edge [right] node
  7113. {\ttfamily\footnotesize\color{red} reveal-functions} (F1-1);
  7114. \path[->,bend left=15] (F1-1) edge [below] node
  7115. {\ttfamily\footnotesize\color{red} limit-functions} (F1-2);
  7116. \path[->,bend right=15] (F1-2) edge [above] node
  7117. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  7118. \path[->,bend right=15] (F1-3) edge [above] node
  7119. {\ttfamily\footnotesize\color{red} remove-complex.} (F1-4);
  7120. \path[->,bend left=15] (F1-4) edge [right] node
  7121. {\ttfamily\footnotesize\color{red} explicate-control} (C3-1);
  7122. \path[->,bend left=15] (C3-1) edge [below] node
  7123. {\ttfamily\footnotesize\color{red} uncover-locals} (C3-2);
  7124. \path[->,bend right=15] (C3-2) edge [left] node
  7125. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  7126. \path[->,bend left=15] (x86-2) edge [left] node
  7127. {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  7128. \path[->,bend right=15] (x86-2-1) edge [below] node
  7129. {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  7130. \path[->,bend right=15] (x86-2-2) edge [left] node
  7131. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7132. \path[->,bend left=15] (x86-3) edge [above] node
  7133. {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  7134. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  7135. \end{tikzpicture}
  7136. \caption{Diagram of the passes for $R_4$, a language with functions.}
  7137. \label{fig:R4-passes}
  7138. \end{figure}
  7139. Figure~\ref{fig:R4-passes} gives an overview of the passes for
  7140. compiling $R_4$ to x86.
  7141. \section{An Example Translation}
  7142. \label{sec:functions-example}
  7143. Figure~\ref{fig:add-fun} shows an example translation of a simple
  7144. function in $R_4$ to x86. The figure also includes the results of the
  7145. \code{explicate-control} and \code{select-instructions} passes.
  7146. \begin{figure}[htbp]
  7147. \begin{tabular}{ll}
  7148. \begin{minipage}{0.5\textwidth}
  7149. % s3_2.rkt
  7150. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7151. (define (add [x : Integer] [y : Integer])
  7152. : Integer
  7153. (+ x y))
  7154. (add 40 2)
  7155. \end{lstlisting}
  7156. $\Downarrow$
  7157. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7158. (define (add86 [x87 : Integer]
  7159. [y88 : Integer]) : Integer
  7160. add86start:
  7161. return (+ x87 y88);
  7162. )
  7163. (define (main) : Integer ()
  7164. mainstart:
  7165. tmp89 = (fun-ref add86);
  7166. (tail-call tmp89 40 2)
  7167. )
  7168. \end{lstlisting}
  7169. \end{minipage}
  7170. &
  7171. $\Rightarrow$
  7172. \begin{minipage}{0.5\textwidth}
  7173. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7174. (define (add86) : Integer
  7175. add86start:
  7176. movq %rdi, x87
  7177. movq %rsi, y88
  7178. movq x87, %rax
  7179. addq y88, %rax
  7180. jmp add11389conclusion
  7181. )
  7182. (define (main) : Integer
  7183. mainstart:
  7184. leaq (fun-ref add86), tmp89
  7185. movq $40, %rdi
  7186. movq $2, %rsi
  7187. tail-jmp tmp89
  7188. )
  7189. \end{lstlisting}
  7190. $\Downarrow$
  7191. \end{minipage}
  7192. \end{tabular}
  7193. \begin{tabular}{ll}
  7194. \begin{minipage}{0.3\textwidth}
  7195. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7196. .globl add86
  7197. .align 16
  7198. add86:
  7199. pushq %rbp
  7200. movq %rsp, %rbp
  7201. jmp add86start
  7202. add86start:
  7203. movq %rdi, %rax
  7204. addq %rsi, %rax
  7205. jmp add86conclusion
  7206. add86conclusion:
  7207. popq %rbp
  7208. retq
  7209. \end{lstlisting}
  7210. \end{minipage}
  7211. &
  7212. \begin{minipage}{0.5\textwidth}
  7213. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7214. .globl main
  7215. .align 16
  7216. main:
  7217. pushq %rbp
  7218. movq %rsp, %rbp
  7219. movq $16384, %rdi
  7220. movq $16384, %rsi
  7221. callq initialize
  7222. movq rootstack_begin(%rip), %r15
  7223. jmp mainstart
  7224. mainstart:
  7225. leaq add86(%rip), %rcx
  7226. movq $40, %rdi
  7227. movq $2, %rsi
  7228. movq %rcx, %rax
  7229. popq %rbp
  7230. jmp *%rax
  7231. mainconclusion:
  7232. popq %rbp
  7233. retq
  7234. \end{lstlisting}
  7235. \end{minipage}
  7236. \end{tabular}
  7237. \caption{Example compilation of a simple function to x86.}
  7238. \label{fig:add-fun}
  7239. \end{figure}
  7240. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7241. \chapter{Lexically Scoped Functions}
  7242. \label{ch:lambdas}
  7243. \index{lambda}
  7244. \index{lexical scoping}
  7245. This chapter studies lexically scoped functions as they appear in
  7246. functional languages such as Racket. By lexical scoping we mean that a
  7247. function's body may refer to variables whose binding site is outside
  7248. of the function, in an enclosing scope.
  7249. %
  7250. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  7251. $R_5$, which extends $R_4$ with anonymous functions using the
  7252. \key{lambda} form. The body of the \key{lambda}, refers to three
  7253. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  7254. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  7255. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  7256. parameter of function \code{f}. The \key{lambda} is returned from the
  7257. function \code{f}. The main expression of the program includes two
  7258. calls to \code{f} with different arguments for \code{x}, first
  7259. \code{5} then \code{3}. The functions returned from \code{f} are bound
  7260. to variables \code{g} and \code{h}. Even though these two functions
  7261. were created by the same \code{lambda}, they are really different
  7262. functions because they use different values for \code{x}. Applying
  7263. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  7264. \code{15} produces \code{22}. The result of this program is \code{42}.
  7265. \begin{figure}[btp]
  7266. % s4_6.rkt
  7267. \begin{lstlisting}
  7268. (define (f [x : Integer]) : (Integer -> Integer)
  7269. (let ([y 4])
  7270. (lambda: ([z : Integer]) : Integer
  7271. (+ x (+ y z)))))
  7272. (let ([g (f 5)])
  7273. (let ([h (f 3)])
  7274. (+ (g 11) (h 15))))
  7275. \end{lstlisting}
  7276. \caption{Example of a lexically scoped function.}
  7277. \label{fig:lexical-scoping}
  7278. \end{figure}
  7279. The approach that we take for implementing lexically scoped
  7280. functions is to compile them into top-level function definitions,
  7281. translating from $R_5$ into $R_4$. However, the compiler will need to
  7282. provide special treatment for variable occurrences such as \code{x}
  7283. and \code{y} in the body of the \code{lambda} of
  7284. Figure~\ref{fig:lexical-scoping}. After all, an $R_4$ function may not
  7285. refer to variables defined outside of it. To identify such variable
  7286. occurrences, we review the standard notion of free variable.
  7287. \begin{definition}
  7288. A variable is \emph{free in expression} $e$ if the variable occurs
  7289. inside $e$ but does not have an enclosing binding in $e$.\index{free
  7290. variable}
  7291. \end{definition}
  7292. For example, in the expression \code{(+ x (+ y z))} the variables
  7293. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  7294. only \code{x} and \code{y} are free in the following expression
  7295. because \code{z} is bound by the \code{lambda}.
  7296. \begin{lstlisting}
  7297. (lambda: ([z : Integer]) : Integer
  7298. (+ x (+ y z)))
  7299. \end{lstlisting}
  7300. So the free variables of a \code{lambda} are the ones that will need
  7301. special treatment. We need to arrange for some way to transport, at
  7302. runtime, the values of those variables from the point where the
  7303. \code{lambda} was created to the point where the \code{lambda} is
  7304. applied. An efficient solution to the problem, due to
  7305. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  7306. free variables together with the function pointer for the lambda's
  7307. code, an arrangement called a \emph{flat closure} (which we shorten to
  7308. just ``closure''). \index{closure}\index{flat closure} Fortunately,
  7309. we have all the ingredients to make closures, Chapter~\ref{ch:tuples}
  7310. gave us vectors and Chapter~\ref{ch:functions} gave us function
  7311. pointers. The function pointer resides at index $0$ and the
  7312. values for the free variables will fill in the rest of the vector.
  7313. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  7314. how closures work. It's a three-step dance. The program first calls
  7315. function \code{f}, which creates a closure for the \code{lambda}. The
  7316. closure is a vector whose first element is a pointer to the top-level
  7317. function that we will generate for the \code{lambda}, the second
  7318. element is the value of \code{x}, which is \code{5}, and the third
  7319. element is \code{4}, the value of \code{y}. The closure does not
  7320. contain an element for \code{z} because \code{z} is not a free
  7321. variable of the \code{lambda}. Creating the closure is step 1 of the
  7322. dance. The closure is returned from \code{f} and bound to \code{g}, as
  7323. shown in Figure~\ref{fig:closures}.
  7324. %
  7325. The second call to \code{f} creates another closure, this time with
  7326. \code{3} in the second slot (for \code{x}). This closure is also
  7327. returned from \code{f} but bound to \code{h}, which is also shown in
  7328. Figure~\ref{fig:closures}.
  7329. \begin{figure}[tbp]
  7330. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  7331. \caption{Example closure representation for the \key{lambda}'s
  7332. in Figure~\ref{fig:lexical-scoping}.}
  7333. \label{fig:closures}
  7334. \end{figure}
  7335. Continuing with the example, consider the application of \code{g} to
  7336. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  7337. obtain the function pointer in the first element of the closure and
  7338. call it, passing in the closure itself and then the regular arguments,
  7339. in this case \code{11}. This technique for applying a closure is step
  7340. 2 of the dance.
  7341. %
  7342. But doesn't this \code{lambda} only take 1 argument, for parameter
  7343. \code{z}? The third and final step of the dance is generating a
  7344. top-level function for a \code{lambda}. We add an additional
  7345. parameter for the closure and we insert a \code{let} at the beginning
  7346. of the function for each free variable, to bind those variables to the
  7347. appropriate elements from the closure parameter.
  7348. %
  7349. This three-step dance is known as \emph{closure conversion}. We
  7350. discuss the details of closure conversion in
  7351. Section~\ref{sec:closure-conversion} and the code generated from the
  7352. example in Section~\ref{sec:example-lambda}. But first we define the
  7353. syntax and semantics of $R_5$ in Section~\ref{sec:r5}.
  7354. \section{The $R_5$ Language}
  7355. \label{sec:r5}
  7356. The concrete and abstract syntax for $R_5$, a language with anonymous
  7357. functions and lexical scoping, is defined in
  7358. Figures~\ref{fig:r5-concrete-syntax} and ~\ref{fig:r5-syntax}. It adds
  7359. the \key{lambda} form to the grammar for $R_4$, which already has
  7360. syntax for function application.
  7361. \begin{figure}[tp]
  7362. \centering
  7363. \fbox{
  7364. \begin{minipage}{0.96\textwidth}
  7365. \small
  7366. \[
  7367. \begin{array}{lcl}
  7368. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7369. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}
  7370. \mid (\Type\ldots \; \key{->}\; \Type)} \\
  7371. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  7372. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  7373. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  7374. &\mid& \gray{\key{\#t} \mid \key{\#f}
  7375. \mid (\key{and}\;\Exp\;\Exp)
  7376. \mid (\key{or}\;\Exp\;\Exp)
  7377. \mid (\key{not}\;\Exp) } \\
  7378. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  7379. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  7380. (\key{vector-ref}\;\Exp\;\Int)} \\
  7381. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  7382. \mid (\Exp \; \Exp\ldots) } \\
  7383. &\mid& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  7384. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  7385. R_5 &::=& \gray{\Def\ldots \; \Exp}
  7386. \end{array}
  7387. \]
  7388. \end{minipage}
  7389. }
  7390. \caption{Concrete syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax})
  7391. with \key{lambda}.}
  7392. \label{fig:r5-concrete-syntax}
  7393. \end{figure}
  7394. \begin{figure}[tp]
  7395. \centering
  7396. \fbox{
  7397. \begin{minipage}{0.96\textwidth}
  7398. \small
  7399. \[
  7400. \begin{array}{lcl}
  7401. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  7402. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  7403. &\mid& \gray{ \BOOL{\itm{bool}}
  7404. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  7405. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  7406. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  7407. &\mid& \LAMBDA{\LP[\Var\code{:}\Type]\ldots\RP}{\Type}{\Exp}\\
  7408. \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  7409. R_5 &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  7410. \end{array}
  7411. \]
  7412. \end{minipage}
  7413. }
  7414. \caption{The abstract syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax}).}
  7415. \label{fig:r5-syntax}
  7416. \end{figure}
  7417. \index{interpreter}
  7418. \label{sec:interp-R5}
  7419. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  7420. $R_5$. The clause for \key{lambda} saves the current environment
  7421. inside the returned \key{lambda}. Then the clause for \key{Apply} uses
  7422. the environment from the \key{lambda}, the \code{lam-env}, when
  7423. interpreting the body of the \key{lambda}. The \code{lam-env}
  7424. environment is extended with the mapping of parameters to argument
  7425. values.
  7426. \begin{figure}[tbp]
  7427. \begin{lstlisting}
  7428. (define (interp-exp env)
  7429. (lambda (e)
  7430. (define recur (interp-exp env))
  7431. (match e
  7432. ...
  7433. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  7434. `(lambda ,xs ,body ,env)]
  7435. [(Apply fun args)
  7436. (define fun-val ((interp-exp env) fun))
  7437. (define arg-vals (map (interp-exp env) args))
  7438. (match fun-val
  7439. [`(lambda ,xs ,body ,lam-env)
  7440. (define new-env (append (map cons xs arg-vals) lam-env))
  7441. ((interp-exp new-env) body)]
  7442. [else (error "interp-exp, expected function, not" fun-val)])]
  7443. [else (error 'interp-exp "unrecognized expression")]
  7444. )))
  7445. \end{lstlisting}
  7446. \caption{Interpreter for $R_5$.}
  7447. \label{fig:interp-R5}
  7448. \end{figure}
  7449. \label{sec:type-check-r5}
  7450. \index{type checking}
  7451. Figure~\ref{fig:type-check-R5} shows how to type check the new
  7452. \key{lambda} form. The body of the \key{lambda} is checked in an
  7453. environment that includes the current environment (because it is
  7454. lexically scoped) and also includes the \key{lambda}'s parameters. We
  7455. require the body's type to match the declared return type.
  7456. \begin{figure}[tbp]
  7457. \begin{lstlisting}
  7458. (define (type-check-R5 env)
  7459. (lambda (e)
  7460. (match e
  7461. [(Lambda (and bnd `([,xs : ,Ts] ...)) rT body)
  7462. (define-values (new-body bodyT)
  7463. ((type-check-exp (append (map cons xs Ts) env)) body))
  7464. (define ty `(,@Ts -> ,rT))
  7465. (cond
  7466. [(equal? rT bodyT)
  7467. (values (HasType (Lambda bnd rT new-body) ty) ty)]
  7468. [else
  7469. (error "mismatch in return type" bodyT rT)])]
  7470. ...
  7471. )))
  7472. \end{lstlisting}
  7473. \caption{Type checking the \key{lambda}'s in $R_5$.}
  7474. \label{fig:type-check-R5}
  7475. \end{figure}
  7476. \section{Closure Conversion}
  7477. \label{sec:closure-conversion}
  7478. \index{closure conversion}
  7479. The compiling of lexically-scoped functions into top-level function
  7480. definitions is accomplished in the pass \code{convert-to-closures}
  7481. that comes after \code{reveal-functions} and before
  7482. \code{limit-functions}.
  7483. As usual, we implement the pass as a recursive function over the
  7484. AST. All of the action is in the clauses for \key{lambda} and
  7485. \key{Apply}. We transform a \key{lambda} expression into an expression
  7486. that creates a closure, that is, creates a vector whose first element
  7487. is a function pointer and the rest of the elements are the free
  7488. variables of the \key{lambda}. The \itm{name} is a unique symbol
  7489. generated to identify the function.
  7490. \begin{tabular}{lll}
  7491. \begin{minipage}{0.4\textwidth}
  7492. \begin{lstlisting}
  7493. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  7494. \end{lstlisting}
  7495. \end{minipage}
  7496. &
  7497. $\Rightarrow$
  7498. &
  7499. \begin{minipage}{0.4\textwidth}
  7500. \begin{lstlisting}
  7501. (vector |\itm{name}| |\itm{fvs}| ...)
  7502. \end{lstlisting}
  7503. \end{minipage}
  7504. \end{tabular} \\
  7505. %
  7506. In addition to transforming each \key{lambda} into a \key{vector}, we
  7507. must create a top-level function definition for each \key{lambda}, as
  7508. shown below.\\
  7509. \begin{minipage}{0.8\textwidth}
  7510. \begin{lstlisting}
  7511. (define (|\itm{name}| [clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps}| ...)
  7512. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  7513. ...
  7514. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  7515. |\itm{body'}|)...))
  7516. \end{lstlisting}
  7517. \end{minipage}\\
  7518. The \code{clos} parameter refers to the closure. The $\itm{ps}$
  7519. parameters are the normal parameters of the \key{lambda}. The types
  7520. $\itm{fvts}$ are the types of the free variables in the lambda and the
  7521. underscore is a dummy type because it is rather difficult to give a
  7522. type to the function in the closure's type, and it does not matter.
  7523. The sequence of \key{let} forms bind the free variables to their
  7524. values obtained from the closure.
  7525. We transform function application into code that retrieves the
  7526. function pointer from the closure and then calls the function, passing
  7527. in the closure as the first argument. We bind $e'$ to a temporary
  7528. variable to avoid code duplication.
  7529. \begin{tabular}{lll}
  7530. \begin{minipage}{0.3\textwidth}
  7531. \begin{lstlisting}
  7532. (app |$e$| |\itm{es}| ...)
  7533. \end{lstlisting}
  7534. \end{minipage}
  7535. &
  7536. $\Rightarrow$
  7537. &
  7538. \begin{minipage}{0.5\textwidth}
  7539. \begin{lstlisting}
  7540. (let ([|\itm{tmp}| |$e'$|])
  7541. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  7542. \end{lstlisting}
  7543. \end{minipage}
  7544. \end{tabular} \\
  7545. There is also the question of what to do with top-level function
  7546. definitions. To maintain a uniform translation of function
  7547. application, we turn function references into closures.
  7548. \begin{tabular}{lll}
  7549. \begin{minipage}{0.3\textwidth}
  7550. \begin{lstlisting}
  7551. (fun-ref |$f$|)
  7552. \end{lstlisting}
  7553. \end{minipage}
  7554. &
  7555. $\Rightarrow$
  7556. &
  7557. \begin{minipage}{0.5\textwidth}
  7558. \begin{lstlisting}
  7559. (vector (fun-ref |$f$|))
  7560. \end{lstlisting}
  7561. \end{minipage}
  7562. \end{tabular} \\
  7563. %
  7564. The top-level function definitions need to be updated as well to take
  7565. an extra closure parameter.
  7566. \section{An Example Translation}
  7567. \label{sec:example-lambda}
  7568. Figure~\ref{fig:lexical-functions-example} shows the result of
  7569. \code{reveal-functions} and then \code{convert-to-closures} for the
  7570. example program demonstrating lexical scoping that we discussed at the
  7571. beginning of this chapter.
  7572. \begin{figure}[h]
  7573. \begin{minipage}{0.8\textwidth}
  7574. % tests/s4_6.rkt
  7575. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  7576. (define (f74 [x75 : Integer]) : (Integer -> Integer)
  7577. (let ([y76 4])
  7578. (lambda: ( [z77 : Integer]) : Integer
  7579. (+ x75 (+ y76 z77)))))
  7580. (define (main) : Integer
  7581. (let ([g78 ((fun-ref f74) 5)])
  7582. (let ([h79 ((fun-ref f74) 3)])
  7583. (+ (g78 11) (h79 15)))))
  7584. \end{lstlisting}
  7585. $\Downarrow$
  7586. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  7587. (define (f74 [fvs82 : _] [x75 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  7588. (let ([y76 4])
  7589. (vector (fun-ref lambda80) x75 y76)))
  7590. (define (lambda80 [fvs81 : (Vector _ Integer Integer)] [z77 : Integer]) : Integer
  7591. (let ([x75 (vector-ref fvs81 1)])
  7592. (let ([y76 (vector-ref fvs81 2)])
  7593. (+ x75 (+ y76 z77)))))
  7594. (define (main) : Integer
  7595. (let ([g78 (let ([app83 (vector (fun-ref f74))])
  7596. ((vector-ref app83 0) app83 5))])
  7597. (let ([h79 (let ([app84 (vector (fun-ref f74))])
  7598. ((vector-ref app84 0) app84 3))])
  7599. (+ (let ([app85 g78])
  7600. ((vector-ref app85 0) app85 11))
  7601. (let ([app86 h79])
  7602. ((vector-ref app86 0) app86 15))))))
  7603. \end{lstlisting}
  7604. \end{minipage}
  7605. \caption{Example of closure conversion.}
  7606. \label{fig:lexical-functions-example}
  7607. \end{figure}
  7608. \begin{figure}[p]
  7609. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7610. \node (R4) at (0,2) {\large $R_4$};
  7611. \node (R4-2) at (3,2) {\large $R_4$};
  7612. \node (R4-3) at (6,2) {\large $R_4$};
  7613. \node (F1-1) at (12,0) {\large $F_1$};
  7614. \node (F1-2) at (9,0) {\large $F_1$};
  7615. \node (F1-3) at (6,0) {\large $F_1$};
  7616. \node (F1-4) at (3,0) {\large $F_1$};
  7617. \node (F1-5) at (0,0) {\large $F_1$};
  7618. \node (C3-1) at (6,-2) {\large $C_3$};
  7619. \node (C3-2) at (3,-2) {\large $C_3$};
  7620. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  7621. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  7622. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  7623. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  7624. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  7625. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  7626. \path[->,bend left=15] (R4) edge [above] node
  7627. {\ttfamily\footnotesize\color{red} type-check} (R4-2);
  7628. \path[->,bend left=15] (R4-2) edge [above] node
  7629. {\ttfamily\footnotesize uniquify} (R4-3);
  7630. \path[->] (R4-3) edge [right] node
  7631. {\ttfamily\footnotesize reveal-functions} (F1-1);
  7632. \path[->,bend left=15] (F1-1) edge [below] node
  7633. {\ttfamily\footnotesize\color{red} convert-to-clos.} (F1-2);
  7634. \path[->,bend right=15] (F1-2) edge [above] node
  7635. {\ttfamily\footnotesize limit-functions} (F1-3);
  7636. \path[->,bend right=15] (F1-3) edge [above] node
  7637. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  7638. \path[->,bend right=15] (F1-4) edge [above] node
  7639. {\ttfamily\footnotesize remove-complex.} (F1-5);
  7640. \path[->] (F1-5) edge [left] node
  7641. {\ttfamily\footnotesize explicate-control} (C3-1);
  7642. \path[->,bend left=15] (C3-1) edge [below] node
  7643. {\ttfamily\footnotesize uncover-locals} (C3-2);
  7644. \path[->,bend right=15] (C3-2) edge [left] node
  7645. {\ttfamily\footnotesize select-instr.} (x86-2);
  7646. \path[->,bend left=15] (x86-2) edge [left] node
  7647. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  7648. \path[->,bend right=15] (x86-2-1) edge [below] node
  7649. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  7650. \path[->,bend right=15] (x86-2-2) edge [left] node
  7651. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7652. \path[->,bend left=15] (x86-3) edge [above] node
  7653. {\ttfamily\footnotesize patch-instr.} (x86-4);
  7654. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  7655. \end{tikzpicture}
  7656. \caption{Diagram of the passes for $R_5$, a language with lexically-scoped
  7657. functions.}
  7658. \label{fig:R5-passes}
  7659. \end{figure}
  7660. Figure~\ref{fig:R5-passes} provides an overview of all the passes needed
  7661. for the compilation of $R_5$.
  7662. \begin{exercise}\normalfont
  7663. Expand your compiler to handle $R_5$ as outlined in this chapter.
  7664. Create 5 new programs that use \key{lambda} functions and make use of
  7665. lexical scoping. Test your compiler on these new programs and all of
  7666. your previously created test programs.
  7667. \end{exercise}
  7668. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7669. \chapter{Dynamic Typing}
  7670. \label{ch:type-dynamic}
  7671. \index{dynamic typing}
  7672. In this chapter we discuss the compilation $R_7$, a dynamically typed
  7673. language and a subset of the Racket language. Recall that in the
  7674. previous chapters we have compiled subsets of the \emph{Typed} Racket
  7675. language. In dynamically typed languages, each evaluation of an
  7676. expression may produce a value of a different type. Consider the
  7677. following example with a conditional expression that may return a
  7678. Boolean or an integer depending on the input to the program.
  7679. \begin{lstlisting}
  7680. (not (if (eq? (read) 1) #f 0))
  7681. \end{lstlisting}
  7682. Languages that allow expressions to produce different kinds of values
  7683. are called \emph{polymorphic}, a word composed of the Greek roots
  7684. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  7685. are several kinds of polymorphism in programming languages, such as
  7686. subtype polymorphism and parametric
  7687. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  7688. study in this chapter does not have a special name but it is the kind
  7689. that arises in dynamically typed languages.
  7690. Another characteristic of dynamically typed languages is that
  7691. primitive operations, such as \code{not}, are often defined to operate
  7692. on many different types of values. In fact, in Racket, the \code{not}
  7693. operator produces a result for any kind of value: given \code{\#f} it
  7694. returns \code{\#t} and given anything else it returns \code{\#f}.
  7695. Furthermore, even when primitive operations restrict their inputs to
  7696. values of a certain type, this restriction is enforced at runtime
  7697. instead of during compilation. For example, the following vector
  7698. reference results in a run-time contract violation because the index
  7699. must be in integer, not a Boolean such as \code{\#t}.
  7700. \begin{lstlisting}
  7701. (vector-ref (vector 42) #t)
  7702. \end{lstlisting}
  7703. \begin{figure}[tp]
  7704. \centering
  7705. \fbox{
  7706. \begin{minipage}{0.97\textwidth}
  7707. \[
  7708. \begin{array}{rcl}
  7709. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  7710. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp}
  7711. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} \\
  7712. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  7713. &\mid& \key{\#t} \mid \key{\#f}
  7714. \mid \CBINOP{\key{and}}{\Exp}{\Exp}
  7715. \mid \CBINOP{\key{or}}{\Exp}{\Exp}
  7716. \mid \CUNIOP{\key{not}}{\Exp} \\
  7717. &\mid& \LP\itm{cmp}\;\Exp\;\Exp\RP \mid \CIF{\Exp}{\Exp}{\Exp} \\
  7718. &\mid& \LP\key{vector}\;\Exp\ldots\RP \mid
  7719. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  7720. &\mid& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \mid \LP\key{void}\RP \\
  7721. &\mid& \LP\Exp \; \Exp\ldots\RP
  7722. \mid \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  7723. & \mid & \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP\\
  7724. & \mid & \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \mid \LP\key{void?}\;\Exp\RP \\
  7725. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  7726. R_7 &::=& \Def\ldots\; \Exp
  7727. \end{array}
  7728. \]
  7729. \end{minipage}
  7730. }
  7731. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  7732. \label{fig:r7-concrete-syntax}
  7733. \end{figure}
  7734. \begin{figure}[tp]
  7735. \centering
  7736. \fbox{
  7737. \begin{minipage}{0.96\textwidth}
  7738. \small
  7739. \[
  7740. \begin{array}{lcl}
  7741. \Exp &::=& \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  7742. &\mid& \PRIM{\itm{op}}{\Exp\ldots} \\
  7743. &\mid& \BOOL{\itm{bool}}
  7744. \mid \IF{\Exp}{\Exp}{\Exp} \\
  7745. &\mid& \VOID{} \mid \APPLY{\Exp}{\Exp\ldots} \\
  7746. &\mid& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  7747. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  7748. R_7 &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  7749. \end{array}
  7750. \]
  7751. \end{minipage}
  7752. }
  7753. \caption{The abstract syntax of $R_7$.}
  7754. \label{fig:r7-syntax}
  7755. \end{figure}
  7756. The concrete and abstract syntax of $R_7$, our subset of Racket, is
  7757. defined in Figures~\ref{fig:r7-concrete-syntax} and
  7758. \ref{fig:r7-syntax}.
  7759. %
  7760. There is no type checker for $R_7$ because it is not a statically
  7761. typed language (it's dynamically typed!).
  7762. %
  7763. The definitional interpreter for $R_7$ is presented in
  7764. Figure~\ref{fig:interp-R7}.
  7765. \begin{figure}[tbp]
  7766. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7767. (define (interp-R7-exp env)
  7768. (lambda (ast)
  7769. (define recur (interp-R7-exp env))
  7770. (match ast
  7771. [(Var x) (lookup x env)]
  7772. [(Int n) `(tagged ,n Integer)]
  7773. [(Bool b) `(tagged ,b Boolean)]
  7774. [(Prim 'read '()) `(tagged ,(read-fixnum) Integer)]
  7775. [(Lambda xs rt body)
  7776. `(tagged (lambda ,xs ,body ,env) (,@(for/list ([x xs]) 'Any) -> Any))]
  7777. [(Prim 'vector es)
  7778. `(tagged ,(apply vector (for/list ([e es]) (recur e)))
  7779. (Vector ,@(for/list ([e es]) 'Any)))]
  7780. [(Prim 'vector-set! (list e1 n e2))
  7781. (define vec (value-of-any (recur e1)))
  7782. (define i (value-of-any (recur n)))
  7783. (vector-set! vec i (recur e2))
  7784. `(tagged ,(void) Void)]
  7785. [(Prim 'vector-ref (list e1 n))
  7786. (define vec (value-of-any (recur e1)))
  7787. (define i (value-of-any (recur n)))
  7788. (vector-ref vec i)]
  7789. [(Let x e body)
  7790. (define v (recur e))
  7791. ((interp-R7-exp (cons (cons x v) env)) body)]
  7792. [(Prim 'and (list e1 e2))
  7793. (recur (If e1 e2 (Bool #f)))]
  7794. [(Prim 'or (list e1 e2))
  7795. (define v1 (recur e1))
  7796. (match (value-of-any v1) [#f (recur e2)] [else v1])]
  7797. [(Prim 'eq? (list l r))
  7798. `(tagged ,(equal? (recur l) (recur r)) Boolean)]
  7799. [(If q t f)
  7800. (match (value-of-any (recur q)) [#f (recur f)] [else (recur t)])]
  7801. [(Prim op es)
  7802. (tag-value
  7803. (apply (interp-op op) (for/list ([e es]) (value-of-any (recur e)))))]
  7804. [(Apply f es)
  7805. (define new-args (map recur es))
  7806. (let ([f-val (value-of-any (recur f))])
  7807. (match f-val
  7808. [`(lambda (,xs ...) ,body ,lam-env)
  7809. (define new-env (append (map cons xs new-args) lam-env))
  7810. ((interp-R7-exp new-env) body)]
  7811. [else (error "interp-R7-exp, expected function, not" f-val)]))]
  7812. )))
  7813. \end{lstlisting}
  7814. \caption{Interpreter for the $R_7$ language.}
  7815. \label{fig:interp-R7}
  7816. \end{figure}
  7817. Let us consider how we might compile $R_7$ to x86, thinking about the
  7818. first example above. Our bit-level representation of the Boolean
  7819. \code{\#f} is zero and similarly for the integer \code{0}. However,
  7820. \code{(not \#f)} should produce \code{\#t} whereas \code{(not 0)}
  7821. should produce \code{\#f}. Furthermore, the behavior of \code{not}, in
  7822. general, cannot be determined at compile time, but depends on the
  7823. runtime type of its input, as in the example above that depends on the
  7824. result of \code{(read)}.
  7825. The way around this problem is to include information about a value's
  7826. runtime type in the value itself, so that this information can be
  7827. inspected by operators such as \code{not}. In particular, we
  7828. steal the 3 right-most bits from our 64-bit values to encode the
  7829. runtime type. We use $001$ to identify integers, $100$ for
  7830. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  7831. void value. We refer to these 3 bits as the \emph{tag} and we
  7832. define the following auxiliary function.
  7833. \begin{align*}
  7834. \itm{tagof}(\key{Integer}) &= 001 \\
  7835. \itm{tagof}(\key{Boolean}) &= 100 \\
  7836. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  7837. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  7838. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  7839. \itm{tagof}(\key{Void}) &= 101
  7840. \end{align*}
  7841. (We say more about the new \key{Vectorof} type shortly.)
  7842. This stealing of 3 bits comes at some
  7843. price: our integers are reduced to ranging from $-2^{60}$ to
  7844. $2^{60}$. The stealing does not adversely affect vectors and
  7845. procedures because those values are addresses, and our addresses are
  7846. 8-byte aligned so the rightmost 3 bits are unused, they are always
  7847. $000$. Thus, we do not lose information by overwriting the rightmost 3
  7848. bits with the tag and we can simply zero-out the tag to recover the
  7849. original address.
  7850. In some sense, these tagged values are a new kind of value. Indeed,
  7851. we can extend our \emph{typed} language with tagged values by adding a
  7852. new type to classify them, called \key{Any}, and with operations for
  7853. creating and using tagged values, yielding the $R_6$ language that we
  7854. define in Section~\ref{sec:r6-lang}. The $R_6$ language provides the
  7855. fundamental support for polymorphism and runtime types that we need to
  7856. support dynamic typing.
  7857. There is an interesting interaction between tagged values and garbage
  7858. collection. A variable of type \code{Any} might refer to a vector and
  7859. therefore it might be a root that needs to be inspected and copied
  7860. during garbage collection. Thus, we need to treat variables of type
  7861. \code{Any} in a similar way to variables of type \code{Vector} for
  7862. purposes of register allocation, which we discuss in
  7863. Section~\ref{sec:register-allocation-r6}. One concern is that, if a
  7864. variable of type \code{Any} is spilled, it must be spilled to the root
  7865. stack. But this means that the garbage collector needs to be able to
  7866. differentiate between (1) plain old pointers to tuples, (2) a tagged
  7867. value that points to a tuple, and (3) a tagged value that is not a
  7868. tuple. We enable this differentiation by choosing not to use the tag
  7869. $000$ in $\itm{tagof}$. Instead, that bit pattern is reserved for
  7870. identifying plain old pointers to tuples. That way, if one of the
  7871. first three bits is set, then we have a tagged value and inspecting
  7872. the tag can differentiation between vectors ($010$) and the other
  7873. kinds of values.
  7874. We implement our untyped language $R_7$ by compiling it to $R_6$
  7875. (Section~\ref{sec:compile-r7}), but first we describe the how to
  7876. extend our compiler to handle the new features of $R_6$
  7877. (Sections~\ref{sec:shrink-r6}, \ref{sec:select-r6}, and
  7878. \ref{sec:register-allocation-r6}).
  7879. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  7880. \label{sec:r6-lang}
  7881. \begin{figure}[tp]
  7882. \centering
  7883. \fbox{
  7884. \begin{minipage}{0.97\textwidth}\small
  7885. \[
  7886. \begin{array}{lcl}
  7887. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7888. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \LP\key{Vectorof}\;\Type\RP \mid \key{Void}} \\
  7889. &\mid& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \mid \key{Any} \\
  7890. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void} \mid \LP\key{Vectorof}\;\key{Any}\RP \mid \LP\key{Vector}\; \key{Any}\ldots\RP \\
  7891. &\mid& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  7892. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  7893. \Exp &::=& \ldots
  7894. \mid \CINJECT{\Exp}{\FType}\RP \mid \CPROJECT{\Exp}{\FType} \\
  7895. & \mid & \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP\\
  7896. & \mid & \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \mid \LP\key{void?}\;\Exp\RP \\
  7897. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  7898. R_6 &::=& \gray{\Def\ldots \; \Exp}
  7899. \end{array}
  7900. \]
  7901. \end{minipage}
  7902. }
  7903. \caption{Concrete syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax})
  7904. with \key{Any}.}
  7905. \label{fig:r6-concrete-syntax}
  7906. \end{figure}
  7907. \begin{figure}[tp]
  7908. \centering
  7909. \fbox{
  7910. \begin{minipage}{0.96\textwidth}
  7911. \small
  7912. \[
  7913. \begin{array}{lcl}
  7914. \itm{op} &::= & \code{boolean?} \mid \code{integer?} \mid \code{vector?}
  7915. \mid \code{procedure?} \mid \code{void?} \\
  7916. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  7917. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  7918. &\mid& \gray{ \BOOL{\itm{bool}}
  7919. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  7920. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  7921. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  7922. &\mid& \gray{ \LAMBDA{\LP[\Var\code{:}\Type]\ldots\RP}{\Type}{\Exp} }\\
  7923. &\mid& \INJECT{\Exp}{\FType} \mid \PROJECT{\Exp}{\FType} \\
  7924. \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  7925. R_5 &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  7926. \end{array}
  7927. \]
  7928. \end{minipage}
  7929. }
  7930. \caption{The abstract syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax}).}
  7931. \label{fig:r6-syntax}
  7932. \end{figure}
  7933. The concrete and abstract syntax of $R_6$ is defined in
  7934. Figures~\ref{fig:r6-concrete-syntax} and \ref{fig:r6-syntax}. The
  7935. $\LP\key{inject}\; e\; T\RP$ form converts the value produced by
  7936. expression $e$ of type $T$ into a tagged value. The
  7937. $\LP\key{project}\;e\;T\RP$ form converts the tagged value produced by
  7938. expression $e$ into a value of type $T$ or else halts the program if
  7939. the type tag is not equivalent to $T$. We treat
  7940. $\LP\key{Vectorof}\;\key{Any}\RP$ as equivalent to
  7941. $\LP\key{Vector}\;\key{Any}\;\ldots\RP$.
  7942. %
  7943. Note that in both \key{inject} and \key{project}, the type $T$ is
  7944. restricted to the flat types $\FType$, which simplifies the
  7945. implementation and corresponds with what is needed for compiling
  7946. untyped Racket.
  7947. The type predicates such as $\LP\key{boolean?}\,e\RP$ expect the
  7948. expression $e$ to produce a tagged value; they return \key{\#t} if the
  7949. tag corresponds to the predicate and they return \key{\#f} otherwise.
  7950. The type checker for $R_6$ is shown in Figure~\ref{fig:type-check-R6}
  7951. and the interpreter for $R_6$ is in Figure~\ref{fig:interp-R6}.
  7952. \begin{figure}[btp]
  7953. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7954. (define (operator-types)
  7955. '(...
  7956. (integer? . ((Any) . Boolean))
  7957. (vector? . ((Any) . Boolean))
  7958. (procedure? . ((Any) . Boolean))
  7959. (void? . ((Any) . Boolean))
  7960. ))
  7961. (define (type-check-exp env)
  7962. (lambda (e)
  7963. (define recur (type-check-exp env))
  7964. (match e
  7965. ...
  7966. [(Inject e ty)
  7967. (unless (flat-ty? ty)
  7968. (error 'type-check-exp
  7969. "may only inject a value of flat type, not ~a" ty))
  7970. (define-values (new-e e-ty) (recur e))
  7971. (cond
  7972. [(type-equal? e-ty ty)
  7973. (values (Inject new-e ty) 'Any)]
  7974. [else
  7975. (error 'type-check-exp
  7976. "injected expression does not have expected type"
  7977. e e-ty ty)])]
  7978. [(Project e ty)
  7979. (unless (flat-ty? ty)
  7980. (error 'type-check-exp
  7981. "may only project to a flat type, not ~a" ty))
  7982. (define-values (new-e e-ty) (recur e))
  7983. (cond
  7984. [(type-equal? e-ty 'Any)
  7985. (values (Project new-e ty) ty)]
  7986. [else
  7987. (error 'type-check-exp
  7988. "project expression does not have type Any" e)])]
  7989. [(Prim pred (list e))
  7990. #:when (set-member? type-predicates pred)
  7991. (define-values (new-e e-ty) (recur e))
  7992. (cond
  7993. [(type-equal? e-ty 'Any)
  7994. (values (Prim pred (list new-e)) 'Boolean)]
  7995. [else
  7996. (error 'type-check-exp
  7997. "type predicate expected argument of type Any, not ~a" e-ty)])]
  7998. ...
  7999. [else
  8000. (error 'type-check-exp "R6/unmatched ~a" e)]
  8001. )))
  8002. \end{lstlisting}
  8003. \caption{Type checker for the $R_6$ language.}
  8004. \label{fig:type-check-R6}
  8005. \end{figure}
  8006. % to do: add rules for vector-ref, etc. for Vectorof
  8007. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  8008. \begin{figure}[btp]
  8009. \begin{lstlisting}
  8010. (define (interp-op op)
  8011. (match op
  8012. ...
  8013. ['boolean? (lambda (v)
  8014. (match v
  8015. [`(tagged ,v1 ,tg)
  8016. (equal? tg (any-tag 'Boolean))]
  8017. [else #f]))]
  8018. ['integer? (lambda (v)
  8019. (match v
  8020. [`(tagged ,v1 ,tg)
  8021. (equal? tg (any-tag 'Integer))]
  8022. [else #f]))]
  8023. ['vector? (lambda (v)
  8024. (match v
  8025. [`(tagged ,v1 ,tg)
  8026. (equal? tg (any-tag `(Vector Any)))]
  8027. [else #f]))]
  8028. ['procedure? (lambda (v)
  8029. (match v
  8030. [`(tagged ,v1 ,tg)
  8031. (equal? tg (any-tag `(Any -> Any)))]
  8032. [else #f]))]
  8033. ...
  8034. ))
  8035. (define (interp-exp env)
  8036. (lambda (e)
  8037. (define recur (interp-exp env))
  8038. (let ([ret
  8039. (match e
  8040. ...
  8041. [(Inject e ty)
  8042. (apply-inject ((interp-exp env) e) (any-tag ty))]
  8043. [(Project e ty2)
  8044. (define v (recur e))
  8045. (apply-project v ty2)]
  8046. [(Exit)
  8047. (error 'interp-exp "exiting")]
  8048. [else (error 'interp-exp "unrecognized expression ~a" e)]
  8049. )])
  8050. (verbose "R6/interp-exp ==>" ret)
  8051. ret)))
  8052. \end{lstlisting}
  8053. \caption{Interpreter for $R_6$.}
  8054. \label{fig:interp-R6}
  8055. \end{figure}
  8056. %\clearpage
  8057. \section{Shrinking $R_6$}
  8058. \label{sec:shrink-r6}
  8059. In the \code{shrink} pass we recommend compiling \code{Project} into
  8060. an explicit \code{If} expression that uses two new forms,
  8061. \code{ValueOf} and \code{Exit}, and a new primitive operation,
  8062. \code{tag-of-any}. The \code{tag-of-any} operation retrieves the type
  8063. tag from a tagged value of type \code{Any}. The \code{ValueOf} form
  8064. retrieves the underlying value from a tagged value. The
  8065. \code{ValueOf} form includes the type for the underlying value, which
  8066. is needed by the type checker. Finally, the \code{Exit} form ends the
  8067. execution of the program by invoking the operating system's
  8068. \code{exit} function. So the translation for \code{Project} is as
  8069. follows.
  8070. %(We have omitted the \code{has-type} AST nodes to make this
  8071. %output more readable.)
  8072. \begin{lstlisting}
  8073. (Project |$e$| |$\FType$|)
  8074. |$\Rightarrow$|
  8075. (Let |$\itm{tmp}$| |$e'$|
  8076. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  8077. (Int |$\itm{tagof}(\FType)$|)))
  8078. (ValueOf |$\itm{tmp}$| |$\FType$|)
  8079. (Exit)))
  8080. \end{lstlisting}
  8081. Regarding \code{Inject}, we recommend compiling it to a slightly
  8082. lower-level primitive operation named \code{make-any}. This operation
  8083. takes the tag instead of the type of the injected value.
  8084. \begin{lstlisting}
  8085. (Inject |$e$| |$\FType$|)
  8086. |$\Rightarrow$|
  8087. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  8088. \end{lstlisting}
  8089. We recommend translating the type predicates (\code{boolean?}, etc.)
  8090. into uses of \code{tag-of-any} and \code{eq?}.
  8091. \section{Instruction Selection for $R_6$}
  8092. \label{sec:select-r6}
  8093. \paragraph{Inject}
  8094. We recommend compiling an \key{inject} as follows if the type is
  8095. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  8096. destination to the left by the number of bits specified its source
  8097. argument (in this case $3$, the length of the tag) and it preserves
  8098. the sign of the integer. We use the \key{orq} instruction to combine
  8099. the tag and the value to form the tagged value. \\
  8100. \begin{tabular}{lll}
  8101. \begin{minipage}{0.4\textwidth}
  8102. \begin{lstlisting}
  8103. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  8104. \end{lstlisting}
  8105. \end{minipage}
  8106. &
  8107. $\Rightarrow$
  8108. &
  8109. \begin{minipage}{0.5\textwidth}
  8110. \begin{lstlisting}
  8111. (movq |$e'$| |\itm{lhs}'|)
  8112. (salq (int 3) |\itm{lhs}'|)
  8113. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  8114. \end{lstlisting}
  8115. \end{minipage}
  8116. \end{tabular} \\
  8117. The instruction selection for vectors and procedures is different
  8118. because their is no need to shift them to the left. The rightmost 3
  8119. bits are already zeros as described above. So we just combine the
  8120. value and the tag using \key{orq}. \\
  8121. \begin{tabular}{lll}
  8122. \begin{minipage}{0.4\textwidth}
  8123. \begin{lstlisting}
  8124. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  8125. \end{lstlisting}
  8126. \end{minipage}
  8127. &
  8128. $\Rightarrow$
  8129. &
  8130. \begin{minipage}{0.5\textwidth}
  8131. \begin{lstlisting}
  8132. (movq |$e'$| |\itm{lhs}'|)
  8133. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  8134. \end{lstlisting}
  8135. \end{minipage}
  8136. \end{tabular}
  8137. \paragraph{Tag of Any}
  8138. Recall that the \code{tag-of-any} operation extracts the type tag from
  8139. a value of type \code{Any}. The type tag is the bottom three bits, so
  8140. we obtain the tag by taking the bitwise-and of the value with $111$
  8141. ($7$ in decimal).
  8142. \begin{tabular}{lll}
  8143. \begin{minipage}{0.4\textwidth}
  8144. \begin{lstlisting}
  8145. (assign |\itm{lhs}| (tag-of-any |$e$|))
  8146. \end{lstlisting}
  8147. \end{minipage}
  8148. &
  8149. $\Rightarrow$
  8150. &
  8151. \begin{minipage}{0.5\textwidth}
  8152. \begin{lstlisting}
  8153. (movq |$e'$| |\itm{lhs}'|)
  8154. (andq (int 7) |\itm{lhs}'|)
  8155. \end{lstlisting}
  8156. \end{minipage}
  8157. \end{tabular}
  8158. \paragraph{Value of Any}
  8159. Like \key{inject}, the instructions for \key{value-of-any} are
  8160. different depending on whether the type $T$ is a pointer (vector or
  8161. procedure) or not (Integer or Boolean). The following shows the
  8162. instruction selection for Integer and Boolean. We produce an untagged
  8163. value by shifting it to the right by 3 bits.
  8164. %
  8165. \\
  8166. \begin{tabular}{lll}
  8167. \begin{minipage}{0.4\textwidth}
  8168. \begin{lstlisting}
  8169. (assign |\itm{lhs}| (project |$e$| |$T$|))
  8170. \end{lstlisting}
  8171. \end{minipage}
  8172. &
  8173. $\Rightarrow$
  8174. &
  8175. \begin{minipage}{0.5\textwidth}
  8176. \begin{lstlisting}
  8177. (movq |$e'$| |\itm{lhs}'|)
  8178. (sarq (int 3) |\itm{lhs}'|)
  8179. \end{lstlisting}
  8180. \end{minipage}
  8181. \end{tabular} \\
  8182. %
  8183. In the case for vectors and procedures, there is no need to
  8184. shift. Instead we just need to zero-out the rightmost 3 bits. We
  8185. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  8186. decimal) and apply \code{bitwise-not} to obtain $\ldots 1000$ which we
  8187. \code{movq} into the destination $\itm{lhs}$. We then generate
  8188. \code{andq} with the tagged value to get the desired result. \\
  8189. %
  8190. \begin{tabular}{lll}
  8191. \begin{minipage}{0.4\textwidth}
  8192. \begin{lstlisting}
  8193. (assign |\itm{lhs}| (project |$e$| |$T$|))
  8194. \end{lstlisting}
  8195. \end{minipage}
  8196. &
  8197. $\Rightarrow$
  8198. &
  8199. \begin{minipage}{0.5\textwidth}
  8200. \begin{lstlisting}
  8201. (movq (int |$\ldots 1000$|) |\itm{lhs}'|)
  8202. (andq |$e'$| |\itm{lhs}'|)
  8203. \end{lstlisting}
  8204. \end{minipage}
  8205. \end{tabular}
  8206. %% \paragraph{Type Predicates} We leave it to the reader to
  8207. %% devise a sequence of instructions to implement the type predicates
  8208. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  8209. \section{Register Allocation for $R_6$}
  8210. \label{sec:register-allocation-r6}
  8211. \index{register allocation}
  8212. As mentioned above, a variable of type \code{Any} might refer to a
  8213. vector. Thus, the register allocator for $R_6$ needs to treat variable
  8214. of type \code{Any} in the same way that it treats variables of type
  8215. \code{Vector} for purposes of garbage collection. In particular,
  8216. \begin{itemize}
  8217. \item If a variable of type \code{Any} is live during a function call,
  8218. then it must be spilled. One way to accomplish this is to augment
  8219. the pass \code{build-interference} to mark all variables that are
  8220. live after a \code{callq} as interfering with all the registers.
  8221. \item If a variable of type \code{Any} is spilled, it must be spilled
  8222. to the root stack instead of the normal procedure call stack.
  8223. \end{itemize}
  8224. \begin{exercise}\normalfont
  8225. Expand your compiler to handle $R_6$ as discussed in the last few
  8226. sections. Create 5 new programs that use the \code{Any} type and the
  8227. new operations (\code{inject}, \code{project}, \code{boolean?},
  8228. etc.). Test your compiler on these new programs and all of your
  8229. previously created test programs.
  8230. \end{exercise}
  8231. \section{Compiling $R_7$ to $R_6$}
  8232. \label{sec:compile-r7}
  8233. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  8234. $R_7$ forms into $R_6$. An important invariant of this pass is that
  8235. given a subexpression $e$ of $R_7$, the pass will produce an
  8236. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  8237. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  8238. the Boolean \code{\#t}, which must be injected to produce an
  8239. expression of type \key{Any}.
  8240. %
  8241. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  8242. addition, is representative of compilation for many operations: the
  8243. arguments have type \key{Any} and must be projected to \key{Integer}
  8244. before the addition can be performed.
  8245. The compilation of \key{lambda} (third row of
  8246. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  8247. produce type annotations: we simply use \key{Any}.
  8248. %
  8249. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  8250. has to account for some differences in behavior between $R_7$ and
  8251. $R_6$. The $R_7$ language is more permissive than $R_6$ regarding what
  8252. kind of values can be used in various places. For example, the
  8253. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  8254. the arguments need not be of the same type (but in that case, the
  8255. result will be \code{\#f}).
  8256. \begin{figure}[btp]
  8257. \centering
  8258. \begin{tabular}{|lll|} \hline
  8259. \begin{minipage}{0.25\textwidth}
  8260. \begin{lstlisting}
  8261. #t
  8262. \end{lstlisting}
  8263. \end{minipage}
  8264. &
  8265. $\Rightarrow$
  8266. &
  8267. \begin{minipage}{0.6\textwidth}
  8268. \begin{lstlisting}
  8269. (inject #t Boolean)
  8270. \end{lstlisting}
  8271. \end{minipage}
  8272. \\[2ex]\hline
  8273. \begin{minipage}{0.25\textwidth}
  8274. \begin{lstlisting}
  8275. (+ |$e_1$| |$e_2$|)
  8276. \end{lstlisting}
  8277. \end{minipage}
  8278. &
  8279. $\Rightarrow$
  8280. &
  8281. \begin{minipage}{0.6\textwidth}
  8282. \begin{lstlisting}
  8283. (inject
  8284. (+ (project |$e'_1$| Integer)
  8285. (project |$e'_2$| Integer))
  8286. Integer)
  8287. \end{lstlisting}
  8288. \end{minipage}
  8289. \\[2ex]\hline
  8290. \begin{minipage}{0.25\textwidth}
  8291. \begin{lstlisting}
  8292. (lambda (|$x_1 \ldots$|) |$e$|)
  8293. \end{lstlisting}
  8294. \end{minipage}
  8295. &
  8296. $\Rightarrow$
  8297. &
  8298. \begin{minipage}{0.6\textwidth}
  8299. \begin{lstlisting}
  8300. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  8301. (Any|$\ldots$|Any -> Any))
  8302. \end{lstlisting}
  8303. \end{minipage}
  8304. \\[2ex]\hline
  8305. \begin{minipage}{0.25\textwidth}
  8306. \begin{lstlisting}
  8307. (app |$e_0$| |$e_1 \ldots e_n$|)
  8308. \end{lstlisting}
  8309. \end{minipage}
  8310. &
  8311. $\Rightarrow$
  8312. &
  8313. \begin{minipage}{0.6\textwidth}
  8314. \begin{lstlisting}
  8315. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  8316. |$e'_1 \ldots e'_n$|)
  8317. \end{lstlisting}
  8318. \end{minipage}
  8319. \\[2ex]\hline
  8320. \begin{minipage}{0.25\textwidth}
  8321. \begin{lstlisting}
  8322. (vector-ref |$e_1$| |$e_2$|)
  8323. \end{lstlisting}
  8324. \end{minipage}
  8325. &
  8326. $\Rightarrow$
  8327. &
  8328. \begin{minipage}{0.6\textwidth}
  8329. \begin{lstlisting}
  8330. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  8331. (let ([tmp2 (project |$e'_2$| Integer)])
  8332. (vector-ref tmp1 tmp2)))
  8333. \end{lstlisting}
  8334. \end{minipage}
  8335. \\[2ex]\hline
  8336. \begin{minipage}{0.25\textwidth}
  8337. \begin{lstlisting}
  8338. (if |$e_1$| |$e_2$| |$e_3$|)
  8339. \end{lstlisting}
  8340. \end{minipage}
  8341. &
  8342. $\Rightarrow$
  8343. &
  8344. \begin{minipage}{0.6\textwidth}
  8345. \begin{lstlisting}
  8346. (if (eq? |$e'_1$| (inject #f Boolean))
  8347. |$e'_3$|
  8348. |$e'_2$|)
  8349. \end{lstlisting}
  8350. \end{minipage}
  8351. \\[2ex]\hline
  8352. \begin{minipage}{0.25\textwidth}
  8353. \begin{lstlisting}
  8354. (eq? |$e_1$| |$e_2$|)
  8355. \end{lstlisting}
  8356. \end{minipage}
  8357. &
  8358. $\Rightarrow$
  8359. &
  8360. \begin{minipage}{0.6\textwidth}
  8361. \begin{lstlisting}
  8362. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  8363. \end{lstlisting}
  8364. \end{minipage}
  8365. \\[2ex]\hline
  8366. \end{tabular}
  8367. \caption{Compiling $R_7$ to $R_6$.}
  8368. \label{fig:compile-r7-r6}
  8369. \end{figure}
  8370. \begin{exercise}\normalfont
  8371. Expand your compiler to handle $R_7$ as outlined in this chapter.
  8372. Create tests for $R_7$ by adapting all of your previous test programs
  8373. by removing type annotations. Add 5 more tests programs that
  8374. specifically rely on the language being dynamically typed. That is,
  8375. they should not be legal programs in a statically typed language, but
  8376. nevertheless, they should be valid $R_7$ programs that run to
  8377. completion without error.
  8378. \end{exercise}
  8379. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8380. \chapter{Gradual Typing}
  8381. \label{ch:gradual-typing}
  8382. \index{gradual typing}
  8383. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  8384. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8385. \chapter{Parametric Polymorphism}
  8386. \label{ch:parametric-polymorphism}
  8387. \index{parametric polymorphism}
  8388. \index{generics}
  8389. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  8390. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  8391. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8392. \chapter{High-level Optimization}
  8393. \label{ch:high-level-optimization}
  8394. This chapter will present a procedure inlining pass based on the
  8395. algorithm of \citet{Waddell:1997fk}.
  8396. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8397. \chapter{Appendix}
  8398. \section{Interpreters}
  8399. \label{appendix:interp}
  8400. \index{interpreter}
  8401. We provide interpreters for each of the source languages $R_0$, $R_1$,
  8402. $\ldots$ in the files \code{interp-R1.rkt}, \code{interp-R2.rkt}, etc.
  8403. The interpreters for the intermediate languages $C_0$ and $C_1$ are in
  8404. \code{interp-C0.rkt} and \code{interp-C1.rkt}. The interpreters for
  8405. the rest of the intermediate languages, including pseudo-x86 and x86
  8406. are in the \key{interp.rkt} file.
  8407. \section{Utility Functions}
  8408. \label{appendix:utilities}
  8409. The utility functions described here are in the \key{utilities.rkt}
  8410. file.
  8411. \paragraph{\code{interp-tests}}
  8412. The \key{interp-tests} function runs the compiler passes and the
  8413. interpreters on each of the specified tests to check whether each pass
  8414. is correct. The \key{interp-tests} function has the following
  8415. parameters:
  8416. \begin{description}
  8417. \item[name (a string)] a name to identify the compiler,
  8418. \item[typechecker] a function of exactly one argument that either
  8419. raises an error using the \code{error} function when it encounters a
  8420. type error, or returns \code{\#f} when it encounters a type
  8421. error. If there is no type error, the type checker returns the
  8422. program.
  8423. \item[passes] a list with one entry per pass. An entry is a list with
  8424. three things: a string giving the name of the pass, the function
  8425. that implements the pass (a translator from AST to AST), and a
  8426. function that implements the interpreter (a function from AST to
  8427. result value) for the language of the output of the pass.
  8428. \item[source-interp] an interpreter for the source language. The
  8429. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  8430. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  8431. \item[tests] a list of test numbers that specifies which tests to
  8432. run. (see below)
  8433. \end{description}
  8434. %
  8435. The \key{interp-tests} function assumes that the subdirectory
  8436. \key{tests} has a collection of Racket programs whose names all start
  8437. with the family name, followed by an underscore and then the test
  8438. number, ending with the file extension \key{.rkt}. Also, for each test
  8439. program that calls \code{read} one or more times, there is a file with
  8440. the same name except that the file extension is \key{.in} that
  8441. provides the input for the Racket program. If the test program is
  8442. expected to fail type checking, then there should be an empty file of
  8443. the same name but with extension \key{.tyerr}.
  8444. \paragraph{\code{compiler-tests}}
  8445. runs the compiler passes to generate x86 (a \key{.s} file) and then
  8446. runs the GNU C compiler (gcc) to generate machine code. It runs the
  8447. machine code and checks that the output is $42$. The parameters to the
  8448. \code{compiler-tests} function are similar to those of the
  8449. \code{interp-tests} function, and consist of
  8450. \begin{itemize}
  8451. \item a compiler name (a string),
  8452. \item a type checker,
  8453. \item description of the passes,
  8454. \item name of a test-family, and
  8455. \item a list of test numbers.
  8456. \end{itemize}
  8457. \paragraph{\code{compile-file}}
  8458. takes a description of the compiler passes (see the comment for
  8459. \key{interp-tests}) and returns a function that, given a program file
  8460. name (a string ending in \key{.rkt}), applies all of the passes and
  8461. writes the output to a file whose name is the same as the program file
  8462. name but with \key{.rkt} replaced with \key{.s}.
  8463. \paragraph{\code{read-program}}
  8464. takes a file path and parses that file (it must be a Racket program)
  8465. into an abstract syntax tree.
  8466. \paragraph{\code{parse-program}}
  8467. takes an S-expression representation of an abstract syntax tree and converts it into
  8468. the struct-based representation.
  8469. \paragraph{\code{assert}}
  8470. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  8471. and displays the message \key{msg} if the Boolean \key{bool} is false.
  8472. \paragraph{\code{lookup}}
  8473. % remove discussion of lookup? -Jeremy
  8474. takes a key and an alist, and returns the first value that is
  8475. associated with the given key, if there is one. If not, an error is
  8476. triggered. The alist may contain both immutable pairs (built with
  8477. \key{cons}) and mutable pairs (built with \key{mcons}).
  8478. %The \key{map2} function ...
  8479. \section{x86 Instruction Set Quick-Reference}
  8480. \label{sec:x86-quick-reference}
  8481. \index{x86}
  8482. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  8483. do. We write $A \to B$ to mean that the value of $A$ is written into
  8484. location $B$. Address offsets are given in bytes. The instruction
  8485. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  8486. registers (such as \code{\%rax}), or memory references (such as
  8487. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  8488. reference per instruction. Other operands must be immediates or
  8489. registers.
  8490. \begin{table}[tbp]
  8491. \centering
  8492. \begin{tabular}{l|l}
  8493. \textbf{Instruction} & \textbf{Operation} \\ \hline
  8494. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  8495. \texttt{negq} $A$ & $- A \to A$ \\
  8496. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  8497. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  8498. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  8499. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  8500. \texttt{retq} & Pops the return address and jumps to it \\
  8501. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  8502. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  8503. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  8504. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  8505. be an immediate) \\
  8506. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  8507. matches the condition code of the instruction, otherwise go to the
  8508. next instructions. The condition codes are \key{e} for ``equal'',
  8509. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  8510. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  8511. \texttt{jl} $L$ & \\
  8512. \texttt{jle} $L$ & \\
  8513. \texttt{jg} $L$ & \\
  8514. \texttt{jge} $L$ & \\
  8515. \texttt{jmp} $L$ & Jump to label $L$ \\
  8516. \texttt{movq} $A$, $B$ & $A \to B$ \\
  8517. \texttt{movzbq} $A$, $B$ &
  8518. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  8519. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  8520. and the extra bytes of $B$ are set to zero.} \\
  8521. & \\
  8522. & \\
  8523. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  8524. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  8525. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  8526. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  8527. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  8528. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  8529. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  8530. description of the condition codes. $A$ must be a single byte register
  8531. (e.g., \texttt{al} or \texttt{cl}).} \\
  8532. \texttt{setl} $A$ & \\
  8533. \texttt{setle} $A$ & \\
  8534. \texttt{setg} $A$ & \\
  8535. \texttt{setge} $A$ &
  8536. \end{tabular}
  8537. \vspace{5pt}
  8538. \caption{Quick-reference for the x86 instructions used in this book.}
  8539. \label{tab:x86-instr}
  8540. \end{table}
  8541. \cleardoublepage
  8542. \addcontentsline{toc}{chapter}{Index}
  8543. \printindex
  8544. \cleardoublepage
  8545. \bibliographystyle{plainnat}
  8546. \bibliography{all}
  8547. \addcontentsline{toc}{chapter}{Bibliography}
  8548. \end{document}
  8549. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  8550. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  8551. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  8552. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  8553. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator
  8554. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  8555. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  8556. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  8557. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs
  8558. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  8559. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  8560. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  8561. %% LocalWords: boolean type-check notq cmpq sete movzbq jmp al xorq
  8562. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  8563. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  8564. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  8565. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  8566. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  8567. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  8568. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  8569. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  8570. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  8571. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  8572. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  8573. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  8574. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  8575. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  8576. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  8577. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  8578. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  8579. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  8580. % LocalWords: struct symtab