book.tex 356 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481
  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 on programming languages by Professor Daniel
  151. Friedman in the 1970's and 1980's. Friedman 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, he returned to teach at Indiana University.
  161. Throughout the 1990's and 2000's, Professor Dybvig continued
  162. development of Chez 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 Friedman's ideas was to split the compiler into many small
  166. ``passes'' so that the code for each pass would be easy to understood
  167. in isolation. (In contrast, most compilers of the time were organized
  168. into only a few monolithic passes for reasons of compile-time
  169. efficiency.) Dybvig, with later help from his students Dipanwita
  170. Sarkar and Andrew Keep, developed infrastructure to support this
  171. approach and evolved the course, first to use smaller micro-passes and
  172. then into even smaller
  173. nano-passes~\citep{Sarkar:2004fk,Keep:2012aa}. I was a student in this
  174. compiler course in the early 2000's as part of his Ph.D. studies at
  175. Indiana University. Needless to say, I enjoyed the course immensely!
  176. During that time, another graduate student named Abdulaziz Ghuloum
  177. observed that the front-to-back organization of the course made it
  178. difficult for students to understand the rationale for the compiler
  179. design. Ghuloum proposed an incremental approach in which the students
  180. build the compiler in stages; they start by implementing a complete
  181. compiler for a very small subset of the input language and in each
  182. subsequent stage they add a language feature and add or modify passes
  183. to handle the new feature~\citep{Ghuloum:2006bh}. In this way, the
  184. students see how the language features motivate aspects of the
  185. compiler design.
  186. After graduating from Indiana University in 2005, I went on to teach
  187. at the University of Colorado. I adapted the nano-pass and incremental
  188. approaches to compiling a subset of the Python
  189. language~\citep{Siek:2012ab}. 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, I was able to teach much of the
  192. same content from the Indiana compiler course. I very much enjoyed
  193. teaching the course organized in this way, and even better, many of
  194. the students learned a lot and got excited about compilers.
  195. I returned to teach at Indiana University in 2013. In my absence the
  196. compiler course had switched from the front-to-back organization to a
  197. back-to-front organization. Seeing how well the incremental approach
  198. worked at Colorado, I started porting and adapting the structure of
  199. the Colorado course back into the land of Scheme. In the meantime
  200. Indiana University had moved on from Scheme to Racket, so the course
  201. is now about compiling a subset of Racket (and Typed Racket) to the
  202. x86 assembly language. The compiler is implemented in
  203. Racket~\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 I
  207. hope to make the Indiana compiler course available to people that have
  208. not had the chance to study compilers at Indiana University. Many of
  209. the compiler design decisions in this book are drawn from the
  210. assignment descriptions of \cite{Dybvig:2010aa}. I have captured what
  211. I think are the most important topics from \cite{Dybvig:2010aa} but
  212. have omitted topics that are less interesting conceptually. I have
  213. also 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 I 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}.
  226. It is helpful but not necessary for the student to have prior exposure
  227. to the x86 assembly language~\citep{Intel:2015aa}, as one might obtain
  228. from a computer systems
  229. course~\citep{Bryant:2010aa}. This book introduces the
  230. parts of x86-64 assembly language that are needed.
  231. %
  232. We follow the System V calling
  233. conventions~\citep{Bryant:2005aa,Matz:2013aa}, which means that the
  234. assembly code that we generate will work properly with our runtime
  235. system (written in C) when it is compiled using the GNU C compiler
  236. (\code{gcc}) on the Linux and MacOS operating systems. (Minor
  237. adjustments are needed for MacOS which we note as they arise.)
  238. %
  239. When running on the Microsoft Windows operating system, the GNU C
  240. compiler follows the Microsoft x64 calling
  241. convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the assembly
  242. code that we generate will \emph{not} work properly with our runtime
  243. system on Windows. One option to consider for using a Windows computer
  244. is to run a virtual machine with Linux as the guest operating system.
  245. %\section*{Structure of book}
  246. % You might want to add short description about each chapter in this book.
  247. %\section*{About the companion website}
  248. %The website\footnote{\url{https://github.com/amberj/latex-book-template}} for %this file contains:
  249. %\begin{itemize}
  250. % \item A link to (freely downlodable) latest version of this document.
  251. % \item Link to download LaTeX source for this document.
  252. % \item Miscellaneous material (e.g. suggested readings etc).
  253. %\end{itemize}
  254. \section*{Acknowledgments}
  255. Many people have contributed to the ideas, techniques, and
  256. organization of this book and have taught courses based on it. We
  257. especially thank John Clements, Bor-Yuh Evan Chang, Kent Dybvig,
  258. Daniel P. Friedman, Ronald Garcia, Abdulaziz Ghuloum, Andrew Keep, Jay
  259. McCarthy, Nate Nystrom, Dipanwita Sarkar, Oscar Waddell, and Michael
  260. Wollowski.
  261. \mbox{}\\
  262. \noindent Jeremy G. Siek \\
  263. \noindent \url{http://homes.soic.indiana.edu/jsiek} \\
  264. %\noindent Spring 2016
  265. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  266. \chapter{Preliminaries}
  267. \label{ch:trees-recur}
  268. In this chapter we review the basic tools that are needed to implement
  269. a compiler. Programs are typically input by a programmer as text,
  270. i.e., a sequence of characters. The program-as-text representation is
  271. called \emph{concrete syntax}. We use concrete syntax to concisely
  272. write down and talk about programs. Inside the compiler, we use
  273. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  274. that efficiently supports the operations that the compiler needs to
  275. perform.
  276. \index{concrete syntax}
  277. \index{abstract syntax}
  278. \index{abstract syntax tree}
  279. \index{AST}
  280. \index{program}
  281. \index{parse}
  282. %
  283. The translation from concrete syntax to abstract syntax is a process
  284. called \emph{parsing}~\cite{Aho:1986qf}. We do not cover the theory
  285. and implementation of parsing in this book. A parser is provided in
  286. the supporting materials for translating from concrete syntax to
  287. abstract syntax for the languages used in this book.
  288. ASTs can be represented in many different ways inside the compiler,
  289. depending on the programming language used to write the compiler.
  290. %
  291. We use Racket's \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  292. feature to represent ASTs (Section~\ref{sec:ast}). We use grammars to
  293. define the abstract syntax of programming languages (Section~\ref{sec:grammar})
  294. and pattern matching to inspect individual nodes in an AST
  295. (Section~\ref{sec:pattern-matching}). We use recursion to construct
  296. and deconstruct entire ASTs (Section~\ref{sec:recursion}). This
  297. chapter provides an brief introduction to these ideas.
  298. \index{struct}
  299. \section{Abstract Syntax Trees and Racket Structures}
  300. \label{sec:ast}
  301. Compilers use abstract syntax trees to represent programs because
  302. compilers often need to ask questions like: for a given part of a
  303. program, what kind of language feature is it? What are the sub-parts
  304. of this part of the program? Consider the program on the left and its
  305. AST on the right. This program is an addition and it has two
  306. sub-parts, a read operation and a negation. The negation has another
  307. sub-part, the integer constant \code{8}. By using a tree to represent
  308. the program, we can easily follow the links to go from one part of a
  309. program to its sub-parts.
  310. \begin{center}
  311. \begin{minipage}{0.4\textwidth}
  312. \begin{lstlisting}
  313. (+ (read) (- 8))
  314. \end{lstlisting}
  315. \end{minipage}
  316. \begin{minipage}{0.4\textwidth}
  317. \begin{equation}
  318. \begin{tikzpicture}
  319. \node[draw, circle] (plus) at (0 , 0) {\key{+}};
  320. \node[draw, circle] (read) at (-1, -1.5) {{\footnotesize\key{read}}};
  321. \node[draw, circle] (minus) at (1 , -1.5) {$\key{-}$};
  322. \node[draw, circle] (8) at (1 , -3) {\key{8}};
  323. \draw[->] (plus) to (read);
  324. \draw[->] (plus) to (minus);
  325. \draw[->] (minus) to (8);
  326. \end{tikzpicture}
  327. \label{eq:arith-prog}
  328. \end{equation}
  329. \end{minipage}
  330. \end{center}
  331. We use the standard terminology for trees to describe ASTs: each
  332. circle above is called a \emph{node}. The arrows connect a node to its
  333. \emph{children} (which are also nodes). The top-most node is the
  334. \emph{root}. Every node except for the root has a \emph{parent} (the
  335. node it is the child of). If a node has no children, it is a
  336. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  337. \index{node}
  338. \index{children}
  339. \index{root}
  340. \index{parent}
  341. \index{leaf}
  342. \index{internal node}
  343. %% Recall that an \emph{symbolic expression} (S-expression) is either
  344. %% \begin{enumerate}
  345. %% \item an atom, or
  346. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  347. %% where $e_1$ and $e_2$ are each an S-expression.
  348. %% \end{enumerate}
  349. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  350. %% null value \code{'()}, etc. We can create an S-expression in Racket
  351. %% simply by writing a backquote (called a quasi-quote in Racket)
  352. %% followed by the textual representation of the S-expression. It is
  353. %% quite common to use S-expressions to represent a list, such as $a, b
  354. %% ,c$ in the following way:
  355. %% \begin{lstlisting}
  356. %% `(a . (b . (c . ())))
  357. %% \end{lstlisting}
  358. %% Each element of the list is in the first slot of a pair, and the
  359. %% second slot is either the rest of the list or the null value, to mark
  360. %% the end of the list. Such lists are so common that Racket provides
  361. %% special notation for them that removes the need for the periods
  362. %% and so many parenthesis:
  363. %% \begin{lstlisting}
  364. %% `(a b c)
  365. %% \end{lstlisting}
  366. %% The following expression creates an S-expression that represents AST
  367. %% \eqref{eq:arith-prog}.
  368. %% \begin{lstlisting}
  369. %% `(+ (read) (- 8))
  370. %% \end{lstlisting}
  371. %% When using S-expressions to represent ASTs, the convention is to
  372. %% represent each AST node as a list and to put the operation symbol at
  373. %% the front of the list. The rest of the list contains the children. So
  374. %% in the above case, the root AST node has operation \code{`+} and its
  375. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  376. %% diagram \eqref{eq:arith-prog}.
  377. %% To build larger S-expressions one often needs to splice together
  378. %% several smaller S-expressions. Racket provides the comma operator to
  379. %% splice an S-expression into a larger one. For example, instead of
  380. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  381. %% we could have first created an S-expression for AST
  382. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  383. %% S-expression.
  384. %% \begin{lstlisting}
  385. %% (define ast1.4 `(- 8))
  386. %% (define ast1.1 `(+ (read) ,ast1.4))
  387. %% \end{lstlisting}
  388. %% In general, the Racket expression that follows the comma (splice)
  389. %% can be any expression that produces an S-expression.
  390. We define a Racket \code{struct} for each kind of node. For this
  391. chapter we require just two kinds of nodes: one for integer constants
  392. and one for primitive operations. The following is the \code{struct}
  393. definition for integer constants.
  394. \begin{lstlisting}
  395. (struct Int (value))
  396. \end{lstlisting}
  397. An integer node includes just one thing: the integer value.
  398. To create a AST node for the integer $8$, we write \code{(Int 8)}.
  399. \begin{lstlisting}
  400. (define eight (Int 8))
  401. \end{lstlisting}
  402. We say that the value created by \code{(Int 8)} is an
  403. \emph{instance} of the \code{Int} structure.
  404. The following is the \code{struct} definition for primitives operations.
  405. \begin{lstlisting}
  406. (struct Prim (op arg*))
  407. \end{lstlisting}
  408. A primitive operation node includes an operator symbol \code{op}
  409. and a list of children \code{arg*}. For example, to create
  410. an AST that negates the number $8$, we write \code{(Prim '- (list eight))}.
  411. \begin{lstlisting}
  412. (define neg-eight (Prim '- (list eight)))
  413. \end{lstlisting}
  414. Primitive operations may have zero or more children. The \code{read}
  415. operator has zero children:
  416. \begin{lstlisting}
  417. (define rd (Prim 'read '()))
  418. \end{lstlisting}
  419. whereas the addition operator has two children:
  420. \begin{lstlisting}
  421. (define ast1.1 (Prim '+ (list rd neg-eight)))
  422. \end{lstlisting}
  423. We have made a design choice regarding the \code{Prim} structure.
  424. Instead of using one structure for many different operations
  425. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  426. structure for each operation, as follows.
  427. \begin{lstlisting}
  428. (struct Read ())
  429. (struct Add (left right))
  430. (struct Neg (value))
  431. \end{lstlisting}
  432. The reason we choose to use just one structure is that in many parts
  433. of the compiler the code for the different primitive operators is the
  434. same, so we might as well just write that code once, which is enabled
  435. by using a single structure.
  436. When compiling a program such as \eqref{eq:arith-prog}, we need to
  437. know that the operation associated with the root node is addition and
  438. we need to be able to access its two children. Racket provides pattern
  439. matching over structures to support these kinds of queries, as we
  440. see in Section~\ref{sec:pattern-matching}.
  441. In this book, we often write down the concrete syntax of a program
  442. even when we really have in mind the AST because the concrete syntax
  443. is more concise. We recommend that, in your mind, you always think of
  444. programs as abstract syntax trees.
  445. \section{Grammars}
  446. \label{sec:grammar}
  447. \index{integer}
  448. \index{literal}
  449. \index{constant}
  450. A programming language can be thought of as a \emph{set} of programs.
  451. The set is typically infinite (one can always create larger and larger
  452. programs), so one cannot simply describe a language by listing all of
  453. the programs in the language. Instead we write down a set of rules, a
  454. \emph{grammar}, for building programs. Grammars are often used to
  455. define the concrete syntax of a language, but they can also be used to
  456. describe the abstract syntax. We write our rules in a variant of
  457. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  458. \index{Backus-Naur Form}\index{BNF}
  459. As an example, we describe a small language, named $R_0$, that consists of
  460. integers and arithmetic operations.
  461. \index{grammar}
  462. The first grammar rule for the abstract syntax of $R_0$ says that an
  463. instance of the \code{Int} structure is an expression:
  464. \begin{equation}
  465. \Exp ::= \INT{\Int} \label{eq:arith-int}
  466. \end{equation}
  467. %
  468. Each rule has a left-hand-side and a right-hand-side. The way to read
  469. a rule is that if you have all the program parts on the
  470. right-hand-side, then you can create an AST node and categorize it
  471. according to the left-hand-side.
  472. %
  473. A name such as $\Exp$ that is
  474. defined by the grammar rules is a \emph{non-terminal}.
  475. \index{non-terminal}
  476. %
  477. The name $\Int$ is a also a non-terminal, but instead of defining it
  478. with a grammar rule, we define it with the following explanation. We
  479. make the simplifying design decision that all of the languages in this
  480. book only handle machine-representable integers. On most modern
  481. machines this corresponds to integers represented with 64-bits, i.e.,
  482. the in range $-2^{63}$ to $2^{63}-1$. We restrict this range further
  483. to match the Racket \texttt{fixnum} datatype, which allows 63-bit
  484. integers on a 64-bit machine. So an $\Int$ is a sequence of decimals
  485. ($0$ to $9$), possibly starting with $-$ (for negative integers), such
  486. that the sequence of decimals represent an integer in range $-2^{62}$
  487. to $2^{62}-1$.
  488. The second grammar rule is the \texttt{read} operation that receives
  489. an input integer from the user of the program.
  490. \begin{equation}
  491. \Exp ::= \READ{} \label{eq:arith-read}
  492. \end{equation}
  493. The third rule says that, given an $\Exp$ node, you can build another
  494. $\Exp$ node by negating it.
  495. \begin{equation}
  496. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  497. \end{equation}
  498. Symbols in typewriter font such as \key{-} and \key{read} are
  499. \emph{terminal} symbols and must literally appear in the program for
  500. the rule to be applicable.
  501. \index{terminal}
  502. We can apply the rules to build ASTs in the $R_0$
  503. language. For example, by rule \eqref{eq:arith-int}, \texttt{(Int 8)} is an
  504. $\Exp$, then by rule \eqref{eq:arith-neg}, the following AST is
  505. an $\Exp$.
  506. \begin{center}
  507. \begin{minipage}{0.4\textwidth}
  508. \begin{lstlisting}
  509. (Prim '- (list (Int 8)))
  510. \end{lstlisting}
  511. \end{minipage}
  512. \begin{minipage}{0.25\textwidth}
  513. \begin{equation}
  514. \begin{tikzpicture}
  515. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  516. \node[draw, circle] (8) at (0, -1.2) {$8$};
  517. \draw[->] (minus) to (8);
  518. \end{tikzpicture}
  519. \label{eq:arith-neg8}
  520. \end{equation}
  521. \end{minipage}
  522. \end{center}
  523. The next grammar rule defines addition expressions:
  524. \begin{equation}
  525. \Exp ::= \ADD{\Exp}{\Exp} \label{eq:arith-add}
  526. \end{equation}
  527. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  528. $R_0$. We know that \lstinline{(Prim 'read '())} is an $\Exp$ by rule
  529. \eqref{eq:arith-read} and we have already shown that \code{(Prim '-
  530. (list (Int 8)))} is an $\Exp$, so we apply rule \eqref{eq:arith-add}
  531. to show that
  532. \begin{lstlisting}
  533. (Prim '+ (list (Prim 'read '()) (Prim '- (list (Int 8)))))
  534. \end{lstlisting}
  535. is an $\Exp$ in the $R_0$ language.
  536. If you have an AST for which the above rules do not apply, then the
  537. AST is not in $R_0$. For example, the program \code{(- (read) (+ 8))}
  538. is not in $R_0$ because there are no rules for \code{+} with only one
  539. argument, nor for \key{-} with two arguments. Whenever we define a
  540. language with a grammar, the language only includes those programs
  541. that are justified by the rules.
  542. The last grammar rule for $R_0$ states that there is a \code{Program}
  543. node to mark the top of the whole program:
  544. \[
  545. R_0 ::= \PROGRAM{\code{'()}}{\Exp}
  546. \]
  547. The \code{Program} structure is defined as follows
  548. \begin{lstlisting}
  549. (struct Program (info body))
  550. \end{lstlisting}
  551. where \code{body} is an expression. In later chapters, the \code{info}
  552. part will be used to store auxiliary information but for now it is
  553. just the empty list.
  554. It is common to have many grammar rules with the same left-hand side
  555. but different right-hand sides, such as the rules for $\Exp$ in the
  556. grammar of $R_0$. As a short-hand, a vertical bar can be used to
  557. combine several right-hand-sides into a single rule.
  558. We collect all of the grammar rules for the abstract syntax of $R_0$
  559. in Figure~\ref{fig:r0-syntax}. The concrete syntax for $R_0$ is
  560. defined in Figure~\ref{fig:r0-concrete-syntax}.
  561. The \code{read-program} function provided in \code{utilities.rkt} of
  562. the support materials reads a program in from a file (the sequence of
  563. characters in the concrete syntax of Racket) and parses it into an
  564. abstract syntax tree. See the description of \code{read-program} in
  565. Appendix~\ref{appendix:utilities} for more details.
  566. \begin{figure}[tp]
  567. \fbox{
  568. \begin{minipage}{0.96\textwidth}
  569. \[
  570. \begin{array}{rcl}
  571. \begin{array}{rcl}
  572. \Exp &::=& \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp)\\
  573. R_0 &::=& \Exp
  574. \end{array}
  575. \end{array}
  576. \]
  577. \end{minipage}
  578. }
  579. \caption{The concrete syntax of $R_0$.}
  580. \label{fig:r0-concrete-syntax}
  581. \end{figure}
  582. \begin{figure}[tp]
  583. \fbox{
  584. \begin{minipage}{0.96\textwidth}
  585. \[
  586. \begin{array}{rcl}
  587. \Exp &::=& \INT{\Int} \mid \READ{} \mid \NEG{\Exp} \\
  588. &\mid& \ADD{\Exp}{\Exp} \\
  589. R_0 &::=& \PROGRAM{\code{'()}}{\Exp}
  590. \end{array}
  591. \]
  592. \end{minipage}
  593. }
  594. \caption{The abstract syntax of $R_0$.}
  595. \label{fig:r0-syntax}
  596. \end{figure}
  597. \section{Pattern Matching}
  598. \label{sec:pattern-matching}
  599. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  600. the parts of an AST node. Racket provides the \texttt{match} form to
  601. access the parts of a structure. Consider the following example and
  602. the output on the right. \index{match} \index{pattern matching}
  603. \begin{center}
  604. \begin{minipage}{0.5\textwidth}
  605. \begin{lstlisting}
  606. (match ast1.1
  607. [(Prim op (list child1 child2))
  608. (print op)])
  609. \end{lstlisting}
  610. \end{minipage}
  611. \vrule
  612. \begin{minipage}{0.25\textwidth}
  613. \begin{lstlisting}
  614. '+
  615. \end{lstlisting}
  616. \end{minipage}
  617. \end{center}
  618. In the above example, the \texttt{match} form takes the AST
  619. \eqref{eq:arith-prog} and binds its parts to the three pattern
  620. variables \texttt{op}, \texttt{child1}, and \texttt{child2}. In
  621. general, a match clause consists of a \emph{pattern} and a
  622. \emph{body}.
  623. \index{pattern}
  624. Patterns are recursively defined to be either a pattern
  625. variable, a structure name followed by a pattern for each of the
  626. structure's arguments, or an S-expression (symbols, lists, etc.).
  627. (See Chapter 12 of The Racket
  628. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  629. and Chapter 9 of The Racket
  630. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  631. for a complete description of \code{match}.)
  632. %
  633. The body of a match clause may contain arbitrary Racket code. The
  634. pattern variables can be used in the scope of the body.
  635. A \code{match} form may contain several clauses, as in the following
  636. function \code{leaf?} that recognizes when an $R_0$ node is
  637. a leaf. The \code{match} proceeds through the clauses in order,
  638. checking whether the pattern can match the input AST. The
  639. body of the first clause that matches is executed. The output of
  640. \code{leaf?} for several ASTs is shown on the right.
  641. \begin{center}
  642. \begin{minipage}{0.6\textwidth}
  643. \begin{lstlisting}
  644. (define (leaf? arith)
  645. (match arith
  646. [(Int n) #t]
  647. [(Prim 'read '()) #t]
  648. [(Prim '- (list c1)) #f]
  649. [(Prim '+ (list c1 c2)) #f]))
  650. (leaf? (Prim 'read '()))
  651. (leaf? (Prim '- (list (Int 8))))
  652. (leaf? (Int 8))
  653. \end{lstlisting}
  654. \end{minipage}
  655. \vrule
  656. \begin{minipage}{0.25\textwidth}
  657. \begin{lstlisting}
  658. #t
  659. #f
  660. #t
  661. \end{lstlisting}
  662. \end{minipage}
  663. \end{center}
  664. When writing a \code{match}, we refer to the grammar definition to
  665. identify which non-terminal we are expecting to match against, then we
  666. make sure that 1) we have one clause for each alternative of that
  667. non-terminal and 2) that the pattern in each clause corresponds to the
  668. corresponding right-hand side of a grammar rule. For the \code{match}
  669. in the \code{leaf?} function, we refer to the grammar for $R_0$ in
  670. Figure~\ref{fig:r0-syntax}. The $\Exp$ non-terminal has 4
  671. alternatives, so the \code{match} has 4 clauses. The pattern in each
  672. clause corresponds to the right-hand side of a grammar rule. For
  673. example, the pattern \code{(Prim '+ (list c1 c2))} corresponds to the
  674. right-hand side $\ADD{\Exp}{\Exp}$. When translating from grammars to
  675. patterns, replace non-terminals such as $\Exp$ with pattern variables
  676. of your choice (e.g. \code{c1} and \code{c2}).
  677. \section{Recursion}
  678. \label{sec:recursion}
  679. \index{recursive function}
  680. Programs are inherently recursive. For example, an $R_0$ expression is
  681. often made of smaller expressions. Thus, the natural way to process an
  682. entire program is with a recursive function. As a first example of
  683. such a recursive function, we define \texttt{exp?} below, which takes
  684. an arbitrary value and determines whether or not it is an $R_0$
  685. expression.
  686. %
  687. When a recursive function is defined using a sequence of match clauses
  688. that correspond to a grammar, and the body of each clause makes a
  689. recursive call on each child node, then we say the function is defined
  690. by \emph{structural recursion}\footnote{This principle of structuring
  691. code according to the data definition is advocated in the book
  692. \emph{How to Design Programs}
  693. \url{http://www.ccs.neu.edu/home/matthias/HtDP2e/}.}. Below we also
  694. define a second function, named \code{R0?}, that determines whether a
  695. value is an $R_0$ program. In general we can expect to write one
  696. recursive function to handle each non-terminal in a grammar.
  697. \index{structural recursion}
  698. %
  699. \begin{center}
  700. \begin{minipage}{0.7\textwidth}
  701. \begin{lstlisting}
  702. (define (exp? ast)
  703. (match ast
  704. [(Int n) #t]
  705. [(Prim 'read '()) #t]
  706. [(Prim '- (list e)) (exp? e)]
  707. [(Prim '+ (list e1 e2))
  708. (and (exp? e1) (exp? e2))]
  709. [else #f]))
  710. (define (R0? ast)
  711. (match ast
  712. [(Program '() e) (exp? e)]
  713. [else #f]))
  714. (R0? (Program '() ast1.1)
  715. (R0? (Program '()
  716. (Prim '- (list (Prim 'read '())
  717. (Prim '+ (list (Num 8)))))))
  718. \end{lstlisting}
  719. \end{minipage}
  720. \vrule
  721. \begin{minipage}{0.25\textwidth}
  722. \begin{lstlisting}
  723. #t
  724. #f
  725. \end{lstlisting}
  726. \end{minipage}
  727. \end{center}
  728. You may be tempted to merge the two functions into one, like this:
  729. \begin{center}
  730. \begin{minipage}{0.5\textwidth}
  731. \begin{lstlisting}
  732. (define (R0? ast)
  733. (match ast
  734. [(Int n) #t]
  735. [(Prim 'read '()) #t]
  736. [(Prim '- (list e)) (R0? e)]
  737. [(Prim '+ (list e1 e2)) (and (R0? e1) (R0? e2))]
  738. [(Program '() e) (R0? e)]
  739. [else #f]))
  740. \end{lstlisting}
  741. \end{minipage}
  742. \end{center}
  743. %
  744. Sometimes such a trick will save a few lines of code, especially when
  745. it comes to the \code{Program} wrapper. Yet this style is generally
  746. \emph{not} recommended because it can get you into trouble.
  747. %
  748. For example, the above function is subtly wrong:
  749. \lstinline{(R0? (Program '() (Program '() (Int 3))))}
  750. will return true, when it should return false.
  751. %% NOTE FIXME - must check for consistency on this issue throughout.
  752. \section{Interpreters}
  753. \label{sec:interp-R0}
  754. \index{interpreter}
  755. The meaning, or semantics, of a program is typically defined in the
  756. specification of the language. For example, the Scheme language is
  757. defined in the report by \cite{SPERBER:2009aa}. The Racket language is
  758. defined in its reference manual~\citep{plt-tr}. In this book we use an
  759. interpreter to define the meaning of each language that we consider,
  760. following Reynolds' advice~\citep{reynolds72:_def_interp}. An
  761. interpreter that is designated (by some people) as the definition of a
  762. language is called a \emph{definitional interpreter}.
  763. \index{definitional interpreter}
  764. We warm up by creating a definitional interpreter for the $R_0$ language, which
  765. serves as a second example of structural recursion. The
  766. \texttt{interp-R0} function is defined in
  767. Figure~\ref{fig:interp-R0}. The body of the function is a match on the
  768. input program followed by a call to the \lstinline{interp-exp} helper
  769. function, which in turn has one match clause per grammar rule for
  770. $R_0$ expressions.
  771. \begin{figure}[tp]
  772. \begin{lstlisting}
  773. (define (interp-exp e)
  774. (match e
  775. [(Int n) n]
  776. [(Prim 'read '())
  777. (define r (read))
  778. (cond [(fixnum? r) r]
  779. [else (error 'interp-R0 "expected an integer" r)])]
  780. [(Prim '- (list e))
  781. (define v (interp-exp e))
  782. (fx- 0 v)]
  783. [(Prim '+ (list e1 e2))
  784. (define v1 (interp-exp e1))
  785. (define v2 (interp-exp e2))
  786. (fx+ v1 v2)]
  787. ))
  788. (define (interp-R0 p)
  789. (match p
  790. [(Program '() e) (interp-exp e)]
  791. ))
  792. \end{lstlisting}
  793. \caption{Interpreter for the $R_0$ language.}
  794. \label{fig:interp-R0}
  795. \end{figure}
  796. Let us consider the result of interpreting a few $R_0$ programs. The
  797. following program adds two integers.
  798. \begin{lstlisting}
  799. (+ 10 32)
  800. \end{lstlisting}
  801. The result is \key{42}. We wrote the above program in concrete syntax,
  802. whereas the parsed abstract syntax is:
  803. \begin{lstlisting}
  804. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  805. \end{lstlisting}
  806. The next example demonstrates that expressions may be nested within
  807. each other, in this case nesting several additions and negations.
  808. \begin{lstlisting}
  809. (+ 10 (- (+ 12 20)))
  810. \end{lstlisting}
  811. What is the result of the above program?
  812. As mentioned previously, the $R_0$ language does not support
  813. arbitrarily-large integers, but only $63$-bit integers, so we
  814. interpret the arithmetic operations of $R_0$ using fixnum arithmetic
  815. in Racket.
  816. Suppose
  817. \[
  818. n = 999999999999999999
  819. \]
  820. which indeed fits in $63$-bits. What happens when we run the
  821. following program in our interpreter?
  822. \begin{lstlisting}
  823. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  824. \end{lstlisting}
  825. It produces an error:
  826. \begin{lstlisting}
  827. fx+: result is not a fixnum
  828. \end{lstlisting}
  829. We establish the convention that if running the definitional
  830. interpreter on a program produces an error, then the meaning of that
  831. program is \emph{unspecified}. That means a compiler for the language
  832. is under no obligations regarding that program; it may or may not
  833. produce an executable, and if it does, that executable can do
  834. anything. This convention applies to the languages defined in this
  835. book, as a way to simplify the student's task of implementing them,
  836. but this convention is not applicable to all programming languages.
  837. \index{unspecified behavior}
  838. Moving on to the last feature of the $R_0$ language, the \key{read}
  839. operation prompts the user of the program for an integer. Recall that
  840. program \eqref{eq:arith-prog} performs a \key{read} and then subtracts
  841. \code{8}. So if we run
  842. \begin{lstlisting}
  843. (interp-R0 (Program '() ast1.1))
  844. \end{lstlisting}
  845. and if the input is \code{50}, then we get the answer to life, the
  846. universe, and everything: \code{42}!\footnote{\emph{The Hitchhiker's
  847. Guide to the Galaxy} by Douglas Adams.}
  848. We include the \key{read} operation in $R_0$ so a clever student
  849. cannot implement a compiler for $R_0$ that simply runs the interpreter
  850. during compilation to obtain the output and then generates the trivial
  851. code to produce the output. (Yes, a clever student did this in the
  852. first instance of this course.)
  853. The job of a compiler is to translate a program in one language into a
  854. program in another language so that the output program behaves the
  855. same way as the input program does according to its definitional
  856. interpreter. This idea is depicted in the following diagram. Suppose
  857. we have two languages, $\mathcal{L}_1$ and $\mathcal{L}_2$, and an
  858. interpreter for each language. Suppose that the compiler translates
  859. program $P_1$ in language $\mathcal{L}_1$ into program $P_2$ in
  860. language $\mathcal{L}_2$. Then interpreting $P_1$ and $P_2$ on their
  861. respective interpreters with input $i$ should yield the same output
  862. $o$.
  863. \begin{equation} \label{eq:compile-correct}
  864. \begin{tikzpicture}[baseline=(current bounding box.center)]
  865. \node (p1) at (0, 0) {$P_1$};
  866. \node (p2) at (3, 0) {$P_2$};
  867. \node (o) at (3, -2.5) {$o$};
  868. \path[->] (p1) edge [above] node {compile} (p2);
  869. \path[->] (p2) edge [right] node {interp-$\mathcal{L}_2$($i$)} (o);
  870. \path[->] (p1) edge [left] node {interp-$\mathcal{L}_1$($i$)} (o);
  871. \end{tikzpicture}
  872. \end{equation}
  873. In the next section we see our first example of a compiler.
  874. \section{Example Compiler: a Partial Evaluator}
  875. \label{sec:partial-evaluation}
  876. In this section we consider a compiler that translates $R_0$ programs
  877. into $R_0$ programs that may be more efficient, that is, this compiler
  878. is an optimizer. This optimizer eagerly computes the parts of the
  879. program that do not depend on any inputs, a process known as
  880. \emph{partial evaluation}~\cite{Jones:1993uq}.
  881. \index{partial evaluation}
  882. For example, given the following program
  883. \begin{lstlisting}
  884. (+ (read) (- (+ 5 3)))
  885. \end{lstlisting}
  886. our compiler will translate it into the program
  887. \begin{lstlisting}
  888. (+ (read) -8)
  889. \end{lstlisting}
  890. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  891. evaluator for the $R_0$ language. The output of the partial evaluator
  892. is an $R_0$ program. In Figure~\ref{fig:pe-arith}, the structural
  893. recursion over $\Exp$ is captured in the \code{pe-exp} function
  894. whereas the code for partially evaluating the negation and addition
  895. operations is factored into two separate helper functions:
  896. \code{pe-neg} and \code{pe-add}. The input to these helper
  897. functions is the output of partially evaluating the children.
  898. \begin{figure}[tp]
  899. \begin{lstlisting}
  900. (define (pe-neg r)
  901. (match r
  902. [(Int n) (Int (fx- 0 n))]
  903. [else (Prim '- (list r))]))
  904. (define (pe-add r1 r2)
  905. (match* (r1 r2)
  906. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  907. [(_ _) (Prim '+ (list r1 r2))]))
  908. (define (pe-exp e)
  909. (match e
  910. [(Int n) (Int n)]
  911. [(Prim 'read '()) (Prim 'read '())]
  912. [(Prim '- (list e1)) (pe-neg (pe-exp e1))]
  913. [(Prim '+ (list e1 e2)) (pe-add (pe-exp e1) (pe-exp e2))]
  914. ))
  915. (define (pe-R0 p)
  916. (match p
  917. [(Program '() e) (Program '() (pe-exp e))]
  918. ))
  919. \end{lstlisting}
  920. \caption{A partial evaluator for $R_0$ expressions.}
  921. \label{fig:pe-arith}
  922. \end{figure}
  923. The \texttt{pe-neg} and \texttt{pe-add} functions check whether their
  924. arguments are integers and if they are, perform the appropriate
  925. arithmetic. Otherwise, they create an AST node for the operation
  926. (either negation or addition).
  927. To gain some confidence that the partial evaluator is correct, we can
  928. test whether it produces programs that get the same result as the
  929. input programs. That is, we can test whether it satisfies Diagram
  930. \eqref{eq:compile-correct}. The following code runs the partial
  931. evaluator on several examples and tests the output program. The
  932. \texttt{parse-program} and \texttt{assert} functions are defined in
  933. Appendix~\ref{appendix:utilities}.\\
  934. \begin{minipage}{1.0\textwidth}
  935. \begin{lstlisting}
  936. (define (test-pe p)
  937. (assert "testing pe-R0"
  938. (equal? (interp-R0 p) (interp-R0 (pe-R0 p)))))
  939. (test-pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  940. (test-pe (parse-program `(program () (+ 1 (+ 3 1)))))
  941. (test-pe (parse-program `(program () (- (+ 3 (- 5))))))
  942. \end{lstlisting}
  943. \end{minipage}
  944. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  945. \chapter{Integers and Variables}
  946. \label{ch:int-exp}
  947. This chapter is about compiling the subset of Racket that includes
  948. integer arithmetic and local variable binding, which we name $R_1$, to
  949. x86-64 assembly code~\citep{Intel:2015aa}. Henceforth we refer
  950. to x86-64 simply as x86. The chapter begins with a description of the
  951. $R_1$ language (Section~\ref{sec:s0}) followed by a description of x86
  952. (Section~\ref{sec:x86}). The x86 assembly language is large, so we
  953. discuss only what is needed for compiling $R_1$. We introduce more of
  954. x86 in later chapters. Once we have introduced $R_1$ and x86, we
  955. reflect on their differences and come up with a plan to break down the
  956. translation from $R_1$ to x86 into a handful of steps
  957. (Section~\ref{sec:plan-s0-x86}). The rest of the sections in this
  958. chapter give detailed hints regarding each step
  959. (Sections~\ref{sec:uniquify-s0} through \ref{sec:patch-s0}). We hope
  960. to give enough hints that the well-prepared reader, together with a
  961. few friends, can implement a compiler from $R_1$ to x86 in a couple
  962. weeks while at the same time leaving room for some fun and creativity.
  963. To give the reader a feeling for the scale of this first compiler, the
  964. instructor solution for the $R_1$ compiler is less than 500 lines of
  965. code.
  966. \section{The $R_1$ Language}
  967. \label{sec:s0}
  968. \index{variable}
  969. The $R_1$ language extends the $R_0$ language with variable
  970. definitions. The concrete syntax of the $R_1$ language is defined by
  971. the grammar in Figure~\ref{fig:r1-concrete-syntax} and the abstract
  972. syntax is defined in Figure~\ref{fig:r1-syntax}. The non-terminal
  973. \Var{} may be any Racket identifier. As in $R_0$, \key{read} is a
  974. nullary operator, \key{-} is a unary operator, and \key{+} is a binary
  975. operator. Similar to $R_0$, the abstract syntax of $R_1$ includes the
  976. \key{Program} struct to mark the top of the program.
  977. %% The $\itm{info}$
  978. %% field of the \key{Program} structure contains an \emph{association
  979. %% list} (a list of key-value pairs) that is used to communicate
  980. %% auxiliary data from one compiler pass the next.
  981. Despite the simplicity of the $R_1$ language, it is rich enough to
  982. exhibit several compilation techniques.
  983. \begin{figure}[tp]
  984. \centering
  985. \fbox{
  986. \begin{minipage}{0.96\textwidth}
  987. \[
  988. \begin{array}{rcl}
  989. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp}\\
  990. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  991. R_1 &::=& \Exp
  992. \end{array}
  993. \]
  994. \end{minipage}
  995. }
  996. \caption{The concrete syntax of $R_1$.}
  997. \label{fig:r1-concrete-syntax}
  998. \end{figure}
  999. \begin{figure}[tp]
  1000. \centering
  1001. \fbox{
  1002. \begin{minipage}{0.96\textwidth}
  1003. \[
  1004. \begin{array}{rcl}
  1005. \Exp &::=& \INT{\Int} \mid \READ{} \\
  1006. &\mid& \NEG{\Exp} \mid \ADD{\Exp}{\Exp} \\
  1007. &\mid& \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  1008. R_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1009. \end{array}
  1010. \]
  1011. \end{minipage}
  1012. }
  1013. \caption{The abstract syntax of $R_1$.}
  1014. \label{fig:r1-syntax}
  1015. \end{figure}
  1016. Let us dive further into the syntax and semantics of the $R_1$
  1017. language. The \key{Let} feature defines a variable for use within its
  1018. body and initializes the variable with the value of an expression.
  1019. The abstract syntax for \key{Let} is defined in Figure~\ref{fig:r1-syntax}.
  1020. The concrete syntax for \key{Let} is
  1021. \begin{lstlisting}
  1022. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1023. \end{lstlisting}
  1024. For example, the following program initializes \code{x} to $32$ and then
  1025. evaluates the body \code{(+ 10 x)}, producing $42$.
  1026. \begin{lstlisting}
  1027. (let ([x (+ 12 20)]) (+ 10 x))
  1028. \end{lstlisting}
  1029. When there are multiple \key{let}'s for the same variable, the closest
  1030. enclosing \key{let} is used. That is, variable definitions overshadow
  1031. prior definitions. Consider the following program with two \key{let}'s
  1032. that define variables named \code{x}. Can you figure out the result?
  1033. \begin{lstlisting}
  1034. (let ([x 32]) (+ (let ([x 10]) x) x))
  1035. \end{lstlisting}
  1036. For the purposes of depicting which variable uses correspond to which
  1037. definitions, the following shows the \code{x}'s annotated with
  1038. subscripts to distinguish them. Double check that your answer for the
  1039. above is the same as your answer for this annotated version of the
  1040. program.
  1041. \begin{lstlisting}
  1042. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1043. \end{lstlisting}
  1044. The initializing expression is always evaluated before the body of the
  1045. \key{let}, so in the following, the \key{read} for \code{x} is
  1046. performed before the \key{read} for \code{y}. Given the input
  1047. $52$ then $10$, the following produces $42$ (not $-42$).
  1048. \begin{lstlisting}
  1049. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1050. \end{lstlisting}
  1051. \begin{wrapfigure}[24]{r}[1.0in]{0.6\textwidth}
  1052. \small
  1053. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1054. An \emph{association list} (alist) is a list of key-value pairs.
  1055. For example, we can map people to their ages with an alist.
  1056. \index{alist}\index{association list}
  1057. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1058. (define ages
  1059. '((jane . 25) (sam . 24) (kate . 45)))
  1060. \end{lstlisting}
  1061. The \emph{dictionary} interface is for mapping keys to values.
  1062. Every alist implements this interface. \index{dictionary} The package
  1063. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1064. provides many functions for working with dictionaries. Here
  1065. are a few of them:
  1066. \begin{description}
  1067. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1068. returns the value associated with the given $\itm{key}$.
  1069. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1070. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1071. but otherwise is the same as $\itm{dict}$.
  1072. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1073. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1074. of keys and values in $\itm{dict}$. For example, the following
  1075. creates a new alist in which the ages are incremented.
  1076. \end{description}
  1077. \vspace{-10pt}
  1078. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  1079. (for/list ([(k v) (in-dict ages)])
  1080. (cons k (add1 v)))
  1081. \end{lstlisting}
  1082. \end{tcolorbox}
  1083. \end{wrapfigure}
  1084. Figure~\ref{fig:interp-R1} shows the definitional interpreter for the
  1085. $R_1$ language. It extends the interpreter for $R_0$ with two new
  1086. \key{match} clauses for variables and for \key{let}. For \key{let},
  1087. we need a way to communicate the value of a variable to all the uses
  1088. of a variable. To accomplish this, we maintain a mapping from
  1089. variables to values. Throughout the compiler we often need to map
  1090. variables to information about them. We refer to these mappings as
  1091. \emph{environments}\index{environment}
  1092. \footnote{Another common term for environment in the compiler
  1093. literature is \emph{symbol table}\index{symbol table}.}.
  1094. For simplicity, we use an
  1095. association list (alist) to represent the environment. The sidebar to
  1096. the right gives a brief introduction to alists and the
  1097. \code{racket/dict} package. The \code{interp-R1} function takes the
  1098. current environment, \code{env}, as an extra parameter. When the
  1099. interpreter encounters a variable, it finds the corresponding value
  1100. using the \code{dict-ref} function. When the interpreter encounters a
  1101. \key{Let}, it evaluates the initializing expression, extends the
  1102. environment with the result value bound to the variable, using
  1103. \code{dict-set}, then evaluates the body of the \key{Let}.
  1104. \begin{figure}[tp]
  1105. \begin{lstlisting}
  1106. (define (interp-exp env)
  1107. (lambda (e)
  1108. (match e
  1109. [(Int n) n]
  1110. [(Prim 'read '())
  1111. (define r (read))
  1112. (cond [(fixnum? r) r]
  1113. [else (error 'interp-R1 "expected an integer" r)])]
  1114. [(Prim '- (list e))
  1115. (define v ((interp-exp env) e))
  1116. (fx- 0 v)]
  1117. [(Prim '+ (list e1 e2))
  1118. (define v1 ((interp-exp env) e1))
  1119. (define v2 ((interp-exp env) e2))
  1120. (fx+ v1 v2)]
  1121. [(Var x) (dict-ref env x)]
  1122. [(Let x e body)
  1123. (define new-env (dict-set env x ((interp-exp env) e)))
  1124. ((interp-exp new-env) body)]
  1125. )))
  1126. (define (interp-R1 p)
  1127. (match p
  1128. [(Program '() e) ((interp-exp '()) e)]
  1129. ))
  1130. \end{lstlisting}
  1131. \caption{Interpreter for the $R_1$ language.}
  1132. \label{fig:interp-R1}
  1133. \end{figure}
  1134. The goal for this chapter is to implement a compiler that translates
  1135. any program $P_1$ written in the $R_1$ language into an x86 assembly
  1136. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  1137. computer as the $P_1$ program interpreted by \code{interp-R1}. That
  1138. is, they both output the same integer $n$. We depict this correctness
  1139. criteria in the following diagram.
  1140. \[
  1141. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1142. \node (p1) at (0, 0) {$P_1$};
  1143. \node (p2) at (4, 0) {$P_2$};
  1144. \node (o) at (4, -2) {$n$};
  1145. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  1146. \path[->] (p1) edge [left] node {\footnotesize interp-$R_1$} (o);
  1147. \path[->] (p2) edge [right] node {\footnotesize interp-x86} (o);
  1148. \end{tikzpicture}
  1149. \]
  1150. In the next section we introduce enough of the x86 assembly
  1151. language to compile $R_1$.
  1152. \section{The x86$_0$ Assembly Language}
  1153. \label{sec:x86}
  1154. \index{x86}
  1155. Figure~\ref{fig:x86-0-concrete} defines the concrete syntax for the subset of
  1156. the x86 assembly language needed for this chapter, which we call x86$_0$.
  1157. %
  1158. An x86 program begins with a \code{main} label followed by a sequence
  1159. of instructions. In the grammar, elipses such as $\ldots$ are used to
  1160. indicate a sequence of items, e.g., $\Instr \ldots$ is a sequence of
  1161. instructions.\index{instruction}
  1162. %
  1163. An x86 program is stored in the computer's memory and the computer has
  1164. a \emph{program counter} (PC)\index{program counter}\index{PC}
  1165. that points to the address of the next
  1166. instruction to be executed. For most instructions, once the
  1167. instruction is executed, the program counter is incremented to point
  1168. to the immediately following instruction in memory. Most x86
  1169. instructions take two operands, where each operand is either an
  1170. integer constant (called \emph{immediate value}\index{immediate value}),
  1171. a \emph{register}\index{register}, or a memory location.
  1172. A register is a special kind of variable. Each
  1173. one holds a 64-bit value; there are 16 registers in the computer and
  1174. their names are given in Figure~\ref{fig:x86-0-concrete}. The computer's memory
  1175. as a mapping of 64-bit addresses to 64-bit values%
  1176. \footnote{This simple story suffices for describing how sequential
  1177. programs access memory but is not sufficient for multi-threaded
  1178. programs. However, multi-threaded execution is beyond the scope of
  1179. this book.}.
  1180. %
  1181. We use the AT\&T syntax expected by the GNU assembler, which comes
  1182. with the \key{gcc} compiler that we use for compiling assembly code to
  1183. machine code.
  1184. %
  1185. Appendix~\ref{sec:x86-quick-reference} is a quick-reference for all of
  1186. the x86 instructions used in this book.
  1187. % to do: finish treatment of imulq
  1188. % it's needed for vector's in R6/R7
  1189. \newcommand{\allregisters}{\key{rsp} \mid \key{rbp} \mid \key{rax} \mid \key{rbx} \mid \key{rcx}
  1190. \mid \key{rdx} \mid \key{rsi} \mid \key{rdi} \mid \\
  1191. && \key{r8} \mid \key{r9} \mid \key{r10}
  1192. \mid \key{r11} \mid \key{r12} \mid \key{r13}
  1193. \mid \key{r14} \mid \key{r15}}
  1194. \begin{figure}[tp]
  1195. \fbox{
  1196. \begin{minipage}{0.96\textwidth}
  1197. \[
  1198. \begin{array}{lcl}
  1199. \Reg &::=& \allregisters{} \\
  1200. \Arg &::=& \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)}\\
  1201. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \mid
  1202. \key{subq} \; \Arg\key{,} \Arg \mid
  1203. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid \\
  1204. && \key{callq} \; \mathit{label} \mid
  1205. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} \\
  1206. && \itm{label}\key{:}\; \Instr \\
  1207. x86_0 &::= & \key{.globl main}\\
  1208. & & \key{main:} \; \Instr\ldots
  1209. \end{array}
  1210. \]
  1211. \end{minipage}
  1212. }
  1213. \caption{The syntax of the x86$_0$ assembly language (AT\&T syntax).}
  1214. \label{fig:x86-0-concrete}
  1215. \end{figure}
  1216. An immediate value is written using the notation \key{\$}$n$ where $n$
  1217. is an integer.
  1218. %
  1219. A register is written with a \key{\%} followed by the register name,
  1220. such as \key{\%rax}.
  1221. %
  1222. An access to memory is specified using the syntax $n(\key{\%}r)$,
  1223. which obtains the address stored in register $r$ and then adds $n$
  1224. bytes to the address. The resulting address is used to either load or
  1225. store to memory depending on whether it occurs as a source or
  1226. destination argument of an instruction.
  1227. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  1228. source $s$ and destination $d$, applies the arithmetic operation, then
  1229. writes the result back to the destination $d$.
  1230. %
  1231. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  1232. stores the result in $d$.
  1233. %
  1234. The $\key{callq}\,\itm{label}$ instruction executes the procedure
  1235. specified by the label and $\key{retq}$ returns from a procedure to
  1236. its caller. The abstract syntax for \code{callq} includes an extra
  1237. integer field that represents the arity (number of parameters) of the
  1238. function being called.
  1239. %
  1240. We discuss procedure calls in more detail later in this
  1241. chapter and in Chapter~\ref{ch:functions}. The
  1242. $\key{jmp}\,\itm{label}$ instruction updates the program counter to
  1243. the address of the instruction after the specified label.
  1244. Figure~\ref{fig:p0-x86} depicts an x86 program that is equivalent
  1245. to \code{(+ 10 32)}. The \key{globl} directive says that the
  1246. \key{main} procedure is externally visible, which is necessary so
  1247. that the operating system can call it. The label \key{main:}
  1248. indicates the beginning of the \key{main} procedure which is where
  1249. the operating system starts executing this program. The instruction
  1250. \lstinline{movq $10, %rax} puts $10$ into register \key{rax}. The
  1251. following instruction \lstinline{addq $32, %rax} adds $32$ to the
  1252. $10$ in \key{rax} and puts the result, $42$, back into
  1253. \key{rax}.
  1254. %
  1255. The last instruction, \key{retq}, finishes the \key{main} function by
  1256. returning the integer in \key{rax} to the operating system. The
  1257. operating system interprets this integer as the program's exit
  1258. code. By convention, an exit code of 0 indicates that a program
  1259. completed successfully, and all other exit codes indicate various
  1260. errors. Nevertheless, we return the result of the program as the exit
  1261. code.
  1262. %\begin{wrapfigure}{r}{2.25in}
  1263. \begin{figure}[tbp]
  1264. \begin{lstlisting}
  1265. .globl main
  1266. main:
  1267. movq $10, %rax
  1268. addq $32, %rax
  1269. retq
  1270. \end{lstlisting}
  1271. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1272. \label{fig:p0-x86}
  1273. %\end{wrapfigure}
  1274. \end{figure}
  1275. Unfortunately, x86 varies in a couple ways depending on what operating
  1276. system it is assembled in. The code examples shown here are correct on
  1277. Linux and most Unix-like platforms, but when assembled on Mac OS X,
  1278. labels like \key{main} must be prefixed with an underscore, as in
  1279. \key{\_main}.
  1280. We exhibit the use of memory for storing intermediate results in the
  1281. next example. Figure~\ref{fig:p1-x86} lists an x86 program that is
  1282. equivalent to \code{(+ 52 (- 10))}. This program uses a region of
  1283. memory called the \emph{procedure call stack} (or \emph{stack} for
  1284. short). \index{stack}\index{procedure call stack} The stack consists
  1285. of a separate \emph{frame}\index{frame} for each procedure call. The
  1286. memory layout for an individual frame is shown in
  1287. Figure~\ref{fig:frame}. The register \key{rsp} is called the
  1288. \emph{stack pointer}\index{stack pointer} and points to the item at
  1289. the top of the stack. The stack grows downward in memory, so we
  1290. increase the size of the stack by subtracting from the stack pointer.
  1291. In the context of a procedure call, the \emph{return
  1292. address}\index{return address} is the instruction after the call
  1293. instruction on the caller side. The function call inststruction,
  1294. \code{callq}, pushes the return address onto the stack. The register
  1295. \key{rbp} is the \emph{base pointer}\index{base pointer} and is used
  1296. to access variables associated with the current procedure call. The
  1297. base pointer of the caller is pushed onto the stack after the return
  1298. address. We number the variables from $1$ to $n$. Variable $1$ is
  1299. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  1300. $-16\key{(\%rbp)}$, etc.
  1301. \begin{figure}[tbp]
  1302. \begin{lstlisting}
  1303. start:
  1304. movq $10, -8(%rbp)
  1305. negq -8(%rbp)
  1306. movq -8(%rbp), %rax
  1307. addq $52, %rax
  1308. jmp conclusion
  1309. .globl main
  1310. main:
  1311. pushq %rbp
  1312. movq %rsp, %rbp
  1313. subq $16, %rsp
  1314. jmp start
  1315. conclusion:
  1316. addq $16, %rsp
  1317. popq %rbp
  1318. retq
  1319. \end{lstlisting}
  1320. \caption{An x86 program equivalent to \code{(+ 10 32)}.}
  1321. \label{fig:p1-x86}
  1322. \end{figure}
  1323. \begin{figure}[tbp]
  1324. \centering
  1325. \begin{tabular}{|r|l|} \hline
  1326. Position & Contents \\ \hline
  1327. 8(\key{\%rbp}) & return address \\
  1328. 0(\key{\%rbp}) & old \key{rbp} \\
  1329. -8(\key{\%rbp}) & variable $1$ \\
  1330. -16(\key{\%rbp}) & variable $2$ \\
  1331. \ldots & \ldots \\
  1332. 0(\key{\%rsp}) & variable $n$\\ \hline
  1333. \end{tabular}
  1334. \caption{Memory layout of a frame.}
  1335. \label{fig:frame}
  1336. \end{figure}
  1337. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  1338. control is transfered from the operating system to the \code{main}
  1339. function. The operating system issues a \code{callq main} instruction
  1340. which pushes its return address on the stack and then jumps to
  1341. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  1342. by 16 bytes prior to the execution of any \code{callq} instruction, so
  1343. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  1344. alignment (because the \code{callq} pushed the return address). The
  1345. first three instructions are the typical \emph{prelude}\index{prelude}
  1346. for a procedure. The instruction \code{pushq \%rbp} saves the base
  1347. pointer for the caller onto the stack and subtracts $8$ from the stack
  1348. pointer. At this point the stack pointer is back to being 16-byte
  1349. aligned. The second instruction \code{movq \%rsp, \%rbp} changes the
  1350. base pointer so that it points the location of the old base
  1351. pointer. The instruction \code{subq \$16, \%rsp} moves the stack
  1352. pointer down to make enough room for storing variables. This program
  1353. needs one variable ($8$ bytes) but we round up to 16 bytes to maintain
  1354. the 16-byte alignment of the \code{rsp}. With the \code{rsp} aligned,
  1355. we are ready to make calls to other functions. The last instruction of
  1356. the prelude is \code{jmp start}, which transfers control to the
  1357. instructions that were generated from the Racket expression \code{(+
  1358. 10 32)}.
  1359. The four instructions under the label \code{start} carry out the work
  1360. of computing \code{(+ 52 (- 10)))}.
  1361. %
  1362. The first instruction \code{movq \$10, -8(\%rbp)} stores $10$ in
  1363. variable $1$.
  1364. %
  1365. The instruction \code{negq -8(\%rbp)} changes variable $1$ to $-10$.
  1366. %
  1367. The following instruction moves the $-10$ from variable $1$ into the
  1368. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  1369. the value in \code{rax}, updating its contents to $42$.
  1370. The three instructions under the label \code{conclusion} are the
  1371. typical \emph{conclusion}\index{conclusion} of a procedure. The first
  1372. two instructions are necessary to get the state of the machine back to
  1373. where it was at the beginning of the procedure. The instruction
  1374. \key{addq \$16, \%rsp} moves the stack pointer back to point at the
  1375. old base pointer. The amount added here needs to match the amount that
  1376. was subtracted in the prelude of the procedure. Then \key{popq \%rbp}
  1377. returns the old base pointer to \key{rbp} and adds $8$ to the stack
  1378. pointer. The last instruction, \key{retq}, jumps back to the
  1379. procedure that called this one and adds 8 to the stack pointer, which
  1380. returns the stack pointer to where it was prior to the procedure call.
  1381. The compiler needs a convenient representation for manipulating x86
  1382. programs, so we define an abstract syntax for x86 in
  1383. Figure~\ref{fig:x86-0-ast}. We refer to this language as x86$_0$ with
  1384. a subscript $0$ because later we introduce extended versions of this
  1385. assembly language. The main difference compared to the concrete syntax
  1386. of x86 (Figure~\ref{fig:x86-0-concrete}) is that it does not allow
  1387. labeled instructions to appear anywhere, but instead organizes
  1388. instructions into a group called a \emph{block}\index{block}\index{basic block}
  1389. and associates a label with every block, which is why the \key{CFG} struct
  1390. (for control-flow graph) includes an alist mapping labels to
  1391. blocks. The reason for this organization becomes apparent in
  1392. Chapter~\ref{ch:bool-types} when we introduce conditional
  1393. branching. The \code{Block} structure includes an $\itm{info}$ field
  1394. that is not needed for this chapter, but will become useful in
  1395. Chapter~\ref{ch:register-allocation-r1}. For now, the $\itm{info}$
  1396. field should just contain an empty list.
  1397. \begin{figure}[tp]
  1398. \fbox{
  1399. \begin{minipage}{0.96\textwidth}
  1400. \small
  1401. \[
  1402. \begin{array}{lcl}
  1403. \Reg &::=& \allregisters{} \\
  1404. \Arg &::=& \IMM{\Int} \mid \REG{\Reg}
  1405. \mid \DEREF{\Reg}{\Int} \\
  1406. \Instr &::=& \BININSTR{\code{'addq}}{\Arg}{\Arg}
  1407. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} \\
  1408. &\mid& \BININSTR{\code{'movq}}{\Arg}{\Arg}
  1409. \mid \UNIINSTR{\code{'negq}}{\Arg}\\
  1410. &\mid& \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  1411. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} \\
  1412. \Block &::= & \BLOCK{\itm{info}}{\Instr\ldots} \\
  1413. x86_0 &::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}}
  1414. \end{array}
  1415. \]
  1416. \end{minipage}
  1417. }
  1418. \caption{The abstract syntax of x86$_0$ assembly.}
  1419. \label{fig:x86-0-ast}
  1420. \end{figure}
  1421. \section{Planning the trip to x86 via the $C_0$ language}
  1422. \label{sec:plan-s0-x86}
  1423. To compile one language to another it helps to focus on the
  1424. differences between the two languages because the compiler will need
  1425. to bridge those differences. What are the differences between $R_1$
  1426. and x86 assembly? Here are some of the most important ones:
  1427. \begin{enumerate}
  1428. \item[(a)] x86 arithmetic instructions typically have two arguments
  1429. and update the second argument in place. In contrast, $R_1$
  1430. arithmetic operations take two arguments and produce a new value.
  1431. An x86 instruction may have at most one memory-accessing argument.
  1432. Furthermore, some instructions place special restrictions on their
  1433. arguments.
  1434. \item[(b)] An argument of an $R_1$ operator can be any expression,
  1435. whereas x86 instructions restrict their arguments to be integers
  1436. constants, registers, and memory locations.
  1437. \item[(c)] The order of execution in x86 is explicit in the syntax: a
  1438. sequence of instructions and jumps to labeled positions, whereas in
  1439. $R_1$ the order of evaluation is a left-to-right depth-first
  1440. traversal of the abstract syntax tree.
  1441. \item[(d)] An $R_1$ program can have any number of variables whereas
  1442. x86 has 16 registers and the procedure calls stack.
  1443. \item[(e)] Variables in $R_1$ can overshadow other variables with the
  1444. same name. The registers and memory locations of x86 all have unique
  1445. names or addresses.
  1446. \end{enumerate}
  1447. We ease the challenge of compiling from $R_1$ to x86 by breaking down
  1448. the problem into several steps, dealing with the above differences one
  1449. at a time. Each of these steps is called a \emph{pass} of the
  1450. compiler.\index{pass}\index{compiler pass}
  1451. %
  1452. This terminology comes from each step traverses (i.e. passes over) the
  1453. AST of the program.
  1454. %
  1455. We begin by sketching how we might implement each pass, and give them
  1456. names. We then figure out an ordering of the passes and the
  1457. input/output language for each pass. The very first pass has $R_1$ as
  1458. its input language and the last pass has x86 as its output
  1459. language. In between we can choose whichever language is most
  1460. convenient for expressing the output of each pass, whether that be
  1461. $R_1$, x86, or new \emph{intermediate languages} of our own design.
  1462. Finally, to implement each pass we write one recursive function per
  1463. non-terminal in the grammar of the input language of the pass.
  1464. \index{intermediate language}
  1465. \begin{description}
  1466. \item[Pass \key{select-instructions}] To handle the difference between
  1467. $R_1$ operations and x86 instructions we convert each $R_1$
  1468. operation to a short sequence of instructions that accomplishes the
  1469. same task.
  1470. \item[Pass \key{remove-complex-opera*}] To ensure that each
  1471. subexpression (i.e. operator and operand, and hence the name
  1472. \key{opera*}) is an \emph{atomic} expression (a variable or
  1473. integer), we introduce temporary variables to hold the results
  1474. of subexpressions.\index{atomic expression}
  1475. \item[Pass \key{explicate-control}] To make the execution order of the
  1476. program explicit, we convert from the abstract syntax tree
  1477. representation into a control-flow graph in which each node
  1478. contains a sequence of statements and the edges between nodes say
  1479. where to go at the end of the sequence.
  1480. \item[Pass \key{assign-homes}] To handle the difference between the
  1481. variables in $R_1$ versus the registers and stack locations in x86,
  1482. we map each variable to a register or stack location.
  1483. \item[Pass \key{uniquify}] This pass deals with the shadowing of variables
  1484. by renaming every variable to a unique name, so that shadowing no
  1485. longer occurs.
  1486. \end{description}
  1487. The next question is: in what order should we apply these passes? This
  1488. question can be challenging because it is difficult to know ahead of
  1489. time which orders will be better (easier to implement, produce more
  1490. efficient code, etc.) so oftentimes trial-and-error is
  1491. involved. Nevertheless, we can try to plan ahead and make educated
  1492. choices regarding the ordering.
  1493. Let us consider the ordering of \key{uniquify} and
  1494. \key{remove-complex-opera*}. The assignment of subexpressions to
  1495. temporary variables involves introducing new variables and moving
  1496. subexpressions, which might change the shadowing of variables and
  1497. inadvertently change the behavior of the program. But if we apply
  1498. \key{uniquify} first, this will not be an issue. Of course, this means
  1499. that in \key{remove-complex-opera*}, we need to ensure that the
  1500. temporary variables that it creates are unique.
  1501. What should be the ordering of \key{explicate-control} with respect to
  1502. \key{uniquify}? The \key{uniquify} pass should come first because
  1503. \key{explicate-control} changes all the \key{let}-bound variables to
  1504. become local variables whose scope is the entire program, which would
  1505. confuse variables with the same name.
  1506. %
  1507. Likewise, we place \key{explicate-control} after
  1508. \key{remove-complex-opera*} because \key{explicate-control} removes
  1509. the \key{let} form, but it is convenient to use \key{let} in the
  1510. output of \key{remove-complex-opera*}.
  1511. %
  1512. Regarding \key{assign-homes}, it is helpful to place
  1513. \key{explicate-control} first because \key{explicate-control} changes
  1514. \key{let}-bound variables into program-scope variables. This means
  1515. that the \key{assign-homes} pass can read off the variables from the
  1516. $\itm{info}$ of the \key{Program} AST node instead of traversing the
  1517. entire program in search of \key{let}-bound variables.
  1518. Last, we need to decide on the ordering of \key{select-instructions}
  1519. and \key{assign-homes}. These two passes are intertwined, creating a
  1520. Gordian Knot. To do a good job of assigning homes, it is helpful to
  1521. have already determined which instructions will be used, because x86
  1522. instructions have restrictions about which of their arguments can be
  1523. registers versus stack locations. One might want to give preferential
  1524. treatment to variables that occur in register-argument positions. On
  1525. the other hand, it may turn out to be impossible to make sure that all
  1526. such variables are assigned to registers, and then one must redo the
  1527. selection of instructions. Some compilers handle this problem by
  1528. iteratively repeating these two passes until a good solution is found.
  1529. We use a simpler approach in which \key{select-instructions}
  1530. comes first, followed by the \key{assign-homes}, then a third
  1531. pass named \key{patch-instructions} that uses a reserved register to
  1532. patch-up outstanding problems regarding instructions with too many
  1533. memory accesses. The disadvantage of this approach is some programs
  1534. may not execute as efficiently as they would if we used the iterative
  1535. approach and used all of the registers for variables.
  1536. \begin{figure}[tbp]
  1537. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1538. \node (R1) at (0,2) {\large $R_1$};
  1539. \node (R1-2) at (3,2) {\large $R_1$};
  1540. \node (R1-3) at (6,2) {\large $R_1^{\dagger}$};
  1541. %\node (C0-1) at (6,0) {\large $C_0$};
  1542. \node (C0-2) at (3,0) {\large $C_0$};
  1543. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}_0$};
  1544. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}_0$};
  1545. \node (x86-4) at (9,-2) {\large $\text{x86}_0$};
  1546. \node (x86-5) at (12,-2) {\large $\text{x86}^{\dagger}_0$};
  1547. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  1548. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  1549. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-2);
  1550. %\path[->,bend right=15] (C0-1) edge [above] node {\ttfamily\footnotesize uncover-locals} (C0-2);
  1551. \path[->,bend right=15] (C0-2) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  1552. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign-homes} (x86-3);
  1553. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  1554. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize print-x86} (x86-5);
  1555. \end{tikzpicture}
  1556. \caption{Overview of the passes for compiling $R_1$. }
  1557. \label{fig:R1-passes}
  1558. \end{figure}
  1559. Figure~\ref{fig:R1-passes} presents the ordering of the compiler
  1560. passes in the form of a graph. Each pass is an edge and the
  1561. input/output language of each pass is a node in the graph. The output
  1562. of \key{uniquify} and \key{remove-complex-opera*} are programs that
  1563. are still in the $R_1$ language, but the output of the pass
  1564. \key{explicate-control} is in a different language $C_0$ that is
  1565. designed to make the order of evaluation explicit in its syntax, which
  1566. we introduce in the next section. The \key{select-instruction} pass
  1567. translates from $C_0$ to a variant of x86. The \key{assign-homes} and
  1568. \key{patch-instructions} passes input and output variants of x86
  1569. assembly. The last pass in Figure~\ref{fig:R1-passes} is
  1570. \key{print-x86}, which converts from the abstract syntax of
  1571. $\text{x86}_0$ to the concrete syntax of x86.
  1572. In the next sections we discuss the $C_0$ language and the
  1573. $\text{x86}^{*}_0$ and $\text{x86}^{\dagger}_0$ dialects of x86. The
  1574. remainder of this chapter gives hints regarding the implementation of
  1575. each of the compiler passes in Figure~\ref{fig:R1-passes}.
  1576. \subsection{The $C_0$ Intermediate Language}
  1577. The output of \key{explicate-control} is similar to the $C$
  1578. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  1579. categories for expressions and statements, so we name it $C_0$. The
  1580. concrete syntax for $C_0$ is defined in
  1581. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for $C_0$
  1582. is defined in Figure~\ref{fig:c0-syntax}.
  1583. %
  1584. The $C_0$ language supports the same operators as $R_1$ but the
  1585. arguments of operators are restricted to atomic expressions (variables
  1586. and integers), thanks to the \key{remove-complex-opera*} pass. Instead
  1587. of \key{Let} expressions, $C_0$ has assignment statements which can be
  1588. executed in sequence using the \key{Seq} form. A sequence of
  1589. statements always ends with \key{Return}, a guarantee that is baked
  1590. into the grammar rules for the \itm{tail} non-terminal. The naming of
  1591. this non-terminal comes from the term \emph{tail position}\index{tail position},
  1592. which refers to an expression that is the last one to execute within a
  1593. function. (An expression in tail position may contain subexpressions,
  1594. and those may or may not be in tail position depending on the kind of
  1595. expression.)
  1596. A $C_0$ program consists of a control-flow graph (represented as an
  1597. alist mapping labels to tails). This is more general than
  1598. necessary for the present chapter, as we do not yet need to introduce
  1599. \key{goto} for jumping to labels, but it saves us from having to
  1600. change the syntax of the program construct in
  1601. Chapter~\ref{ch:bool-types}. For now there will be just one label,
  1602. \key{start}, and the whole program is its tail.
  1603. %
  1604. The $\itm{info}$ field of the \key{Program} form, after the
  1605. \key{explicate-control} pass, contains a mapping from the symbol
  1606. \key{locals} to a list of variables, that is, a list of all the
  1607. variables used in the program. At the start of the program, these
  1608. variables are uninitialized; they become initialized on their first
  1609. assignment.
  1610. \begin{figure}[tbp]
  1611. \fbox{
  1612. \begin{minipage}{0.96\textwidth}
  1613. \[
  1614. \begin{array}{lcl}
  1615. \Atm &::=& \Int \mid \Var \\
  1616. \Exp &::=& \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)}\\
  1617. \Stmt &::=& \Var~\key{=}~\Exp\key{;} \\
  1618. \Tail &::= & \key{return}~\Exp\key{;} \mid \Stmt~\Tail \\
  1619. C_0 & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  1620. \end{array}
  1621. \]
  1622. \end{minipage}
  1623. }
  1624. \caption{The concrete syntax of the $C_0$ intermediate language.}
  1625. \label{fig:c0-concrete-syntax}
  1626. \end{figure}
  1627. \begin{figure}[tbp]
  1628. \fbox{
  1629. \begin{minipage}{0.96\textwidth}
  1630. \[
  1631. \begin{array}{lcl}
  1632. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1633. \Exp &::=& \Atm \mid \READ{} \mid \NEG{\Atm} \\
  1634. &\mid& \ADD{\Atm}{\Atm}\\
  1635. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  1636. \Tail &::= & \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} \\
  1637. C_0 & ::= & \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}\ldots}}
  1638. \end{array}
  1639. \]
  1640. \end{minipage}
  1641. }
  1642. \caption{The abstract syntax of the $C_0$ intermediate language.}
  1643. \label{fig:c0-syntax}
  1644. \end{figure}
  1645. \subsection{The dialects of x86}
  1646. The x86$^{*}_0$ language, pronounced ``pseudo x86'', is the output of
  1647. the pass \key{select-instructions}. It extends x86$_0$ with an
  1648. unbounded number of program-scope variables and has looser rules
  1649. regarding instruction arguments. The x86$^{\dagger}$ language, the
  1650. output of \key{print-x86}, is the concrete syntax for x86.
  1651. \section{Uniquify Variables}
  1652. \label{sec:uniquify-s0}
  1653. The \code{uniquify} pass compiles arbitrary $R_1$ programs into $R_1$
  1654. programs in which every \key{let} uses a unique variable name. For
  1655. example, the \code{uniquify} pass should translate the program on the
  1656. left into the program on the right. \\
  1657. \begin{tabular}{lll}
  1658. \begin{minipage}{0.4\textwidth}
  1659. \begin{lstlisting}
  1660. (let ([x 32])
  1661. (+ (let ([x 10]) x) x))
  1662. \end{lstlisting}
  1663. \end{minipage}
  1664. &
  1665. $\Rightarrow$
  1666. &
  1667. \begin{minipage}{0.4\textwidth}
  1668. \begin{lstlisting}
  1669. (let ([x.1 32])
  1670. (+ (let ([x.2 10]) x.2) x.1))
  1671. \end{lstlisting}
  1672. \end{minipage}
  1673. \end{tabular} \\
  1674. %
  1675. The following is another example translation, this time of a program
  1676. with a \key{let} nested inside the initializing expression of another
  1677. \key{let}.\\
  1678. \begin{tabular}{lll}
  1679. \begin{minipage}{0.4\textwidth}
  1680. \begin{lstlisting}
  1681. (let ([x (let ([x 4])
  1682. (+ x 1))])
  1683. (+ x 2))
  1684. \end{lstlisting}
  1685. \end{minipage}
  1686. &
  1687. $\Rightarrow$
  1688. &
  1689. \begin{minipage}{0.4\textwidth}
  1690. \begin{lstlisting}
  1691. (let ([x.2 (let ([x.1 4])
  1692. (+ x.1 1))])
  1693. (+ x.2 2))
  1694. \end{lstlisting}
  1695. \end{minipage}
  1696. \end{tabular}
  1697. We recommend implementing \code{uniquify} by creating a function named
  1698. \code{uniquify-exp} that is structurally recursive function and mostly
  1699. just copies the input program. However, when encountering a \key{let},
  1700. it should generate a unique name for the variable (the Racket function
  1701. \code{gensym} is handy for this) and associate the old name with the
  1702. new unique name in an alist. The \code{uniquify-exp}
  1703. function will need to access this alist when it gets to a
  1704. variable reference, so we add another parameter to \code{uniquify-exp}
  1705. for the alist.
  1706. The skeleton of the \code{uniquify-exp} function is shown in
  1707. Figure~\ref{fig:uniquify-s0}. The function is curried so that it is
  1708. convenient to partially apply it to a symbol table and then apply it
  1709. to different expressions, as in the last clause for primitive
  1710. 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}}
  1711. form is useful for applying a function to each element of a list to produce
  1712. a new list.
  1713. \index{for/list}
  1714. \begin{exercise}
  1715. \normalfont % I don't like the italics for exercises. -Jeremy
  1716. Complete the \code{uniquify} pass by filling in the blanks, that is,
  1717. implement the clauses for variables and for the \key{let} form.
  1718. \end{exercise}
  1719. \begin{figure}[tbp]
  1720. \begin{lstlisting}
  1721. (define (uniquify-exp symtab)
  1722. (lambda (e)
  1723. (match e
  1724. [(Var x) ___]
  1725. [(Int n) (Int n)]
  1726. [(Let x e body) ___]
  1727. [(Prim op es)
  1728. (Prim op (for/list ([e es]) ((uniquify-exp symtab) e)))]
  1729. )))
  1730. (define (uniquify p)
  1731. (match p
  1732. [(Program '() e)
  1733. (Program '() ((uniquify-exp '()) e))]
  1734. )))
  1735. \end{lstlisting}
  1736. \caption{Skeleton for the \key{uniquify} pass.}
  1737. \label{fig:uniquify-s0}
  1738. \end{figure}
  1739. \begin{exercise}
  1740. \normalfont % I don't like the italics for exercises. -Jeremy
  1741. Test your \key{uniquify} pass by creating five example $R_1$ programs
  1742. and checking whether the output programs produce the same result as
  1743. the input programs. The $R_1$ programs should be designed to test the
  1744. most interesting parts of the \key{uniquify} pass, that is, the
  1745. programs should include \key{let} forms, variables, and variables
  1746. that overshadow each other. The five programs should be in a
  1747. subdirectory named \key{tests} and they should have the same file name
  1748. except for a different integer at the end of the name, followed by the
  1749. ending \key{.rkt}. Use the \key{interp-tests} function
  1750. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1751. your \key{uniquify} pass on the example programs. See the
  1752. \key{run-tests.rkt} script in the student support code for an example
  1753. of how to use \key{interp-tests}.
  1754. \end{exercise}
  1755. \section{Remove Complex Operands}
  1756. \label{sec:remove-complex-opera-R1}
  1757. The \code{remove-complex-opera*} pass compiles $R_1$ programs into
  1758. $R_1$ programs in which the arguments of operations are atomic
  1759. expressions. Put another way, this pass removes complex
  1760. operands\index{complex operand}, such as the expression \code{(- 10)}
  1761. in the program below. This is accomplished by introducing a new
  1762. \key{let}-bound variable, binding the complex operand to the new
  1763. variable, and then using the new variable in place of the complex
  1764. operand, as shown in the output of \code{remove-complex-opera*} on the
  1765. right.\\
  1766. \begin{tabular}{lll}
  1767. \begin{minipage}{0.4\textwidth}
  1768. % s0_19.rkt
  1769. \begin{lstlisting}
  1770. (+ 52 (- 10))
  1771. \end{lstlisting}
  1772. \end{minipage}
  1773. &
  1774. $\Rightarrow$
  1775. &
  1776. \begin{minipage}{0.4\textwidth}
  1777. \begin{lstlisting}
  1778. (let ([tmp.1 (- 10)])
  1779. (+ 52 tmp.1))
  1780. \end{lstlisting}
  1781. \end{minipage}
  1782. \end{tabular}
  1783. \begin{figure}[tp]
  1784. \centering
  1785. \fbox{
  1786. \begin{minipage}{0.96\textwidth}
  1787. \[
  1788. \begin{array}{rcl}
  1789. \Atm &::=& \INT{\Int} \mid \VAR{\Var} \\
  1790. \Exp &::=& \Atm \mid \READ{} \\
  1791. &\mid& \NEG{\Atm} \mid \ADD{\Atm}{\Atm} \\
  1792. &\mid& \LET{\Var}{\Exp}{\Exp} \\
  1793. R^{\dagger}_1 &::=& \PROGRAM{\code{'()}}{\Exp}
  1794. \end{array}
  1795. \]
  1796. \end{minipage}
  1797. }
  1798. \caption{$R_1^{\dagger}$ is $R_1$ in administrative normal form (ANF).}
  1799. \label{fig:r1-anf-syntax}
  1800. \end{figure}
  1801. Figure~\ref{fig:r1-anf-syntax} presents the grammar for the output of
  1802. this pass, language $R_1^{\dagger}$. The main difference is that
  1803. operator arguments are required to be atomic expressions. In the
  1804. literature, this is called \emph{administrative normal form}, or ANF
  1805. for short~\citep{Danvy:1991fk,Flanagan:1993cg}.
  1806. \index{administrative normal form}
  1807. \index{ANF}
  1808. We recommend implementing this pass with two mutually recursive
  1809. functions, \code{rco-atom} and \code{rco-exp}. The idea is to apply
  1810. \code{rco-atom} to subexpressions that are required to be atomic and
  1811. to apply \code{rco-exp} to subexpressions that can be atomic or
  1812. complex (see Figure~\ref{fig:r1-anf-syntax}). Both functions take an
  1813. $R_1$ expression as input. The \code{rco-exp} function returns an
  1814. expression. The \code{rco-atom} function returns two things: an
  1815. atomic expression and alist mapping temporary variables to complex
  1816. subexpressions. You can return multiple things from a function using
  1817. Racket's \key{values} form and you can receive multiple things from a
  1818. function call using the \key{define-values} form. If you are not
  1819. familiar with these features, review the Racket documentation. Also,
  1820. 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}}
  1821. form is useful for applying a function to each
  1822. element of a list, in the case where the function returns multiple
  1823. values.
  1824. \index{for/lists}
  1825. The following shows the output of \code{rco-atom} on the expression
  1826. \code{(- 10)} (using concrete syntax to be concise).
  1827. \begin{tabular}{lll}
  1828. \begin{minipage}{0.4\textwidth}
  1829. \begin{lstlisting}
  1830. (- 10)
  1831. \end{lstlisting}
  1832. \end{minipage}
  1833. &
  1834. $\Rightarrow$
  1835. &
  1836. \begin{minipage}{0.4\textwidth}
  1837. \begin{lstlisting}
  1838. tmp.1
  1839. ((tmp.1 . (- 10)))
  1840. \end{lstlisting}
  1841. \end{minipage}
  1842. \end{tabular}
  1843. Take special care of programs such as the next one that \key{let}-bind
  1844. variables with integers or other variables. You should leave them
  1845. unchanged, as shown in to the program on the right \\
  1846. \begin{tabular}{lll}
  1847. \begin{minipage}{0.4\textwidth}
  1848. % s0_20.rkt
  1849. \begin{lstlisting}
  1850. (let ([a 42])
  1851. (let ([b a])
  1852. b))
  1853. \end{lstlisting}
  1854. \end{minipage}
  1855. &
  1856. $\Rightarrow$
  1857. &
  1858. \begin{minipage}{0.4\textwidth}
  1859. \begin{lstlisting}
  1860. (let ([a 42])
  1861. (let ([b a])
  1862. b))
  1863. \end{lstlisting}
  1864. \end{minipage}
  1865. \end{tabular} \\
  1866. A careless implementation of \key{rco-exp} and \key{rco-atom} might
  1867. produce the following output.\\
  1868. \begin{minipage}{0.4\textwidth}
  1869. \begin{lstlisting}
  1870. (let ([tmp.1 42])
  1871. (let ([a tmp.1])
  1872. (let ([tmp.2 a])
  1873. (let ([b tmp.2])
  1874. b))))
  1875. \end{lstlisting}
  1876. \end{minipage}
  1877. \begin{exercise}
  1878. \normalfont Implement the \code{remove-complex-opera*} pass.
  1879. Test the new pass on all of the example programs that you created to test the
  1880. \key{uniquify} pass and create three new example programs that are
  1881. designed to exercise the interesting code in the
  1882. \code{remove-complex-opera*} pass. Use the \key{interp-tests} function
  1883. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  1884. your passes on the example programs.
  1885. \end{exercise}
  1886. \section{Explicate Control}
  1887. \label{sec:explicate-control-r1}
  1888. The \code{explicate-control} pass compiles $R_1$ programs into $C_0$
  1889. programs that make the order of execution explicit in their
  1890. syntax. For now this amounts to flattening \key{let} constructs into a
  1891. sequence of assignment statements. For example, consider the following
  1892. $R_1$ program.\\
  1893. % s0_11.rkt
  1894. \begin{minipage}{0.96\textwidth}
  1895. \begin{lstlisting}
  1896. (let ([y (let ([x 20])
  1897. (+ x (let ([x 22]) x)))])
  1898. y)
  1899. \end{lstlisting}
  1900. \end{minipage}\\
  1901. %
  1902. The output of the previous pass and of \code{explicate-control} is
  1903. shown below. Recall that the right-hand-side of a \key{let} executes
  1904. before its body, so the order of evaluation for this program is to
  1905. assign \code{20} to \code{x.1}, assign \code{22} to \code{x.2}, assign
  1906. \code{(+ x.1 x.2)} to \code{y}, then return \code{y}. Indeed, the
  1907. output of \code{explicate-control} makes this ordering explicit.\\
  1908. \begin{tabular}{lll}
  1909. \begin{minipage}{0.4\textwidth}
  1910. \begin{lstlisting}
  1911. (let ([y (let ([x.1 20])
  1912. (let ([x.2 22])
  1913. (+ x.1 x.2)))])
  1914. y)
  1915. \end{lstlisting}
  1916. \end{minipage}
  1917. &
  1918. $\Rightarrow$
  1919. &
  1920. \begin{minipage}{0.4\textwidth}
  1921. \begin{lstlisting}
  1922. locals: y x.1 x.2
  1923. start:
  1924. x.1 = 20;
  1925. x.2 = 22;
  1926. y = (+ x.1 x.2);
  1927. return y;
  1928. \end{lstlisting}
  1929. \end{minipage}
  1930. \end{tabular}
  1931. We recommend implementing \code{explicate-control} using two mutually
  1932. recursive functions: \code{explicate-tail} and
  1933. \code{explicate-assign}. The first function should be applied to
  1934. expressions in tail position whereas the second should be applied to
  1935. expressions that occur on the right-hand-side of a \key{let}.
  1936. %
  1937. The \code{explicate-tail} function takes an $R_1$ expression as input
  1938. and produces a $C_0$ $\Tail$ (see Figure~\ref{fig:c0-syntax}) and a
  1939. list of formerly \key{let}-bound variables.
  1940. %
  1941. The \code{explicate-assign} function takes an $R_1$ expression, the
  1942. variable that it is to be assigned to, and $C_0$ code (a $\Tail$) that
  1943. should come after the assignment (e.g., the code generated for the
  1944. body of the \key{let}). It returns a $\Tail$ and a list of
  1945. variables. The \code{explicate-assign} function is in
  1946. accumulator-passing style in that its third parameter is some $C_0$
  1947. code which it then adds to and returns. The reader might be tempted to
  1948. instead organize \code{explicate-assign} in a more direct fashion,
  1949. without the third parameter and perhaps using \code{append} to combine
  1950. statements. We warn against that alternative because the
  1951. accumulator-passing style is key to how we generate high-quality code
  1952. for conditional expressions in Chapter~\ref{ch:bool-types}.
  1953. The top-level \code{explicate-control} function should invoke
  1954. \code{explicate-tail} on the body of the \key{program} and then
  1955. associate the \code{locals} symbol with the resulting list of
  1956. variables in the $\itm{info}$ field, as in the above example.
  1957. \section{Select Instructions}
  1958. \label{sec:select-r1}
  1959. \index{instruction selection}
  1960. In the \code{select-instructions} pass we begin the work of
  1961. translating from $C_0$ to $\text{x86}^{*}_0$. The target language of
  1962. this pass is a variant of x86 that still uses variables, so we add an
  1963. AST node of the form $\VAR{\itm{var}}$ to the $\text{x86}_0$ abstract
  1964. syntax of Figure~\ref{fig:x86-0-ast}. We recommend implementing the
  1965. \code{select-instructions} in terms of three auxiliary functions, one
  1966. for each of the non-terminals of $C_0$: $\Atm$, $\Stmt$, and $\Tail$.
  1967. The cases for $\Atm$ are straightforward, variables stay
  1968. the same and integer constants are changed to immediates:
  1969. $\INT{n}$ changes to $\IMM{n}$.
  1970. Next we consider the cases for $\Stmt$, starting with arithmetic
  1971. operations. For example, in $C_0$ an addition operation can take the
  1972. form below, to the left of the $\Rightarrow$. To translate to x86, we
  1973. need to use the \key{addq} instruction which does an in-place
  1974. update. So we must first move \code{10} to \code{x}. \\
  1975. \begin{tabular}{lll}
  1976. \begin{minipage}{0.4\textwidth}
  1977. \begin{lstlisting}
  1978. x = (+ 10 32);
  1979. \end{lstlisting}
  1980. \end{minipage}
  1981. &
  1982. $\Rightarrow$
  1983. &
  1984. \begin{minipage}{0.4\textwidth}
  1985. \begin{lstlisting}
  1986. movq $10, x
  1987. addq $32, x
  1988. \end{lstlisting}
  1989. \end{minipage}
  1990. \end{tabular} \\
  1991. %
  1992. There are cases that require special care to avoid generating
  1993. needlessly complicated code. If one of the arguments of the addition
  1994. is the same as the left-hand side of the assignment, then there is no
  1995. need for the extra move instruction. For example, the following
  1996. assignment statement can be translated into a single \key{addq}
  1997. instruction.\\
  1998. \begin{tabular}{lll}
  1999. \begin{minipage}{0.4\textwidth}
  2000. \begin{lstlisting}
  2001. x = (+ 10 x);
  2002. \end{lstlisting}
  2003. \end{minipage}
  2004. &
  2005. $\Rightarrow$
  2006. &
  2007. \begin{minipage}{0.4\textwidth}
  2008. \begin{lstlisting}
  2009. addq $10, x
  2010. \end{lstlisting}
  2011. \end{minipage}
  2012. \end{tabular} \\
  2013. The \key{read} operation does not have a direct counterpart in x86
  2014. assembly, so we have instead implemented this functionality in the C
  2015. language~\citep{Kernighan:1988nx}, with the function \code{read\_int}
  2016. in the file \code{runtime.c}. In general, we refer to all of the
  2017. functionality in this file as the \emph{runtime system}\index{runtime system},
  2018. or simply the \emph{runtime} for short. When compiling your generated x86
  2019. assembly code, you need to compile \code{runtime.c} to \code{runtime.o} (an
  2020. ``object file'', using \code{gcc} option \code{-c}) and link it into
  2021. the executable. For our purposes of code generation, all you need to
  2022. do is translate an assignment of \key{read} into some variable
  2023. $\itm{lhs}$ (for left-hand side) into a call to the \code{read\_int}
  2024. function followed by a move from \code{rax} to the left-hand side.
  2025. The move from \code{rax} is needed because the return value from
  2026. \code{read\_int} goes into \code{rax}, as is the case in general. \\
  2027. \begin{tabular}{lll}
  2028. \begin{minipage}{0.3\textwidth}
  2029. \begin{lstlisting}
  2030. |$\itm{var}$| = (read);
  2031. \end{lstlisting}
  2032. \end{minipage}
  2033. &
  2034. $\Rightarrow$
  2035. &
  2036. \begin{minipage}{0.3\textwidth}
  2037. \begin{lstlisting}
  2038. callq read_int
  2039. movq %rax, |$\itm{var}$|
  2040. \end{lstlisting}
  2041. \end{minipage}
  2042. \end{tabular} \\
  2043. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  2044. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  2045. assignment to the \key{rax} register followed by a jump to the
  2046. conclusion of the program (so the conclusion needs to be labeled).
  2047. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  2048. recursively and append the resulting instructions.
  2049. \begin{exercise}
  2050. \normalfont
  2051. Implement the \key{select-instructions} pass and test it on all of the
  2052. example programs that you created for the previous passes and create
  2053. three new example programs that are designed to exercise all of the
  2054. interesting code in this pass. Use the \key{interp-tests} function
  2055. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2056. your passes on the example programs.
  2057. \end{exercise}
  2058. \section{Assign Homes}
  2059. \label{sec:assign-r1}
  2060. The \key{assign-homes} pass compiles $\text{x86}^{*}_0$ programs to
  2061. $\text{x86}^{*}_0$ programs that no longer use program variables.
  2062. Thus, the \key{assign-homes} pass is responsible for placing all of
  2063. the program variables in registers or on the stack. For runtime
  2064. efficiency, it is better to place variables in registers, but as there
  2065. are only 16 registers, some programs must necessarily resort to
  2066. placing some variables on the stack. In this chapter we focus on the
  2067. mechanics of placing variables on the stack. We study an algorithm for
  2068. placing variables in registers in
  2069. Chapter~\ref{ch:register-allocation-r1}.
  2070. Consider again the following $R_1$ program.
  2071. % s0_20.rkt
  2072. \begin{lstlisting}
  2073. (let ([a 42])
  2074. (let ([b a])
  2075. b))
  2076. \end{lstlisting}
  2077. For reference, we repeat the output of \code{select-instructions} on
  2078. the left and show the output of \code{assign-homes} on the right.
  2079. Recall that \key{explicate-control} associated the list of
  2080. variables with the \code{locals} symbol in the program's $\itm{info}$
  2081. field, so \code{assign-homes} has convenient access to the them. In
  2082. this example, we assign variable \code{a} to stack location
  2083. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.\\
  2084. \begin{tabular}{l}
  2085. \begin{minipage}{0.4\textwidth}
  2086. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2087. locals: a b
  2088. start:
  2089. movq $42, a
  2090. movq a, b
  2091. movq b, %rax
  2092. jmp conclusion
  2093. \end{lstlisting}
  2094. \end{minipage}
  2095. {$\Rightarrow$}
  2096. \begin{minipage}{0.4\textwidth}
  2097. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  2098. stack-space: 16
  2099. start:
  2100. movq $42, -8(%rbp)
  2101. movq -8(%rbp), -16(%rbp)
  2102. movq -16(%rbp), %rax
  2103. jmp conclusion
  2104. \end{lstlisting}
  2105. \end{minipage}
  2106. \end{tabular} \\
  2107. In the process of assigning variables to stack locations, it is
  2108. convenient to compute and store the size of the frame (in bytes) in
  2109. the $\itm{info}$ field of the \key{Program} node, with the key
  2110. \code{stack-space}, which will be needed later to generate the
  2111. procedure conclusion. The x86-64 standard requires the frame size to
  2112. be a multiple of 16 bytes.
  2113. \index{frame}
  2114. \begin{exercise}
  2115. \normalfont Implement the \key{assign-homes} pass and test it on all
  2116. of the example programs that you created for the previous passes pass.
  2117. We recommend that \key{assign-homes} take an extra parameter that is a
  2118. mapping of variable names to homes (stack locations for now). Use the
  2119. \key{interp-tests} function (Appendix~\ref{appendix:utilities}) from
  2120. \key{utilities.rkt} to test your passes on the example programs.
  2121. \end{exercise}
  2122. \section{Patch Instructions}
  2123. \label{sec:patch-s0}
  2124. The \code{patch-instructions} pass compiles $\text{x86}^{*}_0$
  2125. programs to $\text{x86}_0$ programs by making sure that each
  2126. instruction adheres to the restrictions of the x86 assembly language.
  2127. In particular, at most one argument of an instruction may be a memory
  2128. reference.
  2129. We return to the following running example.
  2130. % s0_20.rkt
  2131. \begin{lstlisting}
  2132. (let ([a 42])
  2133. (let ([b a])
  2134. b))
  2135. \end{lstlisting}
  2136. After the \key{assign-homes} pass, the above program has been translated to
  2137. the following. \\
  2138. \begin{minipage}{0.5\textwidth}
  2139. \begin{lstlisting}
  2140. stack-space: 16
  2141. start:
  2142. movq $42, -8(%rbp)
  2143. movq -8(%rbp), -16(%rbp)
  2144. movq -16(%rbp), %rax
  2145. jmp conclusion
  2146. \end{lstlisting}
  2147. \end{minipage}\\
  2148. The second \key{movq} instruction is problematic because both
  2149. arguments are stack locations. We suggest fixing this problem by
  2150. moving from the source location to the register \key{rax} and then
  2151. from \key{rax} to the destination location, as follows.
  2152. \begin{lstlisting}
  2153. movq -8(%rbp), %rax
  2154. movq %rax, -16(%rbp)
  2155. \end{lstlisting}
  2156. \begin{exercise}
  2157. \normalfont
  2158. Implement the \key{patch-instructions} pass and test it on all of the
  2159. example programs that you created for the previous passes and create
  2160. three new example programs that are designed to exercise all of the
  2161. interesting code in this pass. Use the \key{interp-tests} function
  2162. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2163. your passes on the example programs.
  2164. \end{exercise}
  2165. \section{Print x86}
  2166. \label{sec:print-x86}
  2167. The last step of the compiler from $R_1$ to x86 is to convert the
  2168. $\text{x86}_0$ AST (defined in Figure~\ref{fig:x86-0-ast}) to the
  2169. string representation (defined in Figure~\ref{fig:x86-0-concrete}). The Racket
  2170. \key{format} and \key{string-append} functions are useful in this
  2171. regard. The main work that this step needs to perform is to create the
  2172. \key{main} function and the standard instructions for its prelude and
  2173. conclusion, as shown in Figure~\ref{fig:p1-x86} of
  2174. Section~\ref{sec:x86}. You need to know the number of stack-allocated
  2175. variables, so we suggest computing it in the \key{assign-homes} pass
  2176. (Section~\ref{sec:assign-r1}) and storing it in the $\itm{info}$ field
  2177. of the \key{program} node.
  2178. %% Your compiled code should print the result of the program's execution
  2179. %% by using the \code{print\_int} function provided in
  2180. %% \code{runtime.c}. If your compiler has been implemented correctly so
  2181. %% far, this final result should be stored in the \key{rax} register.
  2182. %% We'll talk more about how to perform function calls with arguments in
  2183. %% general later on, but for now, place the following after the compiled
  2184. %% code for the $R_1$ program but before the conclusion:
  2185. %% \begin{lstlisting}
  2186. %% movq %rax, %rdi
  2187. %% callq print_int
  2188. %% \end{lstlisting}
  2189. %% These lines move the value in \key{rax} into the \key{rdi} register, which
  2190. %% stores the first argument to be passed into \key{print\_int}.
  2191. If you want your program to run on Mac OS X, your code needs to
  2192. determine whether or not it is running on a Mac, and prefix
  2193. underscores to labels like \key{main}. You can determine the platform
  2194. with the Racket call \code{(system-type 'os)}, which returns
  2195. \code{'macosx}, \code{'unix}, or \code{'windows}.
  2196. %% In addition to
  2197. %% placing underscores on \key{main}, you need to put them in front of
  2198. %% \key{callq} labels (so \code{callq print\_int} becomes \code{callq
  2199. %% \_print\_int}).
  2200. \begin{exercise}
  2201. \normalfont Implement the \key{print-x86} pass and test it on all of
  2202. the example programs that you created for the previous passes. Use the
  2203. \key{compiler-tests} function (Appendix~\ref{appendix:utilities}) from
  2204. \key{utilities.rkt} to test your complete compiler on the example
  2205. programs. See the \key{run-tests.rkt} script in the student support
  2206. code for an example of how to use \key{compiler-tests}. Also, remember
  2207. to compile the provided \key{runtime.c} file to \key{runtime.o} using
  2208. \key{gcc}.
  2209. \end{exercise}
  2210. \section{Challenge: Partial Evaluator for $R_1$}
  2211. \label{sec:pe-R1}
  2212. \index{partial evaluation}
  2213. This section describes optional challenge exercises that involve
  2214. adapting and improving the partial evaluator for $R_0$ that was
  2215. introduced in Section~\ref{sec:partial-evaluation}.
  2216. \begin{exercise}\label{ex:pe-R1}
  2217. \normalfont
  2218. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  2219. (Figure~\ref{fig:pe-arith}) so that it applies to $R_1$ programs
  2220. instead of $R_0$ programs. Recall that $R_1$ adds \key{let} binding
  2221. and variables to the $R_0$ language, so you will need to add cases for
  2222. them in the \code{pe-exp} function. Also, note that the \key{program}
  2223. form changes slightly to include an $\itm{info}$ field. Once
  2224. complete, add the partial evaluation pass to the front of your
  2225. compiler and make sure that your compiler still passes all of the
  2226. tests.
  2227. \end{exercise}
  2228. The next exercise builds on Exercise~\ref{ex:pe-R1}.
  2229. \begin{exercise}
  2230. \normalfont
  2231. Improve on the partial evaluator by replacing the \code{pe-neg} and
  2232. \code{pe-add} auxiliary functions with functions that know more about
  2233. arithmetic. For example, your partial evaluator should translate
  2234. \begin{lstlisting}
  2235. (+ 1 (+ (read) 1))
  2236. \end{lstlisting}
  2237. into
  2238. \begin{lstlisting}
  2239. (+ 2 (read))
  2240. \end{lstlisting}
  2241. To accomplish this, the \code{pe-exp} function should produce output
  2242. in the form of the $\itm{residual}$ non-terminal of the following
  2243. grammar.
  2244. \[
  2245. \begin{array}{lcl}
  2246. \itm{inert} &::=& \Var \mid (\key{read}) \mid (\key{-} \;(\key{read}))
  2247. \mid (\key{+} \; \itm{inert} \; \itm{inert})\\
  2248. \itm{residual} &::=& \Int \mid (\key{+}\; \Int\; \itm{inert}) \mid \itm{inert}
  2249. \end{array}
  2250. \]
  2251. The \code{pe-add} and \code{pe-neg} functions may therefore assume
  2252. that their inputs are $\itm{residual}$ expressions and they should
  2253. return $\itm{residual}$ expressions. Once the improvements are
  2254. complete, make sure that your compiler still passes all of the tests.
  2255. After all, fast code is useless if it produces incorrect results!
  2256. \end{exercise}
  2257. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2258. \chapter{Register Allocation}
  2259. \label{ch:register-allocation-r1}
  2260. \index{register allocation}
  2261. In Chapter~\ref{ch:int-exp} we placed all variables on the stack to
  2262. make our life easier. However, we can improve the performance of the
  2263. generated code if we instead place some variables into registers. The
  2264. CPU can access a register in a single cycle, whereas accessing the
  2265. stack takes many cycles if the relevant data is in cache or many more
  2266. to access main memory if the data is not in cache.
  2267. Figure~\ref{fig:reg-eg} shows a program with four variables that
  2268. serves as a running example. We show the source program and also the
  2269. output of instruction selection. At that point the program is almost
  2270. x86 assembly but not quite; it still contains variables instead of
  2271. stack locations or registers.
  2272. \begin{figure}
  2273. \begin{minipage}{0.45\textwidth}
  2274. Example $R_1$ program:
  2275. % s0_28.rkt
  2276. \begin{lstlisting}
  2277. (let ([v 1])
  2278. (let ([w 42])
  2279. (let ([x (+ v 7)])
  2280. (let ([y x])
  2281. (let ([z (+ x w)])
  2282. (+ z (- y)))))))
  2283. \end{lstlisting}
  2284. \end{minipage}
  2285. \begin{minipage}{0.45\textwidth}
  2286. After instruction selection:
  2287. \begin{lstlisting}
  2288. locals: (v w x y z t)
  2289. start:
  2290. movq $1, v
  2291. movq $42, w
  2292. movq v, x
  2293. addq $7, x
  2294. movq x, y
  2295. movq x, z
  2296. addq w, z
  2297. movq y, t
  2298. negq t
  2299. movq z, %rax
  2300. addq t, %rax
  2301. jmp conclusion
  2302. \end{lstlisting}
  2303. \end{minipage}
  2304. \caption{A running example program for register allocation.}
  2305. \label{fig:reg-eg}
  2306. \end{figure}
  2307. The goal of register allocation is to fit as many variables into
  2308. registers as possible. A program sometimes has more variables than
  2309. registers, so we cannot map each variable to a different
  2310. register. Fortunately, it is common for different variables to be
  2311. needed during different periods of time during program execution, and
  2312. in such cases several variables can be mapped to the same register.
  2313. Consider variables \code{x} and \code{y} in Figure~\ref{fig:reg-eg}.
  2314. After the variable \code{x} is moved to \code{z} it is no longer
  2315. needed. Variable \code{y}, on the other hand, is used only after this
  2316. point, so \code{x} and \code{y} could share the same register. The
  2317. topic of Section~\ref{sec:liveness-analysis-r1} is how to compute
  2318. where a variable is needed. Once we have that information, we compute
  2319. which variables are needed at the same time, i.e., which ones
  2320. \emph{interfere} with each other, and represent this relation as an
  2321. undirected graph whose vertices are variables and edges indicate when
  2322. two variables interfere (Section~\ref{sec:build-interference}). We
  2323. then model register allocation as a graph coloring problem, which we
  2324. discuss in Section~\ref{sec:graph-coloring}.
  2325. In the event that we run out of registers despite these efforts, we
  2326. place the remaining variables on the stack, similar to what we did in
  2327. Chapter~\ref{ch:int-exp}. It is common to use the verb \emph{spill}
  2328. for assigning a variable to a stack location. The process of spilling
  2329. variables is handled as part of the graph coloring process described
  2330. in \ref{sec:graph-coloring}.
  2331. We make the simplifying assumption that each variable is assigned to
  2332. one location (a register or stack address). A more sophisticated
  2333. approach is to assign a variable to one or more locations in different
  2334. regions of the program. For example, if a variable is used many times
  2335. in short sequence and then only used again after many other
  2336. instructions, it could be more efficient to assign the variable to a
  2337. register during the intial sequence and then move it to the stack for
  2338. the rest of its lifetime. We refer the interested reader to
  2339. \citet{Cooper:1998ly} and \citet{Cooper:2011aa} for more information
  2340. about this approach.
  2341. % discuss prioritizing variables based on how much they are used.
  2342. \section{Registers and Calling Conventions}
  2343. \label{sec:calling-conventions}
  2344. \index{calling conventions}
  2345. As we perform register allocation, we need to be aware of the
  2346. \emph{calling conventions} \index{calling conventions} that govern how
  2347. functions calls are performed in x86. Function calls require
  2348. coordination between the caller and the callee, which is often
  2349. assembly code written by different programmers or generated by
  2350. different compilers. Here we follow the System V calling conventions
  2351. that are used by the \code{gcc} compiler on Linux and
  2352. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  2353. %
  2354. Even though $R_1$ does not include programmer-defined functions, our
  2355. generated code will 1) include a \code{main} function that the
  2356. operating system will call to initiate execution, and 2) make calls to
  2357. the \code{read\_int} function in our runtime system.
  2358. The calling conventions include rules about how functions share the
  2359. use of registers. In particular, the caller is responsible for freeing
  2360. up some registers prior to the function call for use by the callee.
  2361. These are called the \emph{caller-saved registers}
  2362. \index{caller-saved registers}
  2363. and they are
  2364. \begin{lstlisting}
  2365. rax rcx rdx rsi rdi r8 r9 r10 r11
  2366. \end{lstlisting}
  2367. On the other hand, the callee is responsible for preserving the values
  2368. of the \emph{callee-saved registers}, \index{callee-saved registers}
  2369. which are
  2370. \begin{lstlisting}
  2371. rsp rbp rbx r12 r13 r14 r15
  2372. \end{lstlisting}
  2373. We can think about this caller/callee convention from two points of
  2374. view, the caller view and the callee view:
  2375. \begin{itemize}
  2376. \item The caller should assume that all the caller-saved registers get
  2377. overwritten with arbitrary values by the callee. On the other hand,
  2378. the caller can safely assume that all the callee-saved registers
  2379. contain the same values after the call that they did before the
  2380. call.
  2381. \item The callee can freely use any of the caller-saved registers.
  2382. However, if the callee wants to use a callee-saved register, the
  2383. callee must arrange to put the original value back in the register
  2384. prior to returning to the caller, which is usually accomplished by
  2385. saving the value to the stack in the prelude of the function and
  2386. restoring the value in the conclusion of the function.
  2387. \end{itemize}
  2388. In x86, registers are also used for passing arguments to a function
  2389. and for the return value. In particular, the first six arguments of a
  2390. function are passed in the following six registers, in the order
  2391. given.
  2392. \begin{lstlisting}
  2393. rdi rsi rdx rcx r8 r9
  2394. \end{lstlisting}
  2395. If there are more than six arguments, then the convention is to use
  2396. space on the frame of the caller for the rest of the
  2397. arguments. However, in Chapter~\ref{ch:functions} we arrange to never
  2398. need more than six arguments. For now, the only function we care about
  2399. is \code{read\_int} and it takes zero argument.
  2400. %
  2401. The register \code{rax} is for the return value of a function.
  2402. The next question is how these calling conventions impact register
  2403. allocation. Consider the $R_1$ program in
  2404. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  2405. example from the caller point of view and then from the callee point
  2406. of view.
  2407. The program makes two calls to the \code{read} function. Also, the
  2408. variable \code{x} is in-use during the second call to \code{read}, so
  2409. we need to make sure that the value in \code{x} does not get
  2410. accidentally wiped out by the call to \code{read}. One obvious
  2411. approach is to save all the values in caller-saved registers to the
  2412. stack prior to each function call, and restore them after each
  2413. call. That way, if the register allocator chooses to assign \code{x}
  2414. to a caller-saved register, its value will be preserved accross the
  2415. call to \code{read}. However, the disadvantage of this approach is
  2416. that saving and restoring to the stack is relatively slow. If \code{x}
  2417. is not used many times, it may be better to assign \code{x} to a stack
  2418. location in the first place. Or better yet, if we can arrange for
  2419. \code{x} to be placed in a callee-saved register, then it won't need
  2420. to be saved and restored during function calls.
  2421. The approach that we recommend for variables that are in-use during a
  2422. function call is to either assign them to callee-saved registers or to
  2423. spill them to the stack. On the other hand, for variables that are not
  2424. in-use during a function call, we try the following alternatives in
  2425. order 1) look for an available caller-saved register (to leave room
  2426. for other variables in the callee-saved register), 2) look for a
  2427. callee-saved register, and 3) spill the variable to the stack.
  2428. It is straightforward to implement this approach in a graph coloring
  2429. register allocator. First, we know which variables are in-use during
  2430. every function call because we compute that information for every
  2431. instruction (Section~\ref{sec:liveness-analysis-r1}). Second, when we
  2432. build the interference graph (Section~\ref{sec:build-interference}),
  2433. we can place an edge between each of these variables and the
  2434. caller-saved registers in the interference graph. This will prevent
  2435. the graph coloring algorithm from assigning those variables to
  2436. caller-saved registers.
  2437. Returning to the example in
  2438. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  2439. generated x86 code on the right-hand side, focusing on the
  2440. \code{start} block. Notice that variable \code{x} is assigned to
  2441. \code{rbx}, a callee-saved register. Thus, it is already in a safe
  2442. place during the second call to \code{read\_int}. Next, notice that
  2443. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  2444. because there are no function calls in the remainder of the block.
  2445. Next we analyze the example from the callee point of view, focusing on
  2446. the prelude and conclusion of the \code{main} function. As usual the
  2447. prelude begins with saving the \code{rbp} register to the stack and
  2448. setting the \code{rbp} to the current stack pointer. We now know why
  2449. it is necessary to save the \code{rbp}: it is a callee-saved register.
  2450. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  2451. is also a callee-saved register and 2) \code{rbx} is assigned to a
  2452. variable (\code{x}). There are several more callee-saved register that
  2453. are not saved in the prelude because they were not assigned to
  2454. variables. The prelude subtracts 8 bytes from the \code{rsp} to make
  2455. it 16-byte aligned and then jumps to the \code{start} block. Shifting
  2456. attention to the \code{conclusion}, we see that \code{rbx} is restored
  2457. from the stack with a \code{popq} instruction.
  2458. \index{prelude}\index{conclusion}
  2459. \begin{figure}[tp]
  2460. \begin{minipage}{0.45\textwidth}
  2461. Example $R_1$ program:
  2462. %s0_14.rkt
  2463. \begin{lstlisting}
  2464. (let ([x (read)])
  2465. (let ([y (read)])
  2466. (+ (+ x y) 42)))
  2467. \end{lstlisting}
  2468. \end{minipage}
  2469. \begin{minipage}{0.45\textwidth}
  2470. Generated x86 assembly:
  2471. \begin{lstlisting}
  2472. start:
  2473. callq read_int
  2474. movq %rax, %rbx
  2475. callq read_int
  2476. movq %rax, %rcx
  2477. addq %rcx, %rbx
  2478. movq %rbx, %rax
  2479. addq $42, %rax
  2480. jmp _conclusion
  2481. .globl main
  2482. main:
  2483. pushq %rbp
  2484. movq %rsp, %rbp
  2485. pushq %rbx
  2486. subq $8, %rsp
  2487. jmp start
  2488. conclusion:
  2489. addq $8, %rsp
  2490. popq %rbx
  2491. popq %rbp
  2492. retq
  2493. \end{lstlisting}
  2494. \end{minipage}
  2495. \caption{An example with function calls.}
  2496. \label{fig:example-calling-conventions}
  2497. \end{figure}
  2498. \clearpage
  2499. \section{Liveness Analysis}
  2500. \label{sec:liveness-analysis-r1}
  2501. \index{liveness analysis}
  2502. A variable or register is \emph{live} at a program point if its
  2503. current value is used at some later point in the program. We
  2504. refer to variables and registers collectively as \emph{locations}.
  2505. %
  2506. Consider the following code fragment in which there are two writes to
  2507. \code{b}. Are \code{a} and \code{b} both live at the same time?
  2508. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2509. movq $5, a
  2510. movq $30, b
  2511. movq a, c
  2512. movq $10, b
  2513. addq b, c
  2514. \end{lstlisting}
  2515. The answer is no because the integer \code{30} written to \code{b} on
  2516. line 2 is never used. The variable \code{b} is read on line 5 and
  2517. there is an intervening write to \code{b} on line 4, so the read on
  2518. line 5 receives the value written on line 4, not line 2.
  2519. \begin{wrapfigure}[18]{l}[1.0in]{0.6\textwidth}
  2520. \small
  2521. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  2522. A \emph{set} is an unordered collection of elements without duplicates.
  2523. \index{set}
  2524. \begin{description}
  2525. \item[$\LP\code{set}\,v\,\ldots\RP$] constructs a set containing the specified elements.
  2526. \item[$\LP\code{set-union}\,set_1\,set_2\RP$] returns the union of the two sets.
  2527. \item[$\LP\code{set-subtract}\,set_1\,set_2\RP$] returns the difference of the two sets.
  2528. \item[$\LP\code{set-member?}\,set\,v\RP$] is element $v$ in $set$?
  2529. \item[$\LP\code{set-count}\,set\RP$] how many unique elements are in $set$?
  2530. \item[$\LP\code{set->list}\,set\RP$] converts the set to a list.
  2531. \end{description}
  2532. \end{tcolorbox}
  2533. \end{wrapfigure}
  2534. The live locations can be computed by traversing the instruction
  2535. sequence back to front (i.e., backwards in execution order). Let
  2536. $I_1,\ldots, I_n$ be the instruction sequence. We write
  2537. $L_{\mathsf{after}}(k)$ for the set of live locations after
  2538. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  2539. locations before instruction $I_k$. The live locations after an
  2540. instruction are always the same as the live locations before the next
  2541. instruction. \index{live-after} \index{live-before}
  2542. \begin{equation} \label{eq:live-after-before-next}
  2543. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  2544. \end{equation}
  2545. To start things off, there are no live locations after the last
  2546. instruction\footnote{Technically, the \code{rax} register is live
  2547. but we do not use it for register allocation.}, so
  2548. \begin{equation}\label{eq:live-last-empty}
  2549. L_{\mathsf{after}}(n) = \emptyset
  2550. \end{equation}
  2551. We then apply the following rule repeatedly, traversing the
  2552. instruction sequence back to front.
  2553. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  2554. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  2555. \end{equation}
  2556. where $W(k)$ are the locations written to by instruction $I_k$ and
  2557. $R(k)$ are the locations read by instruction $I_k$.
  2558. Let us walk through the above example, applying these formulas
  2559. starting with the instruction on line 5. We collect the answers in the
  2560. below listing. The $L_{\mathsf{after}}$ for the \code{addq b, c}
  2561. instruction is $\emptyset$ because it is the last instruction
  2562. (formula~\ref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  2563. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  2564. variables \code{b} and \code{c}
  2565. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  2566. \[
  2567. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  2568. \]
  2569. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  2570. the live-before set from line 5 to be the live-after set for this
  2571. instruction (formula~\ref{eq:live-after-before-next}).
  2572. \[
  2573. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  2574. \]
  2575. This move instruction writes to \code{b} and does not read from any
  2576. variables, so we have the following live-before set
  2577. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  2578. \[
  2579. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  2580. \]
  2581. The live-before for instruction \code{movq a, c}
  2582. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  2583. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  2584. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  2585. variable that is not live and does not read from a variable.
  2586. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  2587. because it writes to variable \code{a}.
  2588. \begin{center}
  2589. \begin{minipage}{0.45\textwidth}
  2590. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  2591. movq $5, a
  2592. movq $30, b
  2593. movq a, c
  2594. movq $10, b
  2595. addq b, c
  2596. \end{lstlisting}
  2597. \end{minipage}
  2598. \vrule\hspace{10pt}
  2599. \begin{minipage}{0.45\textwidth}
  2600. \begin{align*}
  2601. L_{\mathsf{before}}(1)= \emptyset,
  2602. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  2603. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  2604. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  2605. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  2606. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  2607. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  2608. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  2609. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  2610. L_{\mathsf{after}}(5)= \emptyset
  2611. \end{align*}
  2612. \end{minipage}
  2613. \end{center}
  2614. Figure~\ref{fig:live-eg} shows the results of liveness analysis for
  2615. the running example program, with the live-before and live-after sets
  2616. shown between each instruction to make the figure easy to read.
  2617. \begin{figure}[tp]
  2618. \hspace{20pt}
  2619. \begin{minipage}{0.45\textwidth}
  2620. \begin{lstlisting}
  2621. |$\{\}$|
  2622. movq $1, v
  2623. |$\{\ttm{v}\}$|
  2624. movq $42, w
  2625. |$\{\ttm{v},\ttm{w}\}$|
  2626. movq v, x
  2627. |$\{\ttm{w},\ttm{x}\}$|
  2628. addq $7, x
  2629. |$\{\ttm{w},\ttm{x}\}$|
  2630. movq x, y
  2631. |$\{\ttm{w},\ttm{x},\ttm{y}\}$|
  2632. movq x, z
  2633. |$\{\ttm{w},\ttm{y},\ttm{z}\}$|
  2634. addq w, z
  2635. |$\{\ttm{y},\ttm{z}\}$|
  2636. movq y, t
  2637. |$\{\ttm{t},\ttm{z}\}$|
  2638. negq t
  2639. |$\{\ttm{t},\ttm{z}\}$|
  2640. movq z, %rax
  2641. |$\{\ttm{rax},\ttm{t}\}$|
  2642. addq t, %rax
  2643. |$\{\}$|
  2644. jmp conclusion
  2645. |$\{\}$|
  2646. \end{lstlisting}
  2647. \end{minipage}
  2648. \caption{The running example annotated with live-after sets.}
  2649. \label{fig:live-eg}
  2650. \end{figure}
  2651. \begin{exercise}\normalfont
  2652. Implement the compiler pass named \code{uncover-live} that computes
  2653. the live-after sets. We recommend storing the live-after sets (a list
  2654. of a set of variables) in the $\itm{info}$ field of the \code{Block}
  2655. structure.
  2656. %
  2657. We recommend organizing your code to use a helper function that takes
  2658. a list of instructions and an initial live-after set (typically empty)
  2659. and returns the list of live-after sets.
  2660. %
  2661. We recommend creating helper functions to 1) compute the set of
  2662. locations that appear in an argument (of an instruction), 2) compute
  2663. the locations read by an instruction which corresponds to the $R$
  2664. function discussed above, and 3) the locations written by an
  2665. instruction which corresponds to $W$. The \code{callq} instruction
  2666. should include all of the caller-saved registers in its write-set $W$
  2667. because the calling convention says that those registers may be
  2668. written to during the function call. Likewise, the \code{callq}
  2669. instruction should include the appropriate number of argument passing
  2670. registers in its read-set $R$, depending on the arity of the function
  2671. being called. (This is why the abstract syntax for \code{callq}
  2672. includes the arity.)
  2673. \end{exercise}
  2674. \section{Building the Interference Graph}
  2675. \label{sec:build-interference}
  2676. \begin{wrapfigure}[27]{r}[1.0in]{0.6\textwidth}
  2677. \small
  2678. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  2679. A \emph{graph} is a collection of vertices and edges where each
  2680. edge connects two vertices. A graph is \emph{directed} if each
  2681. edge points from a source to a target. Otherwise the graph is
  2682. \emph{undirected}.
  2683. \index{graph}\index{directed graph}\index{undirected graph}
  2684. \begin{description}
  2685. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  2686. directed graph from a list of edges. Each edge is a list
  2687. containing the source and target vertex.
  2688. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  2689. undirected graph from a list of edges. Each edge is represented by
  2690. a list containing two vertices.
  2691. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  2692. inserts a vertex into the graph.
  2693. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  2694. inserts an edge between the two vertices into the graph.
  2695. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  2696. returns a sequence of all the neighbors of the given vertex.
  2697. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  2698. returns a sequence of all the vertices in the graph.
  2699. \end{description}
  2700. \end{tcolorbox}
  2701. \end{wrapfigure}
  2702. Based on the liveness analysis, we know where each variable is needed.
  2703. However, during register allocation, we need to answer questions of
  2704. the specific form: are variables $u$ and $v$ live at the same time?
  2705. (And therefore cannot be assigned to the same register.) To make this
  2706. question easier to answer, we create an explicit data structure, an
  2707. \emph{interference graph}\index{interference graph}. An interference
  2708. graph is an undirected graph that has an edge between two variables if
  2709. they are live at the same time, that is, if they interfere with each
  2710. other.
  2711. The most obvious way to compute the interference graph is to look at
  2712. the set of live location between each statement in the program and add
  2713. an edge to the graph for every pair of variables in the same set.
  2714. This approach is less than ideal for two reasons. First, it can be
  2715. expensive because it takes $O(n^2)$ time to look at every pair in a
  2716. set of $n$ live locations. Second, there is a special case in which
  2717. two locations that are live at the same time do not actually interfere
  2718. with each other: when they both contain the same value because we have
  2719. assigned one to the other.
  2720. A better way to compute the interference graph is to focus on the
  2721. writes~\cite{Appel:2003fk}. We do not want the writes performed by an
  2722. instruction to overwrite something in a live location. So for each
  2723. instruction, we create an edge between the locations being written to
  2724. and all the other live locations. (Except that one should not create
  2725. self edges.) Recall that for a \key{callq} instruction, we consider
  2726. all of the caller-saved registers as being written to, so an edge will
  2727. be added between every live variable and every caller-saved
  2728. register. For \key{movq}, we deal with the above-mentioned special
  2729. case by not adding an edge between a live variable $v$ and destination
  2730. $d$ if $v$ matches the source of the move. So we have the following
  2731. two rules.
  2732. \begin{enumerate}
  2733. \item If instruction $I_k$ is a move such as \key{movq} $s$\key{,}
  2734. $d$, then add the edge $(d,v)$ for every $v \in
  2735. L_{\mathsf{after}}(k)$ unless $v = d$ or $v = s$.
  2736. \item For any other instruction $I_k$, for every $d \in W(k)$
  2737. add an edge $(d,v)$ for every $v \in L_{\mathsf{after}}(k)$ unless $v = d$.
  2738. %% \item If instruction $I_k$ is an arithmetic instruction such as
  2739. %% \code{addq} $s$\key{,} $d$, then add the edge $(d,v)$ for every $v \in
  2740. %% L_{\mathsf{after}}(k)$ unless $v = d$.
  2741. %% \item If instruction $I_k$ is of the form \key{callq}
  2742. %% $\mathit{label}$, then add an edge $(r,v)$ for every caller-saved
  2743. %% register $r$ and every variable $v \in L_{\mathsf{after}}(k)$.
  2744. \end{enumerate}
  2745. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  2746. the above rules to each instruction. We highlight a few of the
  2747. instructions and then refer the reader to
  2748. Figure~\ref{fig:interference-results} for all the interference
  2749. results. The first instruction is \lstinline{movq $1, v}, so rule 3
  2750. applies, and the live-after set is $\{\ttm{v}\}$. We do not add any
  2751. interference edges because the one live variable \code{v} is also the
  2752. destination of this instruction.
  2753. %
  2754. For the second instruction, \lstinline{movq $42, w}, so rule 3 applies
  2755. again, and the live-after set is $\{\ttm{v},\ttm{w}\}$. So the target
  2756. $\ttm{w}$ of \key{movq} interferes with $\ttm{v}$.
  2757. %
  2758. Next we skip forward to the instruction \lstinline{movq x, y}.
  2759. \begin{figure}[tbp]
  2760. \begin{quote}
  2761. \begin{tabular}{ll}
  2762. \lstinline!movq $1, v!& no interference by rule 3,\\
  2763. \lstinline!movq $42, w!& $w$ interferes with $v$ by rule 3,\\
  2764. \lstinline!movq v, x!& $x$ interferes with $w$ by rule 3,\\
  2765. \lstinline!addq $7, x!& $x$ interferes with $w$ by rule 1,\\
  2766. \lstinline!movq x, y!& $y$ interferes with $w$ but not $x$ by rule 3,\\
  2767. \lstinline!movq x, z!& $z$ interferes with $w$ and $y$ by rule 3,\\
  2768. \lstinline!addq w, z!& $z$ interferes with $y$ by rule 1, \\
  2769. \lstinline!movq y, t!& $t$ interferes with $z$ by rule 3, \\
  2770. \lstinline!negq t!& $t$ interferes with $z$ by rule 1, \\
  2771. \lstinline!movq z, %rax! & no interference (ignore rax), \\
  2772. \lstinline!addq t, %rax! & no interference (ignore rax). \\
  2773. \lstinline!jmp conclusion!& no interference.
  2774. \end{tabular}
  2775. \end{quote}
  2776. \caption{Interference results for the running example.}
  2777. \label{fig:interference-results}
  2778. \end{figure}
  2779. The resulting interference graph is shown in
  2780. Figure~\ref{fig:interfere}.
  2781. \begin{figure}[tbp]
  2782. \large
  2783. \[
  2784. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2785. \node (rax) at (0,0) {$\ttm{rax}$};
  2786. \node (t1) at (0,2) {$\ttm{t}$};
  2787. \node (z) at (3,2) {$\ttm{z}$};
  2788. \node (x) at (6,2) {$\ttm{x}$};
  2789. \node (y) at (3,0) {$\ttm{y}$};
  2790. \node (w) at (6,0) {$\ttm{w}$};
  2791. \node (v) at (9,0) {$\ttm{v}$};
  2792. \draw (t1) to (rax);
  2793. \draw (t1) to (z);
  2794. \draw (z) to (y);
  2795. \draw (z) to (w);
  2796. \draw (x) to (w);
  2797. \draw (y) to (w);
  2798. \draw (v) to (w);
  2799. \end{tikzpicture}
  2800. \]
  2801. \caption{The interference graph of the example program.}
  2802. \label{fig:interfere}
  2803. \end{figure}
  2804. %% Our next concern is to choose a data structure for representing the
  2805. %% interference graph. There are many choices for how to represent a
  2806. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  2807. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  2808. %% data structure is to study the algorithm that uses the data structure,
  2809. %% determine what operations need to be performed, and then choose the
  2810. %% data structure that provide the most efficient implementations of
  2811. %% those operations. Often times the choice of data structure can have an
  2812. %% effect on the time complexity of the algorithm, as it does here. If
  2813. %% you skim the next section, you will see that the register allocation
  2814. %% algorithm needs to ask the graph for all of its vertices and, given a
  2815. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  2816. %% correct choice of graph representation is that of an adjacency
  2817. %% list. There are helper functions in \code{utilities.rkt} for
  2818. %% representing graphs using the adjacency list representation:
  2819. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  2820. %% (Appendix~\ref{appendix:utilities}).
  2821. %% %
  2822. %% \margincomment{\footnotesize To do: change to use the
  2823. %% Racket graph library. \\ --Jeremy}
  2824. %% %
  2825. %% In particular, those functions use a hash table to map each vertex to
  2826. %% the set of adjacent vertices, and the sets are represented using
  2827. %% Racket's \key{set}, which is also a hash table.
  2828. \begin{exercise}\normalfont
  2829. Implement the compiler pass named \code{build-interference} according
  2830. to the algorithm suggested above. We recommend using the \code{graph}
  2831. package to create and inspect the interference graph. The output
  2832. graph of this pass should be stored in the $\itm{info}$ field of the
  2833. program, under the key \code{conflicts}.
  2834. \end{exercise}
  2835. \section{Graph Coloring via Sudoku}
  2836. \label{sec:graph-coloring}
  2837. \index{graph coloring}
  2838. \index{Sudoku}
  2839. \index{color}
  2840. We come to the main event, mapping variables to registers (or to stack
  2841. locations in the event that we run out of registers). We need to make
  2842. sure that two variables do not get mapped to the same register if the
  2843. two variables interfere with each other. Thinking about the
  2844. interference graph, this means that adjacent vertices must be mapped
  2845. to different registers. If we think of registers as colors, the
  2846. register allocation problem becomes the widely-studied graph coloring
  2847. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  2848. The reader may be more familiar with the graph coloring problem than he
  2849. or she realizes; the popular game of Sudoku is an instance of the
  2850. graph coloring problem. The following describes how to build a graph
  2851. out of an initial Sudoku board.
  2852. \begin{itemize}
  2853. \item There is one vertex in the graph for each Sudoku square.
  2854. \item There is an edge between two vertices if the corresponding squares
  2855. are in the same row, in the same column, or if the squares are in
  2856. the same $3\times 3$ region.
  2857. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  2858. \item Based on the initial assignment of numbers to squares in the
  2859. Sudoku board, assign the corresponding colors to the corresponding
  2860. vertices in the graph.
  2861. \end{itemize}
  2862. If you can color the remaining vertices in the graph with the nine
  2863. colors, then you have also solved the corresponding game of Sudoku.
  2864. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  2865. the corresponding graph with colored vertices. We map the Sudoku
  2866. number 1 to blue, 2 to yellow, and 3 to red. We only show edges for a
  2867. sampling of the vertices (the colored ones) because showing edges for
  2868. all of the vertices would make the graph unreadable.
  2869. \begin{figure}[tbp]
  2870. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  2871. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph}
  2872. \caption{A Sudoku game board and the corresponding colored graph.}
  2873. \label{fig:sudoku-graph}
  2874. \end{figure}
  2875. Given that Sudoku is an instance of graph coloring, one can use Sudoku
  2876. strategies to come up with an algorithm for allocating registers. For
  2877. example, one of the basic techniques for Sudoku is called Pencil
  2878. Marks. The idea is to use a process of elimination to determine what
  2879. numbers no longer make sense for a square and write down those
  2880. numbers in the square (writing very small). For example, if the number
  2881. $1$ is assigned to a square, then by process of elimination, you can
  2882. write the pencil mark $1$ in all the squares in the same row, column,
  2883. and region. Many Sudoku computer games provide automatic support for
  2884. Pencil Marks.
  2885. %
  2886. The Pencil Marks technique corresponds to the notion of
  2887. \emph{saturation}\index{saturation} due to \cite{Brelaz:1979eu}.
  2888. The saturation of a
  2889. vertex, in Sudoku terms, is the set of numbers that are no longer
  2890. available. In graph terminology, we have the following definition:
  2891. \begin{equation*}
  2892. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{neighbors}(u)
  2893. \text{ and } \mathrm{color}(v) = c \}
  2894. \end{equation*}
  2895. where $\mathrm{neighbors}(u)$ is the set of vertices that share an
  2896. edge with $u$.
  2897. Using the Pencil Marks technique leads to a simple strategy for
  2898. filling in numbers: if there is a square with only one possible number
  2899. left, then choose that number! But what if there are no squares with
  2900. only one possibility left? One brute-force approach is to try them
  2901. all: choose the first and if it ultimately leads to a solution,
  2902. great. If not, backtrack and choose the next possibility. One good
  2903. thing about Pencil Marks is that it reduces the degree of branching in
  2904. the search tree. Nevertheless, backtracking can be horribly time
  2905. consuming. One way to reduce the amount of backtracking is to use the
  2906. most-constrained-first heuristic. That is, when choosing a square,
  2907. always choose one with the fewest possibilities left (the vertex with
  2908. the highest saturation). The idea is that choosing highly constrained
  2909. squares earlier rather than later is better because later on there may
  2910. not be any possibilities left for those squares.
  2911. However, register allocation is easier than Sudoku because the
  2912. register allocator can map variables to stack locations when the
  2913. registers run out. Thus, it makes sense to drop backtracking in favor
  2914. of greedy search, that is, make the best choice at the time and keep
  2915. going. We still wish to minimize the number of colors needed, so
  2916. keeping the most-constrained-first heuristic is a good idea.
  2917. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  2918. algorithm for register allocation based on saturation and the
  2919. most-constrained-first heuristic. It is roughly equivalent to the
  2920. DSATUR algorithm of \cite{Brelaz:1979eu} (also known as saturation
  2921. degree ordering~\citep{Gebremedhin:1999fk,Omari:2006uq}). Just as in
  2922. Sudoku, the algorithm represents colors with integers. The integers
  2923. $0$ through $k-1$ correspond to the $k$ registers that we use for
  2924. register allocation. The integers $k$ and larger correspond to stack
  2925. locations. The registers that are not used for register allocation,
  2926. such as \code{rax}, are assigned to negative integers. In particular,
  2927. we assign $-1$ to \code{rax}.
  2928. \begin{figure}[btp]
  2929. \centering
  2930. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  2931. Algorithm: DSATUR
  2932. Input: a graph |$G$|
  2933. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  2934. |$W \gets \mathrm{vertices}(G)$|
  2935. while |$W \neq \emptyset$| do
  2936. pick a vertex |$u$| from |$W$| with the highest saturation,
  2937. breaking ties randomly
  2938. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  2939. |$\mathrm{color}[u] \gets c$|
  2940. |$W \gets W - \{u\}$|
  2941. \end{lstlisting}
  2942. \caption{The saturation-based greedy graph coloring algorithm.}
  2943. \label{fig:satur-algo}
  2944. \end{figure}
  2945. With this algorithm in hand, let us return to the running example and
  2946. consider how to color the interference graph in
  2947. Figure~\ref{fig:interfere}.
  2948. %
  2949. We color the vertices for registers with their own color. For example,
  2950. \code{rax} is assigned the color $-1$. We then update the saturation
  2951. for their neighboring vertices. In this case, the saturation for
  2952. \code{t} includes $-1$. The remaining vertices are not yet colored,
  2953. so they annotated with a dash, and their saturation sets are empty.
  2954. \[
  2955. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2956. \node (rax) at (0,0) {$\ttm{rax}:-1,\{\}$};
  2957. \node (t1) at (0,2) {$\ttm{t}:-,\{-1\}$};
  2958. \node (z) at (3,2) {$\ttm{z}:-,\{\}$};
  2959. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  2960. \node (y) at (3,0) {$\ttm{y}:-,\{\}$};
  2961. \node (w) at (6,0) {$\ttm{w}:-,\{\}$};
  2962. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  2963. \draw (t1) to (rax);
  2964. \draw (t1) to (z);
  2965. \draw (z) to (y);
  2966. \draw (z) to (w);
  2967. \draw (x) to (w);
  2968. \draw (y) to (w);
  2969. \draw (v) to (w);
  2970. \end{tikzpicture}
  2971. \]
  2972. The algorithm says to select a maximally saturated vertex. So we pick
  2973. $\ttm{t}$ and color it with the first available integer, which is
  2974. $0$. We mark $0$ as no longer available for $\ttm{z}$ and $\ttm{rax}$
  2975. because they interfere with $\ttm{t}$.
  2976. \[
  2977. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2978. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  2979. \node (t1) at (0,2) {$\ttm{t}:0,\{-1\}$};
  2980. \node (z) at (3,2) {$\ttm{z}:-,\{0\}$};
  2981. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  2982. \node (y) at (3,0) {$\ttm{y}:-,\{\}$};
  2983. \node (w) at (6,0) {$\ttm{w}:-,\{\}$};
  2984. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  2985. \draw (t1) to (rax);
  2986. \draw (t1) to (z);
  2987. \draw (z) to (y);
  2988. \draw (z) to (w);
  2989. \draw (x) to (w);
  2990. \draw (y) to (w);
  2991. \draw (v) to (w);
  2992. \end{tikzpicture}
  2993. \]
  2994. We repeat the process, selecting another maximally saturated
  2995. vertex, which is \code{z}, and color it with the first available
  2996. number, which is $1$. We add $1$ to the saturations for the
  2997. neighboring vertices \code{t}, \code{y}, and \code{w}.
  2998. \[
  2999. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3000. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3001. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1\}$};
  3002. \node (z) at (3,2) {$\ttm{z}:1,\{0\}$};
  3003. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  3004. \node (y) at (3,0) {$\ttm{y}:-,\{1\}$};
  3005. \node (w) at (6,0) {$\ttm{w}:-,\{1\}$};
  3006. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  3007. \draw (t1) to (rax);
  3008. \draw (t1) to (z);
  3009. \draw (z) to (y);
  3010. \draw (z) to (w);
  3011. \draw (x) to (w);
  3012. \draw (y) to (w);
  3013. \draw (v) to (w);
  3014. \end{tikzpicture}
  3015. \]
  3016. The most saturated vertices are now \code{w} and \code{y}. We color
  3017. \code{w} with the first available color, which is $0$.
  3018. \[
  3019. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3020. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3021. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1\}$};
  3022. \node (z) at (3,2) {$\ttm{z}:1,\{0\}$};
  3023. \node (x) at (6,2) {$\ttm{x}:-,\{0\}$};
  3024. \node (y) at (3,0) {$\ttm{y}:-,\{0,1\}$};
  3025. \node (w) at (6,0) {$\ttm{w}:0,\{1\}$};
  3026. \node (v) at (9,0) {$\ttm{v}:-,\{0\}$};
  3027. \draw (t1) to (rax);
  3028. \draw (t1) to (z);
  3029. \draw (z) to (y);
  3030. \draw (z) to (w);
  3031. \draw (x) to (w);
  3032. \draw (y) to (w);
  3033. \draw (v) to (w);
  3034. \end{tikzpicture}
  3035. \]
  3036. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  3037. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  3038. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  3039. and \code{z}, whose colors are $0$ and $1$ respectively.
  3040. \[
  3041. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3042. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3043. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1\}$};
  3044. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3045. \node (x) at (6,2) {$\ttm{x}:-,\{0\}$};
  3046. \node (y) at (3,0) {$\ttm{y}:2,\{0,1\}$};
  3047. \node (w) at (6,0) {$\ttm{w}:0,\{1,2\}$};
  3048. \node (v) at (9,0) {$\ttm{v}:-,\{0\}$};
  3049. \draw (t1) to (rax);
  3050. \draw (t1) to (z);
  3051. \draw (z) to (y);
  3052. \draw (z) to (w);
  3053. \draw (x) to (w);
  3054. \draw (y) to (w);
  3055. \draw (v) to (w);
  3056. \end{tikzpicture}
  3057. \]
  3058. Now \code{x} and \code{v} are the most saturated, so we color \code{v} it $1$.
  3059. \[
  3060. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3061. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3062. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1\}$};
  3063. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3064. \node (x) at (6,2) {$\ttm{x}:-,\{0\}$};
  3065. \node (y) at (3,0) {$\ttm{y}:2,\{0,1\}$};
  3066. \node (w) at (6,0) {$\ttm{w}:0,\{1,2\}$};
  3067. \node (v) at (9,0) {$\ttm{v}:1,\{0\}$};
  3068. \draw (t1) to (rax);
  3069. \draw (t1) to (z);
  3070. \draw (z) to (y);
  3071. \draw (z) to (w);
  3072. \draw (x) to (w);
  3073. \draw (y) to (w);
  3074. \draw (v) to (w);
  3075. \end{tikzpicture}
  3076. \]
  3077. In the last step of the algorithm, we color \code{x} with $1$.
  3078. \[
  3079. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3080. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3081. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,\}$};
  3082. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3083. \node (x) at (6,2) {$\ttm{x}:1,\{0\}$};
  3084. \node (y) at (3,0) {$\ttm{y}:2,\{0,1\}$};
  3085. \node (w) at (6,0) {$\ttm{w}:0,\{1,2\}$};
  3086. \node (v) at (9,0) {$\ttm{v}:1,\{0\}$};
  3087. \draw (t1) to (rax);
  3088. \draw (t1) to (z);
  3089. \draw (z) to (y);
  3090. \draw (z) to (w);
  3091. \draw (x) to (w);
  3092. \draw (y) to (w);
  3093. \draw (v) to (w);
  3094. \end{tikzpicture}
  3095. \]
  3096. With the coloring complete, we finalize the assignment of variables to
  3097. registers and stack locations. Recall that if we have $k$ registers to
  3098. use for allocation, we map the first $k$ colors to registers and the
  3099. rest to stack locations. Suppose for the moment that we have just one
  3100. register to use for register allocation, \key{rcx}. Then the following
  3101. is the mapping of colors to registers and stack allocations.
  3102. \[
  3103. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  3104. \]
  3105. Putting this mapping together with the above coloring of the
  3106. variables, we arrive at the following assignment of variables to
  3107. registers and stack locations.
  3108. \begin{gather*}
  3109. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  3110. \ttm{w} \mapsto \key{\%rcx}, \,
  3111. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  3112. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  3113. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  3114. \ttm{t} \mapsto \key{\%rcx} \}
  3115. \end{gather*}
  3116. Applying this assignment to our running example, on the left, yields
  3117. the program on the right.
  3118. % why frame size of 32? -JGS
  3119. \begin{center}
  3120. \begin{minipage}{0.3\textwidth}
  3121. \begin{lstlisting}
  3122. movq $1, v
  3123. movq $42, w
  3124. movq v, x
  3125. addq $7, x
  3126. movq x, y
  3127. movq x, z
  3128. addq w, z
  3129. movq y, t
  3130. negq t
  3131. movq z, %rax
  3132. addq t, %rax
  3133. jmp conclusion
  3134. \end{lstlisting}
  3135. \end{minipage}
  3136. $\Rightarrow\qquad$
  3137. \begin{minipage}{0.45\textwidth}
  3138. \begin{lstlisting}
  3139. movq $1, %rcx
  3140. movq $42, %rcx
  3141. movq %rcx, -8(%rbp)
  3142. addq $7, -8(%rbp)
  3143. movq -8(%rbp), -16(%rbp)
  3144. movq -8(%rbp), -8(%rbp)
  3145. addq %rcx, -8(%rbp)
  3146. movq -16(%rbp), %rcx
  3147. negq %rcx
  3148. movq -8(%rbp), %rax
  3149. addq %rcx, %rax
  3150. jmp conclusion
  3151. \end{lstlisting}
  3152. \end{minipage}
  3153. \end{center}
  3154. The resulting program is almost an x86 program. The remaining step is
  3155. the patch instructions pass. In this example, the trivial move of
  3156. \code{-8(\%rbp)} to itself is deleted and the addition of
  3157. \code{-8(\%rbp)} to \key{-16(\%rbp)} is fixed by going through
  3158. \code{rax} as follows.
  3159. \begin{lstlisting}
  3160. movq -8(%rbp), %rax
  3161. addq %rax, -16(%rbp)
  3162. \end{lstlisting}
  3163. An overview of all of the passes involved in register allocation is
  3164. shown in Figure~\ref{fig:reg-alloc-passes}.
  3165. \begin{figure}[tbp]
  3166. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3167. \node (R1) at (0,2) {\large $R_1$};
  3168. \node (R1-2) at (3,2) {\large $R_1$};
  3169. \node (R1-3) at (6,2) {\large $R_1$};
  3170. \node (C0-1) at (3,0) {\large $C_0$};
  3171. \node (x86-2) at (3,-2) {\large $\text{x86}^{*}$};
  3172. \node (x86-3) at (6,-2) {\large $\text{x86}^{*}$};
  3173. \node (x86-4) at (9,-2) {\large $\text{x86}$};
  3174. \node (x86-5) at (9,-4) {\large $\text{x86}^{\dagger}$};
  3175. \node (x86-2-1) at (3,-4) {\large $\text{x86}^{*}$};
  3176. \node (x86-2-2) at (6,-4) {\large $\text{x86}^{*}$};
  3177. \path[->,bend left=15] (R1) edge [above] node {\ttfamily\footnotesize uniquify} (R1-2);
  3178. \path[->,bend left=15] (R1-2) edge [above] node {\ttfamily\footnotesize remove-complex.} (R1-3);
  3179. \path[->,bend left=15] (R1-3) edge [right] node {\ttfamily\footnotesize explicate-control} (C0-1);
  3180. \path[->,bend right=15] (C0-1) edge [left] node {\ttfamily\footnotesize select-instr.} (x86-2);
  3181. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  3182. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  3183. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  3184. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  3185. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  3186. \end{tikzpicture}
  3187. \caption{Diagram of the passes for $R_1$ with register allocation.}
  3188. \label{fig:reg-alloc-passes}
  3189. \end{figure}
  3190. \begin{wrapfigure}[24]{r}[1.0in]{0.6\textwidth}
  3191. \small
  3192. \begin{tcolorbox}[title=Priority Queue]
  3193. A \emph{priority queue} is a collection of items in which the
  3194. removal of items is governed by priority. In a ``min'' queue,
  3195. lower priority items are removed first. An implementation is in
  3196. \code{priority\_queue.rkt} of the support code. \index{priority
  3197. queue} \index{minimum priority queue}
  3198. \begin{description}
  3199. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  3200. priority queue that uses the $\itm{cmp}$ predicate to determine
  3201. whether its first argument has lower or equal priority to its
  3202. second argument.
  3203. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  3204. items in the queue.
  3205. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  3206. the item into the queue and returns a handle for the item in the
  3207. queue.
  3208. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  3209. the lowest priority.
  3210. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  3211. notifices the queue the the priority has decreased for the item
  3212. associated with the given handle.
  3213. \end{description}
  3214. \end{tcolorbox}
  3215. \end{wrapfigure}
  3216. We recommend creating a helper function named \code{color-graph} that
  3217. takes an interference graph and a list of all the variables in the
  3218. program. This function should return a mapping of variables to their
  3219. colors (represented as natural numbers). By creating this helper
  3220. function, you will be able to reuse it in Chapter~\ref{ch:functions}
  3221. when you add support for functions. To prioritize the process of
  3222. highly saturated nodes inside your \code{color-graph} function, we
  3223. recommend using the priority queue data structure (see the side bar on
  3224. the right). Note that you will also need to maintain a mapping from
  3225. variables to their ``handles'' in the priority queue so that you can
  3226. notify the priority queue when their saturation changes.
  3227. Once you have obtained the coloring from \code{color-graph}, you can
  3228. assign the variables to registers or stack locations and then reuse
  3229. code from the \code{assign-homes} pass from
  3230. Section~\ref{sec:assign-r1} to replace the variables with their
  3231. assigned location.
  3232. \begin{exercise}\normalfont
  3233. Implement the compiler pass \code{allocate-registers}, which should come
  3234. after the \code{build-interference} pass. The three new passes,
  3235. \code{uncover-live}, \code{build-interference}, and
  3236. \code{allocate-registers} replace the \code{assign-homes} pass of
  3237. Section~\ref{sec:assign-r1}.
  3238. Test your updated compiler by creating new example programs that
  3239. exercise all of the register allocation algorithm, such as forcing
  3240. variables to be spilled to the stack.
  3241. \end{exercise}
  3242. \section{Print x86 and Conventions for Registers}
  3243. \label{sec:print-x86-reg-alloc}
  3244. \index{calling conventions}
  3245. \index{prelude}\index{conclusion}
  3246. Recall that the \code{print-x86} pass generates the prelude and
  3247. conclusion instructions for the \code{main} function.
  3248. %
  3249. The prelude saved the values in \code{rbp} and \code{rsp} and the
  3250. conclusion returned those values to \code{rbp} and \code{rsp}. The
  3251. reason for this is that our \code{main} function must adhere to the
  3252. x86 calling conventions that we described in
  3253. Section~\ref{sec:calling-conventions}. Furthermore, if your register
  3254. allocator assigned variables to other callee-saved registers
  3255. (e.g. \code{rbx}, \code{r12}, etc.), then those variables must also be
  3256. saved to the stack in the prelude and restored in the conclusion. The
  3257. simplest approach is to save and restore all of the callee-saved
  3258. registers. The more efficient approach is to keep track of which
  3259. callee-saved registers were used and only save and restore
  3260. them. Either way, make sure to take this use of stack space into
  3261. account when you are calculating the size of the frame and adjusting
  3262. the \code{rsp} in the prelude. Also, don't forget that the size of the
  3263. frame needs to be a multiple of 16 bytes!
  3264. \section{Challenge: Move Biasing}
  3265. \label{sec:move-biasing}
  3266. \index{move biasing}
  3267. This section describes an optional enhancement to register allocation
  3268. for those students who are looking for an extra challenge or who have
  3269. a deeper interest in register allocation.
  3270. We return to the running example, but we remove the supposition that
  3271. we only have one register to use. So we have the following mapping of
  3272. color numbers to registers.
  3273. \[
  3274. \{ 0 \mapsto \key{\%rbx}, \; 1 \mapsto \key{\%rcx}, \; 2 \mapsto \key{\%rdx} \}
  3275. \]
  3276. Using the same assignment of variables to color numbers that was
  3277. produced by the register allocator described in the last section, we
  3278. get the following program.
  3279. \begin{minipage}{0.3\textwidth}
  3280. \begin{lstlisting}
  3281. movq $1, v
  3282. movq $42, w
  3283. movq v, x
  3284. addq $7, x
  3285. movq x, y
  3286. movq x, z
  3287. addq w, z
  3288. movq y, t
  3289. negq t
  3290. movq z, %rax
  3291. addq t, %rax
  3292. jmp conclusion
  3293. \end{lstlisting}
  3294. \end{minipage}
  3295. $\Rightarrow\qquad$
  3296. \begin{minipage}{0.45\textwidth}
  3297. \begin{lstlisting}
  3298. movq $1, %rcx
  3299. movq $42, $rbx
  3300. movq %rcx, %rcx
  3301. addq $7, %rcx
  3302. movq %rcx, %rdx
  3303. movq %rcx, %rcx
  3304. addq %rbx, %rcx
  3305. movq %rdx, %rbx
  3306. negq %rbx
  3307. movq %rcx, %rax
  3308. addq %rbx, %rax
  3309. jmp conclusion
  3310. \end{lstlisting}
  3311. \end{minipage}
  3312. In the above output code there are two \key{movq} instructions that
  3313. can be removed because their source and target are the same. However,
  3314. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  3315. register, we could instead remove three \key{movq} instructions. We
  3316. can accomplish this by taking into account which variables appear in
  3317. \key{movq} instructions with which other variables.
  3318. We say that two variables $p$ and $q$ are \emph{move
  3319. related}\index{move related} if they participate together in a
  3320. \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  3321. \key{movq} $q$\key{,} $p$. When the register allocator chooses a color
  3322. for a variable, it should prefer a color that has already been used
  3323. for a move-related variable (assuming that they do not interfere). Of
  3324. course, this preference should not override the preference for
  3325. registers over stack locations. This preference should be used as a
  3326. tie breaker when choosing between registers or when choosing between
  3327. stack locations.
  3328. We recommend representing the move relationships in a graph, similar
  3329. to how we represented interference. The following is the \emph{move
  3330. graph} for our running example.
  3331. \[
  3332. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3333. \node (rax) at (0,0) {$\ttm{rax}$};
  3334. \node (t) at (0,2) {$\ttm{t}$};
  3335. \node (z) at (3,2) {$\ttm{z}$};
  3336. \node (x) at (6,2) {$\ttm{x}$};
  3337. \node (y) at (3,0) {$\ttm{y}$};
  3338. \node (w) at (6,0) {$\ttm{w}$};
  3339. \node (v) at (9,0) {$\ttm{v}$};
  3340. \draw (v) to (x);
  3341. \draw (x) to (y);
  3342. \draw (x) to (z);
  3343. \draw (y) to (t);
  3344. \end{tikzpicture}
  3345. \]
  3346. Now we replay the graph coloring, pausing to see the coloring of
  3347. \code{y}. Recall the following configuration. The most saturated vertices
  3348. were \code{w} and \code{y}.
  3349. \[
  3350. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3351. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3352. \node (t1) at (0,2) {$\ttm{t}:0,\{1\}$};
  3353. \node (z) at (3,2) {$\ttm{z}:1,\{0\}$};
  3354. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  3355. \node (y) at (3,0) {$\ttm{y}:-,\{1\}$};
  3356. \node (w) at (6,0) {$\ttm{w}:-,\{1\}$};
  3357. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  3358. \draw (t1) to (rax);
  3359. \draw (t1) to (z);
  3360. \draw (z) to (y);
  3361. \draw (z) to (w);
  3362. \draw (x) to (w);
  3363. \draw (y) to (w);
  3364. \draw (v) to (w);
  3365. \end{tikzpicture}
  3366. \]
  3367. %
  3368. Last time we chose to color \code{w} with $0$. But this time we see
  3369. that \code{w} is not move related to any vertex, but \code{y} is move
  3370. related to \code{t}. So we choose to color \code{y} the same color,
  3371. $0$.
  3372. \[
  3373. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3374. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3375. \node (t1) at (0,2) {$\ttm{t}:0,\{1\}$};
  3376. \node (z) at (3,2) {$\ttm{z}:1,\{0\}$};
  3377. \node (x) at (6,2) {$\ttm{x}:-,\{\}$};
  3378. \node (y) at (3,0) {$\ttm{y}:0,\{1\}$};
  3379. \node (w) at (6,0) {$\ttm{w}:-,\{0,1\}$};
  3380. \node (v) at (9,0) {$\ttm{v}:-,\{\}$};
  3381. \draw (t1) to (rax);
  3382. \draw (t1) to (z);
  3383. \draw (z) to (y);
  3384. \draw (z) to (w);
  3385. \draw (x) to (w);
  3386. \draw (y) to (w);
  3387. \draw (v) to (w);
  3388. \end{tikzpicture}
  3389. \]
  3390. Now \code{w} is the most saturated, so we color it $2$.
  3391. \[
  3392. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3393. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3394. \node (t1) at (0,2) {$\ttm{t}:0,\{1\}$};
  3395. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3396. \node (x) at (6,2) {$\ttm{x}:-,\{2\}$};
  3397. \node (y) at (3,0) {$\ttm{y}:0,\{1,2\}$};
  3398. \node (w) at (6,0) {$\ttm{w}:2,\{0,1\}$};
  3399. \node (v) at (9,0) {$\ttm{v}:-,\{2\}$};
  3400. \draw (t1) to (rax);
  3401. \draw (t1) to (z);
  3402. \draw (z) to (y);
  3403. \draw (z) to (w);
  3404. \draw (x) to (w);
  3405. \draw (y) to (w);
  3406. \draw (v) to (w);
  3407. \end{tikzpicture}
  3408. \]
  3409. At this point, vertices \code{x} and \code{v} are most saturated, but
  3410. \code{x} is move related to \code{y} and \code{z}, so we color
  3411. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  3412. \[
  3413. \begin{tikzpicture}[baseline=(current bounding box.center)]
  3414. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0\}$};
  3415. \node (t) at (0,2) {$\ttm{t}:0,\{1\}$};
  3416. \node (z) at (3,2) {$\ttm{z}:1,\{0,2\}$};
  3417. \node (x) at (6,2) {$\ttm{x}:0,\{2\}$};
  3418. \node (y) at (3,0) {$\ttm{y}:0,\{1,2\}$};
  3419. \node (w) at (6,0) {$\ttm{w}:2,\{0,1\}$};
  3420. \node (v) at (9,0) {$\ttm{v}:0,\{2\}$};
  3421. \draw (t1) to (rax);
  3422. \draw (t) to (z);
  3423. \draw (z) to (y);
  3424. \draw (z) to (w);
  3425. \draw (x) to (w);
  3426. \draw (y) to (w);
  3427. \draw (v) to (w);
  3428. \end{tikzpicture}
  3429. \]
  3430. So we have the following assignment of variables to registers.
  3431. \begin{gather*}
  3432. \{ \ttm{v} \mapsto \key{\%rbx}, \,
  3433. \ttm{w} \mapsto \key{\%rdx}, \,
  3434. \ttm{x} \mapsto \key{\%rbx}, \,
  3435. \ttm{y} \mapsto \key{\%rbx}, \,
  3436. \ttm{z} \mapsto \key{\%rcx}, \,
  3437. \ttm{t} \mapsto \key{\%rbx} \}
  3438. \end{gather*}
  3439. We apply this register assignment to the running example, on the left,
  3440. to obtain the code on right.
  3441. \begin{minipage}{0.3\textwidth}
  3442. \begin{lstlisting}
  3443. movq $1, v
  3444. movq $42, w
  3445. movq v, x
  3446. addq $7, x
  3447. movq x, y
  3448. movq x, z
  3449. addq w, z
  3450. movq y, t
  3451. negq t
  3452. movq z, %rax
  3453. addq t, %rax
  3454. jmp conclusion
  3455. \end{lstlisting}
  3456. \end{minipage}
  3457. $\Rightarrow\qquad$
  3458. \begin{minipage}{0.45\textwidth}
  3459. \begin{lstlisting}
  3460. movq $1, %rbx
  3461. movq $42, %rdx
  3462. movq %rbx, %rbx
  3463. addq $7, %rbx
  3464. movq %rbx, %rbx
  3465. movq %rbx, %rcx
  3466. addq %rdx, %rcx
  3467. movq %rbx, %rbx
  3468. negq %rbx
  3469. movq %rcx, %rax
  3470. addq %rbx, %rax
  3471. jmp conclusion
  3472. \end{lstlisting}
  3473. \end{minipage}
  3474. The \code{patch-instructions} then removes the three trivial moves
  3475. from \key{rbx} to \key{rbx} to obtain the following result.
  3476. \begin{minipage}{0.45\textwidth}
  3477. \begin{lstlisting}
  3478. movq $1, %rbx
  3479. movq $42, %rdx
  3480. addq $7, %rbx
  3481. movq %rbx, %rcx
  3482. addq %rdx, %rcx
  3483. negq %rbx
  3484. movq %rcx, %rax
  3485. addq %rbx, %rax
  3486. jmp conclusion
  3487. \end{lstlisting}
  3488. \end{minipage}
  3489. \begin{exercise}\normalfont
  3490. Change your implementation of \code{allocate-registers} to take move
  3491. biasing into account. Make sure that your compiler still passes all of
  3492. the previous tests. Create two new tests that include at least one
  3493. opportunity for move biasing and visually inspect the output x86
  3494. programs to make sure that your move biasing is working properly.
  3495. \end{exercise}
  3496. \margincomment{\footnotesize To do: another neat challenge would be to do
  3497. live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy}
  3498. \section{Output of the Running Example}
  3499. \label{sec:reg-alloc-output}
  3500. \index{prelude}\index{conclusion}
  3501. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  3502. the running example (Figure~\ref{fig:reg-eg}) with register allocation
  3503. and move biasing. To demonstrate both the use of registers and the
  3504. stack, we have limited the register allocator to use just two
  3505. registers: \code{rbx} and \code{rcx}. In the prelude of the
  3506. \code{main} function, we push \code{rbx} onto the stack because it is
  3507. a callee-saved register and it was assigned to variable by the
  3508. register allocator. We substract \code{8} from the \code{rsp} at the
  3509. end of the prelude to reserve space for the one spilled variable.
  3510. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  3511. Moving on the the \code{start} block, we see how the registers were
  3512. allocated. Variables \code{v}, \code{x}, and \code{y} were assigned to
  3513. \code{rbx} and variable \code{z} was assigned to \code{rcx}. Variable
  3514. \code{w} was spilled to the stack location \code{-16(\%rbp)}. Recall
  3515. that the prelude saved the callee-save register \code{rbx} onto the
  3516. stack. The spilled variables must be placed lower on the stack than
  3517. the saved callee-save registers, so in this case \code{w} is placed at
  3518. \code{-16(\%rbp)}.
  3519. In the \code{conclusion}, we undo the work that was done in the
  3520. prelude. We move the stack pointer up by \code{8} bytes (the room for
  3521. spilled variables), then we pop the old values of \code{rbx} and
  3522. \code{rbp} (callee-saved registers), and finish with \code{retq} to
  3523. return control to the operating system.
  3524. \begin{figure}[tbp]
  3525. % s0_28.rkt
  3526. % (use-minimal-set-of-registers! #t)
  3527. % and only rbx rcx
  3528. % tmp 0 rbx
  3529. % z 1 rcx
  3530. % y 0 rbx
  3531. % w 2 16(%rbp)
  3532. % v 0 rbx
  3533. % x 0 rbx
  3534. \begin{lstlisting}
  3535. start:
  3536. movq $1, %rbx
  3537. movq $42, -16(%rbp)
  3538. addq $7, %rbx
  3539. movq %rbx, %rcx
  3540. addq -16(%rbp), %rcx
  3541. negq %rbx
  3542. movq %rcx, %rax
  3543. addq %rbx, %rax
  3544. jmp conclusion
  3545. .globl main
  3546. main:
  3547. pushq %rbp
  3548. movq %rsp, %rbp
  3549. pushq %rbx
  3550. subq $8, %rsp
  3551. jmp start
  3552. conclusion:
  3553. addq $8, %rsp
  3554. popq %rbx
  3555. popq %rbp
  3556. retq
  3557. \end{lstlisting}
  3558. \caption{The x86 output from the running example (Figure~\ref{fig:reg-eg}).}
  3559. \label{fig:running-example-x86}
  3560. \end{figure}
  3561. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3562. \chapter{Booleans and Control Flow}
  3563. \label{ch:bool-types}
  3564. \index{Boolean}
  3565. \index{control flow}
  3566. \index{conditional expression}
  3567. The $R_0$ and $R_1$ languages only have a single kind of value, the
  3568. integers. In this chapter we add a second kind of value, the Booleans,
  3569. to create the $R_2$ language. The Boolean values \emph{true} and
  3570. \emph{false} are written \key{\#t} and \key{\#f} respectively in
  3571. Racket. The $R_2$ language includes several operations that involve
  3572. Booleans (\key{and}, \key{not}, \key{eq?}, \key{<}, etc.) and the
  3573. conditional \key{if} expression. With the addition of \key{if}
  3574. expressions, programs can have non-trivial control flow which which
  3575. significantly impacts the \code{explicate-control} and the liveness
  3576. analysis for register allocation. Also, because we now have two kinds
  3577. of values, we need to handle programs that apply an operation to the
  3578. wrong kind of value, such as \code{(not 1)}.
  3579. There are two language design options for such situations. One option
  3580. is to signal an error and the other is to provide a wider
  3581. interpretation of the operation. The Racket language uses a mixture of
  3582. these two options, depending on the operation and the kind of
  3583. value. For example, the result of \code{(not 1)} in Racket is
  3584. \code{\#f} because Racket treats non-zero integers as if they were
  3585. \code{\#t}. On the other hand, \code{(car 1)} results in a run-time
  3586. error in Racket stating that \code{car} expects a pair.
  3587. The Typed Racket language makes similar design choices as Racket,
  3588. except much of the error detection happens at compile time instead of
  3589. run time. Like Racket, Typed Racket accepts and runs \code{(not 1)},
  3590. producing \code{\#f}. But in the case of \code{(car 1)}, Typed Racket
  3591. reports a compile-time error because Typed Racket expects the type of
  3592. the argument to be of the form \code{(Listof T)} or \code{(Pairof T1 T2)}.
  3593. For the $R_2$ language we choose to be more like Typed Racket in that
  3594. we perform type checking during compilation. In
  3595. Chapter~\ref{ch:type-dynamic} we study the alternative choice, that
  3596. is, how to compile a dynamically typed language like Racket. The
  3597. $R_2$ language is a subset of Typed Racket but by no means includes
  3598. all of Typed Racket. For many operations we take a narrower
  3599. interpretation than Typed Racket, for example, rejecting \code{(not 1)}.
  3600. This chapter is organized as follows. We begin by defining the syntax
  3601. and interpreter for the $R_2$ language (Section~\ref{sec:r2-lang}). We
  3602. then introduce the idea of type checking and build a type checker for
  3603. $R_2$ (Section~\ref{sec:type-check-r2}). To compile $R_2$ we need to
  3604. enlarge the intermediate language $C_0$ into $C_1$, which we do in
  3605. Section~\ref{sec:c1}. The remaining sections of this chapter discuss
  3606. how our compiler passes need to change to accommodate Booleans and
  3607. conditional control flow.
  3608. \section{The $R_2$ Language}
  3609. \label{sec:r2-lang}
  3610. The concrete syntax of the $R_2$ language is defined in
  3611. Figure~\ref{fig:r2-concrete-syntax} and the abstract syntax is defined
  3612. in Figure~\ref{fig:r2-syntax}. The $R_2$ language includes all of
  3613. $R_1$ (shown in gray), the Boolean literals \code{\#t} and \code{\#f},
  3614. and the conditional \code{if} expression. Also, we expand the
  3615. operators to include
  3616. \begin{enumerate}
  3617. \item subtraction on integers,
  3618. \item the logical operators \key{and}, \key{or} and \key{not},
  3619. \item the \key{eq?} operation for comparing two integers or two Booleans, and
  3620. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  3621. comparing integers.
  3622. \end{enumerate}
  3623. We reorganize the abstract syntax for the primitive operations in
  3624. Figure~\ref{fig:r2-syntax}, using only one grammar rule for all of
  3625. them. This means that the grammar no longer checks whether the arity
  3626. of an operators matches the number of arguments. That responsibility
  3627. is moved to the type checker for $R_2$, which we introduce in
  3628. Section~\ref{sec:type-check-r2}.
  3629. \begin{figure}[tp]
  3630. \centering
  3631. \fbox{
  3632. \begin{minipage}{0.96\textwidth}
  3633. \[
  3634. \begin{array}{lcl}
  3635. \itm{bool} &::=& \key{\#t} \mid \key{\#f} \\
  3636. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  3637. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} } \mid \CSUB{\Exp}{\Exp} \\
  3638. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} } \\
  3639. &\mid& \itm{bool}
  3640. \mid (\key{and}\;\Exp\;\Exp) \mid (\key{or}\;\Exp\;\Exp)
  3641. \mid (\key{not}\;\Exp) \\
  3642. &\mid& (\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} \\
  3643. R_2 &::=& \Exp
  3644. \end{array}
  3645. \]
  3646. \end{minipage}
  3647. }
  3648. \caption{The concrete syntax of $R_2$, extending $R_1$
  3649. (Figure~\ref{fig:r1-concrete-syntax}) with Booleans and conditionals.}
  3650. \label{fig:r2-concrete-syntax}
  3651. \end{figure}
  3652. \begin{figure}[tp]
  3653. \centering
  3654. \fbox{
  3655. \begin{minipage}{0.96\textwidth}
  3656. \[
  3657. \begin{array}{lcl}
  3658. \itm{bool} &::=& \code{\#t} \mid \code{\#f} \\
  3659. \itm{cmp} &::= & \code{eq?} \mid \code{<} \mid \code{<=} \mid \code{>} \mid \code{>=} \\
  3660. \itm{op} &::= & \itm{cmp} \mid \code{read} \mid \code{+} \mid \code{-}
  3661. \mid \code{and} \mid \code{or} \mid \code{not} \\
  3662. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  3663. &\mid& \PRIM{\itm{op}}{\Exp\ldots}\\
  3664. &\mid& \BOOL{\itm{bool}} \mid \IF{\Exp}{\Exp}{\Exp} \\
  3665. R_2 &::=& \PROGRAM{\code{'()}}{\Exp}
  3666. \end{array}
  3667. \]
  3668. \end{minipage}
  3669. }
  3670. \caption{The abstract syntax of $R_2$.}
  3671. \label{fig:r2-syntax}
  3672. \end{figure}
  3673. Figure~\ref{fig:interp-R2} defines the interpreter for $R_2$, omitting
  3674. the parts that are the same as the interpreter for $R_1$
  3675. (Figure~\ref{fig:interp-R1}). The literals \code{\#t} and \code{\#f}
  3676. evaluate to the corresponding Boolean values. The conditional
  3677. expression $(\key{if}\, \itm{cnd}\,\itm{thn}\,\itm{els})$ evaluates
  3678. the Boolean expression \itm{cnd} and then either evaluates \itm{thn}
  3679. or \itm{els} depending on whether \itm{cnd} produced \code{\#t} or
  3680. \code{\#f}. The logical operations \code{not} and \code{and} behave as
  3681. you might expect, but note that the \code{and} operation is
  3682. short-circuiting. That is, given the expression
  3683. $(\key{and}\,e_1\,e_2)$, the expression $e_2$ is not evaluated if
  3684. $e_1$ evaluates to \code{\#f}.
  3685. With the increase in the number of primitive operations, the
  3686. interpreter code for them could become repetitive without some
  3687. care. In Figure~\ref{fig:interp-R2} we factor out the different parts
  3688. of the code for primitive operations into the \code{interp-op}
  3689. function and the similar parts of the code into the match clause for
  3690. \code{Prim} shown in Figure~\ref{fig:interp-R2}. We do not use
  3691. \code{interp-op} for the \code{and} operation because of the
  3692. short-circuiting behavior in the order of evaluation of its arguments.
  3693. \begin{figure}[tbp]
  3694. \begin{lstlisting}
  3695. (define (interp-op op)
  3696. (match op
  3697. ...
  3698. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  3699. ['eq? (lambda (v1 v2)
  3700. (cond [(or (and (fixnum? v1) (fixnum? v2))
  3701. (and (boolean? v1) (boolean? v2)))
  3702. (eq? v1 v2)]))]
  3703. ['< (lambda (v1 v2)
  3704. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  3705. ['<= (lambda (v1 v2)
  3706. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  3707. ['> (lambda (v1 v2)
  3708. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  3709. ['>= (lambda (v1 v2)
  3710. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  3711. [else (error 'interp-op "unknown operator")]))
  3712. (define (interp-exp env)
  3713. (lambda (e)
  3714. (define recur (interp-exp env))
  3715. (match e
  3716. ...
  3717. [(Bool b) b]
  3718. [(If cnd thn els)
  3719. (define b (recur cnd))
  3720. (match b
  3721. [#t (recur thn)]
  3722. [#f (recur els)])]
  3723. [(Prim 'and (list e1 e2))
  3724. (define v1 (recur e1))
  3725. (match v1
  3726. [#t (match (recur e2) [#t #t] [#f #f])]
  3727. [#f #f])]
  3728. [(Prim op args)
  3729. (apply (interp-op op) (for/list ([e args]) (recur e)))]
  3730. )))
  3731. (define (interp-R2 p)
  3732. (match p
  3733. [(Program info e)
  3734. ((interp-exp '()) e)]
  3735. ))
  3736. \end{lstlisting}
  3737. \caption{Interpreter for the $R_2$ language.}
  3738. \label{fig:interp-R2}
  3739. \end{figure}
  3740. \section{Type Checking $R_2$ Programs}
  3741. \label{sec:type-check-r2}
  3742. \index{type checking}
  3743. \index{semantic analysis}
  3744. It is helpful to think about type checking in two complementary
  3745. ways. A type checker predicts the type of value that will be produced
  3746. by each expression in the program. For $R_2$, we have just two types,
  3747. \key{Integer} and \key{Boolean}. So a type checker should predict that
  3748. \begin{lstlisting}
  3749. (+ 10 (- (+ 12 20)))
  3750. \end{lstlisting}
  3751. produces an \key{Integer} while
  3752. \begin{lstlisting}
  3753. (and (not #f) #t)
  3754. \end{lstlisting}
  3755. produces a \key{Boolean}.
  3756. Another way to think about type checking is that it enforces a set of
  3757. rules about which operators can be applied to which kinds of
  3758. values. For example, our type checker for $R_2$ will signal an error
  3759. for the below expression because, as we have seen above, the
  3760. expression \code{(+ 10 ...)} has type \key{Integer} but the type
  3761. checker enforces the rule that the argument of \code{not} must be a
  3762. \key{Boolean}.
  3763. \begin{lstlisting}
  3764. (not (+ 10 (- (+ 12 20))))
  3765. \end{lstlisting}
  3766. The type checker for $R_2$ is a structurally recursive function over
  3767. the AST. Figure~\ref{fig:type-check-R2} defines the
  3768. \code{type-check-exp} function. The code for the type checker is
  3769. included in the student support code.
  3770. %
  3771. Given an input expression \code{e}, the type checker either returns a
  3772. type (\key{Integer} or \key{Boolean}) or it signals an error. The
  3773. type of an integer literal is \code{Integer} and the type of a Boolean
  3774. literal is \code{Boolean}. To handle variables, the type checker uses
  3775. the environment \code{env} to map variables to types. Consider the
  3776. clause for \key{let}. We type check the initializing expression to
  3777. obtain its type \key{T} and then associate type \code{T} with the
  3778. variable \code{x} in the environment used to type check the body of
  3779. the \key{let}. Thus, when the type checker encounters a use of
  3780. variable \code{x}, it can find its type in the environment.
  3781. \begin{figure}[tbp]
  3782. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3783. (define (type-check-exp env)
  3784. (lambda (e)
  3785. (match e
  3786. [(Var x)
  3787. (let ([t (dict-ref env x)])
  3788. (values (Var x) t))]
  3789. [(Int n) (values (Int n) 'Integer)]
  3790. [(Bool b) (values (Bool b) 'Boolean)]
  3791. [(Let x e body)
  3792. (define-values (e^ Te) ((type-check-exp env) e))
  3793. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  3794. (values (Let x e^ b) Tb)]
  3795. [(If cnd thn els)
  3796. (define-values (c Tc) ((type-check-exp env) cnd))
  3797. (define-values (t Tt) ((type-check-exp env) thn))
  3798. (define-values (e Te) ((type-check-exp env) els))
  3799. (unless (type-equal? Tc 'Boolean)
  3800. (error 'type-check-exp "condition should be Boolean, not ~a" Tc))
  3801. (unless (type-equal? Tt Te)
  3802. (error 'type-check-exp "types of branches not equal, ~a != ~a" Tt Te))
  3803. (values (If c t e) Te)]
  3804. [(Prim 'eq? (list e1 e2))
  3805. (define-values (e1^ T1) ((type-check-exp env) e1))
  3806. (define-values (e2^ T2) ((type-check-exp env) e2))
  3807. (unless (type-equal? T1 T2)
  3808. (error 'type-check-exp "argument types of eq?: ~a != ~a" T1 T2))
  3809. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  3810. [(Prim op es)
  3811. (define-values (new-es ts)
  3812. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  3813. (define t-ret (type-check-op op ts))
  3814. (values (Prim op new-es) t-ret)]
  3815. [else
  3816. (error 'type-check-exp "couldn't match" e)])))
  3817. (define (type-check-R2 e)
  3818. (match e
  3819. [(Program info body)
  3820. (define-values (body^ Tb) ((type-check-exp '()) body))
  3821. (unless (type-equal? Tb 'Integer)
  3822. (error 'type-check-R2 "result type must be Integer, not ~a" Tb))
  3823. (Program info body^)]
  3824. [else (error 'type-check-R2 "couldn't match ~a" e)]))
  3825. \end{lstlisting}
  3826. \caption{Type checker for the $R_2$ language.}
  3827. \label{fig:type-check-R2}
  3828. \end{figure}
  3829. Figure~\ref{fig:type-check-aux-R2} defines three auxilliary functions
  3830. that are used in the type checker. The \code{operator-types} function
  3831. defines a dictionary that maps the operator names to their parameter
  3832. and return types. The \code{type-equal?} function determines whether
  3833. two types are equal, which for now simply dispatches to \code{equal?}
  3834. (deep equality). The \code{type-check-op} function looks up the
  3835. operator in the \code{operator-types} dictionary and then checks
  3836. whether the argument types are equal to the parameter types. The
  3837. result is the return type of the operator.
  3838. \begin{figure}[tbp]
  3839. \begin{lstlisting}
  3840. (define (operator-types)
  3841. '((+ . ((Integer Integer) . Integer))
  3842. (- . ((Integer Integer) . Integer))
  3843. (and . ((Boolean Boolean) . Boolean))
  3844. (or . ((Boolean Boolean) . Boolean))
  3845. (< . ((Integer Integer) . Boolean))
  3846. (<= . ((Integer Integer) . Boolean))
  3847. (> . ((Integer Integer) . Boolean))
  3848. (>= . ((Integer Integer) . Boolean))
  3849. (- . ((Integer) . Integer))
  3850. (not . ((Boolean) . Boolean))
  3851. (read . (() . Integer))
  3852. ))
  3853. (define (type-equal? t1 t2)
  3854. (equal? t1 t2))
  3855. (define (type-check-op op arg-types)
  3856. (match (dict-ref (operator-types) op)
  3857. [`(,param-types . ,return-type)
  3858. (for ([at arg-types] [pt param-types])
  3859. (unless (type-equal? at pt)
  3860. (error 'type-check-op
  3861. "argument and parameter mismatch, ~a != ~a" at pt)))
  3862. return-type]
  3863. [else
  3864. (error 'type-check-op "unrecognized operator ~a" op)]))
  3865. \end{lstlisting}
  3866. \caption{Auxilliary functions for type checking.}
  3867. \label{fig:type-check-aux-R2}
  3868. \end{figure}
  3869. \begin{exercise}\normalfont
  3870. Create 10 new example programs in $R_2$. Half of the example programs
  3871. should have a type error. For those programs, to signal that a type
  3872. error is expected, create an empty file with the same base name but
  3873. with file extension \code{.tyerr}. For example, if the test
  3874. \code{r2\_14.rkt} is expected to error, then create an empty file
  3875. named \code{r2\_14.tyerr}. The other half of the example programs
  3876. should not have type errors. Note that if the type checker does not
  3877. signal an error for a program, then interpreting that program should
  3878. not encounter an error.
  3879. \end{exercise}
  3880. \section{Shrink the $R_2$ Language}
  3881. \label{sec:shrink-r2}
  3882. The $R_2$ language includes several operators that are easily
  3883. expressible in terms of other operators. For example, subtraction is
  3884. expressible in terms of addition and negation.
  3885. \[
  3886. \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  3887. \]
  3888. Several of the comparison operations are expressible in terms of
  3889. less-than and logical negation.
  3890. \[
  3891. \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  3892. \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  3893. \]
  3894. The \key{let} is needed in the above translation to ensure that
  3895. expression $e_1$ is evaluated before $e_2$.
  3896. By performing these translations near the front-end of the compiler,
  3897. the later passes of the compiler do not need to deal with these
  3898. constructs, making those passes shorter. On the other hand, sometimes
  3899. these translations make it more difficult to generate the most
  3900. efficient code with respect to the number of instructions. However,
  3901. these differences typically do not affect the number of accesses to
  3902. memory, which is the primary factor that determines execution time on
  3903. modern computer architectures.
  3904. \begin{exercise}\normalfont
  3905. Implement the pass \code{shrink} that removes subtraction,
  3906. \key{and}, \key{or}, \key{<=}, \key{>}, and \key{>=} from the language
  3907. by translating them to other constructs in $R_2$. Create tests to
  3908. make sure that the behavior of all of these constructs stays the
  3909. same after translation.
  3910. \end{exercise}
  3911. \section{The x86$_1$ Language}
  3912. \label{sec:x86-1}
  3913. \index{x86}
  3914. To implement the new logical operations, the comparison operations,
  3915. and the \key{if} expression, we need to delve further into the x86
  3916. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} define
  3917. the concrete and abstract syntax for a larger subset of x86 that
  3918. includes instructions for logical operations, comparisons, and
  3919. conditional jumps.
  3920. One small challenge is that x86 does not provide an instruction that
  3921. directly implements logical negation (\code{not} in $R_2$ and $C_1$).
  3922. However, the \code{xorq} instruction can be used to encode \code{not}.
  3923. The \key{xorq} instruction takes two arguments, performs a pairwise
  3924. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  3925. and writes the results into its second argument. Recall the truth
  3926. table for exclusive-or:
  3927. \begin{center}
  3928. \begin{tabular}{l|cc}
  3929. & 0 & 1 \\ \hline
  3930. 0 & 0 & 1 \\
  3931. 1 & 1 & 0
  3932. \end{tabular}
  3933. \end{center}
  3934. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  3935. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  3936. for the bit $1$, the result is the opposite of the second bit. Thus,
  3937. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  3938. the first argument:
  3939. \[
  3940. \Var~ \key{=}~ \LP\key{not}~\Arg\RP\key{;}
  3941. \qquad\Rightarrow\qquad
  3942. \begin{array}{l}
  3943. \key{movq}~ \Arg\key{,} \Var\\
  3944. \key{xorq}~ \key{\$1,} \Var
  3945. \end{array}
  3946. \]
  3947. \begin{figure}[tp]
  3948. \fbox{
  3949. \begin{minipage}{0.96\textwidth}
  3950. \[
  3951. \begin{array}{lcl}
  3952. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  3953. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  3954. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} } \mid \key{\%}\itm{bytereg}\\
  3955. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3956. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \mid
  3957. \key{subq} \; \Arg\key{,} \Arg \mid
  3958. \key{negq} \; \Arg \mid \key{movq} \; \Arg\key{,} \Arg \mid } \\
  3959. && \gray{ \key{callq} \; \itm{label} \mid
  3960. \key{pushq}\;\Arg \mid \key{popq}\;\Arg \mid \key{retq} \mid \key{jmp}\,\itm{label} } \\
  3961. && \gray{ \itm{label}\key{:}\; \Instr }
  3962. \mid \key{xorq}~\Arg\key{,}~\Arg
  3963. \mid \key{cmpq}~\Arg\key{,}~\Arg \mid \\
  3964. && \key{set}cc~\Arg
  3965. \mid \key{movzbq}~\Arg\key{,}~\Arg
  3966. \mid \key{j}cc~\itm{label}
  3967. \\
  3968. x86_1 &::= & \gray{ \key{.globl main} }\\
  3969. & & \gray{ \key{main:} \; \Instr\ldots }
  3970. \end{array}
  3971. \]
  3972. \end{minipage}
  3973. }
  3974. \caption{The concrete syntax of x86$_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-concrete}).}
  3975. \label{fig:x86-1-concrete}
  3976. \end{figure}
  3977. \begin{figure}[tp]
  3978. \fbox{
  3979. \begin{minipage}{0.96\textwidth}
  3980. \small
  3981. \[
  3982. \begin{array}{lcl}
  3983. \itm{bytereg} &::=& \key{ah} \mid \key{al} \mid \key{bh} \mid \key{bl}
  3984. \mid \key{ch} \mid \key{cl} \mid \key{dh} \mid \key{dl} \\
  3985. \Arg &::=& \gray{\IMM{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}}
  3986. \mid \BYTEREG{\itm{bytereg}} \\
  3987. \itm{cc} & ::= & \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} \\
  3988. \Instr &::=& \gray{ \BININSTR{\code{'addq}}{\Arg}{\Arg}
  3989. \mid \BININSTR{\code{'subq}}{\Arg}{\Arg} } \\
  3990. &\mid& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  3991. \mid \UNIINSTR{\code{'negq}}{\Arg} } \\
  3992. &\mid& \gray{ \CALLQ{\itm{label}}{\itm{int}} \mid \RETQ{}
  3993. \mid \PUSHQ{\Arg} \mid \POPQ{\Arg} \mid \JMP{\itm{label}} } \\
  3994. &\mid& \BININSTR{\code{'xorq}}{\Arg}{\Arg}
  3995. \mid \BININSTR{\code{'cmpq}}{\Arg}{\Arg}\\
  3996. &\mid& \BININSTR{\code{'set}}{\itm{cc}}{\Arg}
  3997. \mid \BININSTR{\code{'movzbq}}{\Arg}{\Arg}\\
  3998. &\mid& \JMPIF{\itm{cc}}{\itm{label}} \\
  3999. \Block &::= & \gray{\BLOCK{\itm{info}}{\Instr\ldots}} \\
  4000. x86_1 &::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}}}
  4001. \end{array}
  4002. \]
  4003. \end{minipage}
  4004. }
  4005. \caption{The abstract syntax of x86$_1$ (extends x86$_0$ of Figure~\ref{fig:x86-0-ast}).}
  4006. \label{fig:x86-1}
  4007. \end{figure}
  4008. Next we consider the x86 instructions that are relevant for compiling
  4009. the comparison operations. The \key{cmpq} instruction compares its two
  4010. arguments to determine whether one argument is less than, equal, or
  4011. greater than the other argument. The \key{cmpq} instruction is unusual
  4012. regarding the order of its arguments and where the result is
  4013. placed. The argument order is backwards: if you want to test whether
  4014. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  4015. \key{cmpq} is placed in the special EFLAGS register. This register
  4016. cannot be accessed directly but it can be queried by a number of
  4017. instructions, including the \key{set} instruction. The \key{set}
  4018. instruction puts a \key{1} or \key{0} into its destination depending
  4019. on whether the comparison came out according to the condition code
  4020. \itm{cc} (\key{e} for equal, \key{l} for less, \key{le} for
  4021. less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal).
  4022. The \key{set} instruction has an annoying quirk in that its
  4023. destination argument must be single byte register, such as \code{al}
  4024. (L for lower bits) or \code{ah} (H for higher bits), which are part of
  4025. the \code{rax} register. Thankfully, the \key{movzbq} instruction can
  4026. then be used to move from a single byte register to a normal 64-bit
  4027. register.
  4028. The x86 instruction for conditional jump are relevant to the
  4029. compilation of \key{if} expressions. The \key{JmpIf} instruction
  4030. updates the program counter to point to the instruction after the
  4031. indicated label depending on whether the result in the EFLAGS register
  4032. matches the condition code \itm{cc}, otherwise the \key{JmpIf}
  4033. instruction falls through to the next instruction. The abstract
  4034. syntax for \key{JmpIf} differs from the concrete syntax for x86 in
  4035. that it separates the instruction name from the condition code. For
  4036. example, \code{(JmpIf le foo)} corresponds to \code{jle foo}. Because
  4037. the \key{JmpIf} instruction relies on the EFLAGS register, it is
  4038. common for the \key{JmpIf} to be immediately preceded by a \key{cmpq}
  4039. instruction to set the EFLAGS register.
  4040. \section{The $C_1$ Intermediate Language}
  4041. \label{sec:c1}
  4042. As with $R_1$, we compile $R_2$ to a C-like intermediate language, but
  4043. we need to grow that intermediate language to handle the new features
  4044. in $R_2$: Booleans and conditional expressions.
  4045. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of
  4046. $C_1$ and Figure~\ref{fig:c1-syntax} defines the abstract syntax. In
  4047. particular, we add logical and comparison operators to the $\Exp$
  4048. non-terminal and the literals \key{\#t} and \key{\#f} to the $\Arg$
  4049. non-terminal. Regarding control flow, $C_1$ differs considerably from
  4050. $R_2$. Instead of \key{if} expressions, $C_1$ has \key{goto} and
  4051. conditional \key{goto} in the grammar for $\Tail$. This means that a
  4052. sequence of statements may now end with a \code{goto} or a conditional
  4053. \code{goto}. The conditional \code{goto} jumps to one of two labels
  4054. depending on the outcome of the comparison. In
  4055. Section~\ref{sec:explicate-control-r2} we discuss how to translate
  4056. from $R_2$ to $C_1$, bridging this gap between \key{if} expressions
  4057. and \key{goto}'s.
  4058. \begin{figure}[tbp]
  4059. \fbox{
  4060. \begin{minipage}{0.96\textwidth}
  4061. \small
  4062. \[
  4063. \begin{array}{lcl}
  4064. \Atm &::=& \gray{ \Int \mid \Var } \mid \itm{bool} \\
  4065. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  4066. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  4067. &\mid& \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP \\
  4068. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \\
  4069. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  4070. \mid \key{goto}~\itm{label}\key{;}\\
  4071. &\mid& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} \\
  4072. C_1 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  4073. \end{array}
  4074. \]
  4075. \end{minipage}
  4076. }
  4077. \caption{The concrete syntax of the $C_1$ intermediate language.}
  4078. \label{fig:c1-concrete-syntax}
  4079. \end{figure}
  4080. \begin{figure}[tp]
  4081. \fbox{
  4082. \begin{minipage}{0.96\textwidth}
  4083. \small
  4084. \[
  4085. \begin{array}{lcl}
  4086. \Atm &::=& \gray{\INT{\Int} \mid \VAR{\Var}} \mid \BOOL{\itm{bool}} \\
  4087. \itm{cmp} &::= & \key{eq?} \mid \key{<} \\
  4088. \Exp &::= & \gray{ \Atm \mid \READ{} }\\
  4089. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4090. &\mid& \UNIOP{\key{'not}}{\Atm}
  4091. \mid \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  4092. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} } \\
  4093. \Tail &::= & \gray{\RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail} }
  4094. \mid \GOTO{\itm{label}} \\
  4095. &\mid& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} \\
  4096. C_1 & ::= & \gray{\PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label}\,\key{.}\,\Tail\key{)}\ldots}}}
  4097. \end{array}
  4098. \]
  4099. \end{minipage}
  4100. }
  4101. \caption{The abstract syntax of $C_1$, an extention of $C_0$
  4102. (Figure~\ref{fig:c0-syntax}).}
  4103. \label{fig:c1-syntax}
  4104. \end{figure}
  4105. \clearpage
  4106. \section{Remove Complex Operands}
  4107. \label{sec:remove-complex-opera-R2}
  4108. Add cases for \code{Bool} and \code{If} to the \code{rco-exp} and
  4109. \code{rco-atom} functions according to the definition of the output
  4110. language for this pass, $R_2^{\dagger}$, the administrative normal
  4111. form of $R_2$, which is defined in Figure~\ref{fig:r2-anf-syntax}. The
  4112. \code{Bool} form is an atomic expressions but \code{If} is not. All
  4113. three sub-expressions of an \code{If} are allowed to be complex
  4114. expressions in the output of \code{remove-complex-opera*}, but the
  4115. operands of \code{not} and the comparisons must be atoms. Regarding
  4116. the \code{If} form, it is particularly important to \textbf{not}
  4117. replace its condition with a temporary variable because that would
  4118. interfere with the generation of high-quality output in the
  4119. \code{explicate-control} pass.
  4120. \begin{figure}[tp]
  4121. \centering
  4122. \fbox{
  4123. \begin{minipage}{0.96\textwidth}
  4124. \[
  4125. \begin{array}{rcl}
  4126. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} } \mid \BOOL{\itm{bool}}\\
  4127. \Exp &::=& \gray{ \Atm \mid \READ{} } \\
  4128. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} } \\
  4129. &\mid& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  4130. &\mid& \UNIOP{\key{'not}}{\Atm} \\
  4131. &\mid& \BINOP{\itm{cmp}}{\Atm}{\Atm} \mid \IF{\Exp}{\Exp}{\Exp} \\
  4132. R^{\dagger}_2 &::=& \PROGRAM{\code{'()}}{\Exp}
  4133. \end{array}
  4134. \]
  4135. \end{minipage}
  4136. }
  4137. \caption{$R_2^{\dagger}$ is $R_2$ in administrative normal form (ANF).}
  4138. \label{fig:r2-anf-syntax}
  4139. \end{figure}
  4140. \section{Explicate Control}
  4141. \label{sec:explicate-control-r2}
  4142. Recall that the purpose of \code{explicate-control} is to make the
  4143. order of evaluation explicit in the syntax of the program. With the
  4144. addition of \key{if} in $R_2$ this get more interesting.
  4145. As a motivating example, consider the following program that has an
  4146. \key{if} expression nested in the predicate of another \key{if}.
  4147. % s1_41.rkt
  4148. \begin{center}
  4149. \begin{minipage}{0.96\textwidth}
  4150. \begin{lstlisting}
  4151. (let ([x (read)])
  4152. (let ([y (read)])
  4153. (if (if (< x 1) (eq? x 0) (eq? x 2))
  4154. (+ y 2)
  4155. (+ y 10))))
  4156. \end{lstlisting}
  4157. \end{minipage}
  4158. \end{center}
  4159. %
  4160. The naive way to compile \key{if} and the comparison would be to
  4161. handle each of them in isolation, regardless of their context. Each
  4162. comparison would be translated into a \key{cmpq} instruction followed
  4163. by a couple instructions to move the result from the EFLAGS register
  4164. into a general purpose register or stack location. Each \key{if} would
  4165. be translated into the combination of a \key{cmpq} and a conditional
  4166. jump. The generated code for the inner \key{if} in the above example
  4167. would be as follows.
  4168. \begin{center}
  4169. \begin{minipage}{0.96\textwidth}
  4170. \begin{lstlisting}
  4171. ...
  4172. cmpq $1, x ;; (< x 1)
  4173. setl %al
  4174. movzbq %al, tmp
  4175. cmpq $1, tmp ;; (if (< x 1) ...)
  4176. je then_branch_1
  4177. jmp else_branch_1
  4178. ...
  4179. \end{lstlisting}
  4180. \end{minipage}
  4181. \end{center}
  4182. However, if we take context into account we can do better and reduce
  4183. the use of \key{cmpq} and EFLAG-accessing instructions.
  4184. One idea is to try and reorganize the code at the level of $R_2$,
  4185. pushing the outer \key{if} inside the inner one. This would yield the
  4186. following code.
  4187. \begin{center}
  4188. \begin{minipage}{0.96\textwidth}
  4189. \begin{lstlisting}
  4190. (let ([x (read)])
  4191. (let ([y (read)])
  4192. (if (< x 1)
  4193. (if (eq? x 0)
  4194. (+ y 2)
  4195. (+ y 10))
  4196. (if (eq? x 2)
  4197. (+ y 2)
  4198. (+ y 10)))))
  4199. \end{lstlisting}
  4200. \end{minipage}
  4201. \end{center}
  4202. Unfortunately, this approach duplicates the two branches, and a
  4203. compiler must never duplicate code!
  4204. We need a way to perform the above transformation, but without
  4205. duplicating code. The solution is straightforward if we think at the
  4206. level of x86 assembly: we can label the code for each of the branches
  4207. and insert jumps in all the places that need to execute the
  4208. branches. Put another way, we need to move away from abstract syntax
  4209. \emph{trees} and instead use \emph{graphs}. In particular, we
  4210. use a standard program representation called a \emph{control flow
  4211. graph} (CFG), due to Frances Elizabeth \citet{Allen:1970uq}.
  4212. \index{control-flow graph}
  4213. Each vertex is a labeled sequence of code, called a \emph{basic block}, and
  4214. each edge represents a jump to another block. The \key{Program}
  4215. construct of $C_0$ and $C_1$ contains a control flow graph represented
  4216. as an alist mapping labels to basic blocks. Each basic block is
  4217. represented by the $\Tail$ non-terminal.
  4218. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  4219. \code{remove-complex-opera*} pass and then the
  4220. \code{explicate-control} pass on the example program. We walk through
  4221. the output program and then discuss the algorithm.
  4222. %
  4223. Following the order of evaluation in the output of
  4224. \code{remove-complex-opera*}, we first have two calls to \code{(read)}
  4225. and then the less-than-comparison to \code{1} in the predicate of the
  4226. inner \key{if}. In the output of \code{explicate-control}, in the
  4227. block labeled \code{start}, this becomes two assignment statements
  4228. followed by a conditional \key{goto} to label \code{block96} or
  4229. \code{block97}. The blocks associated with those labels contain the
  4230. translations of the code \code{(eq? x 0)} and \code{(eq? x 2)},
  4231. respectively. Regarding the block labeled with \code{block96}, we
  4232. start with the comparison to \code{0} and then have a conditional
  4233. goto, either to label \code{block92} or label \code{block93}, which
  4234. indirectly take us to labels \code{block90} and \code{block91}, the
  4235. two branches of the outer \key{if}, i.e., \code{(+ y 2)} and \code{(+
  4236. y 10)}. The story for the block labeled \code{block97} is similar.
  4237. \begin{figure}[tbp]
  4238. \begin{tabular}{lll}
  4239. \begin{minipage}{0.4\textwidth}
  4240. % s1_41.rkt
  4241. \begin{lstlisting}
  4242. (let ([x (read)])
  4243. (let ([y (read)])
  4244. (if (if (< x 1)
  4245. (eq? x 0)
  4246. (eq? x 2))
  4247. (+ y 2)
  4248. (+ y 10))))
  4249. \end{lstlisting}
  4250. \hspace{40pt}$\Downarrow$
  4251. \begin{lstlisting}
  4252. (let ([x (read)])
  4253. (let ([y (read)])
  4254. (if (if (< x 1)
  4255. (eq? x 0)
  4256. (eq? x 2))
  4257. (+ y 2)
  4258. (+ y 10))))
  4259. \end{lstlisting}
  4260. \end{minipage}
  4261. &
  4262. $\Rightarrow$
  4263. &
  4264. \begin{minipage}{0.55\textwidth}
  4265. \begin{lstlisting}
  4266. start:
  4267. x = (read);
  4268. y = (read);
  4269. if (< x 1)
  4270. goto block96;
  4271. else
  4272. goto block97;
  4273. block96:
  4274. if (eq? x 0)
  4275. goto block92;
  4276. else
  4277. goto block93;
  4278. block97:
  4279. if (eq? x 2)
  4280. goto block94;
  4281. else
  4282. goto block95;
  4283. block92:
  4284. goto block90;
  4285. block93:
  4286. goto block91;
  4287. block94:
  4288. goto block90;
  4289. block95:
  4290. goto block91;
  4291. block90:
  4292. return (+ y 2);
  4293. block91:
  4294. return (+ y 10);
  4295. \end{lstlisting}
  4296. \end{minipage}
  4297. \end{tabular}
  4298. \caption{Example translation from $R_2$ to $C_1$
  4299. via the \code{explicate-control}.}
  4300. \label{fig:explicate-control-s1-38}
  4301. \end{figure}
  4302. The nice thing about the output of \code{explicate-control} is that
  4303. there are no unnecessary comparisons and every comparison is part of a
  4304. conditional jump. The down-side of this output is that it includes
  4305. trivial blocks, such as the blocks labeled \code{block92} through
  4306. \code{block95}, that only jump to another block. We discuss a solution
  4307. to this problem in Section~\ref{sec:opt-jumps}.
  4308. Recall that in Section~\ref{sec:explicate-control-r1} we implement
  4309. \code{explicate-control} for $R_1$ using two mutually recursive
  4310. functions, \code{explicate-tail} and \code{explicate-assign}. The
  4311. former function translates expressions in tail position whereas the
  4312. later function translates expressions on the right-hand-side of a
  4313. \key{let}. With the addition of \key{if} expression in $R_2$ we have a
  4314. new kind of context to deal with: the predicate position of the
  4315. \key{if}. We need another function, \code{explicate-pred}, that takes
  4316. an $R_2$ expression and two blocks (two $C_1$ $\Tail$ AST nodes) for
  4317. the then-branch and else-branch. The output of \code{explicate-pred}
  4318. is a block and a list of formerly \key{let}-bound variables.
  4319. Note that the three explicate functions need to construct a
  4320. control-flow graph, which we recommend they do via updates to a global
  4321. variable.
  4322. In the following paragraphs we consider the specific additions to the
  4323. \code{explicate-tail} and \code{explicate-assign} functions, and some
  4324. of cases for the \code{explicate-pred} function.
  4325. The \code{explicate-tail} function needs an additional case for
  4326. \key{if}. The branches of the \key{if} inherit the current context, so
  4327. they are in tail position. Let $B_1$ be the result of
  4328. \code{explicate-tail} on the ``then'' branch of the \key{if}, so $B_1$
  4329. is a $\Tail$ AST node. Let $B_2$ be the result of applying
  4330. \code{explicate-tail} to the ``else'' branch. Finally, let $B_3$ be
  4331. the $\Tail$ that results from applying \code{explicate-pred} to the
  4332. predicate $\itm{cnd}$ and the blocks $B_1$ and $B_2$. Then the
  4333. \key{if} as a whole translates to block $B_3$.
  4334. \[
  4335. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  4336. \]
  4337. In the above discussion, we use the metavariables $B_1$, $B_2$, and
  4338. $B_3$ to refer to blocks for the purposes of our discussion, but they
  4339. should not be confused with the labels for the blocks that appear in
  4340. the generated code. We initially construct unlabeled blocks; we only
  4341. attach labels to blocks when we add them to the control-flow graph, as
  4342. we see in the next case.
  4343. Next consider the case for \key{if} in the \code{explicate-assign}
  4344. function. The context of the \key{if} is an assignment to some
  4345. variable $x$ and then the control continues to some block $B_1$. The
  4346. code that we generate for both the ``then'' and ``else'' branches
  4347. needs to continue to $B_1$, so to avoid duplicating $B_1$ we instead
  4348. add it to the control flow graph with a fresh label $\ell_1$. The
  4349. branches of the \key{if} inherit the current context, so they are in
  4350. assignment positions. Let $B_2$ be the result of applying
  4351. \code{explicate-assign} to the ``then'' branch, variable $x$, and the
  4352. block \GOTO{$\ell_1$}. Let $B_3$ be the result of applying
  4353. \code{explicate-assign} to the ``else'' branch, variable $x$, and the
  4354. block \GOTO{$\ell_1$}. Finally, let $B_4$ be the result of applying
  4355. \code{explicate-pred} to the predicate $\itm{cnd}$ and the blocks
  4356. $B_2$ and $B_3$. The \key{if} as a whole translates to the block
  4357. $B_4$.
  4358. \[
  4359. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  4360. \]
  4361. The function \code{explicate-pred} will need a case for every
  4362. expression that can have type \code{Boolean}. We detail a few cases
  4363. here and leave the rest for the reader. The input to this function is
  4364. an expression and two blocks, $B_1$ and $B_2$, for the two branches of
  4365. the enclosing \key{if}. Suppose the expression is the Boolean
  4366. \code{\#t}. Then we can perform a kind of partial evaluation
  4367. \index{partial evaluation} and translate it to the ``then'' branch
  4368. $B_1$. Likewise, we translate \code{\#f} to the ``else`` branch $B_2$.
  4369. \[
  4370. \key{\#t} \quad\Rightarrow\quad B_1,
  4371. \qquad\qquad\qquad
  4372. \key{\#f} \quad\Rightarrow\quad B_2
  4373. \]
  4374. Next, suppose the expression is a less-than comparison. We translate
  4375. it to a conditional \code{goto}. We need labels for the two branches
  4376. $B_1$ and $B_2$, so we add those blocks to the control flow graph and
  4377. obtain their labels $\ell_1$ and $\ell_2$. The translation of the
  4378. less-than comparison is as follows.
  4379. \[
  4380. (\key{<}~e_1~e_2) \quad\Rightarrow\quad
  4381. \begin{array}{l}
  4382. \key{if}~(\key{<}~e_1~e_2) \\
  4383. \qquad\key{goto}~\ell_1\key{;}\\
  4384. \key{else}\\
  4385. \qquad\key{goto}~\ell_2\key{;}
  4386. \end{array}
  4387. \]
  4388. The case for \key{if} in \code{explicate-pred} is particularly
  4389. illuminating as it deals with the challenges that we discussed above
  4390. regarding the example of the nested \key{if} expressions. Again, we
  4391. add the two branches $B_1$ and $B_2$ to the control flow graph and
  4392. obtain their labels $\ell_1$ and $\ell_2$. The ``then'' and ``else''
  4393. branches of the current \key{if} inherit their context from the
  4394. current one, that is, predicate context. So we apply
  4395. \code{explicate-pred} to the ``then'' branch with the two blocks
  4396. \GOTO{$\ell_1$} and \GOTO{$\ell_2$} to obtain $B_3$. Proceed in a
  4397. similar way with the ``else'' branch to obtain $B_4$. Finally, we
  4398. apply \code{explicate-pred} to the predicate of the \code{if} and the
  4399. blocks $B_3$ and $B_4$ to obtain the result $B_5$.
  4400. \[
  4401. (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  4402. \quad\Rightarrow\quad
  4403. B_5
  4404. \]
  4405. Finally, note that the way in which the \code{shrink} pass transforms
  4406. logical operations such as \code{and} and \code{or} can impact the
  4407. quality of code generated by \code{explicate-control}. For example,
  4408. consider the following program.
  4409. \begin{lstlisting}
  4410. (if (and (eq? (read) 0) (eq? (read) 1))
  4411. 0
  4412. 42)
  4413. \end{lstlisting}
  4414. The \code{and} operation should transform into something that the
  4415. \code{explicat-pred} function can still analyze and descend through to
  4416. reach the underlying \code{eq?} conditions. Ideally, your
  4417. \code{explicate-control} pass should generate code similar to the
  4418. following for the above program.\footnote{If the trivial blocks 17,
  4419. 18, and 20 bother you, take a look at the challenge problem in
  4420. Section~\ref{sec:opt-jumps}.}
  4421. \begin{center}
  4422. \begin{minipage}{0.45\textwidth}
  4423. \begin{lstlisting}
  4424. start:
  4425. tmp13 = (read);
  4426. if (eq? tmp13 0)
  4427. goto block19;
  4428. else
  4429. goto block20;
  4430. block19:
  4431. tmp14 = (read);
  4432. if (eq? tmp14 1)
  4433. goto block17;
  4434. else
  4435. goto block18;
  4436. \end{lstlisting}
  4437. \end{minipage}
  4438. \begin{minipage}{0.45\textwidth}
  4439. \begin{lstlisting}
  4440. block20:
  4441. goto block16;
  4442. block17:
  4443. goto block15;
  4444. block18:
  4445. goto block16;
  4446. block15:
  4447. return 0;
  4448. block16:
  4449. return 42;
  4450. \end{lstlisting}
  4451. \end{minipage}
  4452. \end{center}
  4453. \begin{exercise}\normalfont
  4454. Implement the pass \code{explicate-control} by adding the cases for
  4455. \key{if} to the functions for tail and assignment contexts, and
  4456. implement \code{explicate-pred} for predicate contexts. Create test
  4457. cases that exercise all of the new cases in the code for this pass.
  4458. \end{exercise}
  4459. \section{Select Instructions}
  4460. \label{sec:select-r2}
  4461. \index{instruction selection}
  4462. Recall that the \code{select-instructions} pass lowers from our
  4463. $C$-like intermediate representation to the pseudo-x86 language, which
  4464. is suitable for conducting register allocation. The pass is
  4465. implemented using three auxiliary functions, one for each of the
  4466. non-terminals $\Atm$, $\Stmt$, and $\Tail$.
  4467. For $\Atm$, we have new cases for the Booleans. We take the usual
  4468. approach of encoding them as integers, with true as 1 and false as 0.
  4469. \[
  4470. \key{\#t} \Rightarrow \key{1}
  4471. \qquad
  4472. \key{\#f} \Rightarrow \key{0}
  4473. \]
  4474. For $\Stmt$, we discuss a couple cases. The \code{not} operation can
  4475. be implemented in terms of \code{xorq} as we discussed at the
  4476. beginning of this section. Given an assignment
  4477. $\itm{var}$ \key{=} \key{(not} $\Atm$\key{);},
  4478. if the left-hand side $\itm{var}$ is
  4479. the same as $\Atm$, then just the \code{xorq} suffices.
  4480. \[
  4481. \Var~\key{=}~ \key{(not}\; \Var\key{);}
  4482. \quad\Rightarrow\quad
  4483. \key{xorq}~\key{\$}1\key{,}~\Var
  4484. \]
  4485. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  4486. semantics of x86. Let $\Arg$ be the result of translating $\Atm$ to
  4487. x86. Then we have
  4488. \[
  4489. \Var~\key{=}~ \key{(not}\; \Atm\key{);}
  4490. \quad\Rightarrow\quad
  4491. \begin{array}{l}
  4492. \key{movq}~\Arg\key{,}~\Var\\
  4493. \key{xorq}~\key{\$}1\key{,}~\Var
  4494. \end{array}
  4495. \]
  4496. Next consider the cases for \code{eq?} and less-than comparison.
  4497. Translating these operations to x86 is slightly involved due to the
  4498. unusual nature of the \key{cmpq} instruction discussed above. We
  4499. recommend translating an assignment from \code{eq?} into the following
  4500. sequence of three instructions. \\
  4501. \begin{tabular}{lll}
  4502. \begin{minipage}{0.4\textwidth}
  4503. \begin{lstlisting}
  4504. |$\Var$| = (eq? |$\Atm_1$| |$\Atm_2$|);
  4505. \end{lstlisting}
  4506. \end{minipage}
  4507. &
  4508. $\Rightarrow$
  4509. &
  4510. \begin{minipage}{0.4\textwidth}
  4511. \begin{lstlisting}
  4512. cmpq |$\Arg_2$|, |$\Arg_1$|
  4513. sete %al
  4514. movzbq %al, |$\Var$|
  4515. \end{lstlisting}
  4516. \end{minipage}
  4517. \end{tabular} \\
  4518. Regarding the $\Tail$ non-terminal, we have two new cases: \key{goto}
  4519. and conditional \key{goto}. Both are straightforward to handle. A
  4520. \key{goto} becomes a jump instruction.
  4521. \[
  4522. \key{goto}\; \ell\key{;} \quad \Rightarrow \quad \key{jmp}\;\ell
  4523. \]
  4524. A conditional \key{goto} becomes a compare instruction followed
  4525. by a conditional jump (for ``then'') and the fall-through is
  4526. to a regular jump (for ``else'').\\
  4527. \begin{tabular}{lll}
  4528. \begin{minipage}{0.4\textwidth}
  4529. \begin{lstlisting}
  4530. if (eq? |$\Atm_1$| |$\Atm_2$|)
  4531. goto |$\ell_1$|;
  4532. else
  4533. goto |$\ell_2$|;
  4534. \end{lstlisting}
  4535. \end{minipage}
  4536. &
  4537. $\Rightarrow$
  4538. &
  4539. \begin{minipage}{0.4\textwidth}
  4540. \begin{lstlisting}
  4541. cmpq |$\Arg_2$|, |$\Arg_1$|
  4542. je |$\ell_1$|
  4543. jmp |$\ell_2$|
  4544. \end{lstlisting}
  4545. \end{minipage}
  4546. \end{tabular} \\
  4547. \begin{exercise}\normalfont
  4548. Expand your \code{select-instructions} pass to handle the new features
  4549. of the $R_2$ language. Test the pass on all the examples you have
  4550. created and make sure that you have some test programs that use the
  4551. \code{eq?} and \code{<} operators, creating some if necessary. Test
  4552. the output using the \code{interp-x86} interpreter
  4553. (Appendix~\ref{appendix:interp}).
  4554. \end{exercise}
  4555. \section{Register Allocation}
  4556. \label{sec:register-allocation-r2}
  4557. \index{register allocation}
  4558. The changes required for $R_2$ affect liveness analysis, building the
  4559. interference graph, and assigning homes, but the graph coloring
  4560. algorithm itself does not change.
  4561. \subsection{Liveness Analysis}
  4562. \label{sec:liveness-analysis-r2}
  4563. \index{liveness analysis}
  4564. Recall that for $R_1$ we implemented liveness analysis for a single
  4565. basic block (Section~\ref{sec:liveness-analysis-r1}). With the
  4566. addition of \key{if} expressions to $R_2$, \code{explicate-control}
  4567. produces many basic blocks arranged in a control-flow graph. The first
  4568. question we need to consider is: what order should we process the
  4569. basic blocks? Recall that to perform liveness analysis, we need to
  4570. know the live-after set. If a basic block has no successor blocks
  4571. (i.e. no out-edges in the control flow graph), then it has an empty
  4572. live-after set and we can immediately apply liveness analysis to
  4573. it. If a basic block has some successors, then we need to complete
  4574. liveness analysis on those blocks first. Furthermore, we know that
  4575. the control flow graph does not contain any cycles because $R_2$ does
  4576. not include loops
  4577. %
  4578. \footnote{If we were to add loops to the language, then the CFG could
  4579. contain cycles and we would instead need to use the classic worklist
  4580. algorithm for computing the fixed point of the liveness
  4581. analysis~\citep{Aho:1986qf}.}.
  4582. %
  4583. Returning to the question of what order should we process the basic
  4584. blocks, the answer is reverse topological order. We recommend using
  4585. the \code{tsort} (topological sort) and \code{transpose} functions of
  4586. the Racket \code{graph} package to obtain this ordering.
  4587. \index{topological order}
  4588. \index{topological sort}
  4589. The next question is how to compute the live-after set of a block
  4590. given the live-before sets of all its successor blocks. (There can be
  4591. more than one because of conditional jumps.) During compilation we do
  4592. not know which way a conditional jump will go, so we do not know which
  4593. of the successor's live-before set to use. The solution to this
  4594. challenge is based on the observation that there is no harm to the
  4595. correctness of the compiler if we classify more variables as live than
  4596. the ones that are truly live during a particular execution of the
  4597. block. Thus, we can take the union of the live-before sets from all
  4598. the successors to be the live-after set for the block. Once we have
  4599. computed the live-after set, we can proceed to perform liveness
  4600. analysis on the block just as we did in
  4601. Section~\ref{sec:liveness-analysis-r1}.
  4602. The helper functions for computing the variables in an instruction's
  4603. argument and for computing the variables read-from ($R$) or written-to
  4604. ($W$) by an instruction need to be updated to handle the new kinds of
  4605. arguments and instructions in x86$_1$.
  4606. \subsection{Build Interference}
  4607. \label{sec:build-interference-r2}
  4608. Many of the new instructions in x86$_1$ can be handled in the same way
  4609. as the instructions in x86$_0$. Thus, if your code was already quite
  4610. general, it will not need to be changed to handle the new
  4611. instructions. If you code is not general enough, I recommend that you
  4612. change your code to be more general. For example, you can factor out
  4613. the computing of the the read and write sets for each kind of
  4614. instruction into two auxiliary functions.
  4615. Note that the \key{movzbq} instruction requires some special care,
  4616. just like the \key{movq} instruction. See rule number 3 in
  4617. Section~\ref{sec:build-interference}.
  4618. %% \subsection{Assign Homes}
  4619. %% \label{sec:assign-homes-r2}
  4620. %% The \code{assign-homes} function (Section~\ref{sec:assign-r1}) needs
  4621. %% to be updated to handle the \key{if} statement, simply by recursively
  4622. %% processing the child nodes. Hopefully your code already handles the
  4623. %% other new instructions, but if not, you can generalize your code.
  4624. \begin{exercise}\normalfont
  4625. Update the \code{register-allocation} pass so that it works for $R_2$
  4626. and test your compiler using your previously created programs on the
  4627. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4628. \end{exercise}
  4629. \section{Patch Instructions}
  4630. The second argument of the \key{cmpq} instruction must not be an
  4631. immediate value (such as an integer). So if you are comparing two
  4632. immediates, we recommend inserting a \key{movq} instruction to put the
  4633. second argument in \key{rax}.
  4634. %
  4635. The second argument of the \key{movzbq} must be a register.
  4636. %
  4637. There are no special restrictions on the x86 instructions \key{JmpIf}
  4638. and \key{Jmp}.
  4639. \begin{exercise}\normalfont
  4640. Update \code{patch-instructions} to handle the new x86 instructions.
  4641. Test your compiler using your previously created programs on the
  4642. \code{interp-x86} interpreter (Appendix~\ref{appendix:interp}).
  4643. \end{exercise}
  4644. \section{An Example Translation}
  4645. Figure~\ref{fig:if-example-x86} shows a simple example program in
  4646. $R_2$ translated to x86, showing the results of
  4647. \code{explicate-control}, \code{select-instructions}, and the final
  4648. x86 assembly code.
  4649. \begin{figure}[tbp]
  4650. \begin{tabular}{lll}
  4651. \begin{minipage}{0.5\textwidth}
  4652. % s1_20.rkt
  4653. \begin{lstlisting}
  4654. (if (eq? (read) 1) 42 0)
  4655. \end{lstlisting}
  4656. $\Downarrow$
  4657. \begin{lstlisting}
  4658. start:
  4659. tmp7951 = (read);
  4660. if (eq? tmp7951 1) then
  4661. goto block7952;
  4662. else
  4663. goto block7953;
  4664. block7952:
  4665. return 42;
  4666. block7953:
  4667. return 0;
  4668. \end{lstlisting}
  4669. $\Downarrow$
  4670. \begin{lstlisting}
  4671. start:
  4672. callq read_int
  4673. movq %rax, tmp7951
  4674. cmpq $1, tmp7951
  4675. je block7952
  4676. jmp block7953
  4677. block7953:
  4678. movq $0, %rax
  4679. jmp conclusion
  4680. block7952:
  4681. movq $42, %rax
  4682. jmp conclusion
  4683. \end{lstlisting}
  4684. \end{minipage}
  4685. &
  4686. $\Rightarrow\qquad$
  4687. \begin{minipage}{0.4\textwidth}
  4688. \begin{lstlisting}
  4689. start:
  4690. callq read_int
  4691. movq %rax, %rcx
  4692. cmpq $1, %rcx
  4693. je block7952
  4694. jmp block7953
  4695. block7953:
  4696. movq $0, %rax
  4697. jmp conclusion
  4698. block7952:
  4699. movq $42, %rax
  4700. jmp conclusion
  4701. .globl main
  4702. main:
  4703. pushq %rbp
  4704. movq %rsp, %rbp
  4705. pushq %r13
  4706. pushq %r12
  4707. pushq %rbx
  4708. pushq %r14
  4709. subq $0, %rsp
  4710. jmp start
  4711. conclusion:
  4712. addq $0, %rsp
  4713. popq %r14
  4714. popq %rbx
  4715. popq %r12
  4716. popq %r13
  4717. popq %rbp
  4718. retq
  4719. \end{lstlisting}
  4720. \end{minipage}
  4721. \end{tabular}
  4722. \caption{Example compilation of an \key{if} expression to x86.}
  4723. \label{fig:if-example-x86}
  4724. \end{figure}
  4725. \begin{figure}[p]
  4726. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4727. \node (R2) at (0,2) {\large $R_2$};
  4728. \node (R2-2) at (3,2) {\large $R_2$};
  4729. \node (R2-3) at (6,2) {\large $R_2$};
  4730. \node (R2-4) at (9,2) {\large $R_2$};
  4731. \node (R2-5) at (9,0) {\large $R_2$};
  4732. \node (C1-1) at (3,-2) {\large $C_1$};
  4733. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_1$};
  4734. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_1$};
  4735. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_1$};
  4736. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_1$};
  4737. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_1$};
  4738. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_1$};
  4739. \path[->,bend left=15] (R2) edge [above] node {\ttfamily\footnotesize\color{red} type-check} (R2-2);
  4740. \path[->,bend left=15] (R2-2) edge [above] node {\ttfamily\footnotesize\color{red} shrink} (R2-3);
  4741. \path[->,bend left=15] (R2-3) edge [above] node {\ttfamily\footnotesize uniquify} (R2-4);
  4742. \path[->,bend left=15] (R2-4) edge [right] node {\ttfamily\footnotesize remove-complex.} (R2-5);
  4743. \path[->,bend right=15] (R2-5) edge [left] node {\ttfamily\footnotesize\color{red} explicate-control} (C1-1);
  4744. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize\color{red} select-instructions} (x86-2);
  4745. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  4746. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build-inter.} (x86-2-2);
  4747. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate-reg.} (x86-3);
  4748. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  4749. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86 } (x86-5);
  4750. \end{tikzpicture}
  4751. \caption{Diagram of the passes for $R_2$, a language with conditionals.}
  4752. \label{fig:R2-passes}
  4753. \end{figure}
  4754. Figure~\ref{fig:R2-passes} lists all the passes needed for the
  4755. compilation of $R_2$.
  4756. \section{Challenge: Optimize and Remove Jumps}
  4757. \label{sec:opt-jumps}
  4758. Recall that in the example output of \code{explicate-control} in
  4759. Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  4760. \code{block60} are trivial blocks, they do nothing but jump to another
  4761. block. The first goal of this challenge assignment is to remove those
  4762. blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  4763. \code{explicate-control} on the left and shows the result of bypassing
  4764. the trivial blocks on the right. Let us focus on \code{block61}. The
  4765. \code{then} branch jumps to \code{block57}, which in turn jumps to
  4766. \code{block55}. The optimized code on the right of
  4767. Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  4768. \code{then} branch jumping directly to \code{block55}. The story is
  4769. similar for the \code{else} branch, as well as for the two branches in
  4770. \code{block62}. After the jumps in \code{block61} and \code{block62}
  4771. have been optimized in this way, there are no longer any jumps to
  4772. blocks \code{block57} through \code{block60}, so they can be removed.
  4773. \begin{figure}[tbp]
  4774. \begin{tabular}{lll}
  4775. \begin{minipage}{0.4\textwidth}
  4776. \begin{lstlisting}
  4777. block62:
  4778. tmp54 = (read);
  4779. if (eq? tmp54 2) then
  4780. goto block59;
  4781. else
  4782. goto block60;
  4783. block61:
  4784. tmp53 = (read);
  4785. if (eq? tmp53 0) then
  4786. goto block57;
  4787. else
  4788. goto block58;
  4789. block60:
  4790. goto block56;
  4791. block59:
  4792. goto block55;
  4793. block58:
  4794. goto block56;
  4795. block57:
  4796. goto block55;
  4797. block56:
  4798. return (+ 700 77);
  4799. block55:
  4800. return (+ 10 32);
  4801. start:
  4802. tmp52 = (read);
  4803. if (eq? tmp52 1) then
  4804. goto block61;
  4805. else
  4806. goto block62;
  4807. \end{lstlisting}
  4808. \end{minipage}
  4809. &
  4810. $\Rightarrow$
  4811. &
  4812. \begin{minipage}{0.55\textwidth}
  4813. \begin{lstlisting}
  4814. block62:
  4815. tmp54 = (read);
  4816. if (eq? tmp54 2) then
  4817. goto block55;
  4818. else
  4819. goto block56;
  4820. block61:
  4821. tmp53 = (read);
  4822. if (eq? tmp53 0) then
  4823. goto block55;
  4824. else
  4825. goto block56;
  4826. block56:
  4827. return (+ 700 77);
  4828. block55:
  4829. return (+ 10 32);
  4830. start:
  4831. tmp52 = (read);
  4832. if (eq? tmp52 1) then
  4833. goto block61;
  4834. else
  4835. goto block62;
  4836. \end{lstlisting}
  4837. \end{minipage}
  4838. \end{tabular}
  4839. \caption{Optimize jumps by removing trivial blocks.}
  4840. \label{fig:optimize-jumps}
  4841. \end{figure}
  4842. The name of this pass is \code{optimize-jumps}. We recommend
  4843. implementing this pass in two phases. The first phrase builds a hash
  4844. table that maps labels to possibly improved labels. The second phase
  4845. changes the target of each \code{goto} to use the improved label. If
  4846. the label is for a trivial block, then the hash table should map the
  4847. label to the first non-trivial block that can be reached from this
  4848. label by jumping through trivial blocks. If the label is for a
  4849. non-trivial block, then the hash table should map the label to itself;
  4850. we do not want to change jumps to non-trivial blocks.
  4851. The first phase can be accomplished by constructing an empty hash
  4852. table, call it \code{short-cut}, and then iterating over the control
  4853. flow graph. Each time you encouter a block that is just a \code{goto},
  4854. then update the hash table, mapping the block's source to the target
  4855. of the \code{goto}. Also, the hash table may already have mapped some
  4856. labels to the block's source, to you must iterate through the hash
  4857. table and update all of those so that they instead map to the target
  4858. of the \code{goto}.
  4859. For the second phase, we recommend iterating through the $\Tail$ of
  4860. each block in the program, updating the target of every \code{goto}
  4861. according to the mapping in \code{short-cut}.
  4862. \begin{exercise}\normalfont
  4863. Implement the \code{optimize-jumps} pass as a transformation from
  4864. $C_1$ to $C_1$, coming after the \code{explicate-control} pass.
  4865. Check that \code{optimize-jumps} removes trivial blocks in a few
  4866. example programs. Then check that your compiler still passes all of
  4867. your tests.
  4868. \end{exercise}
  4869. There is another opportunity for optimizing jumps that is apparent in
  4870. the example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  4871. end with a jump to \code{block7953} and there are no other jumps to
  4872. \code{block7953} in the rest of the program. In this situation we can
  4873. avoid the runtime overhead of this jump by merging \code{block7953}
  4874. into the preceeding block, in this case the \code{start} block.
  4875. Figure~\ref{fig:remove-jumps} shows the output of
  4876. \code{select-instructions} on the left and the result of this
  4877. optimization on the right.
  4878. \begin{figure}[tbp]
  4879. \begin{tabular}{lll}
  4880. \begin{minipage}{0.5\textwidth}
  4881. % s1_20.rkt
  4882. \begin{lstlisting}
  4883. start:
  4884. callq read_int
  4885. movq %rax, tmp7951
  4886. cmpq $1, tmp7951
  4887. je block7952
  4888. jmp block7953
  4889. block7953:
  4890. movq $0, %rax
  4891. jmp conclusion
  4892. block7952:
  4893. movq $42, %rax
  4894. jmp conclusion
  4895. \end{lstlisting}
  4896. \end{minipage}
  4897. &
  4898. $\Rightarrow\qquad$
  4899. \begin{minipage}{0.4\textwidth}
  4900. \begin{lstlisting}
  4901. start:
  4902. callq read_int
  4903. movq %rax, tmp7951
  4904. cmpq $1, tmp7951
  4905. je block7952
  4906. movq $0, %rax
  4907. jmp conclusion
  4908. block7952:
  4909. movq $42, %rax
  4910. jmp conclusion
  4911. \end{lstlisting}
  4912. \end{minipage}
  4913. \end{tabular}
  4914. \caption{Merging basic blocks by removing unnecessary jumps.}
  4915. \label{fig:remove-jumps}
  4916. \end{figure}
  4917. \begin{exercise}\normalfont
  4918. Implement a pass named \code{remove-jumps} that merges basic blocks
  4919. into their preceeding basic block, when there is only one preceeding
  4920. block. The pass should translate from psuedo $x86_1$ to pseudo
  4921. $x86_1$ and it should come immediately after
  4922. \code{select-instructions}. Check that \code{remove-jumps}
  4923. accomplishes the goal of merging basic blocks on several test
  4924. programs and check that your compiler passes all of your tests.
  4925. \end{exercise}
  4926. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4927. \chapter{Tuples and Garbage Collection}
  4928. \label{ch:tuples}
  4929. \index{tuple}
  4930. \index{vector}
  4931. \margincomment{\scriptsize To do: challenge assignments: mark-and-sweep,
  4932. add simple structures. \\ --Jeremy}
  4933. \margincomment{\scriptsize To do: look through Andre's code comments for extra
  4934. things to discuss in this chapter. \\ --Jeremy}
  4935. \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  4936. all the IR grammars are spelled out! \\ --Jeremy}
  4937. \margincomment{\scriptsize Introduce has-type, but after flatten, remove it,
  4938. but keep type annotations on vector creation and local variables, function
  4939. parameters, etc. \\ --Jeremy}
  4940. \margincomment{\scriptsize Be more explicit about how to deal with
  4941. the root stack. \\ --Jeremy}
  4942. In this chapter we study the implementation of mutable tuples (called
  4943. ``vectors'' in Racket). This language feature is the first to use the
  4944. computer's \emph{heap}\index{heap} because the lifetime of a Racket tuple is
  4945. indefinite, that is, a tuple lives forever from the programmer's
  4946. viewpoint. Of course, from an implementer's viewpoint, it is important
  4947. to reclaim the space associated with a tuple when it is no longer
  4948. needed, which is why we also study \emph{garbage collection}
  4949. \emph{garbage collection}
  4950. techniques in this chapter.
  4951. Section~\ref{sec:r3} introduces the $R_3$ language including its
  4952. interpreter and type checker. The $R_3$ language extends the $R_2$
  4953. language of Chapter~\ref{ch:bool-types} with vectors and Racket's
  4954. \code{void} value. The reason for including the later is that the
  4955. \code{vector-set!} operation returns a value of type
  4956. \code{Void}\footnote{Racket's \code{Void} type corresponds to what is
  4957. called the \code{Unit} type in the programming languages
  4958. literature. Racket's \code{Void} type is inhabited by a single value
  4959. \code{void} which corresponds to \code{unit} or \code{()} in the
  4960. literature~\citep{Pierce:2002hj}.}.
  4961. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  4962. copying live objects back and forth between two halves of the
  4963. heap. The garbage collector requires coordination with the compiler so
  4964. that it can see all of the \emph{root} pointers, that is, pointers in
  4965. registers or on the procedure call stack.
  4966. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  4967. discuss all the necessary changes and additions to the compiler
  4968. passes, including a new compiler pass named \code{expose-allocation}.
  4969. \section{The $R_3$ Language}
  4970. \label{sec:r3}
  4971. Figure~\ref{fig:r3-concrete-syntax} defines the concrete syntax for
  4972. $R_3$ and Figure~\ref{fig:r3-syntax} defines the abstract syntax. The
  4973. $R_3$ language includes three new forms: \code{vector} for creating a
  4974. tuple, \code{vector-ref} for reading an element of a tuple, and
  4975. \code{vector-set!} for writing to an element of a tuple. The program
  4976. in Figure~\ref{fig:vector-eg} shows the usage of tuples in Racket. We
  4977. create a 3-tuple \code{t} and a 1-tuple that is stored at index $2$ of
  4978. the 3-tuple, demonstrating that tuples are first-class values. The
  4979. element at index $1$ of \code{t} is \code{\#t}, so the ``then'' branch
  4980. of the \key{if} is taken. The element at index $0$ of \code{t} is
  4981. \code{40}, to which we add \code{2}, the element at index $0$ of the
  4982. 1-tuple. So the result of the program is \code{42}.
  4983. \begin{figure}[tbp]
  4984. \centering
  4985. \fbox{
  4986. \begin{minipage}{0.96\textwidth}
  4987. \[
  4988. \begin{array}{lcl}
  4989. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}}
  4990. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}\\
  4991. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  4992. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  4993. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  4994. \mid (\key{and}\;\Exp\;\Exp)
  4995. \mid (\key{or}\;\Exp\;\Exp)
  4996. \mid (\key{not}\;\Exp) } \\
  4997. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  4998. \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  4999. &\mid& (\key{vector}\;\Exp\ldots)
  5000. \mid (\key{vector-ref}\;\Exp\;\Int) \\
  5001. &\mid& (\key{vector-set!}\;\Exp\;\Int\;\Exp)
  5002. \mid (\key{vector-length}\;\Exp) \\
  5003. &\mid& (\key{void}) \mid (\key{has-type}~\Exp~\Type)\\
  5004. R_3 &::=& \Exp
  5005. \end{array}
  5006. \]
  5007. \end{minipage}
  5008. }
  5009. \caption{The concrete syntax of $R_3$, extending $R_2$
  5010. (Figure~\ref{fig:r2-concrete-syntax}).}
  5011. \label{fig:r3-concrete-syntax}
  5012. \end{figure}
  5013. \begin{figure}[tbp]
  5014. \begin{lstlisting}
  5015. (let ([t (vector 40 #t (vector 2))])
  5016. (if (vector-ref t 1)
  5017. (+ (vector-ref t 0)
  5018. (vector-ref (vector-ref t 2) 0))
  5019. 44))
  5020. \end{lstlisting}
  5021. \caption{Example program that creates tuples and reads from them.}
  5022. \label{fig:vector-eg}
  5023. \end{figure}
  5024. \begin{figure}[tp]
  5025. \centering
  5026. \fbox{
  5027. \begin{minipage}{0.96\textwidth}
  5028. \[
  5029. \begin{array}{lcl}
  5030. \itm{op} &::=& \ldots
  5031. \mid \code{vector} \mid \code{vector-ref} \mid \code{vector-set!}
  5032. \mid \code{vector-length} \\
  5033. \Exp &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  5034. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots}
  5035. \mid \BOOL{\itm{bool}}
  5036. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  5037. &\mid& \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP \\
  5038. R_3 &::=& \PROGRAM{\key{'()}}{\Exp}
  5039. \end{array}
  5040. \]
  5041. \end{minipage}
  5042. }
  5043. \caption{The abstract syntax of $R_3$.}
  5044. \label{fig:r3-syntax}
  5045. \end{figure}
  5046. \index{allocate}
  5047. \index{heap allocate}
  5048. Tuples are our first encounter with heap-allocated data, which raises
  5049. several interesting issues. First, variable binding performs a
  5050. shallow-copy when dealing with tuples, which means that different
  5051. variables can refer to the same tuple, that is, different variables
  5052. can be \emph{aliases} for the same entity. Consider the following
  5053. example in which both \code{t1} and \code{t2} refer to the same tuple.
  5054. Thus, the mutation through \code{t2} is visible when referencing the
  5055. tuple from \code{t1}, so the result of this program is \code{42}.
  5056. \index{alias}\index{mutation}
  5057. \begin{center}
  5058. \begin{minipage}{0.96\textwidth}
  5059. \begin{lstlisting}
  5060. (let ([t1 (vector 3 7)])
  5061. (let ([t2 t1])
  5062. (let ([_ (vector-set! t2 0 42)])
  5063. (vector-ref t1 0))))
  5064. \end{lstlisting}
  5065. \end{minipage}
  5066. \end{center}
  5067. The next issue concerns the lifetime of tuples. Of course, they are
  5068. created by the \code{vector} form, but when does their lifetime end?
  5069. Notice that $R_3$ does not include an operation for deleting
  5070. tuples. Furthermore, the lifetime of a tuple is not tied to any notion
  5071. of static scoping. For example, the following program returns
  5072. \code{42} even though the variable \code{w} goes out of scope prior to
  5073. the \code{vector-ref} that reads from the vector it was bound to.
  5074. \begin{center}
  5075. \begin{minipage}{0.96\textwidth}
  5076. \begin{lstlisting}
  5077. (let ([v (vector (vector 44))])
  5078. (let ([x (let ([w (vector 42)])
  5079. (let ([_ (vector-set! v 0 w)])
  5080. 0))])
  5081. (+ x (vector-ref (vector-ref v 0) 0))))
  5082. \end{lstlisting}
  5083. \end{minipage}
  5084. \end{center}
  5085. From the perspective of programmer-observable behavior, tuples live
  5086. forever. Of course, if they really lived forever, then many programs
  5087. would run out of memory.\footnote{The $R_3$ language does not have
  5088. looping or recursive functions, so it is nigh impossible to write a
  5089. program in $R_3$ that will run out of memory. However, we add
  5090. recursive functions in the next Chapter!} A Racket implementation
  5091. must therefore perform automatic garbage collection.
  5092. Figure~\ref{fig:interp-R3} shows the definitional interpreter for the
  5093. $R_3$ language. We define the \code{vector}, \code{vector-ref}, and
  5094. \code{vector-set!} operations for $R_3$ in terms of the corresponding
  5095. operations in Racket. One subtle point is that the \code{vector-set!}
  5096. operation returns the \code{\#<void>} value. The \code{\#<void>} value
  5097. can be passed around just like other values inside an $R_3$ program
  5098. and a \code{\#<void>} value can be compared for equality with another
  5099. \code{\#<void>} value. However, there are no other operations specific
  5100. to the the \code{\#<void>} value in $R_3$. In contrast, Racket defines
  5101. the \code{void?} predicate that returns \code{\#t} when applied to
  5102. \code{\#<void>} and \code{\#f} otherwise.
  5103. \begin{figure}[tbp]
  5104. \begin{lstlisting}
  5105. (define primitives (set ... 'vector 'vector-ref 'vector-set!))
  5106. (define (interp-op op)
  5107. (match op
  5108. ...
  5109. ['vector vector]
  5110. ['vector-ref vector-ref]
  5111. ['vector-set! vector-set!]
  5112. [else (error 'interp-op "unknown operator")]))
  5113. (define (interp-exp env)
  5114. (lambda (e)
  5115. (define recur (interp-exp env))
  5116. (match e
  5117. ...
  5118. )))
  5119. (define (interp-R3 p)
  5120. (match p
  5121. [(Program '() e)
  5122. ((interp-exp '()) e)]
  5123. ))
  5124. \end{lstlisting}
  5125. \caption{Interpreter for the $R_3$ language.}
  5126. \label{fig:interp-R3}
  5127. \end{figure}
  5128. Figure~\ref{fig:type-check-R3} shows the type checker for $R_3$, which
  5129. deserves some explanation. As we see in Section~\ref{sec:GC}, we
  5130. need to know which variables contain pointers into the heap, that is,
  5131. which variables contain vectors. Also, when allocating a vector, we
  5132. need to know which elements of the vector are pointers. We can obtain
  5133. this information during type checking. The type checker in
  5134. Figure~\ref{fig:type-check-R3} not only computes the type of an
  5135. expression, it also wraps every sub-expression $e$ with the form
  5136. $(\key{HasType}~e~T)$, where $T$ is $e$'s type.
  5137. Subsequently, in the \code{uncover-locals} pass
  5138. (Section~\ref{sec:uncover-locals-r3}) this type information is
  5139. propagated to all variables (including the temporaries generated by
  5140. \code{remove-complex-opera*}).
  5141. To create the s-expression for the \code{Vector} type in
  5142. Figure~\ref{fig:type-check-R3}, we use the
  5143. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  5144. operator} \code{,@} to insert the list \code{t*} without its usual
  5145. start and end parentheses. \index{unquote-slicing}
  5146. \begin{figure}[tp]
  5147. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5148. (define (type-check-exp env)
  5149. (lambda (e)
  5150. (define recur (type-check-exp env))
  5151. (match e
  5152. ...
  5153. [(Void) (values (HasType (Void) 'Void) 'Void)]
  5154. [(Prim 'vector es)
  5155. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  5156. (let ([t `(Vector ,@t*)])
  5157. (values (HasType (Prim 'vector e*) t) t))]
  5158. [(Prim 'vector-ref (list e (Int i)))
  5159. (define-values (e^ t) (recur e))
  5160. (match t
  5161. [`(Vector ,ts ...)
  5162. (unless (and (exact-nonnegative-integer? i) (< i (length ts)))
  5163. (error 'type-check-exp "invalid index ~a" i))
  5164. (let ([t (list-ref ts i)])
  5165. (values
  5166. (HasType (Prim 'vector-ref
  5167. (list e^ (HasType (Int i) 'Integer)))
  5168. t)
  5169. t))]
  5170. [else (error "expected a vector in vector-ref, not" t)])]
  5171. [(Prim 'vector-set! (list e (Int i) arg) )
  5172. (define-values (e-vec t-vec) (recur e))
  5173. (define-values (e-arg^ t-arg) (recur arg))
  5174. (match t-vec
  5175. [`(Vector ,ts ...)
  5176. (unless (and (exact-nonnegative-integer? i)
  5177. (i . < . (length ts)))
  5178. (error 'type-check-exp "invalid index ~a" i))
  5179. (unless (type-equal? (list-ref ts i) t-arg)
  5180. (error 'type-check-exp "type mismatch in vector-set! ~a ~a"
  5181. (list-ref ts i) t-arg))
  5182. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  5183. [else (error 'type-check-exp
  5184. "expected a vector in vector-set!, not ~a"
  5185. t-vec)])]
  5186. [(Prim 'vector-length (list e))
  5187. (define-values (e^ t) (recur e))
  5188. (match t
  5189. [`(Vector ,ts ...)
  5190. (values (Prim 'vector-length (list e^)) 'Integer)]
  5191. [else (error 'type-check-exp
  5192. "expected a vector in vector-lenfth, not ~a" t)])]
  5193. [(Prim 'eq? (list e1 e2))
  5194. (define-values (e1^ T1) (recur e1))
  5195. (define-values (e2^ T2) (recur e2))
  5196. (unless (equal? T1 T2)
  5197. (error "arguments of eq? must have the same type, but are not"
  5198. (list T1 T2)))
  5199. (values (HasType (Prim 'eq? (list e1^ e2^)) 'Boolean) 'Boolean)]
  5200. ...
  5201. )))
  5202. \end{lstlisting}
  5203. \caption{Type checker for the $R_3$ language.}
  5204. \label{fig:type-check-R3}
  5205. \end{figure}
  5206. \section{Garbage Collection}
  5207. \label{sec:GC}
  5208. Here we study a relatively simple algorithm for garbage collection
  5209. that is the basis of state-of-the-art garbage
  5210. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  5211. particular, we describe a two-space copying
  5212. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  5213. perform the
  5214. copy~\citep{Cheney:1970aa}.
  5215. \index{copying collector}
  5216. \index{two-space copying collector}
  5217. Figure~\ref{fig:copying-collector} gives a
  5218. coarse-grained depiction of what happens in a two-space collector,
  5219. showing two time steps, prior to garbage collection (on the top) and
  5220. after garbage collection (on the bottom). In a two-space collector,
  5221. the heap is divided into two parts named the FromSpace and the
  5222. ToSpace. Initially, all allocations go to the FromSpace until there is
  5223. not enough room for the next allocation request. At that point, the
  5224. garbage collector goes to work to make more room.
  5225. \index{ToSpace}
  5226. \index{FromSpace}
  5227. The garbage collector must be careful not to reclaim tuples that will
  5228. be used by the program in the future. Of course, it is impossible in
  5229. general to predict what a program will do, but we can over approximate
  5230. the will-be-used tuples by preserving all tuples that could be
  5231. accessed by \emph{any} program given the current computer state. A
  5232. program could access any tuple whose address is in a register or on
  5233. the procedure call stack. These addresses are called the \emph{root
  5234. set}\index{root set}. In addition, a program could access any tuple that is
  5235. transitively reachable from the root set. Thus, it is safe for the
  5236. garbage collector to reclaim the tuples that are not reachable in this
  5237. way.
  5238. So the goal of the garbage collector is twofold:
  5239. \begin{enumerate}
  5240. \item preserve all tuple that are reachable from the root set via a
  5241. path of pointers, that is, the \emph{live} tuples, and
  5242. \item reclaim the memory of everything else, that is, the
  5243. \emph{garbage}.
  5244. \end{enumerate}
  5245. A copying collector accomplishes this by copying all of the live
  5246. objects from the FromSpace into the ToSpace and then performs a slight
  5247. of hand, treating the ToSpace as the new FromSpace and the old
  5248. FromSpace as the new ToSpace. In the example of
  5249. Figure~\ref{fig:copying-collector}, there are three pointers in the
  5250. root set, one in a register and two on the stack. All of the live
  5251. objects have been copied to the ToSpace (the right-hand side of
  5252. Figure~\ref{fig:copying-collector}) in a way that preserves the
  5253. pointer relationships. For example, the pointer in the register still
  5254. points to a 2-tuple whose first element is a 3-tuple and whose second
  5255. element is a 2-tuple. There are four tuples that are not reachable
  5256. from the root set and therefore do not get copied into the ToSpace.
  5257. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  5258. created by a well-typed program in $R_3$ because it contains a
  5259. cycle. However, creating cycles will be possible once we get to $R_6$.
  5260. We design the garbage collector to deal with cycles to begin with so
  5261. we will not need to revisit this issue.
  5262. \begin{figure}[tbp]
  5263. \centering
  5264. \includegraphics[width=\textwidth]{figs/copy-collect-1} \\[5ex]
  5265. \includegraphics[width=\textwidth]{figs/copy-collect-2}
  5266. \caption{A copying collector in action.}
  5267. \label{fig:copying-collector}
  5268. \end{figure}
  5269. There are many alternatives to copying collectors (and their bigger
  5270. siblings, the generational collectors) when its comes to garbage
  5271. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  5272. reference counting~\citep{Collins:1960aa}. The strengths of copying
  5273. collectors are that allocation is fast (just a comparison and pointer
  5274. increment), there is no fragmentation, cyclic garbage is collected,
  5275. and the time complexity of collection only depends on the amount of
  5276. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  5277. main disadvantages of a two-space copying collector is that it uses a
  5278. lot of space and takes a long time to perform the copy, though these
  5279. problems are ameliorated in generational collectors. Racket and
  5280. Scheme programs tend to allocate many small objects and generate a lot
  5281. of garbage, so copying and generational collectors are a good fit.
  5282. Garbage collection is an active research topic, especially concurrent
  5283. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  5284. developing new techniques and revisiting old
  5285. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  5286. meet every year at the International Symposium on Memory Management to
  5287. present these findings.
  5288. \subsection{Graph Copying via Cheney's Algorithm}
  5289. \label{sec:cheney}
  5290. \index{Cheney's algorithm}
  5291. Let us take a closer look at the copying of the live objects. The
  5292. allocated objects and pointers can be viewed as a graph and we need to
  5293. copy the part of the graph that is reachable from the root set. To
  5294. make sure we copy all of the reachable vertices in the graph, we need
  5295. an exhaustive graph traversal algorithm, such as depth-first search or
  5296. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  5297. such algorithms take into account the possibility of cycles by marking
  5298. which vertices have already been visited, so as to ensure termination
  5299. of the algorithm. These search algorithms also use a data structure
  5300. such as a stack or queue as a to-do list to keep track of the vertices
  5301. that need to be visited. We use breadth-first search and a trick
  5302. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  5303. and copying tuples into the ToSpace.
  5304. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  5305. copy progresses. The queue is represented by a chunk of contiguous
  5306. memory at the beginning of the ToSpace, using two pointers to track
  5307. the front and the back of the queue. The algorithm starts by copying
  5308. all tuples that are immediately reachable from the root set into the
  5309. ToSpace to form the initial queue. When we copy a tuple, we mark the
  5310. old tuple to indicate that it has been visited. We discuss how this
  5311. marking is accomplish in Section~\ref{sec:data-rep-gc}. Note that any
  5312. pointers inside the copied tuples in the queue still point back to the
  5313. FromSpace. Once the initial queue has been created, the algorithm
  5314. enters a loop in which it repeatedly processes the tuple at the front
  5315. of the queue and pops it off the queue. To process a tuple, the
  5316. algorithm copies all the tuple that are directly reachable from it to
  5317. the ToSpace, placing them at the back of the queue. The algorithm then
  5318. updates the pointers in the popped tuple so they point to the newly
  5319. copied tuples.
  5320. \begin{figure}[tbp]
  5321. \centering \includegraphics[width=0.9\textwidth]{figs/cheney}
  5322. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  5323. \label{fig:cheney}
  5324. \end{figure}
  5325. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  5326. tuple whose second element is $42$ to the back of the queue. The other
  5327. pointer goes to a tuple that has already been copied, so we do not
  5328. need to copy it again, but we do need to update the pointer to the new
  5329. location. This can be accomplished by storing a \emph{forwarding
  5330. pointer} to the new location in the old tuple, back when we initially
  5331. copied the tuple into the ToSpace. This completes one step of the
  5332. algorithm. The algorithm continues in this way until the front of the
  5333. queue is empty, that is, until the front catches up with the back.
  5334. \subsection{Data Representation}
  5335. \label{sec:data-rep-gc}
  5336. The garbage collector places some requirements on the data
  5337. representations used by our compiler. First, the garbage collector
  5338. needs to distinguish between pointers and other kinds of data. There
  5339. are several ways to accomplish this.
  5340. \begin{enumerate}
  5341. \item Attached a tag to each object that identifies what type of
  5342. object it is~\citep{McCarthy:1960dz}.
  5343. \item Store different types of objects in different
  5344. regions~\citep{Steele:1977ab}.
  5345. \item Use type information from the program to either generate
  5346. type-specific code for collecting or to generate tables that can
  5347. guide the
  5348. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  5349. \end{enumerate}
  5350. Dynamically typed languages, such as Lisp, need to tag objects
  5351. anyways, so option 1 is a natural choice for those languages.
  5352. However, $R_3$ is a statically typed language, so it would be
  5353. unfortunate to require tags on every object, especially small and
  5354. pervasive objects like integers and Booleans. Option 3 is the
  5355. best-performing choice for statically typed languages, but comes with
  5356. a relatively high implementation complexity. To keep this chapter
  5357. within a 2-week time budget, we recommend a combination of options 1
  5358. and 2, using separate strategies for the stack and the heap.
  5359. Regarding the stack, we recommend using a separate stack for pointers,
  5360. which we call a \emph{root stack}\index{root stack} (a.k.a. ``shadow
  5361. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  5362. is, when a local variable needs to be spilled and is of type
  5363. \code{(Vector $\Type_1 \ldots \Type_n$)}, then we put it on the root
  5364. stack instead of the normal procedure call stack. Furthermore, we
  5365. always spill vector-typed variables if they are live during a call to
  5366. the collector, thereby ensuring that no pointers are in registers
  5367. during a collection. Figure~\ref{fig:shadow-stack} reproduces the
  5368. example from Figure~\ref{fig:copying-collector} and contrasts it with
  5369. the data layout using a root stack. The root stack contains the two
  5370. pointers from the regular stack and also the pointer in the second
  5371. register.
  5372. \begin{figure}[tbp]
  5373. \centering \includegraphics[width=0.60\textwidth]{figs/root-stack}
  5374. \caption{Maintaining a root stack to facilitate garbage collection.}
  5375. \label{fig:shadow-stack}
  5376. \end{figure}
  5377. The problem of distinguishing between pointers and other kinds of data
  5378. also arises inside of each tuple on the heap. We solve this problem by
  5379. attaching a tag, an extra 64-bits, to each
  5380. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  5381. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  5382. that we have drawn the bits in a big-endian way, from right-to-left,
  5383. with bit location 0 (the least significant bit) on the far right,
  5384. which corresponds to the direction of the x86 shifting instructions
  5385. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  5386. is dedicated to specifying which elements of the tuple are pointers,
  5387. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  5388. indicates there is a pointer and a 0 bit indicates some other kind of
  5389. data. The pointer mask starts at bit location 7. We have limited
  5390. tuples to a maximum size of 50 elements, so we just need 50 bits for
  5391. the pointer mask. The tag also contains two other pieces of
  5392. information. The length of the tuple (number of elements) is stored in
  5393. bits location 1 through 6. Finally, the bit at location 0 indicates
  5394. whether the tuple has yet to be copied to the ToSpace. If the bit has
  5395. value 1, then this tuple has not yet been copied. If the bit has
  5396. value 0 then the entire tag is a forwarding pointer. (The lower 3 bits
  5397. of a pointer are always zero anyways because our tuples are 8-byte
  5398. aligned.)
  5399. \begin{figure}[tbp]
  5400. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  5401. \caption{Representation of tuples in the heap.}
  5402. \label{fig:tuple-rep}
  5403. \end{figure}
  5404. \subsection{Implementation of the Garbage Collector}
  5405. \label{sec:organize-gz}
  5406. \index{prelude}
  5407. An implementation of the copying collector is provided in the
  5408. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  5409. interface to the garbage collector that is used by the compiler. The
  5410. \code{initialize} function creates the FromSpace, ToSpace, and root
  5411. stack and should be called in the prelude of the \code{main}
  5412. function. The arguments of \code{initialize} are the root stack size
  5413. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  5414. good choice for both. The \code{initialize} function puts the address
  5415. of the beginning of the FromSpace into the global variable
  5416. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  5417. the address that is 1-past the last element of the FromSpace. (We use
  5418. half-open intervals to represent chunks of
  5419. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  5420. points to the first element of the root stack.
  5421. As long as there is room left in the FromSpace, your generated code
  5422. can allocate tuples simply by moving the \code{free\_ptr} forward.
  5423. %
  5424. The amount of room left in FromSpace is the difference between the
  5425. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  5426. function should be called when there is not enough room left in the
  5427. FromSpace for the next allocation. The \code{collect} function takes
  5428. a pointer to the current top of the root stack (one past the last item
  5429. that was pushed) and the number of bytes that need to be
  5430. allocated. The \code{collect} function performs the copying collection
  5431. and leaves the heap in a state such that the next allocation will
  5432. succeed.
  5433. \begin{figure}[tbp]
  5434. \begin{lstlisting}
  5435. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  5436. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  5437. int64_t* free_ptr;
  5438. int64_t* fromspace_begin;
  5439. int64_t* fromspace_end;
  5440. int64_t** rootstack_begin;
  5441. \end{lstlisting}
  5442. \caption{The compiler's interface to the garbage collector.}
  5443. \label{fig:gc-header}
  5444. \end{figure}
  5445. %% \begin{exercise}
  5446. %% In the file \code{runtime.c} you will find the implementation of
  5447. %% \code{initialize} and a partial implementation of \code{collect}.
  5448. %% The \code{collect} function calls another function, \code{cheney},
  5449. %% to perform the actual copy, and that function is left to the reader
  5450. %% to implement. The following is the prototype for \code{cheney}.
  5451. %% \begin{lstlisting}
  5452. %% static void cheney(int64_t** rootstack_ptr);
  5453. %% \end{lstlisting}
  5454. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  5455. %% rootstack (which is an array of pointers). The \code{cheney} function
  5456. %% also communicates with \code{collect} through the global
  5457. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  5458. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  5459. %% the ToSpace:
  5460. %% \begin{lstlisting}
  5461. %% static int64_t* tospace_begin;
  5462. %% static int64_t* tospace_end;
  5463. %% \end{lstlisting}
  5464. %% The job of the \code{cheney} function is to copy all the live
  5465. %% objects (reachable from the root stack) into the ToSpace, update
  5466. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  5467. %% update the root stack so that it points to the objects in the
  5468. %% ToSpace, and finally to swap the global pointers for the FromSpace
  5469. %% and ToSpace.
  5470. %% \end{exercise}
  5471. %% \section{Compiler Passes}
  5472. %% \label{sec:code-generation-gc}
  5473. The introduction of garbage collection has a non-trivial impact on our
  5474. compiler passes. We introduce two new compiler passes named
  5475. \code{expose-allocation} and \code{uncover-locals}. We make
  5476. significant changes to \code{select-instructions},
  5477. \code{build-interference}, \code{allocate-registers}, and
  5478. \code{print-x86} and make minor changes in severl more passes. The
  5479. following program will serve as our running example. It creates two
  5480. tuples, one nested inside the other. Both tuples have length one. The
  5481. program accesses the element in the inner tuple tuple via two vector
  5482. references.
  5483. % tests/s2_17.rkt
  5484. \begin{lstlisting}
  5485. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  5486. \end{lstlisting}
  5487. \section{Shrink}
  5488. \label{sec:shrink-R3}
  5489. Recall that the \code{shrink} pass translates the primitives operators
  5490. into a smaller set of primitives. Because this pass comes after type
  5491. checking, but before the passes that require the type information in
  5492. the \code{HasType} AST nodes, the \code{shrink} pass must be modified
  5493. to wrap \code{HasType} around each AST node that it generates.
  5494. \section{Expose Allocation}
  5495. \label{sec:expose-allocation}
  5496. The pass \code{expose-allocation} lowers the \code{vector} creation
  5497. form into a conditional call to the collector followed by the
  5498. allocation. We choose to place the \code{expose-allocation} pass
  5499. before \code{remove-complex-opera*} because the code generated by
  5500. \code{expose-allocation} contains complex operands. We also place
  5501. \code{expose-allocation} before \code{explicate-control} because
  5502. \code{expose-allocation} introduces new variables using \code{let},
  5503. but \code{let} is gone after \code{explicate-control}.
  5504. The output of \code{expose-allocation} is a language $R'_3$ that
  5505. extends $R_3$ with the three new forms that we use in the translation
  5506. of the \code{vector} form.
  5507. \[
  5508. \begin{array}{lcl}
  5509. \Exp &::=& \cdots
  5510. \mid (\key{collect} \,\itm{int})
  5511. \mid (\key{allocate} \,\itm{int}\,\itm{type})
  5512. \mid (\key{global-value} \,\itm{name})
  5513. \end{array}
  5514. \]
  5515. The $(\key{collect}\,n)$ form runs the garbage collector, requesting
  5516. $n$ bytes. It will become a call to the \code{collect} function in
  5517. \code{runtime.c} in \code{select-instructions}. The
  5518. $(\key{allocate}\,n\,T)$ form creates an tuple of $n$ elements.
  5519. \index{allocate}
  5520. The $T$ parameter is the type of the tuple: \code{(Vector $\Type_1 \ldots
  5521. \Type_n$)} where $\Type_i$ is the type of the $i$th element in the
  5522. tuple. The $(\key{global-value}\,\itm{name})$ form reads the value of
  5523. a global variable, such as \code{free\_ptr}.
  5524. In the following, we show the transformation for the \code{vector}
  5525. form into 1) a sequence of let-bindings for the initializing
  5526. expressions, 2) a conditional call to \code{collect}, 3) a call to
  5527. \code{allocate}, and 4) the initialization of the vector. In the
  5528. following, \itm{len} refers to the length of the vector and
  5529. \itm{bytes} is how many total bytes need to be allocated for the
  5530. vector, which is 8 for the tag plus \itm{len} times 8.
  5531. \begin{lstlisting}
  5532. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  5533. |$\Longrightarrow$|
  5534. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  5535. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  5536. (global-value fromspace_end))
  5537. (void)
  5538. (collect |\itm{bytes}|))])
  5539. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  5540. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  5541. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  5542. |$v$|) ... )))) ...)
  5543. \end{lstlisting}
  5544. In the above, we suppressed all of the \code{has-type} forms in the
  5545. output for the sake of readability. The placement of the initializing
  5546. expressions $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} and the
  5547. sequence of \code{vector-set!} is important, as those expressions may
  5548. trigger garbage collection and we cannot have an allocated but
  5549. uninitialized tuple on the heap during a collection.
  5550. Figure~\ref{fig:expose-alloc-output} shows the output of the
  5551. \code{expose-allocation} pass on our running example.
  5552. \begin{figure}[tbp]
  5553. % tests/s2_17.rkt
  5554. \begin{lstlisting}
  5555. (vector-ref
  5556. (vector-ref
  5557. (let ([vecinit7976
  5558. (let ([vecinit7972 42])
  5559. (let ([collectret7974
  5560. (if (< (+ (global-value free_ptr) 16)
  5561. (global-value fromspace_end))
  5562. (void)
  5563. (collect 16)
  5564. )])
  5565. (let ([alloc7971 (allocate 1 (Vector Integer))])
  5566. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  5567. alloc7971)
  5568. )
  5569. )
  5570. )
  5571. ])
  5572. (let ([collectret7978
  5573. (if (< (+ (global-value free_ptr) 16)
  5574. (global-value fromspace_end))
  5575. (void)
  5576. (collect 16)
  5577. )])
  5578. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  5579. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  5580. alloc7975)
  5581. )
  5582. )
  5583. )
  5584. 0)
  5585. 0)
  5586. \end{lstlisting}
  5587. \caption{Output of the \code{expose-allocation} pass, minus
  5588. all of the \code{has-type} forms.}
  5589. \label{fig:expose-alloc-output}
  5590. \end{figure}
  5591. \section{Remove Complex Operands}
  5592. \label{sec:remove-complex-opera-R3}
  5593. The new forms \code{collect}, \code{allocate}, and \code{global-value}
  5594. should all be treated as complex operands. A new case for
  5595. \code{HasType} is needed and the case for \code{Prim} needs to be
  5596. handled carefully to prevent the \code{Prim} node from being separated
  5597. from its enclosing \code{HasType}.
  5598. \section{Explicate Control and the $C_2$ language}
  5599. \label{sec:explicate-control-r3}
  5600. \begin{figure}[tbp]
  5601. \fbox{
  5602. \begin{minipage}{0.96\textwidth}
  5603. \small
  5604. \[
  5605. \begin{array}{lcl}
  5606. \Atm &::=& \gray{ \Int \mid \Var \mid \itm{bool} } \\
  5607. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5608. \Exp &::=& \gray{ \Atm \mid \key{(read)} \mid \key{(-}~\Atm\key{)} \mid \key{(+}~\Atm~\Atm\key{)} } \\
  5609. &\mid& \gray{ \LP \key{not}~\Atm \RP \mid \LP \itm{cmp}~\Atm~\Atm\RP } \\
  5610. &\mid& \LP \key{allocate}~\Int~\Type \RP \\
  5611. &\mid& (\key{vector-ref}\;\Atm\;\Int) \mid (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  5612. &\mid& \LP \key{global-value}~\Var \RP \mid \LP \key{void} \RP \\
  5613. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \mid \LP\key{collect}~\Int \RP\\
  5614. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \mid \Stmt~\Tail }
  5615. \mid \gray{ \key{goto}~\itm{label}\key{;} }\\
  5616. &\mid& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  5617. C_2 & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  5618. \end{array}
  5619. \]
  5620. \end{minipage}
  5621. }
  5622. \caption{The concrete syntax of the $C_2$ intermediate language.}
  5623. \label{fig:c2-concrete-syntax}
  5624. \end{figure}
  5625. \begin{figure}[tp]
  5626. \fbox{
  5627. \begin{minipage}{0.96\textwidth}
  5628. \small
  5629. \[
  5630. \begin{array}{lcl}
  5631. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  5632. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  5633. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  5634. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  5635. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  5636. &\mid& (\key{Allocate} \,\itm{int}\,\itm{type}) \\
  5637. &\mid& \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} \\
  5638. &\mid& (\key{Prim}~\key{'vector-set!}\,(\key{list}\,\Atm\,\INT{\Int}\,\Atm))\\
  5639. &\mid& (\key{GlobalValue} \,\Var) \mid (\key{Void})\\
  5640. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp} }
  5641. \mid (\key{Collect} \,\itm{int}) \\
  5642. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  5643. \mid \GOTO{\itm{label}} } \\
  5644. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  5645. C_2 & ::= & \gray{ \PROGRAM{\itm{info}}{\CFG{(\itm{label}\,\key{.}\,\Tail)\ldots}} }
  5646. \end{array}
  5647. \]
  5648. \end{minipage}
  5649. }
  5650. \caption{The abstract syntax of $C_2$, extending $C_1$
  5651. (Figure~\ref{fig:c1-syntax}).}
  5652. \label{fig:c2-syntax}
  5653. \end{figure}
  5654. The output of \code{explicate-control} is a program in the
  5655. intermediate language $C_2$, whose concrete syntax is defined in
  5656. Figure~\ref{fig:c2-concrete-syntax} and whose abstract syntax is
  5657. defined in Figure~\ref{fig:c2-syntax}. The new forms of $C_2$ include
  5658. the \key{allocate}, \key{vector-ref}, and \key{vector-set!}, and
  5659. \key{global-value} expressions and the \code{collect} statement. The
  5660. \code{explicate-control} pass can treat these new forms much like the
  5661. other forms.
  5662. \section{Uncover Locals}
  5663. \label{sec:uncover-locals-r3}
  5664. Recall that the \code{explicate-control} function collects all of the
  5665. local variables so that it can store them in the $\itm{info}$ field of
  5666. the \code{Program} structure. Also recall that we need to know the
  5667. types of all the local variables for purposes of identifying the root
  5668. set for the garbage collector. Thus, we create a pass named
  5669. \code{uncover-locals} to collect not just the variables but the
  5670. variables and their types in the form of an alist. Thanks to the
  5671. \code{HasType} nodes, the types are readily available at every
  5672. assignment to a variable. We recommend storing the resulting alist in
  5673. the $\itm{info}$ field of the program, associated with the
  5674. \code{locals} key. Figure~\ref{fig:uncover-locals-r3} lists the output
  5675. of the \code{uncover-locals} pass on the running example.
  5676. \begin{figure}[tbp]
  5677. % tests/s2_17.rkt
  5678. \begin{lstlisting}
  5679. locals:
  5680. vecinit7976 : '(Vector Integer), tmp7980 : 'Integer,
  5681. alloc7975 : '(Vector (Vector Integer)), tmp7983 : 'Integer,
  5682. collectret7974 : 'Void, initret7977 : 'Void,
  5683. collectret7978 : 'Void, tmp7985 : '(Vector Integer),
  5684. tmp7984 : 'Integer, tmp7979 : 'Integer, tmp7982 : 'Integer,
  5685. alloc7971 : '(Vector Integer), tmp7981 : 'Integer,
  5686. vecinit7972 : 'Integer, initret7973 : 'Void,
  5687. block91:
  5688. (collect 16)
  5689. goto block89;
  5690. block90:
  5691. collectret7974 = (void);
  5692. goto block89;
  5693. block89:
  5694. alloc7971 = (allocate 1 (Vector Integer));
  5695. initret7973 = (vector-set! alloc7971 0 vecinit7972);
  5696. vecinit7976 = alloc7971;
  5697. tmp7982 = (global-value free_ptr);
  5698. tmp7983 = (+ tmp7982 16);
  5699. tmp7984 = (global-value fromspace_end);
  5700. if (< tmp7983 tmp7984) then
  5701. goto block87;
  5702. else
  5703. goto block88;
  5704. block88:
  5705. (collect 16)
  5706. goto block86;
  5707. block87:
  5708. collectret7978 = (void);
  5709. goto block86;
  5710. block86:
  5711. alloc7975 = (allocate 1 (Vector (Vector Integer)));
  5712. initret7977 = (vector-set! alloc7975 0 vecinit7976);
  5713. tmp7985 = (vector-ref alloc7975 0);
  5714. return (vector-ref tmp7985 0);
  5715. start:
  5716. vecinit7972 = 42;
  5717. tmp7979 = (global-value free_ptr);
  5718. tmp7980 = (+ tmp7979 16);
  5719. tmp7981 = (global-value fromspace_end);
  5720. if (< tmp7980 tmp7981) then
  5721. goto block90;
  5722. else
  5723. goto block91;
  5724. \end{lstlisting}
  5725. \caption{Output of \code{uncover-locals} for the running example.}
  5726. \label{fig:uncover-locals-r3}
  5727. \end{figure}
  5728. \clearpage
  5729. \section{Select Instructions and the x86$_2$ Language}
  5730. \label{sec:select-instructions-gc}
  5731. \index{instruction selection}
  5732. %% void (rep as zero)
  5733. %% allocate
  5734. %% collect (callq collect)
  5735. %% vector-ref
  5736. %% vector-set!
  5737. %% global (postpone)
  5738. In this pass we generate x86 code for most of the new operations that
  5739. were needed to compile tuples, including \code{Allocate},
  5740. \code{Collect}, \code{vector-ref}, \code{vector-set!}, and
  5741. \code{void}. We compile \code{GlobalValue} to \code{Global} because
  5742. the later has a different concrete syntax (see
  5743. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}).
  5744. \index{x86}
  5745. The \code{vector-ref} and \code{vector-set!} forms translate into
  5746. \code{movq} instructions. (The plus one in the offset is to get past
  5747. the tag at the beginning of the tuple representation.)
  5748. \begin{lstlisting}
  5749. |$\itm{lhs}$| = (vector-ref |$\itm{vec}$| |$n$|);
  5750. |$\Longrightarrow$|
  5751. movq |$\itm{vec}'$|, %r11
  5752. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  5753. |$\itm{lhs}$| = (vector-set! |$\itm{vec}$| |$n$| |$\itm{arg}$|);
  5754. |$\Longrightarrow$|
  5755. movq |$\itm{vec}'$|, %r11
  5756. movq |$\itm{arg}'$|, |$8(n+1)$|(%r11)
  5757. movq $0, |$\itm{lhs'}$|
  5758. \end{lstlisting}
  5759. The $\itm{lhs}'$, $\itm{vec}'$, and $\itm{arg}'$ are obtained by
  5760. translating $\itm{vec}$ and $\itm{arg}$ to x86. The move of $\itm{vec}'$ to
  5761. register \code{r11} ensures that offset expression
  5762. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  5763. removing \code{r11} from consideration by the register allocating.
  5764. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  5765. \code{rax}. Then the generated code for \code{vector-set!} would be
  5766. \begin{lstlisting}
  5767. movq |$\itm{vec}'$|, %rax
  5768. movq |$\itm{arg}'$|, |$8(n+1)$|(%rax)
  5769. movq $0, |$\itm{lhs}'$|
  5770. \end{lstlisting}
  5771. Next, suppose that $\itm{arg}'$ ends up as a stack location, so
  5772. \code{patch-instructions} would insert a move through \code{rax}
  5773. as follows.
  5774. \begin{lstlisting}
  5775. movq |$\itm{vec}'$|, %rax
  5776. movq |$\itm{arg}'$|, %rax
  5777. movq %rax, |$8(n+1)$|(%rax)
  5778. movq $0, |$\itm{lhs}'$|
  5779. \end{lstlisting}
  5780. But the above sequence of instructions does not work because we're
  5781. trying to use \code{rax} for two different values ($\itm{vec}'$ and
  5782. $\itm{arg}'$) at the same time!
  5783. We compile the \code{allocate} form to operations on the
  5784. \code{free\_ptr}, as shown below. The address in the \code{free\_ptr}
  5785. is the next free address in the FromSpace, so we copy it into
  5786. \code{r11} and then move it forward by enough space for the tuple
  5787. being allocated, which is $8(\itm{len}+1)$ bytes because each element
  5788. is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  5789. initialize the \itm{tag} and finally copy the address in \code{r11} to
  5790. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  5791. tag is organized. We recommend using the Racket operations
  5792. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  5793. during compilation. The type annotation in the \code{vector} form is
  5794. used to determine the pointer mask region of the tag.
  5795. \begin{lstlisting}
  5796. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  5797. |$\Longrightarrow$|
  5798. movq free_ptr(%rip), %r11
  5799. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  5800. movq $|$\itm{tag}$|, 0(%r11)
  5801. movq %r11, |$\itm{lhs}'$|
  5802. \end{lstlisting}
  5803. The \code{collect} form is compiled to a call to the \code{collect}
  5804. function in the runtime. The arguments to \code{collect} are 1) the
  5805. top of the root stack and 2) the number of bytes that need to be
  5806. allocated. We use another dedicated register, \code{r15}, to
  5807. store the pointer to the top of the root stack. So \code{r15} is not
  5808. available for use by the register allocator.
  5809. \begin{lstlisting}
  5810. (collect |$\itm{bytes}$|)
  5811. |$\Longrightarrow$|
  5812. movq %r15, %rdi
  5813. movq $|\itm{bytes}|, %rsi
  5814. callq collect
  5815. \end{lstlisting}
  5816. \begin{figure}[tp]
  5817. \fbox{
  5818. \begin{minipage}{0.96\textwidth}
  5819. \[
  5820. \begin{array}{lcl}
  5821. \Arg &::=& \gray{ \key{\$}\Int \mid \key{\%}\Reg \mid \Int\key{(}\key{\%}\Reg\key{)} \mid \key{\%}\itm{bytereg} } \mid \Var \key{(\%rip)} \\
  5822. x86_1 &::= & \gray{ \key{.globl main} }\\
  5823. & & \gray{ \key{main:} \; \Instr\ldots }
  5824. \end{array}
  5825. \]
  5826. \end{minipage}
  5827. }
  5828. \caption{The concrete syntax of x86$_2$ (extends x86$_1$ of Figure~\ref{fig:x86-1-concrete}).}
  5829. \label{fig:x86-2-concrete}
  5830. \end{figure}
  5831. \begin{figure}[tp]
  5832. \fbox{
  5833. \begin{minipage}{0.96\textwidth}
  5834. \small
  5835. \[
  5836. \begin{array}{lcl}
  5837. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  5838. \mid \BYTEREG{\Reg}} \\
  5839. &\mid& (\key{Global}~\Var) \\
  5840. x86_2 &::= & \gray{ \PROGRAM{\itm{info}}{\CFG{\key{(}\itm{label} \,\key{.}\, \Block \key{)}\ldots}} }
  5841. \end{array}
  5842. \]
  5843. \end{minipage}
  5844. }
  5845. \caption{The abstract syntax of x86$_2$ (extends x86$_1$ of Figure~\ref{fig:x86-1}).}
  5846. \label{fig:x86-2}
  5847. \end{figure}
  5848. The concrete and abstract syntax of the $x86_2$ language is defined in
  5849. Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It differs from
  5850. x86$_1$ just in the addition of the form for global variables.
  5851. %
  5852. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  5853. \code{select-instructions} pass on the running example.
  5854. \begin{figure}[tbp]
  5855. \centering
  5856. % tests/s2_17.rkt
  5857. \begin{minipage}[t]{0.5\textwidth}
  5858. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5859. block35:
  5860. movq free_ptr(%rip), alloc9024
  5861. addq $16, free_ptr(%rip)
  5862. movq alloc9024, %r11
  5863. movq $131, 0(%r11)
  5864. movq alloc9024, %r11
  5865. movq vecinit9025, 8(%r11)
  5866. movq $0, initret9026
  5867. movq alloc9024, %r11
  5868. movq 8(%r11), tmp9034
  5869. movq tmp9034, %r11
  5870. movq 8(%r11), %rax
  5871. jmp conclusion
  5872. block36:
  5873. movq $0, collectret9027
  5874. jmp block35
  5875. block38:
  5876. movq free_ptr(%rip), alloc9020
  5877. addq $16, free_ptr(%rip)
  5878. movq alloc9020, %r11
  5879. movq $3, 0(%r11)
  5880. movq alloc9020, %r11
  5881. movq vecinit9021, 8(%r11)
  5882. movq $0, initret9022
  5883. movq alloc9020, vecinit9025
  5884. movq free_ptr(%rip), tmp9031
  5885. movq tmp9031, tmp9032
  5886. addq $16, tmp9032
  5887. movq fromspace_end(%rip), tmp9033
  5888. cmpq tmp9033, tmp9032
  5889. jl block36
  5890. jmp block37
  5891. block37:
  5892. movq %r15, %rdi
  5893. movq $16, %rsi
  5894. callq 'collect
  5895. jmp block35
  5896. block39:
  5897. movq $0, collectret9023
  5898. jmp block38
  5899. \end{lstlisting}
  5900. \end{minipage}
  5901. \begin{minipage}[t]{0.45\textwidth}
  5902. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5903. start:
  5904. movq $42, vecinit9021
  5905. movq free_ptr(%rip), tmp9028
  5906. movq tmp9028, tmp9029
  5907. addq $16, tmp9029
  5908. movq fromspace_end(%rip), tmp9030
  5909. cmpq tmp9030, tmp9029
  5910. jl block39
  5911. jmp block40
  5912. block40:
  5913. movq %r15, %rdi
  5914. movq $16, %rsi
  5915. callq 'collect
  5916. jmp block38
  5917. \end{lstlisting}
  5918. \end{minipage}
  5919. \caption{Output of the \code{select-instructions} pass.}
  5920. \label{fig:select-instr-output-gc}
  5921. \end{figure}
  5922. \clearpage
  5923. \section{Register Allocation}
  5924. \label{sec:reg-alloc-gc}
  5925. \index{register allocation}
  5926. As discussed earlier in this chapter, the garbage collector needs to
  5927. access all the pointers in the root set, that is, all variables that
  5928. are vectors. It will be the responsibility of the register allocator
  5929. to make sure that:
  5930. \begin{enumerate}
  5931. \item the root stack is used for spilling vector-typed variables, and
  5932. \item if a vector-typed variable is live during a call to the
  5933. collector, it must be spilled to ensure it is visible to the
  5934. collector.
  5935. \end{enumerate}
  5936. The later responsibility can be handled during construction of the
  5937. interference graph, by adding interference edges between the call-live
  5938. vector-typed variables and all the callee-saved registers. (They
  5939. already interfere with the caller-saved registers.) The type
  5940. information for variables is in the \code{Program} form, so we
  5941. recommend adding another parameter to the \code{build-interference}
  5942. function to communicate this alist.
  5943. The spilling of vector-typed variables to the root stack can be
  5944. handled after graph coloring, when choosing how to assign the colors
  5945. (integers) to registers and stack locations. The \code{Program} output
  5946. of this pass changes to also record the number of spills to the root
  5947. stack.
  5948. % build-interference
  5949. %
  5950. % callq
  5951. % extra parameter for var->type assoc. list
  5952. % update 'program' and 'if'
  5953. % allocate-registers
  5954. % allocate spilled vectors to the rootstack
  5955. % don't change color-graph
  5956. \section{Print x86}
  5957. \label{sec:print-x86-gc}
  5958. \index{prelude}\index{conclusion}
  5959. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  5960. \code{print-x86} pass on the running example. In the prelude and
  5961. conclusion of the \code{main} function, we treat the root stack very
  5962. much like the regular stack in that we move the root stack pointer
  5963. (\code{r15}) to make room for the spills to the root stack, except
  5964. that the root stack grows up instead of down. For the running
  5965. example, there was just one spill so we increment \code{r15} by 8
  5966. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  5967. One issue that deserves special care is that there may be a call to
  5968. \code{collect} prior to the initializing assignments for all the
  5969. variables in the root stack. We do not want the garbage collector to
  5970. accidentally think that some uninitialized variable is a pointer that
  5971. needs to be followed. Thus, we zero-out all locations on the root
  5972. stack in the prelude of \code{main}. In
  5973. Figure~\ref{fig:print-x86-output-gc}, the instruction
  5974. %
  5975. \lstinline{movq $0, (%r15)}
  5976. %
  5977. accomplishes this task. The garbage collector tests each root to see
  5978. if it is null prior to dereferencing it.
  5979. \begin{figure}[htbp]
  5980. \begin{minipage}[t]{0.5\textwidth}
  5981. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  5982. block35:
  5983. movq free_ptr(%rip), %rcx
  5984. addq $16, free_ptr(%rip)
  5985. movq %rcx, %r11
  5986. movq $131, 0(%r11)
  5987. movq %rcx, %r11
  5988. movq -8(%r15), %rax
  5989. movq %rax, 8(%r11)
  5990. movq $0, %rdx
  5991. movq %rcx, %r11
  5992. movq 8(%r11), %rcx
  5993. movq %rcx, %r11
  5994. movq 8(%r11), %rax
  5995. jmp conclusion
  5996. block36:
  5997. movq $0, %rcx
  5998. jmp block35
  5999. block38:
  6000. movq free_ptr(%rip), %rcx
  6001. addq $16, free_ptr(%rip)
  6002. movq %rcx, %r11
  6003. movq $3, 0(%r11)
  6004. movq %rcx, %r11
  6005. movq %rbx, 8(%r11)
  6006. movq $0, %rdx
  6007. movq %rcx, -8(%r15)
  6008. movq free_ptr(%rip), %rcx
  6009. addq $16, %rcx
  6010. movq fromspace_end(%rip), %rdx
  6011. cmpq %rdx, %rcx
  6012. jl block36
  6013. movq %r15, %rdi
  6014. movq $16, %rsi
  6015. callq collect
  6016. jmp block35
  6017. block39:
  6018. movq $0, %rcx
  6019. jmp block38
  6020. \end{lstlisting}
  6021. \end{minipage}
  6022. \begin{minipage}[t]{0.45\textwidth}
  6023. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  6024. start:
  6025. movq $42, %rbx
  6026. movq free_ptr(%rip), %rdx
  6027. addq $16, %rdx
  6028. movq fromspace_end(%rip), %rcx
  6029. cmpq %rcx, %rdx
  6030. jl block39
  6031. movq %r15, %rdi
  6032. movq $16, %rsi
  6033. callq collect
  6034. jmp block38
  6035. .globl main
  6036. main:
  6037. pushq %rbp
  6038. movq %rsp, %rbp
  6039. pushq %r13
  6040. pushq %r12
  6041. pushq %rbx
  6042. pushq %r14
  6043. subq $0, %rsp
  6044. movq $16384, %rdi
  6045. movq $16384, %rsi
  6046. callq initialize
  6047. movq rootstack_begin(%rip), %r15
  6048. movq $0, (%r15)
  6049. addq $8, %r15
  6050. jmp start
  6051. conclusion:
  6052. subq $8, %r15
  6053. addq $0, %rsp
  6054. popq %r14
  6055. popq %rbx
  6056. popq %r12
  6057. popq %r13
  6058. popq %rbp
  6059. retq
  6060. \end{lstlisting}
  6061. \end{minipage}
  6062. \caption{Output of the \code{print-x86} pass.}
  6063. \label{fig:print-x86-output-gc}
  6064. \end{figure}
  6065. \begin{figure}[p]
  6066. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6067. \node (R3) at (0,2) {\large $R_3$};
  6068. \node (R3-2) at (3,2) {\large $R_3$};
  6069. \node (R3-3) at (6,2) {\large $R_3$};
  6070. \node (R3-4) at (9,2) {\large $R_3$};
  6071. \node (R3-5) at (9,0) {\large $R'_3$};
  6072. \node (R3-6) at (6,0) {\large $R'_3$};
  6073. \node (C2-4) at (3,-2) {\large $C_2$};
  6074. \node (C2-3) at (0,-2) {\large $C_2$};
  6075. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_2$};
  6076. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_2$};
  6077. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_2$};
  6078. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_2$};
  6079. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_2$};
  6080. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_2$};
  6081. \path[->,bend left=15] (R3) edge [above] node {\ttfamily\footnotesize\color{red} type-check} (R3-2);
  6082. \path[->,bend left=15] (R3-2) edge [above] node {\ttfamily\footnotesize shrink} (R3-3);
  6083. \path[->,bend left=15] (R3-3) edge [above] node {\ttfamily\footnotesize uniquify} (R3-4);
  6084. \path[->,bend left=15] (R3-4) edge [right] node {\ttfamily\footnotesize\color{red} expose-alloc.} (R3-5);
  6085. \path[->,bend left=15] (R3-5) edge [below] node {\ttfamily\footnotesize remove-complex.} (R3-6);
  6086. \path[->,bend right=20] (R3-6) edge [left] node {\ttfamily\footnotesize explicate-control} (C2-3);
  6087. \path[->,bend right=15] (C2-3) edge [below] node {\ttfamily\footnotesize\color{red} uncover-locals} (C2-4);
  6088. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  6089. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover-live} (x86-2-1);
  6090. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize\color{red} build-inter.} (x86-2-2);
  6091. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize\color{red} allocate-reg.} (x86-3);
  6092. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch-instr.} (x86-4);
  6093. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  6094. \end{tikzpicture}
  6095. \caption{Diagram of the passes for $R_3$, a language with tuples.}
  6096. \label{fig:R3-passes}
  6097. \end{figure}
  6098. Figure~\ref{fig:R3-passes} gives an overview of all the passes needed
  6099. for the compilation of $R_3$.
  6100. \section{Challenge: Simple Structures}
  6101. \label{sec:simple-structures}
  6102. \index{struct}
  6103. \index{structure}
  6104. Figure~\ref{fig:r3s-concrete-syntax} defines the concrete syntax for
  6105. $R^s_3$, which extends $R^3$ with support for simple structures.
  6106. Recall that a \code{struct} in Typed Racket is a user-defined data
  6107. type that contains named fields and that is heap allocated, similar to
  6108. a vector. The following is an example of a structure definition, in
  6109. this case the definition of a \code{point} type.
  6110. \begin{lstlisting}
  6111. (struct point ([x : Integer] [y : Integer]) #:mutable)
  6112. \end{lstlisting}
  6113. \begin{figure}[tbp]
  6114. \centering
  6115. \fbox{
  6116. \begin{minipage}{0.96\textwidth}
  6117. \[
  6118. \begin{array}{lcl}
  6119. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  6120. \mid (\key{Vector}\;\Type \ldots) \mid \key{Void} } \mid \Var \\
  6121. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6122. \Exp &::=& \gray{ \Int \mid (\key{read}) \mid (\key{-}\;\Exp) \mid (\key{+} \; \Exp\;\Exp) \mid (\key{-}\;\Exp\;\Exp) } \\
  6123. &\mid& \gray{ \Var \mid (\key{let}~([\Var~\Exp])~\Exp) }\\
  6124. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6125. \mid (\key{and}\;\Exp\;\Exp)
  6126. \mid (\key{or}\;\Exp\;\Exp)
  6127. \mid (\key{not}\;\Exp) } \\
  6128. &\mid& \gray{ (\itm{cmp}\;\Exp\;\Exp)
  6129. \mid (\key{if}~\Exp~\Exp~\Exp) } \\
  6130. &\mid& \gray{ (\key{vector}\;\Exp \ldots)
  6131. \mid (\key{vector-ref}\;\Exp\;\Int) } \\
  6132. &\mid& \gray{ (\key{vector-set!}\;\Exp\;\Int\;\Exp) }\\
  6133. &\mid& \gray{ (\key{void}) } \mid (\Var\;\Exp \ldots)\\
  6134. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  6135. R_3 &::=& \Def \ldots \; \Exp
  6136. \end{array}
  6137. \]
  6138. \end{minipage}
  6139. }
  6140. \caption{The concrete syntax of $R^s_3$, extending $R_3$
  6141. (Figure~\ref{fig:r3-concrete-syntax}).}
  6142. \label{fig:r3s-concrete-syntax}
  6143. \end{figure}
  6144. An instance of a structure is created using function call syntax, with
  6145. the name of the structure in the function position:
  6146. \begin{lstlisting}
  6147. (point 7 12)
  6148. \end{lstlisting}
  6149. Function-call syntax is also used to read the value in a field of a
  6150. structure. The function name is formed by the structure name, a dash,
  6151. and the field name. The following example uses \code{point-x} and
  6152. \code{point-y} to access the \code{x} and \code{y} fields of two point
  6153. instances.
  6154. \begin{center}
  6155. \begin{lstlisting}
  6156. (let ([pt1 (point 7 12)])
  6157. (let ([pt2 (point 4 3)])
  6158. (+ (- (point-x pt1) (point-x pt2))
  6159. (- (point-y pt1) (point-y pt2)))))
  6160. \end{lstlisting}
  6161. \end{center}
  6162. Similarly, to write to a field of a structure, use its set function,
  6163. whose name starts with \code{set-}, followed by the structure name,
  6164. then a dash, then the field name, and conclused with an exclamation
  6165. mark. The folowing example uses \code{set-point-x!} to change the
  6166. \code{x} field from \code{7} to \code{42}.
  6167. \begin{center}
  6168. \begin{lstlisting}
  6169. (let ([pt (point 7 12)])
  6170. (let ([_ (set-point-x! pt 42)])
  6171. (point-x pt)))
  6172. \end{lstlisting}
  6173. \end{center}
  6174. \begin{exercise}\normalfont
  6175. Extend your compiler with support for simple structures, compiling
  6176. $R^s_3$ to x86 assembly code. Create five new test cases that use
  6177. structures and test your compiler.
  6178. \end{exercise}
  6179. \section{Challenge: Generational Collection}
  6180. The copying collector described in Section~\ref{sec:GC} can incur
  6181. significant runtime overhead because the call to \code{collect} takes
  6182. time proportional to all of the live data. One way to reduce this
  6183. overhead is to reduce how much data is inspected in each call to
  6184. \code{collect}. In particular, researchers have observed that recently
  6185. allocated data is more likely to become garbage then data that has
  6186. survived one or more previous calls to \code{collect}. This insight
  6187. motivated the creation of \emph{generational garbage collectors}
  6188. \index{generational garbage collector} that
  6189. 1) segragates data according to its age into two or more generations,
  6190. 2) allocates less space for younger generations, so collecting them is
  6191. faster, and more space for the older generations, and 3) performs
  6192. collection on the younger generations more frequently then for older
  6193. generations~\citep{Wilson:1992fk}.
  6194. For this challenge assignment, the goal is to adapt the copying
  6195. collector implemented in \code{runtime.c} to use two generations, one
  6196. for young data and one for old data. Each generation consists of a
  6197. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  6198. \code{collect} function to use the two generations.
  6199. \begin{enumerate}
  6200. \item Copy the young generation's FromSpace to its ToSpace then switch
  6201. the role of the ToSpace and FromSpace
  6202. \item If there is enough space for the requested number of bytes in
  6203. the young FromSpace, then return from \code{collect}.
  6204. \item If there is not enough space in the young FromSpace for the
  6205. requested bytes, then move the data from the young generation to the
  6206. old one with the following steps:
  6207. \begin{enumerate}
  6208. \item If there is enough room in the old FromSpace, copy the young
  6209. FromSpace to the old FromSpace and then return.
  6210. \item If there is not enough room in the old FromSpace, then collect
  6211. the old generation by copying the old FromSpace to the old ToSpace
  6212. and swap the roles of the old FromSpace and ToSpace.
  6213. \item If there is enough room now, copy the young FromSpace to the
  6214. old FromSpace and return. Otherwise, allocate a larger FromSpace
  6215. and ToSpace for the old generation. Copy the young FromSpace and
  6216. the old FromSpace into the larger FromSpace for the old
  6217. generation and then return.
  6218. \end{enumerate}
  6219. \end{enumerate}
  6220. We recommend that you generalize the \code{cheney} function so that it
  6221. can be used for all the copies mentioned above: between the young
  6222. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  6223. between the young FromSpace and old FromSpace. This can be
  6224. accomplished by adding parameters to \code{cheney} that replace its
  6225. use of the global variables \code{fromspace\_begin},
  6226. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  6227. Note that the collection of the young generation does not traverse the
  6228. old generation. This introduces a potential problem: there may be
  6229. young data that is only reachable through pointers in the old
  6230. generation. If these pointers are not taken into account, the
  6231. collector could throw away young data that is live! One solution,
  6232. called \emph{pointer recording}, is to maintain a set of all the
  6233. pointers from the old generation into the new generation and consider
  6234. this set as part of the root set. To maintain this set, the compiler
  6235. must insert extra instructions around every \code{vector-set!}. If the
  6236. vector being modified is in the old generation, and if the value being
  6237. written is a pointer into the new generation, than that pointer must
  6238. be added to the set. Also, if the value being overwritten was a
  6239. pointer into the new generation, then that pointer should be removed
  6240. from the set.
  6241. \begin{exercise}\normalfont
  6242. Adapt the \code{collect} function in \code{runtime.c} to implement
  6243. generational garbage collection, as outlined in this section.
  6244. Update the code generation for \code{vector-set!} to implement
  6245. pointer recording. Make sure that your new compiler and runtime
  6246. passes your test suite.
  6247. \end{exercise}
  6248. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6249. \chapter{Functions}
  6250. \label{ch:functions}
  6251. \index{function}
  6252. This chapter studies the compilation of functions similar to those
  6253. found in the C language. This corresponds to a subset of Typed Racket
  6254. in which only top-level function definitions are allowed. This kind of
  6255. function is an important stepping stone to implementing
  6256. lexically-scoped functions, that is, \key{lambda} abstractions, which
  6257. is the topic of Chapter~\ref{ch:lambdas}.
  6258. \section{The $R_4$ Language}
  6259. The concrete and abstract syntax for function definitions and function
  6260. application is shown in Figures~\ref{fig:r4-concrete-syntax} and
  6261. \ref{fig:r4-syntax}, where we define the $R_4$ language. Programs in
  6262. $R_4$ begin with zero or more function definitions. The function
  6263. names from these definitions are in-scope for the entire program,
  6264. including all other function definitions (so the ordering of function
  6265. definitions does not matter). The concrete syntax for function
  6266. application\index{function application} is $(\Exp \; \Exp \ldots)$
  6267. where the first expression must
  6268. evaluate to a function and the rest are the arguments.
  6269. The abstract syntax for function application is
  6270. $\APPLY{\Exp}{\Exp\ldots}$.
  6271. %% The syntax for function application does not include an explicit
  6272. %% keyword, which is error prone when using \code{match}. To alleviate
  6273. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  6274. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  6275. Functions are first-class in the sense that a function pointer
  6276. \index{function pointer} is data and can be stored in memory or passed
  6277. as a parameter to another function. Thus, we introduce a function
  6278. type, written
  6279. \begin{lstlisting}
  6280. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  6281. \end{lstlisting}
  6282. for a function whose $n$ parameters have the types $\Type_1$ through
  6283. $\Type_n$ and whose return type is $\Type_r$. The main limitation of
  6284. these functions (with respect to Racket functions) is that they are
  6285. not lexically scoped. That is, the only external entities that can be
  6286. referenced from inside a function body are other globally-defined
  6287. functions. The syntax of $R_4$ prevents functions from being nested
  6288. inside each other.
  6289. \begin{figure}[tp]
  6290. \centering
  6291. \fbox{
  6292. \begin{minipage}{0.96\textwidth}
  6293. \small
  6294. \[
  6295. \begin{array}{lcl}
  6296. \Type &::=& \gray{ \key{Integer} \mid \key{Boolean}
  6297. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void} } \mid (\Type \ldots \; \key{->}\; \Type) \\
  6298. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} } \\
  6299. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp} \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  6300. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  6301. &\mid& \gray{ \key{\#t} \mid \key{\#f}
  6302. \mid (\key{and}\;\Exp\;\Exp)
  6303. \mid (\key{or}\;\Exp\;\Exp)
  6304. \mid (\key{not}\;\Exp)} \\
  6305. &\mid& \gray{(\itm{cmp}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  6306. &\mid& \gray{(\key{vector}\;\Exp\ldots) \mid
  6307. (\key{vector-ref}\;\Exp\;\Int)} \\
  6308. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  6309. \mid \LP\key{has-type}~\Exp~\Type\RP } \\
  6310. &\mid& \LP\Exp \; \Exp \ldots\RP \\
  6311. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  6312. R_4 &::=& \Def \ldots \; \Exp
  6313. \end{array}
  6314. \]
  6315. \end{minipage}
  6316. }
  6317. \caption{The concrete syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-concrete-syntax}).}
  6318. \label{fig:r4-concrete-syntax}
  6319. \end{figure}
  6320. \begin{figure}[tp]
  6321. \centering
  6322. \fbox{
  6323. \begin{minipage}{0.96\textwidth}
  6324. \small
  6325. \[
  6326. \begin{array}{lcl}
  6327. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6328. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  6329. &\mid& \gray{ \BOOL{\itm{bool}}
  6330. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6331. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP }
  6332. \mid \APPLY{\Exp}{\Exp\ldots}\\
  6333. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}\\
  6334. R_4 &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  6335. \end{array}
  6336. \]
  6337. \end{minipage}
  6338. }
  6339. \caption{The abstract syntax of $R_4$, extending $R_3$ (Figure~\ref{fig:r3-syntax}).}
  6340. \label{fig:r4-syntax}
  6341. \end{figure}
  6342. The program in Figure~\ref{fig:r4-function-example} is a
  6343. representative example of defining and using functions in $R_4$. We
  6344. define a function \code{map-vec} that applies some other function
  6345. \code{f} to both elements of a vector and returns a new
  6346. vector containing the results. We also define a function \code{add1}.
  6347. The program applies
  6348. \code{map-vec} to \code{add1} and \code{(vector 0 41)}. The result is
  6349. \code{(vector 1 42)}, from which we return the \code{42}.
  6350. \begin{figure}[tbp]
  6351. \begin{lstlisting}
  6352. (define (map-vec [f : (Integer -> Integer)]
  6353. [v : (Vector Integer Integer)])
  6354. : (Vector Integer Integer)
  6355. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  6356. (define (add1 [x : Integer]) : Integer
  6357. (+ x 1))
  6358. (vector-ref (map-vec add1 (vector 0 41)) 1)
  6359. \end{lstlisting}
  6360. \caption{Example of using functions in $R_4$.}
  6361. \label{fig:r4-function-example}
  6362. \end{figure}
  6363. The definitional interpreter for $R_4$ is in
  6364. Figure~\ref{fig:interp-R4}. The case for the \code{ProgramDefsExp} form is
  6365. responsible for setting up the mutual recursion between the top-level
  6366. function definitions. We use the classic back-patching \index{back-patching}
  6367. approach that uses mutable variables and makes two passes over the function
  6368. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  6369. top-level environment using a mutable cons cell for each function
  6370. definition. Note that the \code{lambda} value for each function is
  6371. incomplete; it does not yet include the environment. Once the
  6372. top-level environment is constructed, we then iterate over it and
  6373. update the \code{lambda} values to use the top-level environment.
  6374. \begin{figure}[tp]
  6375. \begin{lstlisting}
  6376. (define (interp-exp env)
  6377. (lambda (e)
  6378. (define recur (interp-exp env))
  6379. (match e
  6380. ...
  6381. [(Apply fun args)
  6382. (define fun-val (recur fun))
  6383. (define arg-vals (for/list ([e args]) (recur e)))
  6384. (match fun-val
  6385. [`(lambda (,xs ...) ,body ,fun-env)
  6386. (define new-env (append (map cons xs arg-vals) fun-env))
  6387. ((interp-exp new-env) body)])]
  6388. ...
  6389. )))
  6390. (define (interp-def d)
  6391. (match d
  6392. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  6393. (mcons f `(lambda ,xs ,body ()))]
  6394. ))
  6395. (define (interp-R4 p)
  6396. (match p
  6397. [(ProgramDefsExp info ds body)
  6398. (let ([top-level (for/list ([d ds]) (interp-def d))])
  6399. (for/list ([b top-level])
  6400. (set-mcdr! b (match (mcdr b)
  6401. [`(lambda ,xs ,body ())
  6402. `(lambda ,xs ,body ,top-level)])))
  6403. ((interp-exp top-level) body))]
  6404. ))
  6405. \end{lstlisting}
  6406. \caption{Interpreter for the $R_4$ language.}
  6407. \label{fig:interp-R4}
  6408. \end{figure}
  6409. \margincomment{TODO: explain type checker}
  6410. The type checker for $R_4$ is is in Figure~\ref{fig:type-check-R4}.
  6411. \begin{figure}[tp]
  6412. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6413. (define (fun-def-name d)
  6414. (match d [(Def f (list `[,xs : ,ps] ...) rt info body) f]))
  6415. (define (fun-def-type d)
  6416. (match d
  6417. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  6418. (define (type-check-exp env)
  6419. (lambda (e)
  6420. (match e
  6421. ...
  6422. [(Apply e es)
  6423. (define-values (e^ ty) ((type-check-exp env) e))
  6424. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  6425. ((type-check-exp env) e)))
  6426. (match ty
  6427. [`(,ty^* ... -> ,rt)
  6428. (for ([arg-ty ty*] [prm-ty ty^*])
  6429. (unless (equal? arg-ty prm-ty)
  6430. (error "argument ~a not equal to parameter ~a" arg-ty prm-ty)))
  6431. (values (HasType (Apply e^ e*) rt) rt)]
  6432. [else (error "expected a function, not" ty)])])))
  6433. (define (type-check-def env)
  6434. (lambda (e)
  6435. (match e
  6436. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  6437. (define new-env (append (map cons xs ps) env))
  6438. (define-values (body^ ty^) ((type-check-exp new-env) body))
  6439. (unless (equal? ty^ rt)
  6440. (error "body type ~a not equal to return type ~a" ty^ rt))
  6441. (Def f p:t* rt info body^)])))
  6442. (define (type-check env)
  6443. (lambda (e)
  6444. (match e
  6445. [(ProgramDefsExp info ds body)
  6446. (define new-env (for/list ([d ds])
  6447. (cons (fun-def-name d) (fun-def-type d))))
  6448. (define ds^ (for/list ([d ds])
  6449. ((type-check-def new-env) d)))
  6450. (define-values (body^ ty) ((type-check-exp new-env) body))
  6451. (unless (equal? ty 'Integer)
  6452. (error "result of the program must be an integer, not " ty))
  6453. (ProgramDefsExp info ds^ body^)]
  6454. [else (error 'type-check "R4/type-check unmatched ~a" e)])))
  6455. \end{lstlisting}
  6456. \caption{Type checker for the $R_4$ language.}
  6457. \label{fig:type-check-R4}
  6458. \end{figure}
  6459. \section{Functions in x86}
  6460. \label{sec:fun-x86}
  6461. \margincomment{\tiny Make sure callee-saved registers are discussed
  6462. in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  6463. \margincomment{\tiny Talk about the return address on the
  6464. stack and what callq and retq does.\\ --Jeremy }
  6465. The x86 architecture provides a few features to support the
  6466. implementation of functions. We have already seen that x86 provides
  6467. labels so that one can refer to the location of an instruction, as is
  6468. needed for jump instructions. Labels can also be used to mark the
  6469. beginning of the instructions for a function. Going further, we can
  6470. obtain the address of a label by using the \key{leaq} instruction and
  6471. PC-relative addressing. For example, the following puts the
  6472. address of the \code{add1} label into the \code{rbx} register.
  6473. \begin{lstlisting}
  6474. leaq add1(%rip), %rbx
  6475. \end{lstlisting}
  6476. The instruction pointer register \key{rip} (aka. the program counter
  6477. \index{program counter}) always points to the next instruction to be
  6478. executed. When combined with an label, as in \code{add1(\%rip)}, the
  6479. linker computes the distance $d$ between the address of \code{add1}
  6480. and where the \code{rip} would be at that moment and then changes
  6481. \code{add1(\%rip)} to \code{$d$(\%rip)}, which at runtime will compute
  6482. the address of \code{add1}.
  6483. In Section~\ref{sec:x86} we used of the \code{callq} instruction to
  6484. jump to a function whose location is given by a label. To support
  6485. function calls in this chapter we instead will be jumping to a
  6486. function whose location is given by an address in a register, that is,
  6487. we need to make an \emph{indirect function call}. The x86 syntax for
  6488. this is a \code{callq} instruction but with an asterisk before the
  6489. register name.\index{indirect function call}
  6490. \begin{lstlisting}
  6491. callq *%rbx
  6492. \end{lstlisting}
  6493. \subsection{Calling Conventions}
  6494. \index{calling conventions}
  6495. The \code{callq} instruction provides partial support for implementing
  6496. functions: it pushes the return address on the stack and it jumps to
  6497. the target. However, \code{callq} does not handle
  6498. \begin{enumerate}
  6499. \item parameter passing,
  6500. \item pushing frames on the procedure call stack and popping them off,
  6501. or
  6502. \item determining how registers are shared by different functions.
  6503. \end{enumerate}
  6504. Regarding (1) parameter passing, recall that the following six
  6505. registers are used to pass arguments to a function, in this order.
  6506. \begin{lstlisting}
  6507. rdi rsi rdx rcx r8 r9
  6508. \end{lstlisting}
  6509. If there are
  6510. more than six arguments, then the convention is to use space on the
  6511. frame of the caller for the rest of the arguments. However, to ease
  6512. the implementation of efficient tail calls
  6513. (Section~\ref{sec:tail-call}), we arrange to never need more than six
  6514. arguments.
  6515. %
  6516. Also recall that the register \code{rax} is for the return value of
  6517. the function.
  6518. \index{prelude}\index{conclusion}
  6519. Regarding (2) frames \index{frame} and the procedure call stack,
  6520. \index{procedure call stack} recall from Section~\ref{sec:x86} that
  6521. the stack grows down, with each function call using a chunk of space
  6522. called a frame. The caller sets the stack pointer, register
  6523. \code{rsp}, to the last data item in its frame. The callee must not
  6524. change anything in the caller's frame, that is, anything that is at or
  6525. above the stack pointer. The callee is free to use locations that are
  6526. below the stack pointer.
  6527. Recall that we are storing variables of vector type on the root stack.
  6528. So the prelude needs to move the root stack pointer \code{r15} up and
  6529. the conclusion needs to move the root stack pointer back down. Also,
  6530. the prelude must initialize to \code{0} this frame's slots in the root
  6531. stack to signal to the garbage collector that those slots do not yet
  6532. contain a pointer to a vector. Otherwise the garbage collector will
  6533. interpret the garbage bits in those slots as memory addresses and try
  6534. to traverse them, causing serious mayhem!
  6535. Regarding (3) the sharing of registers between different functions,
  6536. recall from Section~\ref{sec:calling-conventions} that the registers
  6537. are divided into two groups, the caller-saved registers and the
  6538. callee-saved registers. The caller should assume that all the
  6539. caller-saved registers get overwritten with arbitrary values by the
  6540. callee. That is why we recommend in
  6541. Section~\ref{sec:calling-conventions} that variables that are live
  6542. during a function call should not be assigned to caller-saved
  6543. registers.
  6544. On the flip side, if the callee wants to use a callee-saved register,
  6545. the callee must save the contents of those registers on their stack
  6546. frame and then put them back prior to returning to the caller. That
  6547. is why we recommended in Section~\ref{sec:calling-conventions} that if
  6548. the register allocator assigns a variable to a callee-saved register,
  6549. then the prelude of the \code{main} function must save that register
  6550. to the stack and the conclusion of \code{main} must restore it. This
  6551. recommendation now generalizes to all functions.
  6552. Also recall that the base pointer, register \code{rbp}, is used as a
  6553. point-of-reference within a frame, so that each local variable can be
  6554. accessed at a fixed offset from the base pointer
  6555. (Section~\ref{sec:x86}).
  6556. %
  6557. Figure~\ref{fig:call-frames} shows the general layout of the caller
  6558. and callee frames.
  6559. \begin{figure}[tbp]
  6560. \centering
  6561. \begin{tabular}{r|r|l|l} \hline
  6562. Caller View & Callee View & Contents & Frame \\ \hline
  6563. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  6564. 0(\key{\%rbp}) & & old \key{rbp} \\
  6565. -8(\key{\%rbp}) & & callee-saved $1$ \\
  6566. \ldots & & \ldots \\
  6567. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  6568. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  6569. \ldots & & \ldots \\
  6570. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  6571. %% & & \\
  6572. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  6573. %% & \ldots & \ldots \\
  6574. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  6575. \hline
  6576. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  6577. & 0(\key{\%rbp}) & old \key{rbp} \\
  6578. & -8(\key{\%rbp}) & callee-saved $1$ \\
  6579. & \ldots & \ldots \\
  6580. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  6581. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  6582. & \ldots & \ldots \\
  6583. & $-8(n+m)$(\key{\%rsp}) & local variable $m$\\ \hline
  6584. \end{tabular}
  6585. \caption{Memory layout of caller and callee frames.}
  6586. \label{fig:call-frames}
  6587. \end{figure}
  6588. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  6589. %% local variables and for storing the values of callee-saved registers
  6590. %% (we shall refer to all of these collectively as ``locals''), and that
  6591. %% at the beginning of a function we move the stack pointer \code{rsp}
  6592. %% down to make room for them.
  6593. %% We recommend storing the local variables
  6594. %% first and then the callee-saved registers, so that the local variables
  6595. %% can be accessed using \code{rbp} the same as before the addition of
  6596. %% functions.
  6597. %% To make additional room for passing arguments, we shall
  6598. %% move the stack pointer even further down. We count how many stack
  6599. %% arguments are needed for each function call that occurs inside the
  6600. %% body of the function and find their maximum. Adding this number to the
  6601. %% number of locals gives us how much the \code{rsp} should be moved at
  6602. %% the beginning of the function. In preparation for a function call, we
  6603. %% offset from \code{rsp} to set up the stack arguments. We put the first
  6604. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  6605. %% so on.
  6606. %% Upon calling the function, the stack arguments are retrieved by the
  6607. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  6608. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  6609. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  6610. %% the layout of the caller and callee frames. Notice how important it is
  6611. %% that we correctly compute the maximum number of arguments needed for
  6612. %% function calls; if that number is too small then the arguments and
  6613. %% local variables will smash into each other!
  6614. \subsection{Efficient Tail Calls}
  6615. \label{sec:tail-call}
  6616. In general, the amount of stack space used by a program is determined
  6617. by the longest chain of nested function calls. That is, if function
  6618. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, and $f_{n-1}$ calls
  6619. $f_n$, then the amount of stack space is bounded by $O(n)$. The depth
  6620. $n$ can grow quite large in the case of recursive or mutually
  6621. recursive functions. However, in some cases we can arrange to use only
  6622. constant space, i.e. $O(1)$, instead of $O(n)$.
  6623. If a function call is the last action in a function body, then that
  6624. call is said to be a \emph{tail call}\index{tail call}.
  6625. For example, in the following
  6626. program, the recursive call to \code{tail-sum} is a tail call.
  6627. \begin{center}
  6628. \begin{lstlisting}
  6629. (define (tail-sum [n : Integer] [r : Integer]) : Integer
  6630. (if (eq? n 0)
  6631. r
  6632. (tail-sum (- n 1) (+ n r))))
  6633. (+ (tail-sum 5 0) 27)
  6634. \end{lstlisting}
  6635. \end{center}
  6636. At a tail call, the frame of the caller is no longer needed, so we
  6637. can pop the caller's frame before making the tail call. With this
  6638. approach, a recursive function that only makes tail calls will only
  6639. use $O(1)$ stack space. Functional languages like Racket typically
  6640. rely heavily on recursive functions, so they typically guarantee that
  6641. all tail calls will be optimized in this way.
  6642. \index{frame}
  6643. However, some care is needed with regards to argument passing in tail
  6644. calls. As mentioned above, for arguments beyond the sixth, the
  6645. convention is to use space in the caller's frame for passing
  6646. arguments. But for a tail call we pop the caller's frame and can no
  6647. longer use it. Another alternative is to use space in the callee's
  6648. frame for passing arguments. However, this option is also problematic
  6649. because the caller and callee's frame overlap in memory. As we begin
  6650. to copy the arguments from their sources in the caller's frame, the
  6651. target locations in the callee's frame might overlap with the sources
  6652. for later arguments! We solve this problem by not using the stack for
  6653. passing more than six arguments but instead using the heap, as we
  6654. describe in the Section~\ref{sec:limit-functions-r4}.
  6655. As mentioned above, for a tail call we pop the caller's frame prior to
  6656. making the tail call. The instructions for popping a frame are the
  6657. instructions that we usually place in the conclusion of a
  6658. function. Thus, we also need to place such code immediately before
  6659. each tail call. These instructions include restoring the callee-saved
  6660. registers, so it is good that the argument passing registers are all
  6661. caller-saved registers.
  6662. One last note regarding which instruction to use to make the tail
  6663. call. When the callee is finished, it should not return to the current
  6664. function, but it should return to the function that called the current
  6665. one. Thus, the return address that is already on the stack is the
  6666. right one, and we should not use \key{callq} to make the tail call, as
  6667. that would unnecessarily overwrite the return address. Instead we can
  6668. simply use the \key{jmp} instruction. Like the indirect function call,
  6669. we write an \emph{indirect jump}\index{indirect jump} with a register
  6670. prefixed with an asterisk. We recommend using \code{rax} to hold the
  6671. jump target because the preceding conclusion overwrites just about
  6672. everything else.
  6673. \begin{lstlisting}
  6674. jmp *%rax
  6675. \end{lstlisting}
  6676. \section{Shrink $R_4$}
  6677. \label{sec:shrink-r4}
  6678. The \code{shrink} pass performs a minor modification to ease the
  6679. later passes. This pass introduces an explicit \code{main} function
  6680. and changes the top \code{ProgramDefsExp} form to
  6681. \code{ProgramDefs} as follows.
  6682. \begin{lstlisting}
  6683. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  6684. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  6685. \end{lstlisting}
  6686. where $\itm{mainDef}$ is
  6687. \begin{lstlisting}
  6688. (Def 'main '() 'Integer '() |$\Exp'$|)
  6689. \end{lstlisting}
  6690. \section{Reveal Functions and the $F_1$ language}
  6691. \label{sec:reveal-functions-r4}
  6692. The syntax of $R_4$ is inconvenient for purposes of compilation in one
  6693. respect: it conflates the use of function names and local
  6694. variables. This is a problem because we need to compile the use of a
  6695. function name differently than the use of a local variable; we need to
  6696. use \code{leaq} to convert the function name (a label in x86) to an
  6697. address in a register. Thus, it is a good idea to create a new pass
  6698. that changes function references from just a symbol $f$ to
  6699. $\FUNREF{f}$. This pass is named \code{reveal-functions} and the
  6700. output language, $F_1$, is defined in Figure~\ref{fig:f1-syntax}.
  6701. \begin{figure}[tp]
  6702. \centering
  6703. \fbox{
  6704. \begin{minipage}{0.96\textwidth}
  6705. \[
  6706. \begin{array}{lcl}
  6707. \Exp &::=& \gray{ \INT{\Int} \mid \READ{} \mid \NEG{\Exp} } \\
  6708. &\mid& \gray{ \ADD{\Exp}{\Exp}
  6709. \mid \BINOP{\code{'-}}{\Exp}{\Exp} } \\
  6710. &\mid& \gray{ \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  6711. &\mid& \gray{ \BOOL{\itm{bool}}
  6712. \mid \AND{\Exp}{\Exp} }\\
  6713. &\mid& \gray{ \OR{\Exp}{\Exp}
  6714. \mid \NOT{\Exp} } \\
  6715. &\mid& \gray{ \BINOP{\itm{cmp}}{\Exp}{\Exp}
  6716. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  6717. &\mid& \gray{ \VECTOR{\Exp} } \\
  6718. &\mid& \gray{ \VECREF{\Exp}{\INT{\Int}} }\\
  6719. &\mid& \gray{ \VECSET{\Exp}{\INT{\Int}}{\Exp}} \\
  6720. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  6721. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  6722. &\mid& \FUNREF{\Var}\\
  6723. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  6724. F_1 &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  6725. \end{array}
  6726. \]
  6727. \end{minipage}
  6728. }
  6729. \caption{The abstract syntax $F_1$, an extension of $R_4$
  6730. (Figure~\ref{fig:r4-syntax}).}
  6731. \label{fig:f1-syntax}
  6732. \end{figure}
  6733. %% Distinguishing between calls in tail position and non-tail position
  6734. %% requires the pass to have some notion of context. We recommend using
  6735. %% two mutually recursive functions, one for processing expressions in
  6736. %% tail position and another for the rest.
  6737. Placing this pass after \code{uniquify} will make sure that there are
  6738. no local variables and functions that share the same name. On the
  6739. other hand, \code{reveal-functions} needs to come before the
  6740. \code{explicate-control} pass because that pass helps us compile
  6741. \code{FunRef} forms into assignment statements.
  6742. \section{Limit Functions}
  6743. \label{sec:limit-functions-r4}
  6744. Recall that we wish to limit the number of function parameters to six
  6745. so that we do not need to use the stack for argument passing, which
  6746. makes it easier to implement efficient tail calls. However, because
  6747. the input language $R_4$ supports arbitrary numbers of function
  6748. arguments, we have some work to do!
  6749. This pass transforms functions and function calls that involve more
  6750. than six arguments to pass the first five arguments as usual, but it
  6751. packs the rest of the arguments into a vector and passes it as the
  6752. sixth argument.
  6753. Each function definition with too many parameters is transformed as
  6754. follows.
  6755. \begin{lstlisting}
  6756. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  6757. |$\Rightarrow$|
  6758. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [vec : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  6759. \end{lstlisting}
  6760. where the $\itm{body}$ is transformed into $\itm{body}'$ by replacing
  6761. the occurences of the later parameters with vector references.
  6762. \begin{lstlisting}
  6763. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list vec (Int |$(i - 6)$|)))
  6764. \end{lstlisting}
  6765. For function calls with too many arguments, the \code{limit-functions}
  6766. pass transforms them in the following way.
  6767. \begin{tabular}{lll}
  6768. \begin{minipage}{0.2\textwidth}
  6769. \begin{lstlisting}
  6770. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  6771. \end{lstlisting}
  6772. \end{minipage}
  6773. &
  6774. $\Rightarrow$
  6775. &
  6776. \begin{minipage}{0.4\textwidth}
  6777. \begin{lstlisting}
  6778. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  6779. \end{lstlisting}
  6780. \end{minipage}
  6781. \end{tabular}
  6782. \section{Remove Complex Operators and Operands}
  6783. \label{sec:rco-r4}
  6784. The primary decisions to make for this pass is whether to classify
  6785. \code{FunRef} and \code{Apply} as either simple or complex
  6786. expressions. Recall that a simple expression will eventually end up as
  6787. just an ``immediate'' argument of an x86 instruction. Function
  6788. application will be translated to a sequence of instructions, so
  6789. \code{Apply} must be classified as complex expression. Regarding
  6790. \code{FunRef}, as discussed above, the function label needs to
  6791. be converted to an address using the \code{leaq} instruction. Thus,
  6792. even though \code{FunRef} seems rather simple, it needs to be
  6793. classified as a complex expression so that we generate an assignment
  6794. statement with a left-hand side that can serve as the target of the
  6795. \code{leaq}.
  6796. \section{Explicate Control and the $C_3$ language}
  6797. \label{sec:explicate-control-r4}
  6798. Figures~\ref{fig:c3-concrete-syntax} and \ref{fig:c3-syntax} define
  6799. the concrete and abstract syntax for $C_3$, the output of
  6800. \key{explicate-control}. The three mutually recursive functions for
  6801. this pass, for assignment, tail, and predicate contexts, must all be
  6802. updated with cases for \code{FunRef} and \code{Apply}. In assignment
  6803. and predicate contexts, \code{Apply} becomes \code{Call} in $C_3$,
  6804. whereas in tail position \code{Apply} becomes \code{TailCall} in
  6805. $C_3$. We recommend defining a new function for processing function
  6806. definitions. This code is similar to the case for \code{Program} in
  6807. $R_3$. The top-level \code{explicate-control} function that handles
  6808. the \code{ProgramDefs} form of $R_4$ can then apply this new function
  6809. to all the function definitions.
  6810. \begin{figure}[tp]
  6811. \fbox{
  6812. \begin{minipage}{0.96\textwidth}
  6813. \[
  6814. \begin{array}{lcl}
  6815. \Atm &::=& \gray{ \Int \mid \Var \mid \key{\#t} \mid \key{\#f} }
  6816. \\
  6817. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  6818. \Exp &::= & \gray{ \Atm \mid (\key{read}) \mid (\key{-}\;\Atm) \mid (\key{+} \; \Atm\;\Atm)
  6819. \mid (\key{not}\;\Atm) \mid (\itm{cmp}\;\Atm\;\Atm) } \\
  6820. &\mid& \gray{ (\key{allocate}\,\Int\,\Type)
  6821. \mid (\key{vector-ref}\, \Atm\, \Int) } \\
  6822. &\mid& \gray{ (\key{vector-set!}\,\Atm\,\Int\,\Atm) \mid (\key{global-value} \,\itm{name}) \mid (\key{void}) } \\
  6823. &\mid& (\key{fun-ref}~\itm{label}) \mid (\key{call} \,\Atm\,\Atm\ldots) \\
  6824. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \mid \RETURN{\Exp}
  6825. \mid (\key{collect} \,\itm{int}) }\\
  6826. \Tail &::= & \gray{\RETURN{\Exp} \mid (\key{seq}\;\Stmt\;\Tail)} \\
  6827. &\mid& \gray{(\key{goto}\,\itm{label})
  6828. \mid \IF{(\itm{cmp}\, \Atm\,\Atm)}{(\key{goto}\,\itm{label})}{(\key{goto}\,\itm{label})}} \\
  6829. &\mid& (\key{tail-call}\,\Atm\,\Atm\ldots) \\
  6830. \Def &::=& (\key{define}\; (\itm{label} \; [\Var \key{:} \Type]\ldots) \key{:} \Type \; ((\itm{label}\,\key{.}\,\Tail)\ldots)) \\
  6831. C_3 & ::= & \Def\ldots
  6832. \end{array}
  6833. \]
  6834. \end{minipage}
  6835. }
  6836. \caption{The $C_3$ language, extending $C_2$ (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  6837. \label{fig:c3-concrete-syntax}
  6838. \end{figure}
  6839. \begin{figure}[tp]
  6840. \fbox{
  6841. \begin{minipage}{0.96\textwidth}
  6842. \small
  6843. \[
  6844. \begin{array}{lcl}
  6845. \Atm &::=& \gray{ \INT{\Int} \mid \VAR{\Var} \mid \BOOL{\itm{bool}} }\\
  6846. \itm{cmp} &::= & \gray{ \key{eq?} \mid \key{<} } \\
  6847. \Exp &::= & \gray{ \Atm \mid \READ{} } \\
  6848. &\mid& \gray{ \NEG{\Atm} \mid \ADD{\Atm}{\Atm} }\\
  6849. &\mid& \gray{ \UNIOP{\key{not}}{\Atm} \mid \BINOP{\itm{cmp}}{\Atm}{\Atm} } \\
  6850. &\mid& \gray{ (\key{Allocate} \,\itm{int}\,\itm{type}) } \\
  6851. &\mid& \gray{ \BINOP{\key{'vector-ref}}{\Atm}{\INT{\Int}} }\\
  6852. &\mid& \gray{ (\key{Prim}~\key{'vector-set!}\,(\key{list}\,\Atm\,\INT{\Int}\,\Atm)) }\\
  6853. &\mid& \gray{ (\key{GlobalValue} \,\Var) \mid (\key{Void}) }\\
  6854. &\mid& \FUNREF{\itm{label}} \mid \CALL{\Atm}{\Atm\ldots} \\
  6855. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  6856. \mid (\key{Collect} \,\itm{int}) } \\
  6857. \Tail &::= & \gray{ \RETURN{\Exp} \mid \SEQ{\Stmt}{\Tail}
  6858. \mid \GOTO{\itm{label}} } \\
  6859. &\mid& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  6860. &\mid& \TAILCALL{\Atm}{\Atm\ldots} \\
  6861. \Def &::=& \DEF{\itm{label}}{([\Var\key{:}\Type]\ldots)}{\Type}{\itm{info}}{((\itm{label}\,\key{.}\,\Tail)\ldots)}\\
  6862. C_3 & ::= & \PROGRAMDEFS{\itm{info}}{(\Def\ldots)}
  6863. \end{array}
  6864. \]
  6865. \end{minipage}
  6866. }
  6867. \caption{The abstract syntax of $C_3$, extending $C_2$ (Figure~\ref{fig:c2-syntax}).}
  6868. \label{fig:c3-syntax}
  6869. \end{figure}
  6870. \section{Uncover Locals}
  6871. \label{sec:uncover-locals-r4}
  6872. The function for processing $\Tail$ should be updated with a case for
  6873. \code{TailCall}. We also recommend creating a new function for
  6874. processing function definitions. Each function definition in $C_3$ has
  6875. its own set of local variables, so the code for function definitions
  6876. should be similar to the case for the \code{Program} form in $C_2$.
  6877. \section{Select Instructions and the x86$_3$ Language}
  6878. \label{sec:select-r4}
  6879. \index{instruction selection}
  6880. The output of select instructions is a program in the x86$_3$
  6881. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  6882. \index{x86}
  6883. \begin{figure}[tp]
  6884. \fbox{
  6885. \begin{minipage}{0.96\textwidth}
  6886. \[
  6887. \begin{array}{lcl}
  6888. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg}
  6889. \mid (\key{deref}\,\Reg\,\Int) } \\
  6890. &\mid& \gray{ (\key{byte-reg}\; \Reg)
  6891. \mid (\key{global}\; \itm{name}) }
  6892. \mid (\key{fun-ref}\; \itm{label})\\
  6893. \itm{cc} & ::= & \gray{ \key{e} \mid \key{l} \mid \key{le} \mid \key{g} \mid \key{ge} } \\
  6894. \Instr &::=& \gray{ (\key{addq} \; \Arg\; \Arg) \mid
  6895. (\key{subq} \; \Arg\; \Arg) \mid
  6896. (\key{negq} \; \Arg) \mid (\key{movq} \; \Arg\; \Arg) } \\
  6897. &\mid& \gray{ (\key{callq} \; \mathit{label}) \mid
  6898. (\key{pushq}\;\Arg) \mid
  6899. (\key{popq}\;\Arg) \mid
  6900. (\key{retq}) } \\
  6901. &\mid& \gray{ (\key{xorq} \; \Arg\;\Arg)
  6902. \mid (\key{cmpq} \; \Arg\; \Arg) \mid (\key{set}\itm{cc} \; \Arg) } \\
  6903. &\mid& \gray{ (\key{movzbq}\;\Arg\;\Arg)
  6904. \mid (\key{jmp} \; \itm{label})
  6905. \mid (\key{j}\itm{cc} \; \itm{label})
  6906. \mid (\key{label} \; \itm{label}) } \\
  6907. &\mid& (\key{indirect-callq}\;\Arg ) \mid (\key{tail-jmp}\;\Arg) \\
  6908. &\mid& (\key{leaq}\;\Arg\;\Reg)\\
  6909. \Def &::= & (\key{define} \; (\itm{label}) \;((\itm{label} \,\key{.}\, (\Instr\ldots))\ldots))\\
  6910. x86_3 &::= & (\key{program} \;\itm{info} \;\Def\ldots)
  6911. \end{array}
  6912. \]
  6913. \end{minipage}
  6914. }
  6915. \caption{The concrete syntax of x86$_3$ (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  6916. \label{fig:x86-3-concrete}
  6917. \end{figure}
  6918. \begin{figure}[tp]
  6919. \fbox{
  6920. \begin{minipage}{0.96\textwidth}
  6921. \small
  6922. \[
  6923. \begin{array}{lcl}
  6924. \Arg &::=& \gray{ \INT{\Int} \mid \REG{\Reg} \mid \DEREF{\Reg}{\Int}
  6925. \mid \BYTEREG{\Reg} } \\
  6926. &\mid& \gray{ (\key{Global}~\Var) } \mid \FUNREF{\itm{label}} \\
  6927. \Instr &::=& \ldots \mid \INDCALLQ{\itm{label}}{\itm{int}}
  6928. \mid \TAILJMP{\Arg}{\itm{int}}\\
  6929. &\mid& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  6930. \Def &::= & \DEF{\itm{label}}{([\Var\key{:}\Type]\ldots)}{\Type}{\itm{info}}{((\itm{label}\,\key{.}\,\Block)\ldots)} \\
  6931. x86_3 &::= & \PROGRAMDEFS{\itm{info}}{(\Def\ldots)}
  6932. \end{array}
  6933. \]
  6934. \end{minipage}
  6935. }
  6936. \caption{The abstract syntax of x86$_3$ (extends x86$_2$ of Figure~\ref{fig:x86-2}).}
  6937. \label{fig:x86-3}
  6938. \end{figure}
  6939. An assignment of a function reference to a variable becomes a
  6940. load-effective-address instruction as follows: \\
  6941. \begin{tabular}{lcl}
  6942. \begin{minipage}{0.35\textwidth}
  6943. \begin{lstlisting}
  6944. |$\itm{lhs}$| = (fun-ref |$f$|);
  6945. \end{lstlisting}
  6946. \end{minipage}
  6947. &
  6948. $\Rightarrow$\qquad\qquad
  6949. &
  6950. \begin{minipage}{0.3\textwidth}
  6951. \begin{lstlisting}
  6952. leaq (fun-ref |$f$|), |$\itm{lhs}'$|
  6953. \end{lstlisting}
  6954. \end{minipage}
  6955. \end{tabular} \\
  6956. Regarding function definitions, we need to remove the parameters and
  6957. instead perform parameter passing using the conventions discussed in
  6958. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  6959. registers. We recommend turning the parameters into local variables
  6960. and generating instructions at the beginning of the function to move
  6961. from the argument passing registers to these local variables.
  6962. \begin{lstlisting}
  6963. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$G$|)
  6964. |$\Rightarrow$|
  6965. (Def |$f$| '() 'Integer |$\itm{info}'$| |$G'$|)
  6966. \end{lstlisting}
  6967. The $G'$ control-flow graph is the same as $G$ except that the
  6968. \code{start} block is modified to add the instructions for moving from
  6969. the argument registers to the parameter variables. So the \code{start}
  6970. block of $G$ shown on the left is changed to the code on the right.
  6971. \begin{center}
  6972. \begin{minipage}{0.3\textwidth}
  6973. \begin{lstlisting}
  6974. start:
  6975. |$\itm{instr}_1$|
  6976. |$\vdots$|
  6977. |$\itm{instr}_n$|
  6978. \end{lstlisting}
  6979. \end{minipage}
  6980. $\Rightarrow$
  6981. \begin{minipage}{0.3\textwidth}
  6982. \begin{lstlisting}
  6983. start:
  6984. movq %rdi, |$x_1$|
  6985. movq %rsi, |$x_2$|
  6986. |$\vdots$|
  6987. |$\itm{instr}_1$|
  6988. |$\vdots$|
  6989. |$\itm{instr}_n$|
  6990. \end{lstlisting}
  6991. \end{minipage}
  6992. \end{center}
  6993. By changing the parameters to local variables, we are giving the
  6994. register allocator control over which registers or stack locations to
  6995. use for them. If you implemented the move-biasing challenge
  6996. (Section~\ref{sec:move-biasing}), the register allocator will try to
  6997. assign the parameter variables to the corresponding argument register,
  6998. in which case the \code{patch-instructions} pass will remove the
  6999. \code{movq} instruction. This happens in the example translation in
  7000. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  7001. the \code{add} function.
  7002. %
  7003. Also, note that the register allocator will perform liveness analysis
  7004. on this sequence of move instructions and build the interference
  7005. graph. So, for example, $x_1$ will be marked as interfering with
  7006. \code{rsi} and that will prevent the assignment of $x_1$ to
  7007. \code{rsi}, which is good, because that would overwrite the argument
  7008. that needs to move into $x_2$.
  7009. Next, consider the compilation of function calls. In the mirror image
  7010. of handling the parameters of function definitions, the arguments need
  7011. to be moved to the argument passing registers. The function call
  7012. itself is performed with an indirect function call. The return value
  7013. from the function is stored in \code{rax}, so it needs to be moved
  7014. into the \itm{lhs}.
  7015. \begin{lstlisting}
  7016. |\itm{lhs}| = (call |\itm{fun}| |$\itm{arg}_1~\itm{arg}_2\ldots$|));
  7017. |$\Rightarrow$|
  7018. movq |$\itm{arg}_1$|, %rdi
  7019. movq |$\itm{arg}_2$|, %rsi
  7020. |$\vdots$|
  7021. callq *|\itm{fun}|
  7022. movq %rax, |\itm{lhs}|
  7023. \end{lstlisting}
  7024. Regarding tail calls, the parameter passing is the same as non-tail
  7025. calls: generate instructions to move the arguments into to the
  7026. argument passing registers. After that we need to pop the frame from
  7027. the procedure call stack. However, we do not yet know how big the
  7028. frame is; that gets determined during register allocation. So instead
  7029. of generating those instructions here, we invent a new instruction
  7030. that means ``pop the frame and then do an indirect jump'', which we
  7031. name \code{TailJmp}. The abstract syntax for this instruction includes
  7032. an argument that specifies where to jump and an integer that
  7033. represents the arity of the function being called.
  7034. Recall that in Section~\ref{sec:explicate-control-r1} we recommended
  7035. using the label \code{start} for the initial block of a program, and
  7036. in Section~\ref{sec:select-r1} we recommended labeling the conclusion
  7037. of the program with \code{conclusion}, so that $(\key{Return}\;\Arg)$
  7038. can be compiled to an assignment to \code{rax} followed by a jump to
  7039. \code{conclusion}. With the addition of function definitions, we will
  7040. have a starting block and conclusion for each function, but their
  7041. labels need to be unique. We recommend prepending the function's name
  7042. to \code{start} and \code{conclusion}, respectively, to obtain unique
  7043. labels. (Alternatively, one could \code{gensym} labels for the start
  7044. and conclusion and store them in the $\itm{info}$ field of the
  7045. function definition.)
  7046. \section{Uncover Live}
  7047. %% The rest of the passes need only minor modifications to handle the new
  7048. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  7049. %% \code{leaq}.
  7050. The \code{IndirectCallq} instruction should be treated like
  7051. \code{Callq} regarding its written locations $W$, in that they should
  7052. include all the caller-saved registers. Recall that the reason for
  7053. that is to force call-live variables to be assigned to callee-saved
  7054. registers or to be spilled to the stack.
  7055. \section{Build Interference Graph}
  7056. With the addition of function definitions, we compute an interference
  7057. graph for each function (not just one for the whole program).
  7058. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  7059. spill vector-typed variables that are live during a call to the
  7060. \code{collect}. With the addition of functions to our language, we
  7061. need to revisit this issue. Many functions perform allocation and
  7062. therefore have calls to the collector inside of them. Thus, we should
  7063. not only spill a vector-typed variable when it is live during a call
  7064. to \code{collect}, but we should spill the variable if it is live
  7065. during any function call. Thus, in the \code{build-interference} pass,
  7066. we recommend adding interference edges between call-live vector-typed
  7067. variables and the callee-saved registers (in addition to the usual
  7068. addition of edges between call-live variables and the caller-saved
  7069. registers).
  7070. \section{Patch Instructions}
  7071. In \code{patch-instructions}, you should deal with the x86
  7072. idiosyncrasy that the destination argument of \code{leaq} must be a
  7073. register. Additionally, you should ensure that the argument of
  7074. \code{TailJmp} is \itm{rax}, our reserved register---this is to make
  7075. code generation more convenient, because we trample many registers
  7076. before the tail call (as explained in the next section).
  7077. \section{Print x86}
  7078. For the \code{print-x86} pass, the cases for \code{FunRef} and
  7079. \code{IndirectCallq} are straightforward: output their concrete
  7080. syntax.
  7081. \begin{lstlisting}
  7082. (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  7083. (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  7084. \end{lstlisting}
  7085. The \code{TailJmp} node requires a bit work. A straightforward
  7086. translation of \code{TailJmp} would be \code{jmp *$\itm{arg}$}, but
  7087. before the jump we need to pop the current frame. This sequence of
  7088. instructions is the same as the code for the conclusion of a function,
  7089. except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  7090. Note that your \code{print-x86} pass needs to add the code for saving
  7091. and restoring callee-saved registers, if you have not already
  7092. implemented that. This is necessary when generating code for function
  7093. definitions.
  7094. \begin{exercise}\normalfont
  7095. Expand your compiler to handle $R_4$ as outlined in this chapter.
  7096. Create 5 new programs that use functions, including examples that pass
  7097. functions and return functions from other functions and including
  7098. recursive functions. Test your compiler on these new programs and all
  7099. of your previously created test programs.
  7100. \end{exercise}
  7101. \begin{figure}[tbp]
  7102. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7103. \node (R4) at (0,2) {\large $R_4$};
  7104. \node (R4-2) at (3,2) {\large $R_4$};
  7105. \node (R4-3) at (6,2) {\large $R_4$};
  7106. \node (F1-1) at (12,0) {\large $F_1$};
  7107. \node (F1-2) at (9,0) {\large $F_1$};
  7108. \node (F1-3) at (6,0) {\large $F_1$};
  7109. \node (F1-4) at (3,0) {\large $F_1$};
  7110. \node (C3-1) at (6,-2) {\large $C_3$};
  7111. \node (C3-2) at (3,-2) {\large $C_3$};
  7112. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  7113. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  7114. \node (x86-4) at (9,-4) {\large $\text{x86}_3$};
  7115. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  7116. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  7117. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  7118. \path[->,bend left=15] (R4) edge [above] node
  7119. {\ttfamily\footnotesize\color{red} type-check} (R4-2);
  7120. \path[->,bend left=15] (R4-2) edge [above] node
  7121. {\ttfamily\footnotesize uniquify} (R4-3);
  7122. \path[->,bend left=15] (R4-3) edge [right] node
  7123. {\ttfamily\footnotesize\color{red} reveal-functions} (F1-1);
  7124. \path[->,bend left=15] (F1-1) edge [below] node
  7125. {\ttfamily\footnotesize\color{red} limit-functions} (F1-2);
  7126. \path[->,bend right=15] (F1-2) edge [above] node
  7127. {\ttfamily\footnotesize expose-alloc.} (F1-3);
  7128. \path[->,bend right=15] (F1-3) edge [above] node
  7129. {\ttfamily\footnotesize\color{red} remove-complex.} (F1-4);
  7130. \path[->,bend left=15] (F1-4) edge [right] node
  7131. {\ttfamily\footnotesize\color{red} explicate-control} (C3-1);
  7132. \path[->,bend left=15] (C3-1) edge [below] node
  7133. {\ttfamily\footnotesize\color{red} uncover-locals} (C3-2);
  7134. \path[->,bend right=15] (C3-2) edge [left] node
  7135. {\ttfamily\footnotesize\color{red} select-instr.} (x86-2);
  7136. \path[->,bend left=15] (x86-2) edge [left] node
  7137. {\ttfamily\footnotesize\color{red} uncover-live} (x86-2-1);
  7138. \path[->,bend right=15] (x86-2-1) edge [below] node
  7139. {\ttfamily\footnotesize \color{red}build-inter.} (x86-2-2);
  7140. \path[->,bend right=15] (x86-2-2) edge [left] node
  7141. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7142. \path[->,bend left=15] (x86-3) edge [above] node
  7143. {\ttfamily\footnotesize\color{red} patch-instr.} (x86-4);
  7144. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize\color{red} print-x86} (x86-5);
  7145. \end{tikzpicture}
  7146. \caption{Diagram of the passes for $R_4$, a language with functions.}
  7147. \label{fig:R4-passes}
  7148. \end{figure}
  7149. Figure~\ref{fig:R4-passes} gives an overview of the passes for
  7150. compiling $R_4$ to x86.
  7151. \section{An Example Translation}
  7152. \label{sec:functions-example}
  7153. Figure~\ref{fig:add-fun} shows an example translation of a simple
  7154. function in $R_4$ to x86. The figure also includes the results of the
  7155. \code{explicate-control} and \code{select-instructions} passes.
  7156. \begin{figure}[htbp]
  7157. \begin{tabular}{ll}
  7158. \begin{minipage}{0.5\textwidth}
  7159. % s3_2.rkt
  7160. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7161. (define (add [x : Integer] [y : Integer])
  7162. : Integer
  7163. (+ x y))
  7164. (add 40 2)
  7165. \end{lstlisting}
  7166. $\Downarrow$
  7167. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7168. (define (add86 [x87 : Integer]
  7169. [y88 : Integer]) : Integer
  7170. add86start:
  7171. return (+ x87 y88);
  7172. )
  7173. (define (main) : Integer ()
  7174. mainstart:
  7175. tmp89 = (fun-ref add86);
  7176. (tail-call tmp89 40 2)
  7177. )
  7178. \end{lstlisting}
  7179. \end{minipage}
  7180. &
  7181. $\Rightarrow$
  7182. \begin{minipage}{0.5\textwidth}
  7183. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7184. (define (add86) : Integer
  7185. add86start:
  7186. movq %rdi, x87
  7187. movq %rsi, y88
  7188. movq x87, %rax
  7189. addq y88, %rax
  7190. jmp add11389conclusion
  7191. )
  7192. (define (main) : Integer
  7193. mainstart:
  7194. leaq (fun-ref add86), tmp89
  7195. movq $40, %rdi
  7196. movq $2, %rsi
  7197. tail-jmp tmp89
  7198. )
  7199. \end{lstlisting}
  7200. $\Downarrow$
  7201. \end{minipage}
  7202. \end{tabular}
  7203. \begin{tabular}{ll}
  7204. \begin{minipage}{0.3\textwidth}
  7205. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7206. .globl add86
  7207. .align 16
  7208. add86:
  7209. pushq %rbp
  7210. movq %rsp, %rbp
  7211. jmp add86start
  7212. add86start:
  7213. movq %rdi, %rax
  7214. addq %rsi, %rax
  7215. jmp add86conclusion
  7216. add86conclusion:
  7217. popq %rbp
  7218. retq
  7219. \end{lstlisting}
  7220. \end{minipage}
  7221. &
  7222. \begin{minipage}{0.5\textwidth}
  7223. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  7224. .globl main
  7225. .align 16
  7226. main:
  7227. pushq %rbp
  7228. movq %rsp, %rbp
  7229. movq $16384, %rdi
  7230. movq $16384, %rsi
  7231. callq initialize
  7232. movq rootstack_begin(%rip), %r15
  7233. jmp mainstart
  7234. mainstart:
  7235. leaq add86(%rip), %rcx
  7236. movq $40, %rdi
  7237. movq $2, %rsi
  7238. movq %rcx, %rax
  7239. popq %rbp
  7240. jmp *%rax
  7241. mainconclusion:
  7242. popq %rbp
  7243. retq
  7244. \end{lstlisting}
  7245. \end{minipage}
  7246. \end{tabular}
  7247. \caption{Example compilation of a simple function to x86.}
  7248. \label{fig:add-fun}
  7249. \end{figure}
  7250. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7251. \chapter{Lexically Scoped Functions}
  7252. \label{ch:lambdas}
  7253. \index{lambda}
  7254. \index{lexical scoping}
  7255. This chapter studies lexically scoped functions as they appear in
  7256. functional languages such as Racket. By lexical scoping we mean that a
  7257. function's body may refer to variables whose binding site is outside
  7258. of the function, in an enclosing scope.
  7259. %
  7260. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  7261. $R_5$, which extends $R_4$ with anonymous functions using the
  7262. \key{lambda} form. The body of the \key{lambda}, refers to three
  7263. variables: \code{x}, \code{y}, and \code{z}. The binding sites for
  7264. \code{x} and \code{y} are outside of the \key{lambda}. Variable
  7265. \code{y} is bound by the enclosing \key{let} and \code{x} is a
  7266. parameter of function \code{f}. The \key{lambda} is returned from the
  7267. function \code{f}. The main expression of the program includes two
  7268. calls to \code{f} with different arguments for \code{x}, first
  7269. \code{5} then \code{3}. The functions returned from \code{f} are bound
  7270. to variables \code{g} and \code{h}. Even though these two functions
  7271. were created by the same \code{lambda}, they are really different
  7272. functions because they use different values for \code{x}. Applying
  7273. \code{g} to \code{11} produces \code{20} whereas applying \code{h} to
  7274. \code{15} produces \code{22}. The result of this program is \code{42}.
  7275. \begin{figure}[btp]
  7276. % s4_6.rkt
  7277. \begin{lstlisting}
  7278. (define (f [x : Integer]) : (Integer -> Integer)
  7279. (let ([y 4])
  7280. (lambda: ([z : Integer]) : Integer
  7281. (+ x (+ y z)))))
  7282. (let ([g (f 5)])
  7283. (let ([h (f 3)])
  7284. (+ (g 11) (h 15))))
  7285. \end{lstlisting}
  7286. \caption{Example of a lexically scoped function.}
  7287. \label{fig:lexical-scoping}
  7288. \end{figure}
  7289. The approach that we take for implementing lexically scoped
  7290. functions is to compile them into top-level function definitions,
  7291. translating from $R_5$ into $R_4$. However, the compiler will need to
  7292. provide special treatment for variable occurrences such as \code{x}
  7293. and \code{y} in the body of the \code{lambda} of
  7294. Figure~\ref{fig:lexical-scoping}. After all, an $R_4$ function may not
  7295. refer to variables defined outside of it. To identify such variable
  7296. occurrences, we review the standard notion of free variable.
  7297. \begin{definition}
  7298. A variable is \emph{free in expression} $e$ if the variable occurs
  7299. inside $e$ but does not have an enclosing binding in $e$.\index{free
  7300. variable}
  7301. \end{definition}
  7302. For example, in the expression \code{(+ x (+ y z))} the variables
  7303. \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  7304. only \code{x} and \code{y} are free in the following expression
  7305. because \code{z} is bound by the \code{lambda}.
  7306. \begin{lstlisting}
  7307. (lambda: ([z : Integer]) : Integer
  7308. (+ x (+ y z)))
  7309. \end{lstlisting}
  7310. So the free variables of a \code{lambda} are the ones that will need
  7311. special treatment. We need to arrange for some way to transport, at
  7312. runtime, the values of those variables from the point where the
  7313. \code{lambda} was created to the point where the \code{lambda} is
  7314. applied. An efficient solution to the problem, due to
  7315. \citet{Cardelli:1983aa}, is to bundle into a vector the values of the
  7316. free variables together with the function pointer for the lambda's
  7317. code, an arrangement called a \emph{flat closure} (which we shorten to
  7318. just ``closure''). \index{closure}\index{flat closure} Fortunately,
  7319. we have all the ingredients to make closures, Chapter~\ref{ch:tuples}
  7320. gave us vectors and Chapter~\ref{ch:functions} gave us function
  7321. pointers. The function pointer resides at index $0$ and the
  7322. values for the free variables will fill in the rest of the vector.
  7323. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  7324. how closures work. It's a three-step dance. The program first calls
  7325. function \code{f}, which creates a closure for the \code{lambda}. The
  7326. closure is a vector whose first element is a pointer to the top-level
  7327. function that we will generate for the \code{lambda}, the second
  7328. element is the value of \code{x}, which is \code{5}, and the third
  7329. element is \code{4}, the value of \code{y}. The closure does not
  7330. contain an element for \code{z} because \code{z} is not a free
  7331. variable of the \code{lambda}. Creating the closure is step 1 of the
  7332. dance. The closure is returned from \code{f} and bound to \code{g}, as
  7333. shown in Figure~\ref{fig:closures}.
  7334. %
  7335. The second call to \code{f} creates another closure, this time with
  7336. \code{3} in the second slot (for \code{x}). This closure is also
  7337. returned from \code{f} but bound to \code{h}, which is also shown in
  7338. Figure~\ref{fig:closures}.
  7339. \begin{figure}[tbp]
  7340. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  7341. \caption{Example closure representation for the \key{lambda}'s
  7342. in Figure~\ref{fig:lexical-scoping}.}
  7343. \label{fig:closures}
  7344. \end{figure}
  7345. Continuing with the example, consider the application of \code{g} to
  7346. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  7347. obtain the function pointer in the first element of the closure and
  7348. call it, passing in the closure itself and then the regular arguments,
  7349. in this case \code{11}. This technique for applying a closure is step
  7350. 2 of the dance.
  7351. %
  7352. But doesn't this \code{lambda} only take 1 argument, for parameter
  7353. \code{z}? The third and final step of the dance is generating a
  7354. top-level function for a \code{lambda}. We add an additional
  7355. parameter for the closure and we insert a \code{let} at the beginning
  7356. of the function for each free variable, to bind those variables to the
  7357. appropriate elements from the closure parameter.
  7358. %
  7359. This three-step dance is known as \emph{closure conversion}. We
  7360. discuss the details of closure conversion in
  7361. Section~\ref{sec:closure-conversion} and the code generated from the
  7362. example in Section~\ref{sec:example-lambda}. But first we define the
  7363. syntax and semantics of $R_5$ in Section~\ref{sec:r5}.
  7364. \section{The $R_5$ Language}
  7365. \label{sec:r5}
  7366. The concrete and abstract syntax for $R_5$, a language with anonymous
  7367. functions and lexical scoping, is defined in
  7368. Figures~\ref{fig:r5-concrete-syntax} and ~\ref{fig:r5-syntax}. It adds
  7369. the \key{lambda} form to the grammar for $R_4$, which already has
  7370. syntax for function application.
  7371. \begin{figure}[tp]
  7372. \centering
  7373. \fbox{
  7374. \begin{minipage}{0.96\textwidth}
  7375. \small
  7376. \[
  7377. \begin{array}{lcl}
  7378. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7379. \mid (\key{Vector}\;\Type\ldots) \mid \key{Void}
  7380. \mid (\Type\ldots \; \key{->}\; \Type)} \\
  7381. \Exp &::=& \gray{ \Int \mid \CREAD{} \mid \CNEG{\Exp}
  7382. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} } \\
  7383. &\mid& \gray{ \Var \mid \CLET{\Var}{\Exp}{\Exp} }\\
  7384. &\mid& \gray{\key{\#t} \mid \key{\#f}
  7385. \mid (\key{and}\;\Exp\;\Exp)
  7386. \mid (\key{or}\;\Exp\;\Exp)
  7387. \mid (\key{not}\;\Exp) } \\
  7388. &\mid& \gray{ (\key{eq?}\;\Exp\;\Exp) \mid \CIF{\Exp}{\Exp}{\Exp} } \\
  7389. &\mid& \gray{ (\key{vector}\;\Exp\ldots) \mid
  7390. (\key{vector-ref}\;\Exp\;\Int)} \\
  7391. &\mid& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\mid (\key{void})
  7392. \mid (\Exp \; \Exp\ldots) } \\
  7393. &\mid& \LP \key{procedure-arity}~\Exp\RP \\
  7394. &\mid& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  7395. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  7396. R_5 &::=& \gray{\Def\ldots \; \Exp}
  7397. \end{array}
  7398. \]
  7399. \end{minipage}
  7400. }
  7401. \caption{Concrete syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax})
  7402. with \key{lambda}.}
  7403. \label{fig:r5-concrete-syntax}
  7404. \end{figure}
  7405. \begin{figure}[tp]
  7406. \centering
  7407. \fbox{
  7408. \begin{minipage}{0.96\textwidth}
  7409. \small
  7410. \[
  7411. \begin{array}{lcl}
  7412. \itm{op} &::=& \ldots \mid \code{procedure-arity} \\
  7413. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  7414. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  7415. &\mid& \gray{ \BOOL{\itm{bool}}
  7416. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  7417. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  7418. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  7419. &\mid& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  7420. \Def &::=& \gray{ \FUNDEF{\Var}{\LP\LS\Var \code{:} \Type\RS\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  7421. R_5 &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  7422. \end{array}
  7423. \]
  7424. \end{minipage}
  7425. }
  7426. \caption{The abstract syntax of $R_5$, extending $R_4$ (Figure~\ref{fig:r4-syntax}).}
  7427. \label{fig:r5-syntax}
  7428. \end{figure}
  7429. \index{interpreter}
  7430. \label{sec:interp-R5}
  7431. Figure~\ref{fig:interp-R5} shows the definitional interpreter for
  7432. $R_5$. The clause for \key{lambda} saves the current environment
  7433. inside the returned \key{lambda}. Then the clause for \key{Apply} uses
  7434. the environment from the \key{lambda}, the \code{lam-env}, when
  7435. interpreting the body of the \key{lambda}. The \code{lam-env}
  7436. environment is extended with the mapping of parameters to argument
  7437. values.
  7438. \begin{figure}[tbp]
  7439. \begin{lstlisting}
  7440. UPDATE ME
  7441. \end{lstlisting}
  7442. \caption{Interpreter for $R_5$.}
  7443. \label{fig:interp-R5}
  7444. \end{figure}
  7445. \label{sec:type-check-r5}
  7446. \index{type checking}
  7447. Figure~\ref{fig:type-check-R5} shows how to type check the new
  7448. \key{lambda} form. The body of the \key{lambda} is checked in an
  7449. environment that includes the current environment (because it is
  7450. lexically scoped) and also includes the \key{lambda}'s parameters. We
  7451. require the body's type to match the declared return type.
  7452. \begin{figure}[tbp]
  7453. \begin{lstlisting}
  7454. (define (type-check-R5 env)
  7455. (lambda (e)
  7456. (match e
  7457. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  7458. (define-values (new-body bodyT)
  7459. ((type-check-exp (append (map cons xs Ts) env)) body))
  7460. (define ty `(,@Ts -> ,rT))
  7461. (cond
  7462. [(equal? rT bodyT)
  7463. (values (HasType (Lambda params rT new-body) ty) ty)]
  7464. [else
  7465. (error "mismatch in return type" bodyT rT)])]
  7466. ...
  7467. )))
  7468. \end{lstlisting}
  7469. \caption{Type checking the \key{lambda}'s in $R_5$.}
  7470. \label{fig:type-check-R5}
  7471. \end{figure}
  7472. \section{Closure Conversion}
  7473. \label{sec:closure-conversion}
  7474. \index{closure conversion}
  7475. The compiling of lexically-scoped functions into top-level function
  7476. definitions is accomplished in the pass \code{convert-to-closures}
  7477. that comes after \code{reveal-functions} and before
  7478. \code{limit-functions}.
  7479. As usual, we implement the pass as a recursive function over the
  7480. AST. All of the action is in the clauses for \key{lambda} and
  7481. \key{Apply}. We transform a \key{lambda} expression into an expression
  7482. that creates a closure, that is, creates a vector whose first element
  7483. is a function pointer and the rest of the elements are the free
  7484. variables of the \key{lambda}. The \itm{name} is a unique symbol
  7485. generated to identify the function.
  7486. \begin{tabular}{lll}
  7487. \begin{minipage}{0.4\textwidth}
  7488. \begin{lstlisting}
  7489. (lambda: (|\itm{ps}| ...) : |\itm{rt}| |\itm{body}|)
  7490. \end{lstlisting}
  7491. \end{minipage}
  7492. &
  7493. $\Rightarrow$
  7494. &
  7495. \begin{minipage}{0.4\textwidth}
  7496. \begin{lstlisting}
  7497. (vector |\itm{name}| |\itm{fvs}| ...)
  7498. \end{lstlisting}
  7499. \end{minipage}
  7500. \end{tabular} \\
  7501. %
  7502. In addition to transforming each \key{lambda} into a \key{vector}, we
  7503. must create a top-level function definition for each \key{lambda}, as
  7504. shown below.\\
  7505. \begin{minipage}{0.8\textwidth}
  7506. \begin{lstlisting}
  7507. (define (|\itm{name}| [clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps}| ...)
  7508. (let ([|$\itm{fvs}_1$| (vector-ref clos 1)])
  7509. ...
  7510. (let ([|$\itm{fvs}_n$| (vector-ref clos |$n$|)])
  7511. |\itm{body'}|)...))
  7512. \end{lstlisting}
  7513. \end{minipage}\\
  7514. The \code{clos} parameter refers to the closure. The $\itm{ps}$
  7515. parameters are the normal parameters of the \key{lambda}. The types
  7516. $\itm{fvts}$ are the types of the free variables in the lambda and the
  7517. underscore is a dummy type because it is rather difficult to give a
  7518. type to the function in the closure's type, and it does not matter.
  7519. The sequence of \key{let} forms bind the free variables to their
  7520. values obtained from the closure.
  7521. We transform function application into code that retrieves the
  7522. function pointer from the closure and then calls the function, passing
  7523. in the closure as the first argument. We bind $e'$ to a temporary
  7524. variable to avoid code duplication.
  7525. \begin{tabular}{lll}
  7526. \begin{minipage}{0.3\textwidth}
  7527. \begin{lstlisting}
  7528. (app |$e$| |\itm{es}| ...)
  7529. \end{lstlisting}
  7530. \end{minipage}
  7531. &
  7532. $\Rightarrow$
  7533. &
  7534. \begin{minipage}{0.5\textwidth}
  7535. \begin{lstlisting}
  7536. (let ([|\itm{tmp}| |$e'$|])
  7537. (app (vector-ref |\itm{tmp}| 0) |\itm{tmp}| |\itm{es'}|))
  7538. \end{lstlisting}
  7539. \end{minipage}
  7540. \end{tabular} \\
  7541. There is also the question of what to do with top-level function
  7542. definitions. To maintain a uniform translation of function
  7543. application, we turn function references into closures.
  7544. \begin{tabular}{lll}
  7545. \begin{minipage}{0.3\textwidth}
  7546. \begin{lstlisting}
  7547. (fun-ref |$f$|)
  7548. \end{lstlisting}
  7549. \end{minipage}
  7550. &
  7551. $\Rightarrow$
  7552. &
  7553. \begin{minipage}{0.5\textwidth}
  7554. \begin{lstlisting}
  7555. (vector (fun-ref |$f$|))
  7556. \end{lstlisting}
  7557. \end{minipage}
  7558. \end{tabular} \\
  7559. %
  7560. The top-level function definitions need to be updated as well to take
  7561. an extra closure parameter.
  7562. \section{An Example Translation}
  7563. \label{sec:example-lambda}
  7564. Figure~\ref{fig:lexical-functions-example} shows the result of
  7565. \code{reveal-functions} and then \code{convert-to-closures} for the
  7566. example program demonstrating lexical scoping that we discussed at the
  7567. beginning of this chapter.
  7568. \begin{figure}[h]
  7569. \begin{minipage}{0.8\textwidth}
  7570. % tests/s4_6.rkt
  7571. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  7572. (define (f74 [x75 : Integer]) : (Integer -> Integer)
  7573. (let ([y76 4])
  7574. (lambda: ( [z77 : Integer]) : Integer
  7575. (+ x75 (+ y76 z77)))))
  7576. (define (main) : Integer
  7577. (let ([g78 ((fun-ref f74) 5)])
  7578. (let ([h79 ((fun-ref f74) 3)])
  7579. (+ (g78 11) (h79 15)))))
  7580. \end{lstlisting}
  7581. $\Downarrow$
  7582. \begin{lstlisting}%[basicstyle=\ttfamily\footnotesize]
  7583. (define (f74 [fvs82 : _] [x75 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  7584. (let ([y76 4])
  7585. (vector (fun-ref lambda80) x75 y76)))
  7586. (define (lambda80 [fvs81 : (Vector _ Integer Integer)] [z77 : Integer]) : Integer
  7587. (let ([x75 (vector-ref fvs81 1)])
  7588. (let ([y76 (vector-ref fvs81 2)])
  7589. (+ x75 (+ y76 z77)))))
  7590. (define (main) : Integer
  7591. (let ([g78 (let ([app83 (vector (fun-ref f74))])
  7592. ((vector-ref app83 0) app83 5))])
  7593. (let ([h79 (let ([app84 (vector (fun-ref f74))])
  7594. ((vector-ref app84 0) app84 3))])
  7595. (+ (let ([app85 g78])
  7596. ((vector-ref app85 0) app85 11))
  7597. (let ([app86 h79])
  7598. ((vector-ref app86 0) app86 15))))))
  7599. \end{lstlisting}
  7600. \end{minipage}
  7601. \caption{Example of closure conversion.}
  7602. \label{fig:lexical-functions-example}
  7603. \end{figure}
  7604. \begin{figure}[p]
  7605. \begin{tikzpicture}[baseline=(current bounding box.center)]
  7606. \node (R4) at (0,2) {\large $R_4$};
  7607. \node (R4-2) at (3,2) {\large $R_4$};
  7608. \node (R4-3) at (6,2) {\large $R_4$};
  7609. \node (F1-1) at (12,0) {\large $F_1$};
  7610. \node (F1-2) at (9,0) {\large $F_1$};
  7611. \node (F1-3) at (6,0) {\large $F_1$};
  7612. \node (F1-4) at (3,0) {\large $F_1$};
  7613. \node (F1-5) at (0,0) {\large $F_1$};
  7614. \node (C3-1) at (6,-2) {\large $C_3$};
  7615. \node (C3-2) at (3,-2) {\large $C_3$};
  7616. \node (x86-2) at (3,-4) {\large $\text{x86}^{*}_3$};
  7617. \node (x86-3) at (6,-4) {\large $\text{x86}^{*}_3$};
  7618. \node (x86-4) at (9,-4) {\large $\text{x86}^{*}_3$};
  7619. \node (x86-5) at (9,-6) {\large $\text{x86}^{\dagger}_3$};
  7620. \node (x86-2-1) at (3,-6) {\large $\text{x86}^{*}_3$};
  7621. \node (x86-2-2) at (6,-6) {\large $\text{x86}^{*}_3$};
  7622. \path[->,bend left=15] (R4) edge [above] node
  7623. {\ttfamily\footnotesize\color{red} type-check} (R4-2);
  7624. \path[->,bend left=15] (R4-2) edge [above] node
  7625. {\ttfamily\footnotesize uniquify} (R4-3);
  7626. \path[->] (R4-3) edge [right] node
  7627. {\ttfamily\footnotesize reveal-functions} (F1-1);
  7628. \path[->,bend left=15] (F1-1) edge [below] node
  7629. {\ttfamily\footnotesize\color{red} convert-to-clos.} (F1-2);
  7630. \path[->,bend right=15] (F1-2) edge [above] node
  7631. {\ttfamily\footnotesize limit-functions} (F1-3);
  7632. \path[->,bend right=15] (F1-3) edge [above] node
  7633. {\ttfamily\footnotesize expose-alloc.} (F1-4);
  7634. \path[->,bend right=15] (F1-4) edge [above] node
  7635. {\ttfamily\footnotesize remove-complex.} (F1-5);
  7636. \path[->] (F1-5) edge [left] node
  7637. {\ttfamily\footnotesize explicate-control} (C3-1);
  7638. \path[->,bend left=15] (C3-1) edge [below] node
  7639. {\ttfamily\footnotesize uncover-locals} (C3-2);
  7640. \path[->,bend right=15] (C3-2) edge [left] node
  7641. {\ttfamily\footnotesize select-instr.} (x86-2);
  7642. \path[->,bend left=15] (x86-2) edge [left] node
  7643. {\ttfamily\footnotesize uncover-live} (x86-2-1);
  7644. \path[->,bend right=15] (x86-2-1) edge [below] node
  7645. {\ttfamily\footnotesize build-inter.} (x86-2-2);
  7646. \path[->,bend right=15] (x86-2-2) edge [left] node
  7647. {\ttfamily\footnotesize allocate-reg.} (x86-3);
  7648. \path[->,bend left=15] (x86-3) edge [above] node
  7649. {\ttfamily\footnotesize patch-instr.} (x86-4);
  7650. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  7651. \end{tikzpicture}
  7652. \caption{Diagram of the passes for $R_5$, a language with lexically-scoped
  7653. functions.}
  7654. \label{fig:R5-passes}
  7655. \end{figure}
  7656. Figure~\ref{fig:R5-passes} provides an overview of all the passes needed
  7657. for the compilation of $R_5$.
  7658. \begin{exercise}\normalfont
  7659. Expand your compiler to handle $R_5$ as outlined in this chapter.
  7660. Create 5 new programs that use \key{lambda} functions and make use of
  7661. lexical scoping. Test your compiler on these new programs and all of
  7662. your previously created test programs.
  7663. \end{exercise}
  7664. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7665. \chapter{Dynamic Typing}
  7666. \label{ch:type-dynamic}
  7667. \index{dynamic typing}
  7668. In this chapter we discuss the compilation $R_7$, a dynamically typed
  7669. language and a subset of the Racket language. Recall that in the
  7670. previous chapters we have compiled subsets of the \emph{Typed} Racket
  7671. language. In dynamically typed languages, each evaluation of an
  7672. expression may produce a value of a different type. Consider the
  7673. following example with a conditional expression that may return a
  7674. Boolean or an integer depending on the input to the program.
  7675. \begin{lstlisting}
  7676. (not (if (eq? (read) 1) #f 0))
  7677. \end{lstlisting}
  7678. Languages that allow expressions to produce different kinds of values
  7679. are called \emph{polymorphic}, a word composed of the Greek roots
  7680. ``poly'', meaning ``many'', and ``morph'', meaning ``shape''. There
  7681. are several kinds of polymorphism in programming languages, such as
  7682. subtype polymorphism and parametric
  7683. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  7684. study in this chapter does not have a special name but it is the kind
  7685. that arises in dynamically typed languages.
  7686. Another characteristic of dynamically typed languages is that
  7687. primitive operations, such as \code{not}, are often defined to operate
  7688. on many different types of values. In fact, in Racket, the \code{not}
  7689. operator produces a result for any kind of value: given \code{\#f} it
  7690. returns \code{\#t} and given anything else it returns \code{\#f}.
  7691. Furthermore, even when primitive operations restrict their inputs to
  7692. values of a certain type, this restriction is enforced at runtime
  7693. instead of during compilation. For example, the following vector
  7694. reference results in a run-time contract violation because the index
  7695. must be in integer, not a Boolean such as \code{\#t}.
  7696. \begin{lstlisting}
  7697. (vector-ref (vector 42) #t)
  7698. \end{lstlisting}
  7699. \begin{figure}[tp]
  7700. \centering
  7701. \fbox{
  7702. \begin{minipage}{0.97\textwidth}
  7703. \[
  7704. \begin{array}{rcl}
  7705. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  7706. \Exp &::=& \Int \mid \CREAD{} \mid \CNEG{\Exp}
  7707. \mid \CADD{\Exp}{\Exp} \mid \CSUB{\Exp}{\Exp} \\
  7708. &\mid& \Var \mid \CLET{\Var}{\Exp}{\Exp} \\
  7709. &\mid& \key{\#t} \mid \key{\#f}
  7710. \mid \CBINOP{\key{and}}{\Exp}{\Exp}
  7711. \mid \CBINOP{\key{or}}{\Exp}{\Exp}
  7712. \mid \CUNIOP{\key{not}}{\Exp} \\
  7713. &\mid& \LP\itm{cmp}\;\Exp\;\Exp\RP \mid \CIF{\Exp}{\Exp}{\Exp} \\
  7714. &\mid& \LP\key{vector}\;\Exp\ldots\RP \mid
  7715. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  7716. &\mid& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \mid \LP\key{void}\RP \\
  7717. &\mid& \LP\Exp \; \Exp\ldots\RP
  7718. \mid \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  7719. & \mid & \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP\\
  7720. & \mid & \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \mid \LP\key{void?}\;\Exp\RP \\
  7721. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  7722. R_7 &::=& \Def\ldots\; \Exp
  7723. \end{array}
  7724. \]
  7725. \end{minipage}
  7726. }
  7727. \caption{Syntax of $R_7$, an untyped language (a subset of Racket).}
  7728. \label{fig:r7-concrete-syntax}
  7729. \end{figure}
  7730. \begin{figure}[tp]
  7731. \centering
  7732. \fbox{
  7733. \begin{minipage}{0.96\textwidth}
  7734. \small
  7735. \[
  7736. \begin{array}{lcl}
  7737. \Exp &::=& \INT{\Int} \mid \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} \\
  7738. &\mid& \PRIM{\itm{op}}{\Exp\ldots} \\
  7739. &\mid& \BOOL{\itm{bool}}
  7740. \mid \IF{\Exp}{\Exp}{\Exp} \\
  7741. &\mid& \VOID{} \mid \APPLY{\Exp}{\Exp\ldots} \\
  7742. &\mid& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  7743. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  7744. R_7 &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  7745. \end{array}
  7746. \]
  7747. \end{minipage}
  7748. }
  7749. \caption{The abstract syntax of $R_7$.}
  7750. \label{fig:r7-syntax}
  7751. \end{figure}
  7752. The concrete and abstract syntax of $R_7$, our subset of Racket, is
  7753. defined in Figures~\ref{fig:r7-concrete-syntax} and
  7754. \ref{fig:r7-syntax}.
  7755. %
  7756. There is no type checker for $R_7$ because it is not a statically
  7757. typed language (it's dynamically typed!).
  7758. %
  7759. The definitional interpreter for $R_7$ is presented in
  7760. Figure~\ref{fig:interp-R7}.
  7761. \begin{figure}[tbp]
  7762. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7763. (define (interp-R7-exp env)
  7764. (lambda (ast)
  7765. (define recur (interp-R7-exp env))
  7766. (match ast
  7767. [(Var x) (lookup x env)]
  7768. [(Int n) `(tagged ,n Integer)]
  7769. [(Bool b) `(tagged ,b Boolean)]
  7770. [(Prim 'read '()) `(tagged ,(read-fixnum) Integer)]
  7771. [(Lambda xs rt body)
  7772. `(tagged (lambda ,xs ,body ,env) (,@(for/list ([x xs]) 'Any) -> Any))]
  7773. [(Prim 'vector es)
  7774. `(tagged ,(apply vector (for/list ([e es]) (recur e)))
  7775. (Vector ,@(for/list ([e es]) 'Any)))]
  7776. [(Prim 'vector-set! (list e1 n e2))
  7777. (define vec (value-of-any (recur e1)))
  7778. (define i (value-of-any (recur n)))
  7779. (vector-set! vec i (recur e2))
  7780. `(tagged ,(void) Void)]
  7781. [(Prim 'vector-ref (list e1 n))
  7782. (define vec (value-of-any (recur e1)))
  7783. (define i (value-of-any (recur n)))
  7784. (vector-ref vec i)]
  7785. [(Let x e body)
  7786. (define v (recur e))
  7787. ((interp-R7-exp (cons (cons x v) env)) body)]
  7788. [(Prim 'and (list e1 e2))
  7789. (recur (If e1 e2 (Bool #f)))]
  7790. [(Prim 'or (list e1 e2))
  7791. (define v1 (recur e1))
  7792. (match (value-of-any v1) [#f (recur e2)] [else v1])]
  7793. [(Prim 'eq? (list l r))
  7794. `(tagged ,(equal? (recur l) (recur r)) Boolean)]
  7795. [(If q t f)
  7796. (match (value-of-any (recur q)) [#f (recur f)] [else (recur t)])]
  7797. [(Prim op es)
  7798. (tag-value
  7799. (apply (interp-op op) (for/list ([e es]) (value-of-any (recur e)))))]
  7800. [(Apply f es)
  7801. (define new-args (map recur es))
  7802. (let ([f-val (value-of-any (recur f))])
  7803. (match f-val
  7804. [`(lambda (,xs ...) ,body ,lam-env)
  7805. (define new-env (append (map cons xs new-args) lam-env))
  7806. ((interp-R7-exp new-env) body)]
  7807. [else (error "interp-R7-exp, expected function, not" f-val)]))]
  7808. )))
  7809. \end{lstlisting}
  7810. \caption{Interpreter for the $R_7$ language.}
  7811. \label{fig:interp-R7}
  7812. \end{figure}
  7813. Let us consider how we might compile $R_7$ to x86, thinking about the
  7814. first example above. Our bit-level representation of the Boolean
  7815. \code{\#f} is zero and similarly for the integer \code{0}. However,
  7816. \code{(not \#f)} should produce \code{\#t} whereas \code{(not 0)}
  7817. should produce \code{\#f}. Furthermore, the behavior of \code{not}, in
  7818. general, cannot be determined at compile time, but depends on the
  7819. runtime type of its input, as in the example above that depends on the
  7820. result of \code{(read)}.
  7821. The way around this problem is to include information about a value's
  7822. runtime type in the value itself, so that this information can be
  7823. inspected by operators such as \code{not}. In particular, we
  7824. steal the 3 right-most bits from our 64-bit values to encode the
  7825. runtime type. We use $001$ to identify integers, $100$ for
  7826. Booleans, $010$ for vectors, $011$ for procedures, and $101$ for the
  7827. void value. We refer to these 3 bits as the \emph{tag} and we
  7828. define the following auxiliary function.
  7829. \begin{align*}
  7830. \itm{tagof}(\key{Integer}) &= 001 \\
  7831. \itm{tagof}(\key{Boolean}) &= 100 \\
  7832. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  7833. \itm{tagof}((\key{Vectorof} \ldots)) &= 010 \\
  7834. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  7835. \itm{tagof}(\key{Void}) &= 101
  7836. \end{align*}
  7837. (We say more about the new \key{Vectorof} type shortly.)
  7838. This stealing of 3 bits comes at some
  7839. price: our integers are reduced to ranging from $-2^{60}$ to
  7840. $2^{60}$. The stealing does not adversely affect vectors and
  7841. procedures because those values are addresses, and our addresses are
  7842. 8-byte aligned so the rightmost 3 bits are unused, they are always
  7843. $000$. Thus, we do not lose information by overwriting the rightmost 3
  7844. bits with the tag and we can simply zero-out the tag to recover the
  7845. original address.
  7846. In some sense, these tagged values are a new kind of value. Indeed,
  7847. we can extend our \emph{typed} language with tagged values by adding a
  7848. new type to classify them, called \key{Any}, and with operations for
  7849. creating and using tagged values, yielding the $R_6$ language that we
  7850. define in Section~\ref{sec:r6-lang}. The $R_6$ language provides the
  7851. fundamental support for polymorphism and runtime types that we need to
  7852. support dynamic typing.
  7853. There is an interesting interaction between tagged values and garbage
  7854. collection. A variable of type \code{Any} might refer to a vector and
  7855. therefore it might be a root that needs to be inspected and copied
  7856. during garbage collection. Thus, we need to treat variables of type
  7857. \code{Any} in a similar way to variables of type \code{Vector} for
  7858. purposes of register allocation, which we discuss in
  7859. Section~\ref{sec:register-allocation-r6}. One concern is that, if a
  7860. variable of type \code{Any} is spilled, it must be spilled to the root
  7861. stack. But this means that the garbage collector needs to be able to
  7862. differentiate between (1) plain old pointers to tuples, (2) a tagged
  7863. value that points to a tuple, and (3) a tagged value that is not a
  7864. tuple. We enable this differentiation by choosing not to use the tag
  7865. $000$ in $\itm{tagof}$. Instead, that bit pattern is reserved for
  7866. identifying plain old pointers to tuples. That way, if one of the
  7867. first three bits is set, then we have a tagged value and inspecting
  7868. the tag can differentiation between vectors ($010$) and the other
  7869. kinds of values.
  7870. We implement our untyped language $R_7$ by compiling it to $R_6$
  7871. (Section~\ref{sec:compile-r7}), but first we describe the how to
  7872. extend our compiler to handle the new features of $R_6$
  7873. (Sections~\ref{sec:shrink-r6}, \ref{sec:select-r6}, and
  7874. \ref{sec:register-allocation-r6}).
  7875. \section{The $R_6$ Language: Typed Racket $+$ \key{Any}}
  7876. \label{sec:r6-lang}
  7877. \begin{figure}[tp]
  7878. \centering
  7879. \fbox{
  7880. \begin{minipage}{0.97\textwidth}\small
  7881. \[
  7882. \begin{array}{lcl}
  7883. \Type &::=& \gray{\key{Integer} \mid \key{Boolean}
  7884. \mid \LP\key{Vector}\;\Type\ldots\RP \mid \LP\key{Vectorof}\;\Type\RP \mid \key{Void}} \\
  7885. &\mid& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \mid \key{Any} \\
  7886. \FType &::=& \key{Integer} \mid \key{Boolean} \mid \key{Void} \mid \LP\key{Vectorof}\;\key{Any}\RP \mid \LP\key{Vector}\; \key{Any}\ldots\RP \\
  7887. &\mid& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  7888. \itm{cmp} &::= & \key{eq?} \mid \key{<} \mid \key{<=} \mid \key{>} \mid \key{>=} \\
  7889. \Exp &::=& \ldots
  7890. \mid \CINJECT{\Exp}{\FType}\RP \mid \CPROJECT{\Exp}{\FType} \\
  7891. & \mid & \LP\key{boolean?}\;\Exp\RP \mid \LP\key{integer?}\;\Exp\RP\\
  7892. & \mid & \LP\key{vector?}\;\Exp\RP \mid \LP\key{procedure?}\;\Exp\RP \mid \LP\key{void?}\;\Exp\RP \\
  7893. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  7894. R_6 &::=& \gray{\Def\ldots \; \Exp}
  7895. \end{array}
  7896. \]
  7897. \end{minipage}
  7898. }
  7899. \caption{Concrete syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax})
  7900. with \key{Any}.}
  7901. \label{fig:r6-concrete-syntax}
  7902. \end{figure}
  7903. \begin{figure}[tp]
  7904. \centering
  7905. \fbox{
  7906. \begin{minipage}{0.96\textwidth}
  7907. \small
  7908. \[
  7909. \begin{array}{lcl}
  7910. \itm{op} &::= & \code{boolean?} \mid \code{integer?} \mid \code{vector?}
  7911. \mid \code{procedure?} \mid \code{void?} \\
  7912. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \mid \LET{\Var}{\Exp}{\Exp} } \\
  7913. &\mid& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  7914. &\mid& \gray{ \BOOL{\itm{bool}}
  7915. \mid \IF{\Exp}{\Exp}{\Exp} } \\
  7916. &\mid& \gray{ \VOID{} \mid \LP\key{HasType}~\Exp~\Type \RP
  7917. \mid \APPLY{\Exp}{\Exp\ldots} }\\
  7918. &\mid& \gray{ \LAMBDA{\LP[\Var\code{:}\Type]\ldots\RP}{\Type}{\Exp} }\\
  7919. &\mid& \INJECT{\Exp}{\FType} \mid \PROJECT{\Exp}{\FType} \\
  7920. \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  7921. R_5 &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  7922. \end{array}
  7923. \]
  7924. \end{minipage}
  7925. }
  7926. \caption{The abstract syntax of $R_6$, extending $R_5$ (Figure~\ref{fig:r5-syntax}).}
  7927. \label{fig:r6-syntax}
  7928. \end{figure}
  7929. The concrete and abstract syntax of $R_6$ is defined in
  7930. Figures~\ref{fig:r6-concrete-syntax} and \ref{fig:r6-syntax}. The
  7931. $\LP\key{inject}\; e\; T\RP$ form converts the value produced by
  7932. expression $e$ of type $T$ into a tagged value. The
  7933. $\LP\key{project}\;e\;T\RP$ form converts the tagged value produced by
  7934. expression $e$ into a value of type $T$ or else halts the program if
  7935. the type tag is not equivalent to $T$. We treat
  7936. $\LP\key{Vectorof}\;\key{Any}\RP$ as equivalent to
  7937. $\LP\key{Vector}\;\key{Any}\;\ldots\RP$.
  7938. %
  7939. Note that in both \key{inject} and \key{project}, the type $T$ is
  7940. restricted to the flat types $\FType$, which simplifies the
  7941. implementation and corresponds with what is needed for compiling
  7942. untyped Racket.
  7943. The type predicates such as $\LP\key{boolean?}\,e\RP$ expect the
  7944. expression $e$ to produce a tagged value; they return \key{\#t} if the
  7945. tag corresponds to the predicate and they return \key{\#f} otherwise.
  7946. The type checker for $R_6$ is shown in Figure~\ref{fig:type-check-R6}
  7947. and the interpreter for $R_6$ is in Figure~\ref{fig:interp-R6}.
  7948. \begin{figure}[btp]
  7949. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7950. (define (operator-types)
  7951. '(...
  7952. (integer? . ((Any) . Boolean))
  7953. (vector? . ((Any) . Boolean))
  7954. (procedure? . ((Any) . Boolean))
  7955. (void? . ((Any) . Boolean))
  7956. ))
  7957. (define (type-check-exp env)
  7958. (lambda (e)
  7959. (define recur (type-check-exp env))
  7960. (match e
  7961. ...
  7962. [(Inject e ty)
  7963. (unless (flat-ty? ty)
  7964. (error 'type-check-exp
  7965. "may only inject a value of flat type, not ~a" ty))
  7966. (define-values (new-e e-ty) (recur e))
  7967. (cond
  7968. [(type-equal? e-ty ty)
  7969. (values (Inject new-e ty) 'Any)]
  7970. [else
  7971. (error 'type-check-exp
  7972. "injected expression does not have expected type"
  7973. e e-ty ty)])]
  7974. [(Project e ty)
  7975. (unless (flat-ty? ty)
  7976. (error 'type-check-exp
  7977. "may only project to a flat type, not ~a" ty))
  7978. (define-values (new-e e-ty) (recur e))
  7979. (cond
  7980. [(type-equal? e-ty 'Any)
  7981. (values (Project new-e ty) ty)]
  7982. [else
  7983. (error 'type-check-exp
  7984. "project expression does not have type Any" e)])]
  7985. [(Prim pred (list e))
  7986. #:when (set-member? type-predicates pred)
  7987. (define-values (new-e e-ty) (recur e))
  7988. (cond
  7989. [(type-equal? e-ty 'Any)
  7990. (values (Prim pred (list new-e)) 'Boolean)]
  7991. [else
  7992. (error 'type-check-exp
  7993. "type predicate expected argument of type Any, not ~a" e-ty)])]
  7994. ...
  7995. [else
  7996. (error 'type-check-exp "R6/unmatched ~a" e)]
  7997. )))
  7998. \end{lstlisting}
  7999. \caption{Type checker for the $R_6$ language.}
  8000. \label{fig:type-check-R6}
  8001. \end{figure}
  8002. % to do: add rules for vector-ref, etc. for Vectorof
  8003. %Also, \key{eq?} is extended to operate on values of type \key{Any}.
  8004. \begin{figure}[btp]
  8005. \begin{lstlisting}
  8006. (define (interp-op op)
  8007. (match op
  8008. ...
  8009. ['boolean? (lambda (v)
  8010. (match v
  8011. [`(tagged ,v1 ,tg)
  8012. (equal? tg (any-tag 'Boolean))]
  8013. [else #f]))]
  8014. ['integer? (lambda (v)
  8015. (match v
  8016. [`(tagged ,v1 ,tg)
  8017. (equal? tg (any-tag 'Integer))]
  8018. [else #f]))]
  8019. ['vector? (lambda (v)
  8020. (match v
  8021. [`(tagged ,v1 ,tg)
  8022. (equal? tg (any-tag `(Vector Any)))]
  8023. [else #f]))]
  8024. ['procedure? (lambda (v)
  8025. (match v
  8026. [`(tagged ,v1 ,tg)
  8027. (equal? tg (any-tag `(Any -> Any)))]
  8028. [else #f]))]
  8029. ...
  8030. ))
  8031. (define (interp-exp env)
  8032. (lambda (e)
  8033. (define recur (interp-exp env))
  8034. (let ([ret
  8035. (match e
  8036. ...
  8037. [(Inject e ty)
  8038. (apply-inject ((interp-exp env) e) (any-tag ty))]
  8039. [(Project e ty2)
  8040. (define v (recur e))
  8041. (apply-project v ty2)]
  8042. [(Exit)
  8043. (error 'interp-exp "exiting")]
  8044. [else (error 'interp-exp "unrecognized expression ~a" e)]
  8045. )])
  8046. (verbose "R6/interp-exp ==>" ret)
  8047. ret)))
  8048. \end{lstlisting}
  8049. \caption{Interpreter for $R_6$.}
  8050. \label{fig:interp-R6}
  8051. \end{figure}
  8052. %\clearpage
  8053. \section{Shrinking $R_6$}
  8054. \label{sec:shrink-r6}
  8055. In the \code{shrink} pass we recommend compiling \code{Project} into
  8056. an explicit \code{If} expression that uses two new forms,
  8057. \code{ValueOf} and \code{Exit}, and a new primitive operation,
  8058. \code{tag-of-any}. The \code{tag-of-any} operation retrieves the type
  8059. tag from a tagged value of type \code{Any}. The \code{ValueOf} form
  8060. retrieves the underlying value from a tagged value. The
  8061. \code{ValueOf} form includes the type for the underlying value which
  8062. is used by the type checker. Finally, the \code{Exit} form ends the
  8063. execution of the program.
  8064. %
  8065. If the target type of the projection is \code{Boolean} or
  8066. \code{Integer}, then \code{Project} can be translated as follows.
  8067. %(We have omitted the \code{has-type} AST nodes to make this
  8068. %output more readable.)
  8069. \begin{center}
  8070. \begin{minipage}{1.0\textwidth}
  8071. \begin{lstlisting}
  8072. (Project |$e$| |$\FType$|)
  8073. |$\Rightarrow$|
  8074. (Let |$\itm{tmp}$| |$e'$|
  8075. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  8076. (Int |$\itm{tagof}(\FType)$|)))
  8077. (ValueOf |$\itm{tmp}$| |$\FType$|)
  8078. (Exit)))
  8079. \end{lstlisting}
  8080. \end{minipage}
  8081. \end{center}
  8082. If the target type of the projection is a vector or function type,
  8083. then there is a bit more work to do. For vectors, check that the
  8084. length of the vector (use the \code{vector-length} primitive) matches
  8085. the length of the vector type. For functions, check that its arity
  8086. (\code{procedure-arity}) matches the number of parameters in the
  8087. function type.
  8088. Regarding \code{Inject}, we recommend compiling it to a slightly
  8089. lower-level primitive operation named \code{make-any}. This operation
  8090. takes a tag instead of a type. \\
  8091. \begin{center}
  8092. \begin{minipage}{1.0\textwidth}
  8093. \begin{lstlisting}
  8094. (Inject |$e$| |$\FType$|)
  8095. |$\Rightarrow$|
  8096. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  8097. \end{lstlisting}
  8098. \end{minipage}
  8099. \end{center}
  8100. We recommend translating the type predicates (\code{boolean?}, etc.)
  8101. into uses of \code{tag-of-any} and \code{eq?}.
  8102. \section{Closure Conversion for $R_6$}
  8103. \label{sec:closure-conversion-R6}
  8104. \section{Instruction Selection for $R_6$}
  8105. \label{sec:select-r6}
  8106. \paragraph{Inject}
  8107. We recommend compiling an \key{inject} as follows if the type is
  8108. \key{Integer} or \key{Boolean}. The \key{salq} instruction shifts the
  8109. destination to the left by the number of bits specified its source
  8110. argument (in this case $3$, the length of the tag) and it preserves
  8111. the sign of the integer. We use the \key{orq} instruction to combine
  8112. the tag and the value to form the tagged value. \\
  8113. \begin{tabular}{lll}
  8114. \begin{minipage}{0.4\textwidth}
  8115. \begin{lstlisting}
  8116. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  8117. \end{lstlisting}
  8118. \end{minipage}
  8119. &
  8120. $\Rightarrow$
  8121. &
  8122. \begin{minipage}{0.5\textwidth}
  8123. \begin{lstlisting}
  8124. (movq |$e'$| |\itm{lhs}'|)
  8125. (salq (int 3) |\itm{lhs}'|)
  8126. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  8127. \end{lstlisting}
  8128. \end{minipage}
  8129. \end{tabular} \\
  8130. The instruction selection for vectors and procedures is different
  8131. because their is no need to shift them to the left. The rightmost 3
  8132. bits are already zeros as described above. So we just combine the
  8133. value and the tag using \key{orq}. \\
  8134. \begin{tabular}{lll}
  8135. \begin{minipage}{0.4\textwidth}
  8136. \begin{lstlisting}
  8137. (assign |\itm{lhs}| (inject |$e$| |$T$|))
  8138. \end{lstlisting}
  8139. \end{minipage}
  8140. &
  8141. $\Rightarrow$
  8142. &
  8143. \begin{minipage}{0.5\textwidth}
  8144. \begin{lstlisting}
  8145. (movq |$e'$| |\itm{lhs}'|)
  8146. (orq (int |$\itm{tagof}(T)$|) |\itm{lhs}'|)
  8147. \end{lstlisting}
  8148. \end{minipage}
  8149. \end{tabular}
  8150. \paragraph{Tag of Any}
  8151. Recall that the \code{tag-of-any} operation extracts the type tag from
  8152. a value of type \code{Any}. The type tag is the bottom three bits, so
  8153. we obtain the tag by taking the bitwise-and of the value with $111$
  8154. ($7$ in decimal).
  8155. \begin{tabular}{lll}
  8156. \begin{minipage}{0.4\textwidth}
  8157. \begin{lstlisting}
  8158. (assign |\itm{lhs}| (tag-of-any |$e$|))
  8159. \end{lstlisting}
  8160. \end{minipage}
  8161. &
  8162. $\Rightarrow$
  8163. &
  8164. \begin{minipage}{0.5\textwidth}
  8165. \begin{lstlisting}
  8166. (movq |$e'$| |\itm{lhs}'|)
  8167. (andq (int 7) |\itm{lhs}'|)
  8168. \end{lstlisting}
  8169. \end{minipage}
  8170. \end{tabular}
  8171. \paragraph{Value of Any}
  8172. Like \key{inject}, the instructions for \key{value-of-any} are
  8173. different depending on whether the type $T$ is a pointer (vector or
  8174. procedure) or not (Integer or Boolean). The following shows the
  8175. instruction selection for Integer and Boolean. We produce an untagged
  8176. value by shifting it to the right by 3 bits.
  8177. %
  8178. \\
  8179. \begin{tabular}{lll}
  8180. \begin{minipage}{0.4\textwidth}
  8181. \begin{lstlisting}
  8182. (assign |\itm{lhs}| (project |$e$| |$T$|))
  8183. \end{lstlisting}
  8184. \end{minipage}
  8185. &
  8186. $\Rightarrow$
  8187. &
  8188. \begin{minipage}{0.5\textwidth}
  8189. \begin{lstlisting}
  8190. (movq |$e'$| |\itm{lhs}'|)
  8191. (sarq (int 3) |\itm{lhs}'|)
  8192. \end{lstlisting}
  8193. \end{minipage}
  8194. \end{tabular} \\
  8195. %
  8196. In the case for vectors and procedures, there is no need to
  8197. shift. Instead we just need to zero-out the rightmost 3 bits. We
  8198. accomplish this by creating the bit pattern $\ldots 0111$ ($7$ in
  8199. decimal) and apply \code{bitwise-not} to obtain $\ldots 1000$ which we
  8200. \code{movq} into the destination $\itm{lhs}$. We then generate
  8201. \code{andq} with the tagged value to get the desired result. \\
  8202. %
  8203. \begin{tabular}{lll}
  8204. \begin{minipage}{0.4\textwidth}
  8205. \begin{lstlisting}
  8206. (assign |\itm{lhs}| (project |$e$| |$T$|))
  8207. \end{lstlisting}
  8208. \end{minipage}
  8209. &
  8210. $\Rightarrow$
  8211. &
  8212. \begin{minipage}{0.5\textwidth}
  8213. \begin{lstlisting}
  8214. (movq (int |$\ldots 1000$|) |\itm{lhs}'|)
  8215. (andq |$e'$| |\itm{lhs}'|)
  8216. \end{lstlisting}
  8217. \end{minipage}
  8218. \end{tabular}
  8219. %% \paragraph{Type Predicates} We leave it to the reader to
  8220. %% devise a sequence of instructions to implement the type predicates
  8221. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  8222. \section{Register Allocation for $R_6$}
  8223. \label{sec:register-allocation-r6}
  8224. \index{register allocation}
  8225. As mentioned above, a variable of type \code{Any} might refer to a
  8226. vector. Thus, the register allocator for $R_6$ needs to treat variable
  8227. of type \code{Any} in the same way that it treats variables of type
  8228. \code{Vector} for purposes of garbage collection. In particular,
  8229. \begin{itemize}
  8230. \item If a variable of type \code{Any} is live during a function call,
  8231. then it must be spilled. One way to accomplish this is to augment
  8232. the pass \code{build-interference} to mark all variables that are
  8233. live after a \code{callq} as interfering with all the registers.
  8234. \item If a variable of type \code{Any} is spilled, it must be spilled
  8235. to the root stack instead of the normal procedure call stack.
  8236. \end{itemize}
  8237. \begin{exercise}\normalfont
  8238. Expand your compiler to handle $R_6$ as discussed in the last few
  8239. sections. Create 5 new programs that use the \code{Any} type and the
  8240. new operations (\code{inject}, \code{project}, \code{boolean?},
  8241. etc.). Test your compiler on these new programs and all of your
  8242. previously created test programs.
  8243. \end{exercise}
  8244. \section{Compiling $R_7$ to $R_6$}
  8245. \label{sec:compile-r7}
  8246. Figure~\ref{fig:compile-r7-r6} shows the compilation of many of the
  8247. $R_7$ forms into $R_6$. An important invariant of this pass is that
  8248. given a subexpression $e$ of $R_7$, the pass will produce an
  8249. expression $e'$ of $R_6$ that has type \key{Any}. For example, the
  8250. first row in Figure~\ref{fig:compile-r7-r6} shows the compilation of
  8251. the Boolean \code{\#t}, which must be injected to produce an
  8252. expression of type \key{Any}.
  8253. %
  8254. The second row of Figure~\ref{fig:compile-r7-r6}, the compilation of
  8255. addition, is representative of compilation for many operations: the
  8256. arguments have type \key{Any} and must be projected to \key{Integer}
  8257. before the addition can be performed.
  8258. The compilation of \key{lambda} (third row of
  8259. Figure~\ref{fig:compile-r7-r6}) shows what happens when we need to
  8260. produce type annotations: we simply use \key{Any}.
  8261. %
  8262. The compilation of \code{if} and \code{eq?} demonstrate how this pass
  8263. has to account for some differences in behavior between $R_7$ and
  8264. $R_6$. The $R_7$ language is more permissive than $R_6$ regarding what
  8265. kind of values can be used in various places. For example, the
  8266. condition of an \key{if} does not have to be a Boolean. For \key{eq?},
  8267. the arguments need not be of the same type (but in that case, the
  8268. result will be \code{\#f}).
  8269. \begin{figure}[btp]
  8270. \centering
  8271. \begin{tabular}{|lll|} \hline
  8272. \begin{minipage}{0.25\textwidth}
  8273. \begin{lstlisting}
  8274. #t
  8275. \end{lstlisting}
  8276. \end{minipage}
  8277. &
  8278. $\Rightarrow$
  8279. &
  8280. \begin{minipage}{0.6\textwidth}
  8281. \begin{lstlisting}
  8282. (inject #t Boolean)
  8283. \end{lstlisting}
  8284. \end{minipage}
  8285. \\[2ex]\hline
  8286. \begin{minipage}{0.25\textwidth}
  8287. \begin{lstlisting}
  8288. (+ |$e_1$| |$e_2$|)
  8289. \end{lstlisting}
  8290. \end{minipage}
  8291. &
  8292. $\Rightarrow$
  8293. &
  8294. \begin{minipage}{0.6\textwidth}
  8295. \begin{lstlisting}
  8296. (inject
  8297. (+ (project |$e'_1$| Integer)
  8298. (project |$e'_2$| Integer))
  8299. Integer)
  8300. \end{lstlisting}
  8301. \end{minipage}
  8302. \\[2ex]\hline
  8303. \begin{minipage}{0.25\textwidth}
  8304. \begin{lstlisting}
  8305. (lambda (|$x_1 \ldots$|) |$e$|)
  8306. \end{lstlisting}
  8307. \end{minipage}
  8308. &
  8309. $\Rightarrow$
  8310. &
  8311. \begin{minipage}{0.6\textwidth}
  8312. \begin{lstlisting}
  8313. (inject (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  8314. (Any|$\ldots$|Any -> Any))
  8315. \end{lstlisting}
  8316. \end{minipage}
  8317. \\[2ex]\hline
  8318. \begin{minipage}{0.25\textwidth}
  8319. \begin{lstlisting}
  8320. (app |$e_0$| |$e_1 \ldots e_n$|)
  8321. \end{lstlisting}
  8322. \end{minipage}
  8323. &
  8324. $\Rightarrow$
  8325. &
  8326. \begin{minipage}{0.6\textwidth}
  8327. \begin{lstlisting}
  8328. (app (project |$e'_0$| (Any|$\ldots$|Any -> Any))
  8329. |$e'_1 \ldots e'_n$|)
  8330. \end{lstlisting}
  8331. \end{minipage}
  8332. \\[2ex]\hline
  8333. \begin{minipage}{0.25\textwidth}
  8334. \begin{lstlisting}
  8335. (vector-ref |$e_1$| |$e_2$|)
  8336. \end{lstlisting}
  8337. \end{minipage}
  8338. &
  8339. $\Rightarrow$
  8340. &
  8341. \begin{minipage}{0.6\textwidth}
  8342. \begin{lstlisting}
  8343. (let ([tmp1 (project |$e'_1$| (Vectorof Any))])
  8344. (let ([tmp2 (project |$e'_2$| Integer)])
  8345. (vector-ref tmp1 tmp2)))
  8346. \end{lstlisting}
  8347. \end{minipage}
  8348. \\[2ex]\hline
  8349. \begin{minipage}{0.25\textwidth}
  8350. \begin{lstlisting}
  8351. (if |$e_1$| |$e_2$| |$e_3$|)
  8352. \end{lstlisting}
  8353. \end{minipage}
  8354. &
  8355. $\Rightarrow$
  8356. &
  8357. \begin{minipage}{0.6\textwidth}
  8358. \begin{lstlisting}
  8359. (if (eq? |$e'_1$| (inject #f Boolean))
  8360. |$e'_3$|
  8361. |$e'_2$|)
  8362. \end{lstlisting}
  8363. \end{minipage}
  8364. \\[2ex]\hline
  8365. \begin{minipage}{0.25\textwidth}
  8366. \begin{lstlisting}
  8367. (eq? |$e_1$| |$e_2$|)
  8368. \end{lstlisting}
  8369. \end{minipage}
  8370. &
  8371. $\Rightarrow$
  8372. &
  8373. \begin{minipage}{0.6\textwidth}
  8374. \begin{lstlisting}
  8375. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  8376. \end{lstlisting}
  8377. \end{minipage}
  8378. \\[2ex]\hline
  8379. \end{tabular}
  8380. \caption{Compiling $R_7$ to $R_6$.}
  8381. \label{fig:compile-r7-r6}
  8382. \end{figure}
  8383. \begin{exercise}\normalfont
  8384. Expand your compiler to handle $R_7$ as outlined in this chapter.
  8385. Create tests for $R_7$ by adapting all of your previous test programs
  8386. by removing type annotations. Add 5 more tests programs that
  8387. specifically rely on the language being dynamically typed. That is,
  8388. they should not be legal programs in a statically typed language, but
  8389. nevertheless, they should be valid $R_7$ programs that run to
  8390. completion without error.
  8391. \end{exercise}
  8392. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8393. \chapter{Gradual Typing}
  8394. \label{ch:gradual-typing}
  8395. \index{gradual typing}
  8396. This chapter will be based on the ideas of \citet{Siek:2006bh}.
  8397. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8398. \chapter{Parametric Polymorphism}
  8399. \label{ch:parametric-polymorphism}
  8400. \index{parametric polymorphism}
  8401. \index{generics}
  8402. This chapter may be based on ideas from \citet{Cardelli:1984aa},
  8403. \citet{Leroy:1992qb}, \citet{Shao:1997uj}, or \citet{Harper:1995um}.
  8404. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8405. \chapter{High-level Optimization}
  8406. \label{ch:high-level-optimization}
  8407. This chapter will present a procedure inlining pass based on the
  8408. algorithm of \citet{Waddell:1997fk}.
  8409. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8410. \chapter{Appendix}
  8411. \section{Interpreters}
  8412. \label{appendix:interp}
  8413. \index{interpreter}
  8414. We provide interpreters for each of the source languages $R_0$, $R_1$,
  8415. $\ldots$ in the files \code{interp-R1.rkt}, \code{interp-R2.rkt}, etc.
  8416. The interpreters for the intermediate languages $C_0$ and $C_1$ are in
  8417. \code{interp-C0.rkt} and \code{interp-C1.rkt}. The interpreters for
  8418. the rest of the intermediate languages, including pseudo-x86 and x86
  8419. are in the \key{interp.rkt} file.
  8420. \section{Utility Functions}
  8421. \label{appendix:utilities}
  8422. The utility functions described here are in the \key{utilities.rkt}
  8423. file.
  8424. \paragraph{\code{interp-tests}}
  8425. The \key{interp-tests} function runs the compiler passes and the
  8426. interpreters on each of the specified tests to check whether each pass
  8427. is correct. The \key{interp-tests} function has the following
  8428. parameters:
  8429. \begin{description}
  8430. \item[name (a string)] a name to identify the compiler,
  8431. \item[typechecker] a function of exactly one argument that either
  8432. raises an error using the \code{error} function when it encounters a
  8433. type error, or returns \code{\#f} when it encounters a type
  8434. error. If there is no type error, the type checker returns the
  8435. program.
  8436. \item[passes] a list with one entry per pass. An entry is a list with
  8437. three things: a string giving the name of the pass, the function
  8438. that implements the pass (a translator from AST to AST), and a
  8439. function that implements the interpreter (a function from AST to
  8440. result value) for the language of the output of the pass.
  8441. \item[source-interp] an interpreter for the source language. The
  8442. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  8443. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  8444. \item[tests] a list of test numbers that specifies which tests to
  8445. run. (see below)
  8446. \end{description}
  8447. %
  8448. The \key{interp-tests} function assumes that the subdirectory
  8449. \key{tests} has a collection of Racket programs whose names all start
  8450. with the family name, followed by an underscore and then the test
  8451. number, ending with the file extension \key{.rkt}. Also, for each test
  8452. program that calls \code{read} one or more times, there is a file with
  8453. the same name except that the file extension is \key{.in} that
  8454. provides the input for the Racket program. If the test program is
  8455. expected to fail type checking, then there should be an empty file of
  8456. the same name but with extension \key{.tyerr}.
  8457. \paragraph{\code{compiler-tests}}
  8458. runs the compiler passes to generate x86 (a \key{.s} file) and then
  8459. runs the GNU C compiler (gcc) to generate machine code. It runs the
  8460. machine code and checks that the output is $42$. The parameters to the
  8461. \code{compiler-tests} function are similar to those of the
  8462. \code{interp-tests} function, and consist of
  8463. \begin{itemize}
  8464. \item a compiler name (a string),
  8465. \item a type checker,
  8466. \item description of the passes,
  8467. \item name of a test-family, and
  8468. \item a list of test numbers.
  8469. \end{itemize}
  8470. \paragraph{\code{compile-file}}
  8471. takes a description of the compiler passes (see the comment for
  8472. \key{interp-tests}) and returns a function that, given a program file
  8473. name (a string ending in \key{.rkt}), applies all of the passes and
  8474. writes the output to a file whose name is the same as the program file
  8475. name but with \key{.rkt} replaced with \key{.s}.
  8476. \paragraph{\code{read-program}}
  8477. takes a file path and parses that file (it must be a Racket program)
  8478. into an abstract syntax tree.
  8479. \paragraph{\code{parse-program}}
  8480. takes an S-expression representation of an abstract syntax tree and converts it into
  8481. the struct-based representation.
  8482. \paragraph{\code{assert}}
  8483. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  8484. and displays the message \key{msg} if the Boolean \key{bool} is false.
  8485. \paragraph{\code{lookup}}
  8486. % remove discussion of lookup? -Jeremy
  8487. takes a key and an alist, and returns the first value that is
  8488. associated with the given key, if there is one. If not, an error is
  8489. triggered. The alist may contain both immutable pairs (built with
  8490. \key{cons}) and mutable pairs (built with \key{mcons}).
  8491. %The \key{map2} function ...
  8492. \section{x86 Instruction Set Quick-Reference}
  8493. \label{sec:x86-quick-reference}
  8494. \index{x86}
  8495. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  8496. do. We write $A \to B$ to mean that the value of $A$ is written into
  8497. location $B$. Address offsets are given in bytes. The instruction
  8498. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  8499. registers (such as \code{\%rax}), or memory references (such as
  8500. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  8501. reference per instruction. Other operands must be immediates or
  8502. registers.
  8503. \begin{table}[tbp]
  8504. \centering
  8505. \begin{tabular}{l|l}
  8506. \textbf{Instruction} & \textbf{Operation} \\ \hline
  8507. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  8508. \texttt{negq} $A$ & $- A \to A$ \\
  8509. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  8510. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  8511. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  8512. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  8513. \texttt{retq} & Pops the return address and jumps to it \\
  8514. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  8515. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  8516. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  8517. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  8518. be an immediate) \\
  8519. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  8520. matches the condition code of the instruction, otherwise go to the
  8521. next instructions. The condition codes are \key{e} for ``equal'',
  8522. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  8523. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  8524. \texttt{jl} $L$ & \\
  8525. \texttt{jle} $L$ & \\
  8526. \texttt{jg} $L$ & \\
  8527. \texttt{jge} $L$ & \\
  8528. \texttt{jmp} $L$ & Jump to label $L$ \\
  8529. \texttt{movq} $A$, $B$ & $A \to B$ \\
  8530. \texttt{movzbq} $A$, $B$ &
  8531. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  8532. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  8533. and the extra bytes of $B$ are set to zero.} \\
  8534. & \\
  8535. & \\
  8536. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  8537. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  8538. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  8539. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  8540. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  8541. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  8542. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  8543. description of the condition codes. $A$ must be a single byte register
  8544. (e.g., \texttt{al} or \texttt{cl}).} \\
  8545. \texttt{setl} $A$ & \\
  8546. \texttt{setle} $A$ & \\
  8547. \texttt{setg} $A$ & \\
  8548. \texttt{setge} $A$ &
  8549. \end{tabular}
  8550. \vspace{5pt}
  8551. \caption{Quick-reference for the x86 instructions used in this book.}
  8552. \label{tab:x86-instr}
  8553. \end{table}
  8554. \cleardoublepage
  8555. \addcontentsline{toc}{chapter}{Index}
  8556. \printindex
  8557. \cleardoublepage
  8558. \bibliographystyle{plainnat}
  8559. \bibliography{all}
  8560. \addcontentsline{toc}{chapter}{Bibliography}
  8561. \end{document}
  8562. %% LocalWords: Dybvig Waddell Abdulaziz Ghuloum Dipanwita Sussman
  8563. %% LocalWords: Sarkar lcl Matz aa representable Chez Ph Dan's nano
  8564. %% LocalWords: fk bh Siek plt uq Felleisen Bor Yuh ASTs AST Naur eq
  8565. %% LocalWords: BNF fixnum datatype arith prog backquote quasiquote
  8566. %% LocalWords: ast Reynold's reynolds interp cond fx evaluator
  8567. %% LocalWords: quasiquotes pe nullary unary rcl env lookup gcc rax
  8568. %% LocalWords: addq movq callq rsp rbp rbx rcx rdx rsi rdi subq nx
  8569. %% LocalWords: negq pushq popq retq globl Kernighan uniquify lll ve
  8570. %% LocalWords: allocator gensym env subdirectory scm rkt tmp lhs
  8571. %% LocalWords: runtime Liveness liveness undirected Balakrishnan je
  8572. %% LocalWords: Rosen DSATUR SDO Gebremedhin Omari morekeywords cnd
  8573. %% LocalWords: fullflexible vertices Booleans Listof Pairof thn els
  8574. %% LocalWords: boolean type-check notq cmpq sete movzbq jmp al xorq
  8575. %% LocalWords: EFLAGS thns elss elselabel endlabel Tuples tuples os
  8576. %% LocalWords: tuple args lexically leaq Polymorphism msg bool nums
  8577. %% LocalWords: macosx unix Cormen vec callee xs maxStack numParams
  8578. %% LocalWords: arg bitwise XOR'd thenlabel immediates optimizations
  8579. %% LocalWords: deallocating Ungar Detlefs Tene kx FromSpace ToSpace
  8580. %% LocalWords: Appel Diwan Siebert ptr fromspace rootstack typedef
  8581. %% LocalWords: len prev rootlen heaplen setl lt Kohlbecker dk multi
  8582. % LocalWords: Bloomington Wollowski definitional whitespace deref JM
  8583. % LocalWords: subexpression subexpressions iteratively ANF Danvy rco
  8584. % LocalWords: goto stmt JS ly cmp ty le ge jle goto's EFLAG CFG pred
  8585. % LocalWords: acyclic worklist Aho qf tsort implementer's hj Shidal
  8586. % LocalWords: nonnegative Shahriyar endian salq sarq uint cheney ior
  8587. % LocalWords: tospace vecinit collectret alloc initret decrement jl
  8588. % LocalWords: dereferencing GC di vals ps mcons ds mcdr callee's th
  8589. % LocalWords: mainDef tailcall prepending mainstart num params rT qb
  8590. % LocalWords: mainconclusion Cardelli bodyT fvs clos fvts subtype uj
  8591. % LocalWords: polymorphism untyped elts tys tagof Vectorof tyeq orq
  8592. % LocalWords: andq untagged Shao inlining ebp jge setle setg setge
  8593. % LocalWords: struct symtab